Is there a cleaner way to find p*q = n, when p and q are coprime?
Basically trying to write a simple RSA brute force. I have modulus N and I'm trying to find p*q=n where p and q are coprimes.
So far i'm able to find the prime factors of N and I can put them in a list. Then taking that list apart into variables then going through each pair to find coprimes. It's messy, and was wondering if there was a cleaner way of doing it?
my code so far:
from fractions import gcd
import sys
n= 17
print "Modulus (n) = ", n
print("p & q are:")
# While Loop to find prime factors
i=1
list=[]
while(i<=n):
k=0
if(n%i==0):
j=1
while(j<=i):
if(i%j==0):
k=k+1
j=j+1
if(k==2):
list.append(i)
i=i+1
# takes list of prime factors and splits to variables
for n, val in enumerate(list):
globals()["var%d"%n] = val
# really messy, tries to multiply first 2 variables, if coprime, print the variables
# if no coprime factors move on to next 2 variables
# if no prime factors in the first place, exit
try:
gg0 = gcd(var0,var1)
except:
print "No Prime Factors"
sys.exit()
try:
gg1 = gcd(var1,var2)
if gg1 == True:
print var1, var2
except:
if gg0 == True:
print var0, var1
See also questions close to this topic

Regex Pattern Comprising From the Elements in List
I am trying to make a script that reads the list element sequentially and concatenate them each into regex pattern.
for example,
I have a list like this:
lst = ['B.', 'Article', 'III']
And want to comprise regex something like this:
re.search(r lst[0]\s+lst[1]\s+lst[2]).group()
so that it can match below regardless of white_spaces between each elements from the list:
candidate_1 = 'B. Article III' candidate_2 = 'B. Article III'

How do i do shift Caesar cipher in python?
how do I move certain number back to make a caesar cipher ex. abcd would be zabc
1 is for how many you would have to move
def cipher(plainText, shift): cipherText = "" for ch in plainText: if ch.isalpha(): stayInAlphabet = ord(ch)  shift if stayInAlphabet > ord('z'): stayInAlphabet = 26 finalLetter = chr(stayInAlphabet) cipherText += finalLetter return cipherText print(cipher("abcd",1))
this returns 'bcd how do i change that

Object reference issue in Python while creating a tree
I'm trying to construct a tree from a list in python. The nodes in my tree have values of indices of my list, and the parent of each node will be the node specified in the list at that index.
In the code sample below,varlist
stores the node elements of the tree with values in the inputarray
. For example, an input list of [1, 0, 4, 0, 3] should give the following tree:0 / \ 1 3 \ 4 \ 2
The way I'm doing this is to first initialize the nodes separately in a list with default parent as None. Then I'm assigning the parent and child as I traverse the array as follows:
class Node1: def __init__(self, val, parent, children = []): self.val = val if parent == 1: self.parent = None else: self.parent = parent self.children = children def __str__(self): return(str(self.val)) def treeHeight(array): varlist = [0] * len(array) for i in range(len(array)): varlist[i] = Node1(i, None) for i in range(len(varlist)): if array[i] != 1: varlist[i].parent = varlist[array[i]] varlist[array[i]].children.append(varlist[i]) else: root = varlist[i] for i in range(len(array)): print(varlist[i].val,varlist[i].parent, varlist[i].children) return(None) if __name__ == '__main__': print(treeHeight([1, 0, 4, 0, 3]))
The output I get is this:
0 None [<__main__.Node1 object at 0x1041051d0>, <__main__.Node1 object at 0x104105208>, <__main__.Node1 object at 0x104105780>, <__main__.Node1 object at 0x104105cc0>] 1 0 [<__main__.Node1 object at 0x1041051d0>, <__main__.Node1 object at 0x104105208>, <__main__.Node1 object at 0x104105780>, <__main__.Node1 object at 0x104105cc0>] 2 4 [<__main__.Node1 object at 0x1041051d0>, <__main__.Node1 object at 0x104105208>, <__main__.Node1 object at 0x104105780>, <__main__.Node1 object at 0x104105cc0>] 3 0 [<__main__.Node1 object at 0x1041051d0>, <__main__.Node1 object at 0x104105208>, <__main__.Node1 object at 0x104105780>, <__main__.Node1 object at 0x104105cc0>] 4 3 [<__main__.Node1 object at 0x1041051d0>, <__main__.Node1 object at 0x104105208>, <__main__.Node1 object at 0x104105780>, <__main__.Node1 object at 0x104105cc0>]
The output is not what I'm expecting because somehow, the
children
list of all the nodes have 4 elements in them, when I was expecting 2 of them to have 2 children and the rest empty. Can someone please help me explain what is going on here? 
How to set a program that count similar items in a string?
I have this list
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
I need a function that would tell me that there is 3 gold coin, 1 dagger and 1 ruby in the dragon loot.

Is there another way to split a list into bins of equal size and put the remainder if any into the first bin?
Given a sorted list:
x = list(range(20))
I could split the list into equal sizes and put the remainder into the left bins as such:
def split_qustions_into_levels(questions, num_bins=3): num_questions = len(questions) equal_size = int(num_questions / num_bins) slices = [equal_size] * num_bins slices[0] += len(questions) % num_bins return [[questions.pop(0) for _ in questions[:s]] for s in slices]
If I have 3 bins from the list of 20 items, I should get a output list of list with sizes
(7,7,6)
:>>> x = list(range(20)) >>> split_qustions_into_levels(x, 3) [[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13], [14, 15, 16, 17, 18, 19]]
If I want 6 bins from the list of 20 items, I should get the output list of list with size
(5,3,3,3,3,3)
:>>> x = list(range(20)) >>> split_qustions_into_levels(x, 6) [[0, 1, 2, 3, 4], [5, 6, 7], [8, 9, 10], [11, 12, 13], [14, 15, 16], [17, 18, 19]]
Is there another way to do this without the messy calculation of slice and equal sizes and the left popping each item into a list of list?
Is there a
numpy
solution? 
how to create dynamic detail cards as image given below in c# windows form
how to create dynamic detail cards as image using c# windows form.all the details coming from the database.thank you

Generate public key from module and exponent using JSEncrypt mismatch with java
In my js code i am trying to generate public key from modulus and exponent using JSEncrypt library.
But the generated public key is not matched with java code.
Below is my code.
this.exponent='010001'; this.modulus='96518069736851770465507126477764180178790654237995866867543110338910852589430926664353243433531145405111315650993549181579863577045594288695458795648936206204355932074042171926595601924679006398922132106252498346239856831108091821764242087251474691687777518072069350367687597158222422562390956429433989056209'; var jsencrypt = new JSEncrypt(this.modulus, this.exponent); console.log('Base64 Public Key'+jsencrypt.getPublicKeyB64());
Expected Output:
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJckBNJas36vkMxult53z3E5pX 1NTCEUe+eG5yagXyFskX8xQscJO5wGxzdUWmVmiXDGBKmdOTzRGUTDDUOE7crUyJ BUUEp0V3xxs67SGtbEbmVCUe8nIyYoBF9twb2Nn9Zm767aJdysH0+uWNLvfGKtDUT 7GAgwxBjpxyjT1G0QIDAQAB
But Actual Output:
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVwqhJzCHEePwxOjAOdaOFt7ACV PVShRzo6JFgqsQ/6Y20AW3ToNWzzEZcF4tnort5ltbHt6mvV6mifRixennZPcNkn4K mrjsf1fGE7V2x9Tg34ZqyLvCkfznInjXsiyBMjgitaUDaFX9jGBZNbsBGhhpqOGQdxs Sd3tTM4H2ywQIDAQAB
In my javascript code for the same modulus and exponent public key value changes every time.But in java public key remains same for same modulus and exponent.
Why the java and javascript public key mismatch.Is any other way to generate public key from modulus and exponent?
Any help will be greatly appreciated!!!

Why not to use RSA 2048 over RSA 1024?
I want to know the advantages that RSA 1024 has over RSA 2048. Be it code size, execution time , anything.
Any help would be appreciated. Thanks!

Ansibleplaybook says file exists, and than says it doesn't exist
I am trying to debug my ansibleplaybook, and figure out why an RSA key I copy onto a Docker Image fails to be authenticated when cloning a git repository onto that Docker Image. The first thing I wanted to look at is if the RSA key file I moved even exists in the Docker Image my playbook is creating. I run a couple tasks, one to see if the file exists, and than another than displays the RSA key to me. The first task that sees whether the file exists saves that result to a variable, and in that variable I can see that the file does in fact exist. When I try to print the contents of that file though, I get an error message saying that file path doesn't exist.
ANSIBLE
 name: Upload Deploy Private Key /home/appuser/.ssh/id_rsa copy: src=keys/keys dest="/home/appuser/.ssh/id_rsa" mode=0400  name: Check that /home/appuser/.ssh/id_rsa exists stat: path: /home/appuser/.ssh/id_rsa register: stat_result  debug: var: stat_result  debug: msg="the value of id_rsa is {{lookup('file', '/home/appuser/.ssh/id_rsa') }}"
TERMINAL
docker: TASK [base : Upload Deploy Private Key /home/appuser/.ssh/id_rsa] ******** docker: Sunday 18 February 2018 13:24:36 0600 (0:00:00.508) 0:02:20.492 ******* docker: changed: [default] docker: docker: TASK [base : Check that /home/appuser/.ssh/id_rsa exists] **************** docker: Sunday 18 February 2018 13:24:36 0600 (0:00:00.864) 0:02:21.357 ******* docker: ok: [default] docker: docker: TASK [base : debug] ******************************************************* docker: Sunday 18 February 2018 13:24:37 0600 (0:00:00.322) 0:02:21.679 ******* docker: ok: [default] => { docker: "stat_result": { docker: "changed": false, docker: "stat": { docker: "exists": true, docker: "path": "/home/appuser/.ssh/id_rsa", docker: } docker: } docker: } docker: docker: TASK [xenabase : debug] ******************************************************* docker: Sunday 18 February 2018 14:12:09 0600 (0:00:00.337) 0:02:08.254 ******* docker: [WARNING]: Unable to find '/home/appuser/.ssh/id_rsa' in expected paths. docker: fatal: [default]: FAILED! => {"failed": true, "msg": "An unhandled exception occurred while running the lookup plugin 'file'. Error was a <class 'ansible.errors.AnsibleError'>, original message: could not locate file in lookup: /home/appuser/.ssh/id_rsa"}

Math in Multiple fields
Having trouble doing multiplication, division and addition in multiple fields that are populated by picker view selections. All of my picker views display the data but when I click the button to calculate, nothing happens then it errors out on the calculate function.
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var textColor: UITextField! @IBOutlet weak var textRatio: UITextField! @IBOutlet weak var textDensity: UITextField! @IBOutlet weak var textRnumber: UITextField! @IBOutlet weak var textWeight: UITextField! @IBOutlet weak var textCdensity: UITextField! @IBOutlet weak var textCatalyst: UITextField! @IBAction func Calculate(_ sender: UIButton) { let a: Int? = Int(textColor.text!) let b: Int? = Int(textWeight.text!) let c: Int? = Int(textRnumber.text!) let d: Int? = Int(textCdensity.text!) let volume = b! / a! let total = volume * d! let catalyst = total * c! let catalysttext = String(catalyst) textCatalyst.text = catalysttext } var colorBase = ["E100 Blackout","E110 Midnight","E120 Smoke", "E130 Earth", "E140 Jungle", "E150 Sand", "E160 Concrete", "E170 Coyote M17", "E180 Daniel Defense Deep Woods","E190 20150", "H109 Gloss Black", "H112 Cobalt", "H115 Sig Teal", "H122 Gold", "H125 ICON Grey", "H126 Dewalt Yellow", "H127 Kel Tec Blue", "H128 Hunter Orange", "H130 Combat Grey", "H131 Dark Green", "H133 Cross Canyon Arms Green", "H135 Ratio Gold", "H136 Snow White", "H137 Gloss White", "H139 Steel Grey", "H140 Bright White", "H141 Prison Pink", "H142 Light Sand", "H143 Benelli Sand", "H144 Corvette Yellow", "H145 Great White", "H146 Graphite Black", "H147 Satin Mag", "H148 Burnt Bronze", "H149 Copper Brown", "H150 Savage Stainless", "H151 Satin Aluminum", "H151E Stain Aluminum Electrostatic", "H152 Stainless", "H153 Shimmer Gold", "H154 Medium Brown", "H155 Taurus Stainless", "H157 Bright Nickel", "H158 Shimmer Aluminum", "H160 Colt Coyote", "H166 Electric Yellow", "H167 USMC Red", "H168 Zombie Green", "H169 Sky Blue", "H170 Titanium", "H171 NRA Blue", "H172 Sea Blue", "H175 Robin's Egg Blue", "H184 Glock Grey", "H185 Blue Titanium", "H188 Magpul Stealth Grey", "H189 Noveske Bazooka Green", "H190 Armor Black", "H196 A.I. Sage Green", "H197 Wild Purple", "H198 A.I. Pale Brown", "H199 Desert Sand", "H200 Highland Green", "H201 McMillan Grey", "H20180 FS Tan", "H202 McMillan Olive", "H203 McMillan Tan", "H204 Multicam Green", "H205 APA Sage", "H206 Tarjac Green", "H207 Wild Green", "H208 Wild Pink", "H210 Sig Dark Grey", "H211 BAE Green", "H212 Federal Brown", "H213 Battleship Grey", "H214 Smith's Grey", "H215 Smith's Brown", "H216 Smith and Wesson Red", "H217 Bright Purple", "H218 School Bus Yellow", "H219 Gun Metal Grey", "H220 Ridgeway Blue", "H221 Crimson", "H222 Peach Melba", "H223 Rode Pink", "H224 Sig Pink", "H225 Mud Brown", "H226 Patriot Brown", "H227 Tactical Grey", "H229 Sniper Green", "H231 Magpul Foliage Green", "H232 Magpul O.D. Green", "H233 Benchmade O.D. Green", "H234 Sniper Grey", "H235 Coyote Tan", "H236 O.D. Green", "H237 Tungsten", "H238 Midnight Blue", "H239 Benchmade Coyote Tan", "H240 Mil Spec O.D. Green", "H241 GA O.D. Green", "H242 Hidden White", "H243 Safety Orange", "H244 Bright Pink", "H245 SOCOM Blue", "H246 Desert Gold", "H247 Desert Sage", "H248 Forest Green", "H249 Nut Brown", "H250 A.I. Dark Earth", "H251 Green Beret Green", "H252 Midnight Green", "H254 Muddy River", "H255 Crushed Silver", "H256 Desert Verde", "H257 Texas Tan", "H258 Chocolate Brown", "H259 Barrett Bronze", "H260 Standard ACU Green", "H261 Austrian Flat Dark Earth", "H262 Stone Grey", "H263 Foliage Green", "H264 Mil Spec Green", "H265 Flat Dark Earth", "H266 RedOrange", "H267 Magpul Flat Dark Earth", "H268 Troy Coyote Tan", "H269 Barrett Brown", "H270 Daniel Defense Mil Spec+", "H271 Daniel Defense Tornado", "H272 Daniel Defense Deep Woods", "H280 MultiRegional Earth", "H281 Woodland Tan", "H294 Midnight Bronze", "H295 Cobalt Kinetics Slate", "H296 Cobalt Kinetics Green", "H300 Armor Clear", "H301 Matte Armor Clear", "H30118 FS Field Drab", "H302 Pearl Clear", "H303 RotoBlue Clear", "H30372 FS Brown Sand", "H30372 FS Brown Sand(Big Blue)", "H33446 FS Sabre Sand", "H36357 FS Grey", "H400 Jesse James Eastern Front Green", "H401 Jessie James Civil Defense Blue", "H402 Jesse James Cold War Grey", "H7504M Matte Brown", "H8000 RAL 8000", "H900 Electrical Barrier"] var outBase = ["1.33", "1.38", "1.38", "1.42", "1.40", "1.42", "1.38", "1.42", "1.40", "1.40", "1.34", "1.47", "1.10", "1.43", "1.41", "1.52", "1.39", "1.33", "1.41", "1.34", "1.36", "1.38", "1.43", "1.43", "1.41", "1.39", "1.39", "1.35", "1.36", "1.09", "1.52", "1.43", "1.38", "1.36", "1.36", "1.38", "1.36", "1.10", "1.40", "1.38", "1.40", "1.35", "1.12", "1.36", "1.36", "1.04", "1.37", "1.46", "1.42", "1.38", "1.39", "1.05", "1.48", "1.39", "1.43", "1.39", "1.36", "1.37", "1.43", "1.41", "1.38", "1.36", "1.38", "1.37", "1.36", "1.38", "1.37", "1.40", "1.40", "1.38", "1.05", "1.39", "1.37", "1.37", "1.35", "1.35", "1.40", "1.32", "1.36", "1.33", "1.36", "1.35", "1.36", "1.49", "1.40", "1.38", "1.41", "1.42", "1.37", "1.40", "1.36", "1.37", "1.37", "1.36", "1.37", "1.38", "1.36", "1.42", "1.39", "1.34", "1.37", "1.30", "1.38", "1.32", "1.38", "1.39", "1.35", "1.36", "1.37", "1.34", "1.39", "1.39", "1.38", "1.33", "1.31", "1.35", "1.35", "1.36", "1.38", "1.39", "1.38", "1.37", "1.44", "1.36", "1.39", "1.30", "1.37", "1.33", "1.35", "1.35", "1.48", "1.36", "1.45", "1.38", "1.38", "1.37", "1.38", "0.93", "0.92", "1.40", "0.93", "0.92", "1.36", "1.36", "1.40", "1.36", "1.37", "1.05", "1.04", "1.37", "1.40", "1.48"] var ratioBase = ["HClear", "12:1", "13:1", "14:1", "15:1", "16:1", "17:1", "18:1", "19:1", "20:1", "21:1", "22:1", "23:1", "24:1"] var rnumberBase = ["1/9", "1/12", "1/13", "1/14", "1/15", "1/16", "1/17", "1/18", "1/19", "1/20", "1/21", "1/22", "1/23", "1/24"] var cdensityBase = ["1.05", "1.07", "1.07", "1.07", "1.07", "1.07", "1.07", "1.07", "1.07", "1.07", "1.07", "1.07", "1.07", "1.07"] var picker = UIPickerView() var picker2 = UIPickerView() override func viewDidLoad() { super.viewDidLoad() picker.delegate = self picker.dataSource = self textColor.inputView = picker picker2.delegate = self picker2.dataSource = self textRatio.inputView = picker2 textCdensity.inputView = picker2 self.picker.selectRow(32, inComponent: 0, animated: false) self.picker2.selectRow(7, inComponent: 0, animated: true) let toolBar = UIToolbar() toolBar.sizeToFit() let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(doneClicked)) toolBar.setItems([doneButton], animated: false) textColor.inputAccessoryView = toolBar textRatio.inputAccessoryView = toolBar textWeight.inputAccessoryView = toolBar } @objc func doneClicked() { view.endEditing(true) } func numberOfComponents(in pickerView: UIPickerView) > Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) > Int { if pickerView == picker{ return colorBase.count }else if pickerView == picker2{ return ratioBase.count }else if pickerView == picker2{ return cdensityBase.count } return 1 } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if pickerView == picker{ textDensity.text = outBase[row] }; if pickerView == picker{ textColor.text = colorBase[row]}; if pickerView == picker2{ textRnumber.text = rnumberBase[row] }; if pickerView == picker2{ textRatio.text = ratioBase[row]}; if pickerView == picker2{ textCdensity.text = cdensityBase[row] } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) > String? { if pickerView == picker{ return colorBase[row] }else if pickerView == picker2{ return ratioBase[row] }else if pickerView == picker2{ return cdensityBase[row] } return "" }

Multiplying Variables Together
So, I know that this question has probably been answered, but I couldn't find anything. So, keeping in mind I don't know anything in terms of the stuff most people on this site would normally mention nonchalantly, how do you multiply variables?
>>> print("This is a basic multiplication calculator, useable for two numbers and only two.") This is a basic multiplication calculator, useable for two numbers and only two. >>> num1 = input("Num1, please.") Num1, please. >>> num2 = input("Num2, please.") Num2, please. >>> numfin = num1 * num2 Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> numfin = num1 * num2 TypeError: can't multiply sequence by nonint of type 'str'
That's my code basic, obviously, but I don't know what went wrong.

Issue with Multiplication Table
I'm looking to see if anyone can help me figure out what I've got missing here in my code:
def Table(n): for x in range(1,n): for y in range(1,n): z = (x*y) print(z+1, end="\t") print()
I'm using Spyder using Python 3.6. My current output is as such
Table(10)
:2 3 4 5 6 7 8 9 10 3 5 7 9 11 13 15 17 19 4 7 10 13 16 19 22 25 28 5 9 13 17 21 25 29 33 37 6 11 16 21 26 31 36 41 46 7 13 19 25 31 37 43 49 55 8 15 22 29 36 43 50 57 64 9 17 25 33 41 49 57 65 73 10 19 28 37 46 55 64 73 82
As you can see I'm missing the column for
1
when I call the variable & put inTable(10)
. However, if I add the+1
inprint(z+1, end="\t")
then the10
will not appear. Anyone know what I'm missing? I'd like to have the whole table show up. 
What does the prime_division do?
rubydoc doesn't clearly explain what this method does. It states that a it returns a factorization of a number. And yet in their example they had:
Prime.prime_division(12) #=> [[2,2],[3,1]]
I don't understand how
prime_division(12) == [[2,2],[3,1]]
. Also when I try to call prime_division it doesn't work. I need a clear and thorough explanation. 
Latent factor recovery with probabilistic matrix factorization using Edward
I implemented a probabilistic matrix factorization model (R = U'V) following the example in Edward's repo:
# data U_true = np.random.randn(D, N) V_true = np.random.randn(D, M) R_true = np.dot(np.transpose(U_true), V_true) + np.random.normal(0, 0.1, size=(N, M)) # model I = tf.placeholder(tf.float32, [N, M]) U = Normal(loc=tf.zeros([D, N]), scale=tf.ones([D, N])) V = Normal(loc=tf.zeros([D, M]), scale=tf.ones([D, M])) R = Normal(loc=tf.matmul(tf.transpose(U), V), scale=tf.ones([N, M]))
I get a good performance when predicting the data in matrix R. However, when I evaluate the inferred traits in U and V, the error varies a lot and can get very high.
I tried with a latent space of small dimension (e.g. 2) and checked if latent traits weren't simply permuted. They sometimes get permuted but even after realigning them the error is still significant.
To throw some numbers: for a synthetic R matrix generated from U and V both normally distributed (mean 0 and variance 1), I can achieve a mean absolute error of 0.003 on R, but on U and V it's usually around 0.5.
I know this model is symmetric, but I am not sure about the implications. I would like to ask:
 Is it actually possible to guarantee the recovery of the original latent traits in some way?
 If so, how could it be achieved, preferably using Edward?

how to factorize two lists
is there a way to factorize some lists easily in perl?
For example with 2 lists
('a', 'b', 'c')
and('d', 'e', 'f')
I want the output('ad', 'ae', 'af' .... 'ce', 'cf')
for now i'm doing
use strict; use warnings; my @listA = ('a', 'b', 'c'); my @listB = ('d', 'e', 'f'); my @listC = (); foreach my $elementA (@listA) { foreach my $elementB (@listB) { push(@listC, $elementA.$elementB); } }
This works fine, but I would like to know if there is a more "perlish" way to do so?
thanks :)