title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Pandas - Self reference of instances in column
39,883,232
<p>I have the following DF</p> <pre><code> SampleID ParentID 0 S10 S20 1 S10 S30 2 S20 S40 3 S30 4 S40 </code></pre> <p>How can I put the id of the other row in the column 'ParentID' instead of the string?</p> <p>Expected result:</p> <pre><code> SampleID ParentID 0 S10 2 1 S10 3 2 S20 4 3 S30 4 S40 </code></pre> <p>The closest result I found for this problem was: <a href="http://stackoverflow.com/questions/28101317/how-to-self-reference-column-in-pandas-data-frame">How to self-reference column in pandas Data Frame?</a></p>
0
2016-10-05T20:37:35Z
39,883,828
<p>Use <code>replace</code> by passing along the mapping lists of values to replace:</p> <pre><code>df.ParentID.replace(df.SampleID.tolist(), df.index.tolist(), inplace=True) df Out[22]: SampleID ParentID 0 S10 2.0 1 S10 3.0 2 S20 4.0 3 S30 NaN 4 S40 NaN </code></pre>
1
2016-10-05T21:17:35Z
[ "python", "pandas" ]
How to get a var out of beautifulsoup soup
39,883,332
<p>How would I get the variable out into like a json or any other way to just take out like challenge</p> <pre><code>&lt;html&gt;&lt;body&gt;&lt;p&gt;var rechallengeState = { challenge : '03AHJ_Vuv8ZHJfsjnR3ueIvm89Jfa6oUJ3-kuzA-VcQIaR30A9CZva7lMaBrYlvcGG4cOPCeKXfERQe_u-cMw_8ZVi6CipeJVAYAsrOeBHryWRCMIaMt4V-TQlTgyUA4ndejEgBGUCUw7rwM-ltDr-do8ry-MRv26qQTpS-iCtvONYc6xZBURPEaTo2Nkfq8HJeFA_g6mMLUBG', timeout : 1800, lang : 'en', site : '6LceKe0SAAAAACFIVHolzCVkrGgSfzFASoOmELIc', error_message : '', programming_error : '', is_incorrect : false, rtl : false, t1 : 'Ly93d3cuZ29vZ2xlLmNvbS9qcy90aC83ZFZqVVRQN3pmYXh1UnMtNFV3Q19KT0dvbHU4LWdXcXhHTlhNMjRoV1VZLmpz', t2 : '', t3 : 'ZnlxN0NEbUtzcEZVSUJDcnNFaVp2Z1FKSyt2S0gxNmZ0ZEN3MGQ2VEhrRTE2UjY3QWJpNGphRStKaisxVlZDbFR6clRxUU1aTFFqME04clpBWEF1RGViQ3JwUjFOcnkvMTVKTHFwdWlkcU53R0lIeVJlditZc0p5TnRPQy9lNUNqV3BMRlJiVkh6ZjgvZ1czc25LV3FnZ1ZQWG96NHlJWmJacGI2Z3VCTVF6VVdublBmSkFRVXJzVGg5RFhHTmw0NjR6czZML0JSeWl0WE5keGVTTUsvN3VIWmw5OFpSeUhiU3lTTEhhUzZsUVU3R1k4MGloYktXeGpHYnI2VWl0bkFPR1dzZDYwb052a2xjUjI4aFBBTTdOdW51a1lGNzh5ck9maTRyU0dkYTluTDBWb2VxRTZTUEtUNWxiTW5Idk5lUFpWNzJwb2o1OWRMeWN1S3BoLzdDMlU1c0F5UFQwQXM1SytTdFZobDFVdjFhUFlGOHZVa25CZ3E5S0I1c3A4ZnVrQ01XSHE4bll5SVNscVJSRjJKbU1JaFRZSURmZW4xd2wyZU52bHpRM0pEQzc3Ly9TSzdmV2IySjJmeHJ4Yk43TStmSnZWUnpWeVFUNnBmdWpKaDdLbFF1eEZkaHl3TnFDTlR6RElsNHBvRDNDc0NHcWw3OE9oWmYrVzlDbXFneEV4RHYvNWdaVU40TVJYaExzSGNVYklaRExtTGtqZkpDem1FNWhKQktpVkxNWmxYSWNCb096K2cwbHVCQVRYeXFTQnE3bmF0VGUrenY0Rm9iaUNIQkRhaFI2ZTQwTDhoRHlRZGI1WXo5eDU3MUdxU3UyVFZ5Qm40S1FsRTBvM2tlLzdhZGtKbThONnpFTkhYYTVBakx4UkpBSGlDRTB5a2lSY2xFVU56RldDVHZlVVhsQitKUmJFeDloQ2RhODFZUUlVTTNSSkJKV0swTnVOb0syRktGdDZQeTQ2emFucFo0TWh5Z1hVaHVORUE0RE9NemJUR1ZEdVhrSHhJcWZENXc0L0R5eG8vOHZMdnZjUUJUYjhycjNXSDRmUWwycmpEaTBHUGZJTkpLVTU1cWNFamtRdE41WUlERHlESmoyRXlGUUtCMFRHSTR5YnhwdlBwNEpvVk9BQlNZWXJaWmpvWW1SMjZTdzF0Y1ZOR3J0MFNzc1Q3bWRVMzFRUDYxYWlmTE1GK2t0TktEMTVLb0h4R0sxV01jcUNVLzYyVkpXaVFkRWpJVXg5K3dOckVLeERMbGw2V1laRERLbmxoQlpMR2xLSWh3QWVCOGVUWFZ3YkE3UkJjNHFnSDdzS1dZVC8yVk5wcncrNjltUHlsM3F0VCtpOEwvYzZGOE4raWE2L0dQbTd6WXpSVkoxS2lVL1NPMXpyMGNrSjY2Z1N6NWNxaFIyRjBsWlJlMmR4NW9LRWtEamNqN0dvOE8yTUx2R1VkMTNleGhFTmlldXhrYUpGOEowcnFKaDMzT2xQNFZZWWFkSXRRMVI0aC9NREFMWmZjdGFDWEQxTzNvVU9NQWdiSkw3TEQvcy9vVklmTVhxTndZL2pmb0VZaU45bVRNS0syNEkrV0hOeWxnTVFpUDJsUDVjekVLRmI5czRCelp0T09hZ29QYTJTMUFTcVB4cWhOek5kMkFXZldlbFU3UHdQOHo0QjNLOVhiWk82ckp6dzRwQ29CTmhQcVVpSUttYTU0NzYrdnc0VW1jVDdhb2RMUVl0RXlqR2k0NWIwclg3bXdkcUVFK1Q2SkVDUmROM3JRdWR3TytZMTljbjRwQlN0Wnd3VXFCZzM2NTJJQlZ6OVpJcVNpYjNsWVlrZVBOUi9qeGlLT2lZTXNGZitVaGY3eFNaakhDTnpsNUlwWHcvTnJIU09RNEJWWGhyb3drR1pFeG16Yy90djVwSW4vNkNnSnRnR0R1QlZQQkJ5bTkyZDR5dzhyd3JLR1J1YkFGdWZvcmVwRGlRYWR1QjZuNmtVTHptZ2p6THZHamk2S0JSK0RMT3hscWpES3h0Ym1zMjVuREdkdm43RTZ0bnhGUDhNNzk4cDkxU2VtenZMT00rcjdrZzBVMitNNWJFNVVaVUtIQVN5ZXcyTk1zVFhrTVZwUW9yYlJkZ0xyZVBTOTU4TFV6VmF3MlV2WUZ1OVI1YUhPVm9BN2hxVkJhQ2tLcWRiR2xLUmVTbkFIVEpyNi9RUU5lQytESGluOWJGSmNyb1hROURZMk9hVHdZUWlBWjhuTzBWTGtTY3RIRGZUSi9qS1BpSEdEQVVXZm5VdjNvaHpoRFpyYXBET24vKytxNlhEZXNXNTE3SlZTRE9WWDYxeFNKRjRIU2FuK0VJUksvUlp6VEpaamloRXlOVGdFcjJjMFp0NWpSdWFDemROZHA4RHRackpzK2VDS3VIMjEzdWk2cEsxOFNZYUFkN1BGSEQ4bHQzWEtaNms4VVM2WTlHeXlpaUp2Tks3cXBsRGNrRlptb1RWVE1FYnc5dFJYSUMya2JpYStWV0F5TU1meUZGekp4dUMwTFNrdUlqelV3S3NjampUQ2ptbkZoakc4VTBiWEZjenI5aWJvNHl3OW9PaTRvWGsxN3hwOFpxeEM2NXdBbURvVWJNKzl4MkFwWUM3SlJtL2hkYnlXU3NRc3pnVjQ0TEtDY080N0FYbjdiVXdkSVMrcStUWU1BNkI3cG42a2t2OVM2aGJZZEgrTUhDTjhLQUVlY0FrVEtKR1ZxWTNoL1dYeFJwWGY2NWhEUGVzT1pmVXdreVo3bGVBTmtrakpPMUlXWDhjcExpTk5zRDVLcWRuT1Q4YW9EYVIrVHcyS3VCeEFqUzZuMTZFTGNOaUcvUm0zVGU0WW51dVIrL0xPNGV6QU9lMjZQS2FIbW00ZVBxZDUrSThPOWhXTVd6UWZCWTJqZUhUbUVZODdIZnZLeUl1V1ordlZVM21OQzVsTXpIQlZVSHpIV2tWN1VuTVFOZ3FxOS8xYzZlaC8wWmZBVFNtWlVBNGUrcm83Z0VMZHZVeUVWclpzWGRSOGNjaVZsT0xzNXlqMHUzd2IvZm9kenJhSjBZcmY4WmlnMXdUL1pYNnJBcmhnRUFYNWV4Sm5KWTRGYmhaTHFxOTJhM21jT1pyYWo0SWlJNk1zeGFMLzEzVWZXSm9pcG9MY2Z2YmhoWG93Um1hR2k0c00reVBvQnFFcFE2RFBhTGJzaHdnWWNYRDRTY0Zha0NIQ2c0dW5XWkxuZTlIdmZ3Qzh2SXNQMitQazRJYnVCMERvOWtIZDRHUWFYRlNobGxsSzlnK1FqSW1RenhDVGw2aUs0WEFzTERvZ1dBeFBuRzR6VzJ5VURrdCs2TXE4N2VQYitPRmF3QzBLSnFzTHJNdDIydWsvQWNHTjNRYU0rZzVtOEIxN3FaWmUwWUxnTXNGcy9KYWlIcGtKU2pGYTNuaDczR2graklObzhsOEc4b0tsNmljMDZ6QkVEY3liNnRUREpVVWJ0MGgrOEZQdjlBb2FJa3dtUGtyTkZmVlU0Wnh2MzFoeDAvNVZURG84eTRYcXE5UEV0NHZOS3c4MExQVUV3MzZyL1kvdFpldDJFRm4vWk4vaVFBdWRxanFPTGQxcURoc2FGaFdOd29XS2FPUmN6dmRGSGJkSWZFZ3VyeGdPeCtKdkFqWjF0OVRZN21KRUJYeVdQaHp1TkJDU3JwRjVkQWRMZW1xcTd4UzZTY2tnN0gxczl6U3RYOENic2ZHeWswbjlzMXppR0F0aThvNjNDdDJZd1pGRHZDQmd2bEk2aEFmWEQ0R1ZJc3pTMzZqSGJCdTlUeGZOMk9PeGk4MWVrcE9rWC9WeE5qLzdDSHA0TERuK2ZrLytFYVRTWXBnOWxMd01pZVVBU2l1czgyUGlMNS9wM0JES2NwMDE2alVDMldlTDdma1pQclIzOVR6ZVorODNHb2lYTlQ3WDFtcXVyR1JEWlZXWWVHZGU1M3o5WWFtTmY0RWh2OXFQWFJUV005NnlBUXZMNTRDS3A0TzBxWCs5VGtHcVVmb1c3ZlM2VTRWSFdTTDVscE9aaVZqTi9LblZOazVINkRZNWlqUEVjSTRpRk9vN0U2TXgrMUhicEd3VjBIbzYvekVQcUs3czZUM0RhekpCVFRwNVM5YTI2SysxUDRIVGVFTFV1eVV4NUpIMVRseDJCTjVqVFVVVUl6anNiOU5xV1VrUDJIYnFqOXF4bkluQnVWZStyQ0RzekcvdEhxZVJ6bGNReGxuaGFTeEd4TTRsSVRtQWJ1bHBkVXJ4dk9lakxZQ05OWDRXWXVBQ1NNQ0hpOTZ6bmpxVTdXMFIzMkRwWHNtc1NOVlZITkNRYkpXMVhFa1FSN1VVZEFwYUs1WHFZL1RCMW1qcGRIUjcwclJHWm5SMitpelB0c3lkeDdNZVlyOWdaUTU5eEFEaWJsc1dnZlFXSU9Gc0loUUNCL1h4NHNLQklZUW1vWEJBSFJYZmVyWUZOVjZ2UUovUUVHTFJNcDlPVnY1K0tUQ2RERzFkbUc2Z2JxRzErbTl3WTY0K2lVRHlwbHFpaXk2cEJNWUt3Z3dDVjJvZUZSdXg4VDNNZjhBYTM5VW5FczdGdlhrMmhKMk42WkFpNWZOc3Y1NVFJM0Z5RTBQYTZMRlhUekk2NDFKQ2dPOVdNelI4Z2M1cC9FZnNFWC9YcUVXY3gxYTU0WDF4aHQrcUpuSERwVVZ2UVJJK0JrczVzeFFCbUcwQkpPUWpWOVBna1oxMEtvK2xRSXNPMTgwL05wS1JUVWpaQ3lVNGpIZldOTUx3bWVKcDlwVEZjUWNacW16TjMyaU0vbTR6bWZlVkNuZUt5TDU0Y2RkbFlXNVFmWEl6MXZyR05aa2FUd0k5WDNFN3E0TFlCZlM2TG9XNlZabnB3c2xSWUNmVytaQUJUYjA1RVJVWnNMM1FaYzdvVGJSVGZwb2ZDaWRtdkdpeUVlYTVKY2E3d1lNd2RzSkJiQzBSOVpvTDhpbVE0a1lHRnNDdXpqekMraEdiMHgreW5JQTM2MmhVTXdxZnNhWDM5aFRnZWROMnNqdC9LdmlCQVhvK2F3aUFIU2ZpckNYelFLT0V2VGVPTGhNY1gzYWdHMUxVQ25oY2hCUXNRQmJ0U21xdmwxMDhPbU9xUGlnOVUydEJkUFJ4bjhlWUlmSnlqeHNtSFE4YUlCelJtVmxPWnZaRzlDbkVIK0Q5WGZSY0tCdmIzZVpMb2lCRjlkYVJieGRuTko5TndKRy9TbnR5bE9uN2NxaVVNL2hwQTdaMy9EckZlbHZFQXNTL09WS3c2K2x1OWFQNUZiN1lSVmdkWDg5RnlSU1N4TDJMWHdFbzdHU3dwS28xenVwdDg2YlY4QmpRZ3FYZ2FpeGJhRWJTNC90SkQ5TVo5WE1xeWV6dlJTaWQwZUM3akhXcVZ2b2o5VHBHTTJNS2o2MHZ6YzZKQnhiMjJSTUFLQ01oYVlXaEk0dFYxWVpHcVp4T24vdjFCamF6ZzdoN2s2NTYvVUZJdFhHTWNHbjZXNVdZaHNCL09aeVIzZ1NDakIrWndxbmhzY045Mm1xZUhOZjdubU9FMmx1K3NzOGVBYktCZjNPdk1SMnBRM2RvTmRMTHhNRVN0OEQ4Q0IyNG9VSFRZZVR3dFh6QW5MUFVXWkFnRmJwbjB6VmcvR251ZVdCMXZ3ZXNLbkVDK1JtNHVkbkdxMnA2ME92SWFVblQzRUVuR0VBUFhtazYvWFYwamxaUSs2Tmp1QnVYMDZpdnlNZzh1Qk1wNFBUTUJFNTVlaTJPODV0b1JIR1FiZ1lXUFowdGltcVk0SVZPZlRMTGpqYTNyblo1aUtZSFNaTWp2STVwNkxlU2FEa282aVBoTFpwdnMzNDFaYjJnUnZoNHY5b0pzQmhkQmxTek5DWnhSR2NpK0xpNWJDaEtud0NXcFhFQ1NmcW9QNlFMY2xxYkpRVkU5SHVzWk9SSldZb2hFQmQ4aFpZOGFrcVpUaCtNLzh6OE14d04wOEZuWTRlN2FicStrU3R1RHY3OHFrY253WDNjemNENFhMNiswZDBoUWtESHg4QUtOVDVTeE5YN3pJSDF0ckoxWTNaeXVsRUhydk1vdW1ZK1RIa0VURGJDMGFtQXR6VTJIRlVrSzN5aWJVMXB3MmdmZ0EzdDBjSnVmUUxUSDIxVUN4VXpxZnYyUWpvQThDSUlmSSsyTHoxYnhvSG1KZFBXdW16U1o1REU3QXE2UVVPaFR0V1UxdjBxTHVsa1dKQlJacGtCZHkzRGhSeStxei9uT1FYbEZ1aHduSFQ3SWJ3L0JSczZKdjdkalRKbnZKL08zZUNvM0FnQkh3RXp1d2RrdkQ2Ynd3dit0aU1peEFQSi9FZGIwZyt4VndrcUg4VklrcGJIclZzWmEzWGJDK0ZKaXFKcFpuYWZsTDNjUjFBVEI4Zyt4eDBRMGsvTUxSVU40R29KR0w1M3Bxbk4wWmFVSk1COUhBL1BuZ0ZxOFgrazJlMEhzODZqVWprWXA2Vm95RTRDcTZRQnRHNCsvTElodnRvZC9kVWxZZUJsL2xCQU5iV0FkaVZtMjlLcnZid01kS2Z1bmE0QWlTZGt6bWc1ek5EZHExdGhjQVpIY204eHJzY0hkYXNMMTVUSHFnNUFtNm1ydzJzOVNLV3M3Nmk3b3phYkxFMWRJYjFwcWtRMVZwL1p0aWhSQVZSMVVVc1AzZVdjcVBVZThRUUFXdGpnR2loZ1VSMHdmSk5xUHJxUWNYUEowQUxrZ0NxOGQ4ZS9qWmhUbUpaSDQ2UW5sT0h5dFR2R2g1Vlkwa281RlJFVm1RdG5LSUhnUTJlV1lFRG1HL1BsYjVLamhOQVg4NlI5MTd0ZitIQlRQbTJkWkF5QkZUejdvZ244aGFmNCtMTmVwb25PMy9YNlJsc3FYVW5WMjRYS094YmhCMnVFSGVVWWtHR0RYci9HSGJiMGdURXZZdVlTb0dVOUVmRE9SOC9weHlDV3Q2ajV1UXBualdXQ1FJdVoxS3UxMnU1YXhReGRlYWRzU2lIei9jelVmUElqakVScysrbkc1ZWh6MlV5YlUrUFQrbG81OVI4Vlk5aWJRd000cytBRy9DVThKVkllaHR6M1o3a2U2S0xXTVpJdHJYSWpraTFCMzUvRDhqdHBpaEo4NlBTbUxzVHpGNzcxU2YycHBZOWFQUEhwSzhVM29MbWpEOXh4VURXaC9ya2k1ZUZBWnFBTTBBM0drQmpiWEd2VjZIRmxJazJDNU9lRnRnWmxSRGRNVS82emFqbS9QMU5ib1VScDFNTDNMM096WmdGR0c0MFBPeDh1bkZ6OGFmcFlVLzhFSkNHUnhvaUluYkNmRGV5NmhSbXIxUyszR0JDRTdkYnJobW9meVhmN3BmcW9BM0dXaVI1dHhrcUxOSjlRcmFsVEJQMkdXT0VUS2hjTGNVRkpMWUdFWnVRTUFvYXpXVDJPUzJQazN2cEdNckpKMzJRSDJRQTR0aU5jQTJHUFhVcjBKY2FLRytCcXc3Nk9jbWNma2c5TEFjM1E5akF0aHZ0V2JySGRicFFQWGQwcjhYQVRDNHhRUHdwQ3JRcy91QUhwYlh3eFowODRoMGlrQ2RiNjNxNFZUaEZ6elFObUpVWDIzbDF3NWpRQk5NTjB3dmY3MFZqb2ZUNUZRaURFVEJZRUd3PQ\x3d\x3d' }; &lt;/p&gt;&lt;/body&gt;&lt;/html&gt; </code></pre> <p>This is my Soup from beautifulsoup4. How would I get the variable out into like a json or any other way to just take out like challenge Thank you very much for the help!</p>
-2
2016-10-05T20:45:29Z
39,884,339
<p>Description in code</p> <pre><code>from bs4 import BeautifulSoup html = '''&lt;html&gt;&lt;body&gt;&lt;p&gt;var rechallengeState = { challenge : '03AHJ_Vuv8ZHJfsjnR3ueIvm89Jfa6oUJ3-kuzA-VcQIaR30A9CZva7lMaBrYlvcGG4cOPCeKXfERQe_u-cMw_8ZVi6CipeJVAYAsrOeBHryWRCMIaMt4V-TQlTgyUA4ndejEgBGUCUw7rwM-ltDr-do8ry-MRv26qQTpS-iCtvONYc6xZBURPEaTo2Nkfq8HJeFA_g6mMLUBG', timeout : 1800, lang : 'en', site : '6LceKe0SAAAAACFIVHolzCVkrGgSfzFASoOmELIc', error_message : '', programming_error : '', is_incorrect : false, rtl : false, t1 : 'Ly93d3cuZ29vZ2xlLmNvbS9qcy90aC83ZFZqVVRQN3pmYXh1UnMtNFV3Q19KT0dvbHU4LWdXcXhHTlhNMjRoV1VZLmpz', t2 : '', t3 : 'NjliZ0lya2VaS3JHpaaU9sbFJuSREF6Sk9KMNZbW9tcjlvcVlEnV5Y3NlWHN2YWt6ZEdleDZQcVkyaForVXJZclVsZGN0ek5rSGZlU3BuNlkrNkE9PQ\x3d\x3d' }; &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;''' soup = BeautifulSoup(html) # get only text - without `var rechallengeState = {` and `};` text = soup.find('p').text.strip()[29:-3] # split to rows, clean row and split row to columns rows = [x.strip(',').split(':') for x in text.split('\n')] # clean and convert to dictionary data = {a.strip():b.strip(" '") for a,b in rows} print(data['challenge']) </code></pre> <p>result</p> <pre><code>03AHJ_Vuv8ZHJfsjnR3ueIvm89Jfa6oUJ3-kuzA-VcQIaR30A9CZva7lMaBrYlvcGG4cOPCeKXfERQe_u-cMw_8ZVi6CipeJVAYAsrOeBHryWRCMIaMt4V-TQlTgyUA4ndejEgBGUCUw7rwM-ltDr-do8ry-MRv26qQTpS-iCtvONYc6xZBURPEaTo2Nkfq8HJeFA_g6mMLUBG </code></pre>
-1
2016-10-05T21:56:14Z
[ "python", "html", "python-3.x", "web-scraping" ]
Creating an upside down asterisk triangle in Python using for loop
39,883,386
<p>I hate that I have to ask this, but I can't for the life of me figure out how to make this work. The program is supposed to ask for an input of an odd integer and then create an upside down pyramid with the first row containing the amount of asterisks as the number, and the last row having only one, centered asterisk. I've managed to figure out most of it, but my asterisks refuse to line up centered no matter what I try. I've looked at the other topics similar here, and tried to use them but still cannot figure it out. I'm not sure why 'i' is being used, but saw it on another post and it looked marginally better than what I had before.</p> <p>Here is my code, I have tinkered with it quite a bit to no avail. </p> <pre><code>x=input('Enter an odd number width: ') x_int = int(x) print('Triangle:') for i in range(x_int+1, 0, -1) : numwhite = (x_int - i)/2 white_int= int(numwhite) print(' '* white_int + '*'*i) </code></pre> <p>Which outputs (input 13):</p> <pre><code>Triangle: ************** ************* ************ *********** ********** ********* ******** ******* ****** ***** **** *** ** * </code></pre> <p>I want it to look something like (input 7)</p> <pre><code>******* ***** *** * </code></pre>
2
2016-10-05T20:48:52Z
39,883,497
<p>I don't think you can center them due to not being able to place characters between half-spaces. Maybe try inserting a space between all stars so you can center them better and produce something like this.</p> <pre><code>* * * * * * * * * * </code></pre> <p>Instead of:</p> <pre><code>**** *** ** * </code></pre>
0
2016-10-05T20:55:27Z
[ "python", "python-3.x", "for-loop" ]
Creating an upside down asterisk triangle in Python using for loop
39,883,386
<p>I hate that I have to ask this, but I can't for the life of me figure out how to make this work. The program is supposed to ask for an input of an odd integer and then create an upside down pyramid with the first row containing the amount of asterisks as the number, and the last row having only one, centered asterisk. I've managed to figure out most of it, but my asterisks refuse to line up centered no matter what I try. I've looked at the other topics similar here, and tried to use them but still cannot figure it out. I'm not sure why 'i' is being used, but saw it on another post and it looked marginally better than what I had before.</p> <p>Here is my code, I have tinkered with it quite a bit to no avail. </p> <pre><code>x=input('Enter an odd number width: ') x_int = int(x) print('Triangle:') for i in range(x_int+1, 0, -1) : numwhite = (x_int - i)/2 white_int= int(numwhite) print(' '* white_int + '*'*i) </code></pre> <p>Which outputs (input 13):</p> <pre><code>Triangle: ************** ************* ************ *********** ********** ********* ******** ******* ****** ***** **** *** ** * </code></pre> <p>I want it to look something like (input 7)</p> <pre><code>******* ***** *** * </code></pre>
2
2016-10-05T20:48:52Z
39,883,562
<p>You need to set the 'step' of the <code>range</code> to <code>-2</code>, so that it only grabs odds ints in reverse. Then the number of white spaces needed to have a <code>+ 1</code> to work properly. </p> <pre><code>x=input('Enter an odd number width: ') x_int = int(x) print('Triangle:') for i in range(x_int, 0, -2): numwhite = ((x_int - i)/2) + 1 white_int= int(numwhite) print(' ' * white_int + '*'*i) </code></pre> <p>Ouput:</p> <pre><code>Enter an odd number width: 7 Triangle: ******* ***** *** * </code></pre> <p><strong>More readable code with explanations</strong></p> <pre><code>x_int = int(input('Enter an odd number width: ')) # reducing print('Triangle:') for i in range(x_int, 0, -2): # -2 means only do every 2nd number in reverse num_white = int(((x_int - i)/2) + 1) # Checking the math here, needed a +1 print(' ' * num_white + '*' * i) # Could be changed to .format but works </code></pre> <p>Output</p> <pre><code>Enter an odd number width: 13 Triangle: ************* *********** ********* ******* ***** *** * </code></pre>
1
2016-10-05T20:59:29Z
[ "python", "python-3.x", "for-loop" ]
Creating an upside down asterisk triangle in Python using for loop
39,883,386
<p>I hate that I have to ask this, but I can't for the life of me figure out how to make this work. The program is supposed to ask for an input of an odd integer and then create an upside down pyramid with the first row containing the amount of asterisks as the number, and the last row having only one, centered asterisk. I've managed to figure out most of it, but my asterisks refuse to line up centered no matter what I try. I've looked at the other topics similar here, and tried to use them but still cannot figure it out. I'm not sure why 'i' is being used, but saw it on another post and it looked marginally better than what I had before.</p> <p>Here is my code, I have tinkered with it quite a bit to no avail. </p> <pre><code>x=input('Enter an odd number width: ') x_int = int(x) print('Triangle:') for i in range(x_int+1, 0, -1) : numwhite = (x_int - i)/2 white_int= int(numwhite) print(' '* white_int + '*'*i) </code></pre> <p>Which outputs (input 13):</p> <pre><code>Triangle: ************** ************* ************ *********** ********** ********* ******** ******* ****** ***** **** *** ** * </code></pre> <p>I want it to look something like (input 7)</p> <pre><code>******* ***** *** * </code></pre>
2
2016-10-05T20:48:52Z
39,883,601
<p>Apart from setting your step value to <code>-2</code>, you'll have a more readable code if you use Python's string <code>format</code> method. You can easily center your asterisks by using <em>center alignment</em> viz. <code>^</code>: </p> <pre><code>x = input('Enter an odd number width: ') x_int = int(x) print('Triangle:') fmt = '{' + ':^{}'.format(x_int) + '}' # Notice the caret ^ and how the width is set for i in range(x_int, 0, -2): stars = '*'*i print(fmt.format(stars)) </code></pre> <p>Trial:</p> <pre><code>Enter an odd number width: 15 Triangle: *************** ************* *********** ********* ******* ***** *** * </code></pre> <p>You can do more with <em>string formatting</em>. Have a look at the reference: <a href="https://pyformat.info" rel="nofollow">https://pyformat.info</a></p>
2
2016-10-05T21:01:45Z
[ "python", "python-3.x", "for-loop" ]
Creating an upside down asterisk triangle in Python using for loop
39,883,386
<p>I hate that I have to ask this, but I can't for the life of me figure out how to make this work. The program is supposed to ask for an input of an odd integer and then create an upside down pyramid with the first row containing the amount of asterisks as the number, and the last row having only one, centered asterisk. I've managed to figure out most of it, but my asterisks refuse to line up centered no matter what I try. I've looked at the other topics similar here, and tried to use them but still cannot figure it out. I'm not sure why 'i' is being used, but saw it on another post and it looked marginally better than what I had before.</p> <p>Here is my code, I have tinkered with it quite a bit to no avail. </p> <pre><code>x=input('Enter an odd number width: ') x_int = int(x) print('Triangle:') for i in range(x_int+1, 0, -1) : numwhite = (x_int - i)/2 white_int= int(numwhite) print(' '* white_int + '*'*i) </code></pre> <p>Which outputs (input 13):</p> <pre><code>Triangle: ************** ************* ************ *********** ********** ********* ******** ******* ****** ***** **** *** ** * </code></pre> <p>I want it to look something like (input 7)</p> <pre><code>******* ***** *** * </code></pre>
2
2016-10-05T20:48:52Z
39,883,673
<p>Try something like:</p> <pre><code>x = int(input('Enter an odd number width: ')) print('Triangle:') for i in range(x_int, 0, -1): print('{:^{str_len}}'.format('* ' * i, str_len= x_int * 2)) </code></pre> <p>That should work not only for odd numbers.</p>
2
2016-10-05T21:06:32Z
[ "python", "python-3.x", "for-loop" ]
Limit Python Threads : Resource Temporarily Unavailable
39,883,387
<p>I use python threading.Thread to spawn threads that execute a small utility for every filename found in os.walk() and get its output. I tried limiting number of threads using:</p> <pre><code>ThreadLimiter = threading.BoundedSemaphore(3) </code></pre> <p>and </p> <pre><code>ThreadLimiter.acquire() </code></pre> <p>in start of run method and </p> <pre><code>ThreadLimiter.release() </code></pre> <p>at end of run method</p> <p>But I still get the below error message when I run the python program. Any suggestions on improving this ?</p> <pre><code>bash: fork: retry: Resource temporarily unavailable bash: fork: retry: Resource temporarily unavailable </code></pre>
0
2016-10-05T20:48:58Z
39,883,674
<p>When <code>run</code> executes, the Thread has <em>already</em> started. Using a limit inside of <code>run</code> will not limit the number of <em>running</em> threads but of <em>finishing</em> threads - making the problem worse!</p> <p>Either:</p> <ul> <li>Modify <code>start</code> to delay launching the threads.</li> <li>In your <code>os.walk</code> loop, keep a list of active threads and block using <code>thread.join</code> when there are too many.</li> <li>Use a thread pool, e.g. <code>multiprocessing.pool.ThreadPool</code>.</li> </ul>
0
2016-10-05T21:06:33Z
[ "python", "multithreading" ]
Limit Python Threads : Resource Temporarily Unavailable
39,883,387
<p>I use python threading.Thread to spawn threads that execute a small utility for every filename found in os.walk() and get its output. I tried limiting number of threads using:</p> <pre><code>ThreadLimiter = threading.BoundedSemaphore(3) </code></pre> <p>and </p> <pre><code>ThreadLimiter.acquire() </code></pre> <p>in start of run method and </p> <pre><code>ThreadLimiter.release() </code></pre> <p>at end of run method</p> <p>But I still get the below error message when I run the python program. Any suggestions on improving this ?</p> <pre><code>bash: fork: retry: Resource temporarily unavailable bash: fork: retry: Resource temporarily unavailable </code></pre>
0
2016-10-05T20:48:58Z
39,883,760
<p>Use a thread pool and save yourself a lot of work! Here I md5sum files:</p> <pre><code>import os import multiprocessing.pool import subprocess as subp def walker(path): """Walk the file system returning file names""" for dirpath, dirs, files in os.walk(path): for fn in files: yield os.path.join(dirpath, fn) def worker(filename): """get md5 sum of file""" p = subp.Popen(['md5sum', filename], stdin=subp.PIPE, stdout=subp.PIPE, stderr=subp.PIPE) out, err = p.communicate() return filename, p.returncode, out, err pool = multiprocessing.pool.ThreadPool(3) for filename, returncode, out, err in pool.imap(worker, walker('.'), chunksize=1): print(filename, out.strip()) </code></pre>
1
2016-10-05T21:13:22Z
[ "python", "multithreading" ]
Is there array_count_values() analogue for Python 3.x or best way to do this?
39,883,472
<p>Is there array_count_values() analogue or fastest way to do this in Python 3.x</p> <p>from</p> <pre><code>d = ["1", "this", "1", "is", "Sparta", "Sparta"] </code></pre> <p>to</p> <pre><code>{ '1': 2, 'this': 1, 'is': 1, 'Sparta': 2 } </code></pre>
0
2016-10-05T20:54:01Z
39,883,540
<p>You can count the occurrence of each element in a list using <code>Counter</code>:</p> <pre><code>from collections import Counter l = [1, "this", 1, "is", "Sparta", "Sparta"] print(Counter(l)) </code></pre> <p>This prints</p> <pre><code>Counter({1: 2, 'Sparta': 2, 'this': 1, 'is': 1}) </code></pre> <p><a href="https://repl.it/DpTq" rel="nofollow">repl.it link</a></p>
2
2016-10-05T20:58:28Z
[ "python" ]
How do I make matplotlib generate a single plot instead of a plot for each data point?
39,883,478
<p>I am trying to generate three plots, each using the same inputs. When I run my code I generate a plot for each x input instead of three plots consisting of all of their data points.</p> <p>See my code below:</p> <pre><code>xlist = np.linspace(0, 2.5) for name, f, df in zip(func_names, funcs, diff_funcs): for x in xlist: plt.plot(diff(f, x, h=0.01), 'bs', forwdiff(f, x, h=0.01), 'g^') plt.title(name) plt.xlabel('x') plt.ylabel('f(x)') bluesq = plt.Line2D([], [], color='blue', marker='s', markersize=15, label='Centered Difference') greentr = plt.Line2D([], [], color='green', marker='^', markersize=15, label='Forward Difference') l1 = plt.legend(handles = [bluesq], loc=1) l2 = plt.legend(handles = [greentr], loc=4) plt.gca().add_artist(l1) plt.gca().add_artist(l2) plt.show() </code></pre> <p>Full code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt print("---Forward Diff---") def forwdiff(f, x, h=1e-5): """ Returns the forward derivative of a function f """ return 1 / (h) * (f(x + h) - f(x)) from math import exp, cos, sin, pi, log f1 = lambda x: exp(-2 * x ** 2) df1 = lambda x: -4 * x * exp(-2 * x ** 2) f2 = lambda x: cos(x) df2 = lambda x: -sin(x) f3 = lambda x: sin(x) df3 = lambda x: cos(x) funcs = [f1, f2, f3] diff_funcs = [df1, df2, df3] func_names = ['exp(-2x^2)', 'cos(x)', 'sin(x)'] values = [2, 0.6, 0.6] print '%10s %8s %8s %8s' % ('function', 'exact', 'approx', 'error') for name, f, df, x in zip(func_names, funcs, diff_funcs, values): exact = df(x) approx = forwdiff(f, x, h=0.01) error = abs(exact - approx) print '%10s %.6f %.6f %.6f' % (name, exact, approx, error) def test_forwdiff(): success = 6 - forwdiff(lambda x: x**2, 3, h=0.01) &lt; 0.00000000001 msg = "test_forwdiff failed" assert success, msg print("---Centered Diff---") def diff(f, x, h=1e-5): """ Returns the derivative of a function f """ return 1 / (2 * h) * (f(x + h) - f(x - h)) from math import exp, cos, sin, pi, log f1 = lambda x: exp(-2 * x ** 2) df1 = lambda x: -4 * x * exp(-2 * x ** 2) f2 = lambda x: cos(x) df2 = lambda x: -sin(x) f3 = lambda x: sin(x) df3 = lambda x: cos(x) funcs = [f1, f2, f3] diff_funcs = [df1, df2, df3] func_names = ['exp(-2x^2)', 'cos(x)', 'sin(x)'] values = [2, 0.6, 0.6] print '%10s %8s %8s %8s' % ('function', 'exact', 'approx', 'error') for name, f, df, x in zip(func_names, funcs, diff_funcs, values): exact = df(x) approx = diff(f, x, h=0.01) error = abs(exact - approx) print '%10s %.6f %.6f %.6f' % (name, exact, approx, error) def test_diff(): success = 6 - diff(lambda x: x**2, 3, h=0.01) &lt; 0.00000000001 msg = "test_diff failed" assert success, msg xlist = np.linspace(0, 2.5) for name, f, df in zip(func_names, funcs, diff_funcs): for x in xlist: plt.plot(diff(f, x, h=0.01), 'bs', forwdiff(f, x, h=0.01), 'g^') plt.title(name) plt.xlabel('x') plt.ylabel('f(x)') bluesq = plt.Line2D([], [], color='blue', marker='s', markersize=15, label='Centered Difference') greentr = plt.Line2D([], [], color='green', marker='^', markersize=15, label='Forward Difference') l1 = plt.legend(handles = [bluesq], loc=1) l2 = plt.legend(handles = [greentr], loc=4) plt.gca().add_artist(l1) plt.gca().add_artist(l2) plt.show() </code></pre> <p>So, I found out that plot() needs to have the entire x_list and y_list as arguments.</p> <p>which got me to this:</p> <pre><code> xlist = np.linspace(0, 2.5) for name, f in zip(func_names, funcs): ylist = [forwdiff(f, x, h=0.01) for x in xlist] plt.plot(xlist, ylist, 'g^') ylist = [diff(f, x, h=0.01) for x in xlist] plt.plot(xlist, ylist, 'bs') plt.title(name) plt.xlabel('x') plt.ylabel('f(x)') bluesq = plt.Line2D([], [], color='blue', marker='s', markersize=15, label='Centered Difference') greentr = plt.Line2D([], [], color='green', marker='^', markersize=15, label='Forward Difference') l1 = plt.legend(handles = [bluesq], loc=1) l2 = plt.legend(handles = [greentr], loc=4) plt.gca().add_artist(l1) plt.gca().add_artist(l2) plt.show() </code></pre> <p>This correctly plots all of the inputs onto one plot, but I was attempting to generate three plots. One for each f input. The code given calls f and df and generates a single plot for each, but plots them to the same window. How would I separate that plot into three different windows showing forwdiff and diff for each f?</p> <p>Sorry if this is a stupid question, my background is not in computer science/programming.</p> <p>I want to separate the plots into three plots of forwdiff and diff for each of exp(-2x2), cos(x), and sin(x).</p>
1
2016-10-05T20:54:36Z
39,884,738
<p>So, I found out that plot() needs to have the entire x_list and y_list as arguments.</p> <p>which got me to this:</p> <pre><code> xlist = np.linspace(0, 2.5) for name, f in zip(func_names, funcs): ylist = [forwdiff(f, x, h=0.01) for x in xlist] plt.plot(xlist, ylist, 'g^') ylist = [diff(f, x, h=0.01) for x in xlist] plt.plot(xlist, ylist, 'bs') plt.title(name) plt.xlabel('x') plt.ylabel('f(x)') bluesq = plt.Line2D([], [], color='blue', marker='s', markersize=15, label='Centered Difference') greentr = plt.Line2D([], [], color='green', marker='^', markersize=15, label='Forward Difference') l1 = plt.legend(handles = [bluesq], loc=1) l2 = plt.legend(handles = [greentr], loc=4) plt.gca().add_artist(l1) plt.gca().add_artist(l2) plt.show() </code></pre> <p>This correctly plots all of the inputs onto one plot, but I was attempting to generate three plots. One for each f input. The code given calls f and df and generates a single plot for each, but plots them to the same window. How would I separate that plot into three different windows showing forwdiff and diff for each f?</p> <p>Sorry if this is a stupid question, my background is not in computer science/programming.</p> <p>I want to separate the plots into three plots of forwdiff and diff for each of exp(-2x2), cos(x), and sin(x).</p>
0
2016-10-05T22:34:06Z
[ "python", "matplotlib", "plot" ]
How do I make matplotlib generate a single plot instead of a plot for each data point?
39,883,478
<p>I am trying to generate three plots, each using the same inputs. When I run my code I generate a plot for each x input instead of three plots consisting of all of their data points.</p> <p>See my code below:</p> <pre><code>xlist = np.linspace(0, 2.5) for name, f, df in zip(func_names, funcs, diff_funcs): for x in xlist: plt.plot(diff(f, x, h=0.01), 'bs', forwdiff(f, x, h=0.01), 'g^') plt.title(name) plt.xlabel('x') plt.ylabel('f(x)') bluesq = plt.Line2D([], [], color='blue', marker='s', markersize=15, label='Centered Difference') greentr = plt.Line2D([], [], color='green', marker='^', markersize=15, label='Forward Difference') l1 = plt.legend(handles = [bluesq], loc=1) l2 = plt.legend(handles = [greentr], loc=4) plt.gca().add_artist(l1) plt.gca().add_artist(l2) plt.show() </code></pre> <p>Full code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt print("---Forward Diff---") def forwdiff(f, x, h=1e-5): """ Returns the forward derivative of a function f """ return 1 / (h) * (f(x + h) - f(x)) from math import exp, cos, sin, pi, log f1 = lambda x: exp(-2 * x ** 2) df1 = lambda x: -4 * x * exp(-2 * x ** 2) f2 = lambda x: cos(x) df2 = lambda x: -sin(x) f3 = lambda x: sin(x) df3 = lambda x: cos(x) funcs = [f1, f2, f3] diff_funcs = [df1, df2, df3] func_names = ['exp(-2x^2)', 'cos(x)', 'sin(x)'] values = [2, 0.6, 0.6] print '%10s %8s %8s %8s' % ('function', 'exact', 'approx', 'error') for name, f, df, x in zip(func_names, funcs, diff_funcs, values): exact = df(x) approx = forwdiff(f, x, h=0.01) error = abs(exact - approx) print '%10s %.6f %.6f %.6f' % (name, exact, approx, error) def test_forwdiff(): success = 6 - forwdiff(lambda x: x**2, 3, h=0.01) &lt; 0.00000000001 msg = "test_forwdiff failed" assert success, msg print("---Centered Diff---") def diff(f, x, h=1e-5): """ Returns the derivative of a function f """ return 1 / (2 * h) * (f(x + h) - f(x - h)) from math import exp, cos, sin, pi, log f1 = lambda x: exp(-2 * x ** 2) df1 = lambda x: -4 * x * exp(-2 * x ** 2) f2 = lambda x: cos(x) df2 = lambda x: -sin(x) f3 = lambda x: sin(x) df3 = lambda x: cos(x) funcs = [f1, f2, f3] diff_funcs = [df1, df2, df3] func_names = ['exp(-2x^2)', 'cos(x)', 'sin(x)'] values = [2, 0.6, 0.6] print '%10s %8s %8s %8s' % ('function', 'exact', 'approx', 'error') for name, f, df, x in zip(func_names, funcs, diff_funcs, values): exact = df(x) approx = diff(f, x, h=0.01) error = abs(exact - approx) print '%10s %.6f %.6f %.6f' % (name, exact, approx, error) def test_diff(): success = 6 - diff(lambda x: x**2, 3, h=0.01) &lt; 0.00000000001 msg = "test_diff failed" assert success, msg xlist = np.linspace(0, 2.5) for name, f, df in zip(func_names, funcs, diff_funcs): for x in xlist: plt.plot(diff(f, x, h=0.01), 'bs', forwdiff(f, x, h=0.01), 'g^') plt.title(name) plt.xlabel('x') plt.ylabel('f(x)') bluesq = plt.Line2D([], [], color='blue', marker='s', markersize=15, label='Centered Difference') greentr = plt.Line2D([], [], color='green', marker='^', markersize=15, label='Forward Difference') l1 = plt.legend(handles = [bluesq], loc=1) l2 = plt.legend(handles = [greentr], loc=4) plt.gca().add_artist(l1) plt.gca().add_artist(l2) plt.show() </code></pre> <p>So, I found out that plot() needs to have the entire x_list and y_list as arguments.</p> <p>which got me to this:</p> <pre><code> xlist = np.linspace(0, 2.5) for name, f in zip(func_names, funcs): ylist = [forwdiff(f, x, h=0.01) for x in xlist] plt.plot(xlist, ylist, 'g^') ylist = [diff(f, x, h=0.01) for x in xlist] plt.plot(xlist, ylist, 'bs') plt.title(name) plt.xlabel('x') plt.ylabel('f(x)') bluesq = plt.Line2D([], [], color='blue', marker='s', markersize=15, label='Centered Difference') greentr = plt.Line2D([], [], color='green', marker='^', markersize=15, label='Forward Difference') l1 = plt.legend(handles = [bluesq], loc=1) l2 = plt.legend(handles = [greentr], loc=4) plt.gca().add_artist(l1) plt.gca().add_artist(l2) plt.show() </code></pre> <p>This correctly plots all of the inputs onto one plot, but I was attempting to generate three plots. One for each f input. The code given calls f and df and generates a single plot for each, but plots them to the same window. How would I separate that plot into three different windows showing forwdiff and diff for each f?</p> <p>Sorry if this is a stupid question, my background is not in computer science/programming.</p> <p>I want to separate the plots into three plots of forwdiff and diff for each of exp(-2x2), cos(x), and sin(x).</p>
1
2016-10-05T20:54:36Z
39,885,579
<p>Going off your answer, you are looking for something like this:</p> <pre><code># axarr is an array of axes objects (1 row, 3 columns) fig, axarr = plt.subplots(1, 3) for ax, name, f in zip(ax, func_names, funcs): for df, dfname in zip((forwdiff, diff), ('forward', 'central')): ylist = [df(f, x, h=0.01) for x in xlist] ax.plot(xlist, ylist, 'g^', label=dfname) ax.set_title(name) # either set the axes labels here so all axes get them #ax.set_xlabel('x') #ax.set_ylabel('f(x)') # similarly, you can add a legend to each plot here #ax.legend(loc='upper right') # or set axes labels here: # all plots get x labels [ax.set_xlabel('x') for ax in axarr] # only the left most plot gets a ylabel axarr[0].set_ylabel('f(x)') # set only one legend and make it outside the rightmost plot axarr[-1].legend(loc='upper left', bbox_to_anchor=(1.02, 1)) # move subplots over so you can see the legend fig.subplots_adjust(right=0.8) plt.show() </code></pre> <p>You may want to look into <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html" rel="nofollow"><code>numpy.gradient</code></a> which can compute the derivatives in a vectorized way. That way you could do something like:</p> <pre><code>xlist = np.linspace(0, 2.5) dx = np.gradient(xlist) dydx = np.gradient(f(xlist), dx) </code></pre>
0
2016-10-06T00:14:43Z
[ "python", "matplotlib", "plot" ]
How to pick one number of an Integer
39,883,517
<p>How can I pick one of the digits from an Integer like: 97723 and choose (for example) the number 2 from that number and check if its an odd or an even number?</p> <p>Also, can I print only the odd numbers from an Integer directly? (Is there any default function for that already?)</p> <p>Thanks in advance</p>
0
2016-10-05T20:56:37Z
39,883,577
<p>2 is the 4th digit.</p> <p>You can get the digits of a number using this construct.</p> <pre><code>digits = [int(_) for _ in str(97723)] </code></pre> <p>This expression will be <code>true</code> if the 4th digit is even.</p> <pre><code>digits[3] % 2 == 0 </code></pre>
2
2016-10-05T21:00:21Z
[ "python", "python-3.x" ]
How to pick one number of an Integer
39,883,517
<p>How can I pick one of the digits from an Integer like: 97723 and choose (for example) the number 2 from that number and check if its an odd or an even number?</p> <p>Also, can I print only the odd numbers from an Integer directly? (Is there any default function for that already?)</p> <p>Thanks in advance</p>
0
2016-10-05T20:56:37Z
39,883,751
<pre><code>even = lambda integer: int("".join([num for num in str(integer) if int(num) % 2 == 0])) </code></pre> <p>or</p> <pre><code>def even(integer): result = "" integer = str(integer) for num in integer: if int(num) % 2 == 0: result += num result = int(result) return(result) </code></pre>
0
2016-10-05T21:12:39Z
[ "python", "python-3.x" ]
How to pick one number of an Integer
39,883,517
<p>How can I pick one of the digits from an Integer like: 97723 and choose (for example) the number 2 from that number and check if its an odd or an even number?</p> <p>Also, can I print only the odd numbers from an Integer directly? (Is there any default function for that already?)</p> <p>Thanks in advance</p>
0
2016-10-05T20:56:37Z
39,883,830
<p>If you want to "parse" a number the easiest way to do this is to convert it to string. You can convert an int to string like this <code>s = string(500)</code>. Then use string index to get character that you want. For example if you want first character (number) then use this <code>string_name[0]</code>, for second character (number) use <code>string_name[1]</code> . To get length of your string (number) use <code>len(string)</code>. And to check if number is odd or even mod it with 2.</p> <pre><code># Converting int to string int_to_sting = str(97723) # Getting number of characters in your string (in this case number) n_of_numbers = len(int_to_sting) # Example usage of string index print("First number in your number is: ",int_to_sting[0]) print("Second number in your number is: ",int_to_sting[1]) # We need to check for every number, and since the first number is int_to_sting[0] and len(int_to_sting) returns actual length of string we need to reduce it by 1 for i in range(n_of_numbers-1): if int_to_sting[i]%2==0: print(int_to_sting[i]," is even") else: print(int_to_sting[i]," is odd") </code></pre>
0
2016-10-05T21:17:40Z
[ "python", "python-3.x" ]
How to pick one number of an Integer
39,883,517
<p>How can I pick one of the digits from an Integer like: 97723 and choose (for example) the number 2 from that number and check if its an odd or an even number?</p> <p>Also, can I print only the odd numbers from an Integer directly? (Is there any default function for that already?)</p> <p>Thanks in advance</p>
0
2016-10-05T20:56:37Z
39,883,860
<pre><code># choose a digit (by index) integer = 97723 digit_3 = str(integer)[3] print(digit_3) # check if even: if int(digit_3) % 2 == 0: print(digit_3, "is even") # get all odd numbers directly odd_digits = [digit for digit in str(integer) if int(digit) % 2 == 1] print(odd_digits) </code></pre>
0
2016-10-05T21:19:40Z
[ "python", "python-3.x" ]
Hovertool callback source selection for multi-plot graph
39,883,625
<p>I currently use bokeh version 0.12.2. I am plotting a graph with two series of circles.</p> <pre><code>graph1 = figure(plot_width=800, plot_height=800) graph1.circle('fpr1', 'tpr1', color='red', source=source) graph1.circle('fpr2', 'tpr2', color='blue', source=source) </code></pre> <p>Now, I would like to add a HoverTool which is done with :</p> <pre><code>code = "source.set('selected', cb_data['index']);" callback = CustomJS(args={'source': source}, code=code) hover1 = HoverTool( tooltips=[ .... ], callback=callback, ) graph1.add_tools(hover1) </code></pre> <p>The behavior of this code is that when I put mouse cursor hover a red circle, the callback is called and the tooltip is displayed. However, when I hover a blue circle, the tooltip is displayed but the callback is not called. How to fix that ?</p>
0
2016-10-05T21:02:58Z
39,884,251
<p>I'm afraid this is a <a href="https://github.com/bokeh/bokeh/issues/2136" rel="nofollow">known bug</a>. There is a <a href="https://github.com/bokeh/bokeh/pull/5158" rel="nofollow">"WIP" PR to fix it</a> but it will not go in this weeks <code>0.12.3</code> release. It should be in <code>0.12.4</code>, though. </p>
1
2016-10-05T21:48:18Z
[ "javascript", "python", "bokeh" ]
Combining dataframes in pandas with the same rows and columns, but different cell values
39,883,656
<p>I'm interested in combining two dataframes in pandas that have the same row indices and column names, but different cell values. See the example below:</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame({'A':[22,2,np.NaN,np.NaN], 'B':[23,4,np.NaN,np.NaN], 'C':[24,6,np.NaN,np.NaN], 'D':[25,8,np.NaN,np.NaN]}) df2 = pd.DataFrame({'A':[np.NaN,np.NaN,56,100], 'B':[np.NaN,np.NaN,58,101], 'C':[np.NaN,np.NaN,59,102], 'D':[np.NaN,np.NaN,60,103]}) In[6]: print(df1) A B C D 0 22.0 23.0 24.0 25.0 1 2.0 4.0 6.0 8.0 2 NaN NaN NaN NaN 3 NaN NaN NaN NaN In[7]: print(df2) A B C D 0 NaN NaN NaN NaN 1 NaN NaN NaN NaN 2 56.0 58.0 59.0 60.0 3 100.0 101.0 102.0 103.0 </code></pre> <p>I would like the resulting frame to look like this:</p> <pre><code> A B C D 0 22.0 23.0 24.0 25.0 1 2.0 4.0 6.0 8.0 2 56.0 58.0 59.0 60.0 3 100.0 101.0 102.0 103.0 </code></pre> <p>I have tried different ways of pd.concat and pd.merge but some of the data always gets replaced with NaNs. Any pointers in the right direction would be greatly appreciated.</p>
3
2016-10-05T21:04:53Z
39,883,694
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow"><code>combine_first</code></a>:</p> <pre><code>print (df1.combine_first(df2)) A B C D 0 22.0 23.0 24.0 25.0 1 2.0 4.0 6.0 8.0 2 56.0 58.0 59.0 60.0 3 100.0 101.0 102.0 103.0 </code></pre> <p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a>:</p> <pre><code>print (df1.fillna(df2)) A B C D 0 22.0 23.0 24.0 25.0 1 2.0 4.0 6.0 8.0 2 56.0 58.0 59.0 60.0 3 100.0 101.0 102.0 103.0 </code></pre> <p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.update.html" rel="nofollow"><code>update</code></a>:</p> <pre><code>df1.update(df2) print (df1) A B C D 0 22.0 23.0 24.0 25.0 1 2.0 4.0 6.0 8.0 2 56.0 58.0 59.0 60.0 3 100.0 101.0 102.0 103.0 </code></pre>
1
2016-10-05T21:07:49Z
[ "python", "pandas", "dataframe", "merge", "concat" ]
Combining dataframes in pandas with the same rows and columns, but different cell values
39,883,656
<p>I'm interested in combining two dataframes in pandas that have the same row indices and column names, but different cell values. See the example below:</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame({'A':[22,2,np.NaN,np.NaN], 'B':[23,4,np.NaN,np.NaN], 'C':[24,6,np.NaN,np.NaN], 'D':[25,8,np.NaN,np.NaN]}) df2 = pd.DataFrame({'A':[np.NaN,np.NaN,56,100], 'B':[np.NaN,np.NaN,58,101], 'C':[np.NaN,np.NaN,59,102], 'D':[np.NaN,np.NaN,60,103]}) In[6]: print(df1) A B C D 0 22.0 23.0 24.0 25.0 1 2.0 4.0 6.0 8.0 2 NaN NaN NaN NaN 3 NaN NaN NaN NaN In[7]: print(df2) A B C D 0 NaN NaN NaN NaN 1 NaN NaN NaN NaN 2 56.0 58.0 59.0 60.0 3 100.0 101.0 102.0 103.0 </code></pre> <p>I would like the resulting frame to look like this:</p> <pre><code> A B C D 0 22.0 23.0 24.0 25.0 1 2.0 4.0 6.0 8.0 2 56.0 58.0 59.0 60.0 3 100.0 101.0 102.0 103.0 </code></pre> <p>I have tried different ways of pd.concat and pd.merge but some of the data always gets replaced with NaNs. Any pointers in the right direction would be greatly appreciated.</p>
3
2016-10-05T21:04:53Z
39,883,697
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow">combine_first</a></p> <pre><code>df1.combine_first(df2) </code></pre>
1
2016-10-05T21:07:57Z
[ "python", "pandas", "dataframe", "merge", "concat" ]
Selenium, Python, Can't Click Button by Checking the Table Items Name
39,883,704
<p>I am trying to improve my <code>Selenium</code> skills and for this task, I try to click a button the way that chooses it by table elements name.</p> <p>For example, in this case, I want to locate <code>EB Trial 2</code> then click the <code>import</code> button which is related to that.</p> <pre><code>&lt;tr ng-repeat="event in bcEvents" class="ng-scope"&gt; &lt;td&gt; &lt;div class="dib fxac"&gt; &lt;i class="icon-event fs32 text-light-blue mr15"&gt;&lt;/i&gt; &lt;div class="event-inner"&gt; &lt;a href="" class="link link-underline db ng-binding"&gt;EB Trial2&lt;/a&gt; &lt;span class="db fs-small text-light-blue ng-binding"&gt;11/15/2016&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td ng-switch="bc_source"&gt; &lt;!-- ngSwitchWhen: 2 --&gt;&lt;div ng-switch-when="2" class="ng-scope"&gt; &lt;a href="" ng-click="import_bc_event(event)" class="btn btn-icon btn-orange"&gt; &lt;i class="icon icon-eventbrite-icon"&gt;&lt;/i&gt; Import &lt;/a&gt; &lt;/div&gt; &lt;!-- ngSwitchWhen: 8 --&gt; &lt;!-- ngSwitchWhen: A --&gt; &lt;!-- ngSwitchWhen: 9 --&gt; &lt;!-- ngSwitchWhen: B --&gt; &lt;/td&gt; &lt;!-- ngIf: bc_source != 2 --&gt; &lt;/tr&gt; </code></pre> <p>I try to reach it by <code>XPath</code> but it didn't work </p> <pre><code>driver.find_element_by_xpath("//td[contains(text(),'EB Trial2')]/preceding-sibling::td[1]").click() </code></pre> <p>I can't figured it out how to do it</p> <p>Can anybody help me about this ?</p>
1
2016-10-05T21:08:47Z
39,886,202
<blockquote> <p>I want to locate EB Trial 2 then click the import button which is related to that</p> </blockquote> <p>You should try using <code>xpath</code> as :</p> <pre><code>driver.find_element_by_xpath(".//td[descendant::a[text()='EB Trial2']]/following-sibling::td//a[normalize-space(.)='Import']").click() </code></pre>
0
2016-10-06T01:41:02Z
[ "python", "osx", "google-chrome", "selenium" ]
How to efficiently write a binary file containing mixed label and image data
39,883,715
<p>The <a href="https://github.com/tensorflow/tensorflow/tree/411f57e291839094108afdaa9c43094f44979eaa/tensorflow/models/image/cifar10" rel="nofollow">cifar10 tutorial</a> deals with binary files as input. Each record/example on these CIFAR10 datafiles contain mixed label (first element) and image data information. The first answer in <a href="http://stackoverflow.com/questions/34631852/attach-a-queue-to-a-numpy-array-in-tensorflow-for-data-fetch-instead-of-files">this page</a> shows how to write binary file from a numpy array (which accumulates the label and image data information in each row) using <strong>ndarray.tofile()</strong> as follows: </p> <pre><code>import numpy as np images_and_labels_array = np.array([[...], ...], dtype=np.uint8) images_and_labels_array.tofile("/tmp/images.bin") </code></pre> <p>This is perfect for me when the maximum number of classes is 256 as the uint8 datatype is sufficient. However, when the maximum number of classes is more than 256, then I have to change the dtype=np.uint16 in the images_and_labels_array. The consequence is just doubling the size. I would like to know if there is an efficient way to overcome it. If yes, please provide an example.</p>
0
2016-10-05T21:09:42Z
39,889,727
<p>When I write binary files I usually just use the python module <em>struct</em>, which works somehow like this:</p> <pre><code>import struct import numpy as np image = np.zeros([2, 300, 300], dtype=np.uint8) label = np.zeros([2, 1], dtype=np.uint16) with open('data.bin', 'w') as fo: s = image.shape for k in range(s[0]): # write label as uint16 fo.write(struct.pack('H', label[k, 0])) # write image as uint8 for i in range(s[1]): for j in range(s[2]): fo.write(struct.pack('B', image[k, i, j])) </code></pre> <p>This should result in a 300*300*2 + 2*1*2 = 180004 bytes big binary file. Its probably not the fastest way to get the job done, but for me it worked sufficiently fast so far. For other datatypes see the <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">documentation</a></p>
1
2016-10-06T07:12:42Z
[ "python", "io", "tensorflow" ]
web scraping with beautifulsoup
39,883,726
<p>I'm trying to parsing the website only particular part. Here is my code below. Is there anyway to do it more efficient.</p> <pre><code>from bs4 import BeautifulSoup import requests import urllib.request import json soup = BeautifulSoup(requests.get("http://www.example.com").content, "html.parser") for d in soup.select("script[type=text/javascript]"): print(d.text[2300:2600]) </code></pre> <p>Here is the output what i need</p> <pre><code>&gt; dataLayer = [{ &gt; 'page':'ProductPage', &gt; 'OAM':'False', &gt; 'storeNum':'075', &gt; 'brand':'Seagate', &gt; 'productPrice':'69.99', &gt; 'SKU':'106674', &gt; 'productID':'467336', &gt; 'mpn':'ST2000DM006', &gt; 'ean':'763649110218', &gt; 'category':'Internal Hard Drives', &gt; 'isMobile':'False' }]; </code></pre>
0
2016-10-05T21:10:45Z
39,884,013
<p>It can change on other page - (I didn't check it with other pages)</p> <pre><code>for d in soup.select("script[type=text/javascript]")[27].text.split('\n')[51:62]: print(d.strip()) </code></pre> <p>result </p> <pre><code>'page':'ProductPage', 'OAM':'False', 'storeNum':'029', 'brand':'Microsoft', 'productPrice':'129.99', 'SKU':'883785', 'productID':'456088', 'mpn':'QC7-00001', 'ean':'889842010060', 'category':'Tablet Accessories', 'isMobile':'False' </code></pre> <hr> <p><strong>EDIT:</strong> other version:</p> <pre><code>text = soup.select("head script[type=text/javascript]")[-1].text start = text.find('dataLayer = [{') + len('dataLayer = [{') end = text.rfind('}];') rows = text[start:end].strip().split('\n') for d in rows: print(d.strip()) </code></pre>
0
2016-10-05T21:30:20Z
[ "python", "parsing", "web-scraping" ]
Match two groups but none of them should be empty
39,883,786
<p>I want my regex to be able to match strings of random chars optionally followed by some digits - but if both matches are empty I want the match to fail. I am currently constructing the regex as in:</p> <pre><code>regex = u'^(.*)' if has_digits: regex += u'(\d*)' regex += ext + u'$' # extension group as in u'(\.exe)' rePattern = re.compile(regex, re.I | re.U) </code></pre> <p>but this also matches empty filenames (with extension only). Can't wrap my head around similar questions like:</p> <ul> <li><a href="http://stackoverflow.com/q/13351990/281545">In a regular expression, match one thing or another, or both</a></li> <li><a href="http://stackoverflow.com/q/6664015/281545">Matching a group that may or may not exist</a></li> </ul> <p>The extra complication is that the second group (the digits) may not be added</p> <p>So valid:</p> <pre><code>abc%.exe 123.exe </code></pre> <p>If has_digits is true:</p> <pre><code>abc 123.exe # I want the second group to contain the 123 not the first one </code></pre> <p>Invalid : <code>.exe</code></p>
0
2016-10-05T21:14:58Z
39,884,080
<p>Regex:</p> <pre><code>^(.*?)(\d+)?(?&lt;=.)\.exe$ </code></pre> <p>Positive lookbehind assures that there is at least one character before extension part.</p> <p><strong><a href="https://www.regex101.com/r/CNBQyG/1" rel="nofollow">Live demo</a></strong></p> <p>Integrated:</p> <pre><code>regex = '^(.*?)' if has_digits: regex += '(\d+)?' regex += '(?&lt;=.)' + ext + '$' rePattern = re.compile(regex, re.I | re.U) </code></pre>
2
2016-10-05T21:33:57Z
[ "python", "regex", "python-2.7", "regex-lookarounds" ]
Match two groups but none of them should be empty
39,883,786
<p>I want my regex to be able to match strings of random chars optionally followed by some digits - but if both matches are empty I want the match to fail. I am currently constructing the regex as in:</p> <pre><code>regex = u'^(.*)' if has_digits: regex += u'(\d*)' regex += ext + u'$' # extension group as in u'(\.exe)' rePattern = re.compile(regex, re.I | re.U) </code></pre> <p>but this also matches empty filenames (with extension only). Can't wrap my head around similar questions like:</p> <ul> <li><a href="http://stackoverflow.com/q/13351990/281545">In a regular expression, match one thing or another, or both</a></li> <li><a href="http://stackoverflow.com/q/6664015/281545">Matching a group that may or may not exist</a></li> </ul> <p>The extra complication is that the second group (the digits) may not be added</p> <p>So valid:</p> <pre><code>abc%.exe 123.exe </code></pre> <p>If has_digits is true:</p> <pre><code>abc 123.exe # I want the second group to contain the 123 not the first one </code></pre> <p>Invalid : <code>.exe</code></p>
0
2016-10-05T21:14:58Z
39,884,234
<p>You can use this lookahead based regex:</p> <pre><code>ext = r'\.exe' regex = r'^(?=.+\.)(.*?)' if has_digits: regex += r'(\d*)' regex += ext + '$' rePattern = re.compile(regex, re.I | re.U) # ^(?=.+\.)(.*?)(\d*)\.exe$ </code></pre> <p><a href="https://regex101.com/r/DXv0ep/1" rel="nofollow">RegEx Demo</a></p> <p>Lookahead <code>(?=.+\.)</code> ensures presence of at least one character before DOT.</p>
1
2016-10-05T21:46:43Z
[ "python", "regex", "python-2.7", "regex-lookarounds" ]
__str__ returned non-string (type tuple)
39,883,950
<p>I have a form that keeps throwing me an error in django, Ive tried searching online tried str() on my models but wouldnt work at all. Googled a couple of times tried a couple different methods but none worked still get the same django error page everytime i click the link to the form.</p> <pre><code>TypeError: __str__ returned non-string (type tuple) </code></pre> <p>my model</p> <pre><code># Injury Parameters -&gt; SOI Level 2 # #################################### class SourceOfInjuryLevel2(models.Model): creator = models.ForeignKey('auth.User') id = models.AutoField(primary_key=True) soi_l1 = models.CharField(max_length=80) soi_l2 = models.CharField(max_length=80) status = models.CharField(max_length=8) created_date = models.DateTimeField(default=timezone.now) modified_date = models.DateTimeField(blank=True, null=True) modified_by = models.CharField(max_length=60, blank=True, null=True) def create(self): self.save() def __str__(self): return self.soi_l1, self.soi_l2, self.status </code></pre> <p>my form</p> <pre><code># Soure of Injury Level 2 # ########################### class SourceOfInjuryLevel2Form(forms.ModelForm): options = (('Enabled', 'Enabled',), ('Disabled', 'Disabled')) soi_l1 = forms.ModelChoiceField( queryset=SourceOfInjuryLevel1.objects.filter(status='Enabled'), widget=forms.Select(attrs={'class': 'form-control'}) ) soi_l2 = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}) ) status = forms.CharField( widget=forms.Select( attrs={'class': 'form-control'}, choices=options ) ) class Meta: model = SourceOfInjuryLevel2 fields = ('soi_l1', 'soi_l2', 'status') </code></pre> <p>My Views</p> <pre><code># New Source of Injury Level 2 # ################################ def new_source_of_injury_level2(request): form = SourceOfInjuryLevel2Form() if request.method == "POST": form = SourceOfInjuryLevel2Form(request.POST) if form.is_valid(): source_of_injury_level2 = form.save(commit=False) source_of_injury_level2.creator = request.user source_of_injury_level2.created_date = timezone.now() source_of_injury_level2.save() messages.success(request, 'Object Has Been Created') return redirect(injury_parameters) else: messages.error(request, 'Object Has Not Been Created') else: form = SourceOfInjuryLevel2Form() return render(request, 'process_injury_management/source_of_injury_level2.html', {'form': form, 'title': 'New Source of Injury Level 2'}) </code></pre>
0
2016-10-05T21:26:04Z
39,884,000
<p>Those commas aren't actually doing what you think they do. The commas make your return value a <em>tuple</em> instead of a <em>string</em> which a <code>__str__</code> method is supposed to return.</p> <p>You can instead do:</p> <pre><code>def __str__(self): return '%s %s %s'%(self.soi_l1, self.soi_l2, self.status) </code></pre> <p>Or use the <em>new-style</em> formatting:</p> <pre><code>def __str__(self): return '{} {} {}'.format(self.soi_l1, self.soi_l2, self.status) </code></pre>
1
2016-10-05T21:29:24Z
[ "python", "django" ]
__str__ returned non-string (type tuple)
39,883,950
<p>I have a form that keeps throwing me an error in django, Ive tried searching online tried str() on my models but wouldnt work at all. Googled a couple of times tried a couple different methods but none worked still get the same django error page everytime i click the link to the form.</p> <pre><code>TypeError: __str__ returned non-string (type tuple) </code></pre> <p>my model</p> <pre><code># Injury Parameters -&gt; SOI Level 2 # #################################### class SourceOfInjuryLevel2(models.Model): creator = models.ForeignKey('auth.User') id = models.AutoField(primary_key=True) soi_l1 = models.CharField(max_length=80) soi_l2 = models.CharField(max_length=80) status = models.CharField(max_length=8) created_date = models.DateTimeField(default=timezone.now) modified_date = models.DateTimeField(blank=True, null=True) modified_by = models.CharField(max_length=60, blank=True, null=True) def create(self): self.save() def __str__(self): return self.soi_l1, self.soi_l2, self.status </code></pre> <p>my form</p> <pre><code># Soure of Injury Level 2 # ########################### class SourceOfInjuryLevel2Form(forms.ModelForm): options = (('Enabled', 'Enabled',), ('Disabled', 'Disabled')) soi_l1 = forms.ModelChoiceField( queryset=SourceOfInjuryLevel1.objects.filter(status='Enabled'), widget=forms.Select(attrs={'class': 'form-control'}) ) soi_l2 = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}) ) status = forms.CharField( widget=forms.Select( attrs={'class': 'form-control'}, choices=options ) ) class Meta: model = SourceOfInjuryLevel2 fields = ('soi_l1', 'soi_l2', 'status') </code></pre> <p>My Views</p> <pre><code># New Source of Injury Level 2 # ################################ def new_source_of_injury_level2(request): form = SourceOfInjuryLevel2Form() if request.method == "POST": form = SourceOfInjuryLevel2Form(request.POST) if form.is_valid(): source_of_injury_level2 = form.save(commit=False) source_of_injury_level2.creator = request.user source_of_injury_level2.created_date = timezone.now() source_of_injury_level2.save() messages.success(request, 'Object Has Been Created') return redirect(injury_parameters) else: messages.error(request, 'Object Has Not Been Created') else: form = SourceOfInjuryLevel2Form() return render(request, 'process_injury_management/source_of_injury_level2.html', {'form': form, 'title': 'New Source of Injury Level 2'}) </code></pre>
0
2016-10-05T21:26:04Z
39,884,003
<p>The error is in your model:</p> <pre><code>class SourceOfInjuryLevel2(models.Model): ... def __str__(self): return self.soi_l1, self.soi_l2, self.status </code></pre> <p>I guess you were confused because the Python 2 print statement looks like it turns tuples into strings, but that's not actually how the print statement works - it's a confusing detail that was changed in Python 3. </p> <p>Try this instead:</p> <pre><code>def __str__(self): template = '{0.soi_l1} {0.soi_l2} {0.status}' return template.format(self) </code></pre>
1
2016-10-05T21:29:26Z
[ "python", "django" ]
How can I append this elements to an array in python?
39,883,994
<pre><code>input_elements = ["a", "b", "c", "d"] my_array = ["1", "2", "3", "4"] </code></pre> <p>the output I want is:</p> <pre><code>["1", "2", "3", "4", "a"] ["1", "2", "3", "4", "b"] ["1", "2", "3", "4", "c"] ["1", "2", "3", "4", "d"] </code></pre> <p>I tried:</p> <pre><code>for e in input_elements: my_array.append(e) </code></pre> <p>I know the code right above is wrong, so I am wondering how I can generate the output like that.</p>
4
2016-10-05T21:29:01Z
39,884,043
<p>You can use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to solve your issue. </p> <pre><code>&gt;&gt;&gt; input_elements = ["a", "b", "c", "d"] &gt;&gt;&gt; my_array = ["1", "2", "3", "4"] &gt;&gt;&gt; [my_array+[i] for i in input_elements] </code></pre> <p>The result looks like</p> <pre><code>&gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; pprint([my_array+[i] for i in input_elements]) [['1', '2', '3', '4', 'a'], ['1', '2', '3', '4', 'b'], ['1', '2', '3', '4', 'c'], ['1', '2', '3', '4', 'd']] </code></pre> <p>See <a href="http://stackoverflow.com/questions/34835951/what-does-list-comprehension-in-python-mean-how-does-it-work-and-how-can-i-us">What does &quot;list comprehension&quot; in Python mean? How does it work and how can I use it?</a> for more details about them. </p>
4
2016-10-05T21:31:59Z
[ "python", "list" ]
How can I append this elements to an array in python?
39,883,994
<pre><code>input_elements = ["a", "b", "c", "d"] my_array = ["1", "2", "3", "4"] </code></pre> <p>the output I want is:</p> <pre><code>["1", "2", "3", "4", "a"] ["1", "2", "3", "4", "b"] ["1", "2", "3", "4", "c"] ["1", "2", "3", "4", "d"] </code></pre> <p>I tried:</p> <pre><code>for e in input_elements: my_array.append(e) </code></pre> <p>I know the code right above is wrong, so I am wondering how I can generate the output like that.</p>
4
2016-10-05T21:29:01Z
39,884,088
<p>You need to make a copy of the old list in the loop:</p> <pre><code>input_elements = ["a", "b", "c", "d"] my_array = ["1", "2", "3", "4"] new_list = [] for e in input_elements: tmp_list = list(my_array) tmp_list.append(e) new_list.append(tmp_list) print(new_list) </code></pre> <p>Output:</p> <pre><code>[['1', '2', '3', '4', 'a'], ['1', '2', '3', '4', 'b'], ['1', '2', '3', '4', 'c'], ['1', '2', '3', '4', 'd']] </code></pre> <p>Note that <code>tmp_list = list(my_array)</code> makes a new copy of <code>my_array</code>.</p>
1
2016-10-05T21:34:46Z
[ "python", "list" ]
How can I append this elements to an array in python?
39,883,994
<pre><code>input_elements = ["a", "b", "c", "d"] my_array = ["1", "2", "3", "4"] </code></pre> <p>the output I want is:</p> <pre><code>["1", "2", "3", "4", "a"] ["1", "2", "3", "4", "b"] ["1", "2", "3", "4", "c"] ["1", "2", "3", "4", "d"] </code></pre> <p>I tried:</p> <pre><code>for e in input_elements: my_array.append(e) </code></pre> <p>I know the code right above is wrong, so I am wondering how I can generate the output like that.</p>
4
2016-10-05T21:29:01Z
39,884,191
<p>I'm assuming the output you're getting is:</p> <pre><code>['1', '2', '3', '4', 'a', 'b', 'c', 'd'] </code></pre> <p>...because, that's what I'm getting.</p> <p>The problem is, in your loop, you're simply adding a new element to the existing array, then printing the "grand total." So, you add a, then you add b, then you add c, then d... all to the same array, then printing out the whole shebang.</p> <p>The easiest solution for your particular problem is, in your for loop, print the array as it is, with the <code>e</code> selection concatenated. Like so:</p> <pre><code>input_elements = ["a", "b", "c", "d"] my_array = ["1", "2", "3", "4"] for e in input_elements: print my_array + [e] </code></pre> <p>That way, you're printing the array with the extra element, without actually affecting the original array... keeping it "clean" to loop back through and add the next element.</p> <p>This method allows you to achieve the desired result without having to result to extra memory allocation or unnecessary variables.</p> <p>If you have other things to do during the <code>for</code> loop, you could always add the element, then remove it after processing using the <code>pop</code> function, like so:</p> <pre><code>for e in input_elements: my_array.append(e) print my_array # Do some other nifty stuff my_array.pop() </code></pre> <p>Another option is to use List Comprehension, which allows you to iterate through an array as more of an inherent statement:</p> <p><code>print [my_array+[e] for e in input_elements]</code></p>
1
2016-10-05T21:42:48Z
[ "python", "list" ]
How does xarray broadcasting work with numpy functions?
39,884,068
<p>I am trying to do a coordinate transformation with my xarray coordinates so </p> <p>I have a DataArray like:</p> <pre><code>d = xr.DataArray(np.zeros((10, 10, 1)), dims=['x', 'y', 'z'] </code></pre> <p>and am doing operations like:</p> <pre><code>r = np.sqrt(d.x**2 + d.y**2 + d.z**2) theta = np.arctan2(np.sqrt(d.x**2 + d.y**2), d.z) phi = np.arctan2(d.y, d.x) </code></pre> <p>I get shapes of:</p> <pre><code>In [212]: r.shape Out[212]: (10, 10, 1) In [214]: theta.shape Out[214]: (10, 10) In [216]: phi.shape Out[216]: (10,) </code></pre> <p>I would like to see the <code>(10, 10, 1)</code> shape that I get for r for all of them. </p> <p>It looks like xarray's fancy broadcasting only kicks in for basic arithmetic operations and the numpy functions are broadcasting naively. </p> <p>Is this correct?</p> <p>Is there an approved way to get around this? I can write my own xarray aware arctan2 function which gets the broadcasting right, but I am hoping I don't have to.</p>
2
2016-10-05T21:33:24Z
39,884,270
<p>Unfortunately, NumPy functions generally don't do appropriate broadcasting on xarray objects. But xarray does come with wrapped versions of many of these functions, including <code>arctan2</code>, in the <a href="http://xarray.pydata.org/en/stable/api.html#universal-functions" rel="nofollow"><code>xarray.ufuncs</code> module</a>. So <code>xarray.ufuncs.arctan2</code> should do exactly what you're looking for.</p>
2
2016-10-05T21:49:52Z
[ "python", "numpy", "python-xarray" ]
count certain words on html file by python
39,884,197
<p>I am a rookie in Python. I am trying to count some words or expressions on html files. For example,I have a piece of html with source codes as below:</p> <pre><code>&lt;div style="line-height:120%;text-align:justify;text-indent:24px;font-size:10.5pt;"&gt; &lt;font style="font-family:inherit;font-size:10.5pt;font-style:italic;font-weight:bold;"&gt;2013 vs. 2012&amp;#160;&amp;#160;&lt;/font&gt; &lt;font style="font-family:inherit;font-size:10.5pt;"&gt;During 2013, the Company recognized a decommissioning charge of $117 million and a restoration liability of $50 million, partially offset by the 2013 reversal of the $56&amp;#160;million tax indemnification liability associated with the 2006 sale of the Company&amp;#8217;s Canadian subsidiary.&lt;/font&gt;&lt;/div&gt; </code></pre> <p>I want to count how many times "liability" show up in the piece. Below is my code, which is not working:</p> <pre><code>import os from bs4 import BeautifulSoup lst=os.listdir("C:/html/") for x in lst: print (x) html = open ("C:/html/"+x,'rb') bsobj = BeautifulSoup(html,"html.parser") metricslist = bsobj.findAll(div.string ='liability') print(len(metricslist)) </code></pre> <p>I know bsobj.findAll(div.string ='liability') is very wrong, but have no idea on what the code should be. Any help will be appreciated!</p>
0
2016-10-05T21:43:05Z
39,904,363
<p>You can apply a <em>partial string match</em> on an element's text when using <code>find()</code> or <code>find_all()</code>:</p> <pre><code>soup.find(text=lambda text: text and "liability" in text) </code></pre> <p>Or, a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-regular-expression" rel="nofollow">regular expression pattern</a> can be used in place of a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function" rel="nofollow">function</a>:</p> <pre><code>soup.find(text=re.compile(r"\bliability\b") </code></pre>
0
2016-10-06T19:39:44Z
[ "python", "beautifulsoup" ]
Variation of iterating through a single column
39,884,225
<p>I know there are a zillion ways to iterate through data in a data frame. I am acquiring data from a detector, power, frequency, time. The time and power columns have values in every row. The frequency changes with time <strong>but</strong> for each frequency 'segment' the frequency and duty cycle are only listed in the column at the beginning of the segment. Below what it looks like.</p> <pre class="lang-none prettyprint-override"><code>time power frequency duty cycle 1.4 1.2 500.0 45.0 2.1 49.9 NaN NaN 3.4 245.0 NaN NaN 4.5 323.0 NaN NaN 5.6 320.0 NaN NaN 6.6 309.0 1000 45 7.6 306.0 NaN NaN 8.7 305.0 NaN NaN 9.7 304.0 NaN NaN 10.8 300.0 NaN NaN </code></pre> <p>Using:</p> <pre><code>InitFreqs = df['frequency'] InitDuty = df['dutycycle'] for i in np.arange(1, len(InitFreqs)): if np.isnan(InitFreqs[i]): InitFreqs[i] = InitFreqs[i - 1] InitDuty[i] = InitDuty[i - 1] </code></pre> <p>I get the result I want which looks like this:</p> <pre class="lang-none prettyprint-override"><code>time power frequency duty cycle 1.4 1.2 500.0 45.0 2.1 49.9 500.0 45.0 3.4 245.0 500.0 45.0 4.5 323.0 500.0 45.0 5.6 320.0 500.0 45.0 6.6 309.0 1000 45.0 7.6 306.0 1000 45.0 8.7 305.0 1000 45.0 9.7 304.0 1000 45.0 10.8 300.0 1000 45.0 </code></pre> <p>The 45 in this example might or might not change as well and subsequent values need to reflect this. While this does the job it is horribly slow and inefficient. I have found examples of how to replace <em>all</em> values in a column with something else or all NaN's but not exactly what I am looking for. I should be able to perform this operation on a column as a whole vs the <code>for i</code> statement.</p>
0
2016-10-05T21:45:56Z
39,884,514
<p>You want <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a>:</p> <pre><code>data = '''time power frequency duty_cycle 1.4 1.2 500.0 45.0 2.1 49.9 NaN NaN 3.4 245.0 NaN NaN 4.5 323.0 NaN NaN 5.6 320.0 NaN NaN 6.6 309.0 1000 450 7.6 306.0 NaN NaN 8.7 305.0 NaN NaN 9.7 304.0 NaN NaN 10.8 300.0 NaN NaN''' dd = [d.split() for d in data.split('\n')] df = pd.DataFrame(dd[1:],columns=dd[0]) df.replace('NaN',np.nan,inplace=True) df.fillna(method='ffill',axis=0) time power frequency duty_cycle 0 1.4 1.2 500.0 45.0 1 2.1 49.9 500.0 45.0 2 3.4 245.0 500.0 45.0 3 4.5 323.0 500.0 45.0 4 5.6 320.0 500.0 45.0 5 6.6 309.0 1000 450 6 7.6 306.0 1000 450 7 8.7 305.0 1000 450 8 9.7 304.0 1000 450 9 10.8 300.0 1000 450 </code></pre>
1
2016-10-05T22:11:37Z
[ "python", "python-3.x", "numpy", "dataframe" ]
Efficient way to retrieve and merge returned arrays from multiprocess function call
39,884,292
<pre><code>def get_version_list(env): list = [] #do some intensive work return list if __name__ == '__main__': from multiprocessing import Pool pool = Pool() result1 = pool.apply_async(get_version_list, ['prod']) result2 = pool.apply_async(get_version_list, ['uat']) #etc, I have six environment to check. alist = result1.get() blist = result2.get() </code></pre> <p>Ideally, I would like to have a list containing my six environments, and loop on that list to call my function for each environment (in parallel) then unite all the returned lists. The united list should not contain a value multiple times.</p> <p>something like so (I knwo that code does not work, but it's to give an idea of what wish to do)</p> <pre><code>if __name__ == '__main__': from multiprocessing import Pool pool = Pool() env = ['uat', 'prod', 'lt', 'lt2', 'cert', 'sin'] for e in env: result = pool.apply_async(get_version_list, [e]) #Merging the lists of the 6 function calls (unique entries) list = result.get() </code></pre> <p>Is there a simple way to do it?</p>
0
2016-10-05T21:52:06Z
39,884,539
<p>Use <code>map_async</code> instead of <code>apply_async</code>.</p> <pre><code>pool = Pool() env = ['uat', 'prod', 'lt', 'lt2', 'cert', 'sin'] x = pool.map_async(get_version_list, env) </code></pre> <p>And now <code>x</code> will be a list of the results.</p>
1
2016-10-05T22:14:29Z
[ "python", "multiprocessing", "python-multiprocessing" ]
Efficient way to retrieve and merge returned arrays from multiprocess function call
39,884,292
<pre><code>def get_version_list(env): list = [] #do some intensive work return list if __name__ == '__main__': from multiprocessing import Pool pool = Pool() result1 = pool.apply_async(get_version_list, ['prod']) result2 = pool.apply_async(get_version_list, ['uat']) #etc, I have six environment to check. alist = result1.get() blist = result2.get() </code></pre> <p>Ideally, I would like to have a list containing my six environments, and loop on that list to call my function for each environment (in parallel) then unite all the returned lists. The united list should not contain a value multiple times.</p> <p>something like so (I knwo that code does not work, but it's to give an idea of what wish to do)</p> <pre><code>if __name__ == '__main__': from multiprocessing import Pool pool = Pool() env = ['uat', 'prod', 'lt', 'lt2', 'cert', 'sin'] for e in env: result = pool.apply_async(get_version_list, [e]) #Merging the lists of the 6 function calls (unique entries) list = result.get() </code></pre> <p>Is there a simple way to do it?</p>
0
2016-10-05T21:52:06Z
39,884,546
<p>You can take inspiration from <a href="https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers" rel="nofollow">the documentation</a>:</p> <pre><code>def get_version_list(env): lst = [] #do some intensive work return lst if __name__ == '__main__': from multiprocessing import Pool pool = Pool() env = ['uat', 'prod', 'lt', 'lt2', 'cert', 'sin'] result = [ pool.apply_async(get_version_list, [e]) for e in env ] lst = [r.get() for r in result] </code></pre> <p><code>result</code> will contain a list of <code>AsyncResult</code>s, on which the last <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> will "join" through the <code>get</code> method in order to provide final <code>lst</code> (off topic: <code>list</code> is already a data type name, don't call the variable that name).</p>
0
2016-10-05T22:15:19Z
[ "python", "multiprocessing", "python-multiprocessing" ]
Build 2D array using append
39,884,409
<p>Python: I would like to read set of data</p> <pre><code>(category, value): (0, 1) (0, 2) (1, 3) (1, 4) </code></pre> <p>To an array as</p> <pre><code>[[1, 2],[3, 4]] </code></pre> <p>Since max number of category is unknown, I would like to create 2D-array dynamically using "append" method.</p> <p>I wrote a sample code:</p> <pre><code>data = [] data.append([]) data[0].append(1) data[0].append(2) try: print (data[1]) except IndexError: data.append([]) finally: data[1].append(3) data[1].append(4) print(data) </code></pre> <p>But, I understand that the code is really ugly because I am using "print" to check the access to <code>data[1]</code>.</p> <p>Is there any more beautiful solution for this problem?</p>
1
2016-10-05T22:02:15Z
39,884,449
<p>You can use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to do this easily along with a <a href="https://docs.python.org/3/library/functions.html#iter" rel="nofollow"><code>iter</code></a>. </p> <pre><code>&gt;&gt;&gt; l = [(0, 1), (0, 2), (1, 3), (1, 4)] &gt;&gt;&gt; i = iter(l) &gt;&gt;&gt; [[x[1],y[1]] for x,y in zip(i,i)] [[1, 2], [3, 4]] </code></pre> <p>The algorithm here is to iterate over the list of tuples in pairs. This is where <code>iter</code> comes to use. <code>iter</code> creates an iterator that is consumed by the <code>zip</code> function. We then read the tuples into the list comprehension and add only the required two numbers, which is the second indices. </p> <p>See <a href="http://stackoverflow.com/questions/34835951/what-does-list-comprehension-in-python-mean-how-does-it-work-and-how-can-i-us">What does &quot;list comprehension&quot; in Python mean? How does it work and how can I use it?</a> for more details about them. </p>
1
2016-10-05T22:06:01Z
[ "python", "list", "append" ]
Build 2D array using append
39,884,409
<p>Python: I would like to read set of data</p> <pre><code>(category, value): (0, 1) (0, 2) (1, 3) (1, 4) </code></pre> <p>To an array as</p> <pre><code>[[1, 2],[3, 4]] </code></pre> <p>Since max number of category is unknown, I would like to create 2D-array dynamically using "append" method.</p> <p>I wrote a sample code:</p> <pre><code>data = [] data.append([]) data[0].append(1) data[0].append(2) try: print (data[1]) except IndexError: data.append([]) finally: data[1].append(3) data[1].append(4) print(data) </code></pre> <p>But, I understand that the code is really ugly because I am using "print" to check the access to <code>data[1]</code>.</p> <p>Is there any more beautiful solution for this problem?</p>
1
2016-10-05T22:02:15Z
39,884,532
<p>Use <code>itertools.groupby</code>:</p> <pre><code>import itertools a = [(0, 1), (0, 2), (1, 3), (1, 4)] g = itertools.groupby(a, key=lambda x: x[0]) g = [list(i[1]) for i in g] </code></pre>
1
2016-10-05T22:13:35Z
[ "python", "list", "append" ]
Delete blank columns from header row
39,884,456
<p>I'm pretty new to python and I'm having trouble deleting the header columns after the 25th column. There are 8 more extra columns that have no data so I'm trying to delete those columns. Columns 1-25 have like 50,000k of data and the rest of the columns are blank.How would I do this? My code for now is able to clean up the file but I cant delete the headers for row[0] AFTER COLUMN 25.<br> Thanks </p> <pre><code>import csv my_file_name = "NVG.txt" cleaned_file = "cleanNVG.csv" remove_words = ['INAC-EIM','-INAC','TO-INAC','TO_INAC','SHIP_TO-inac','SHIP_TOINAC'] with open(my_file_name, 'r', newline='') as infile, open(cleaned_file, 'w',newline='') as outfile: writer = csv.writer(outfile) cr = csv.reader(infile, delimiter='|') writer.writerow(next(cr)) #I think this is why is not working for line in (r[0:25] for r in cr): #del line [26:32] if not any(remove_word in element for element in line for remove_word in remove_words): line[11]= line[11][:5] writer.writerow(line) </code></pre>
0
2016-10-05T22:06:44Z
39,885,791
<p>You've found the line with the problem - all you have to do is only print the headers you want. <code>next(cr)</code> reads the header line, but you pass the entire line to <code>writer.writerow()</code>.</p> <p>Instead of</p> <pre><code>writer.writerow(next(cr)) </code></pre> <p>you want:</p> <pre><code>writer.writerow(next(cr)[:25]) </code></pre> <p>(<code>[:25]</code> and <code>[0:25]</code> are the same in Python)</p>
1
2016-10-06T00:44:05Z
[ "python", "python-3.x" ]
Specify what Y labels to use
39,884,482
<p>Using python and Matplotlib, I am trying to explicitly control what Y labels are shown on Y axis:</p> <pre><code>def plot_sample_top(sample, chrom): ax = fig.add_subplot(23, 1, subplot_coord[sample]) ax.set_xlim([1, chrom_lengths[chrom]]) ax.set_ylim([-10, 10]) # scatter ax.scatter(df_strain['POS'], df_strain["SD"], color='black', label="&lt; 1 SD") </code></pre> <p>I need the bounds of Y axis to be -10 and 10, and I want only the numbers -10, 0, and 10 to be shown as Y axis labels. with current code it shows -10, -5, 0, 5, 10 and is too squeezed together</p>
0
2016-10-05T22:09:27Z
39,884,784
<p>You will want to use <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_yticks" rel="nofollow">axes.set_yticks</a> and/or <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_yticklabels" rel="nofollow">axes.set_yticklabels</a>.</p> <p>To set the ticks and labels as you specify, you would do:</p> <pre><code>ax.set_yticks([-10, 0, 10]) </code></pre> <p>This will eliminate all of the other ticks. If you want the ticks to remain, but the labels to disappear (e.g. you want to have grid lines on -9, -8, -7 etc. but don't want the label), you could do:</p> <pre><code>ax.set_yticks(range(-10,11)) # to make sure they are what you think they are labels = [-10,'','','','','','','','','',0,'','','','','','','','','',10] ax.set_yticklabels(labels) </code></pre> <p>If you wanted to make the labels a little more elegantly, you could do:</p> <pre><code>labels = [y if y in [-10,0,10] else '' for y in xrange(-10,11)] </code></pre>
0
2016-10-05T22:40:39Z
[ "python", "matplotlib" ]
conda command will prompts error
39,884,499
<p>I'm using arch linux and I've installed Anaconda as per the instruction on the Anaconda site. When I'm attempting to run <code>conda info --envs </code> I get the following error:</p> <pre><code>bash: /home/lukasz/anaconda3/bin/conda: /opt/anaconda1anaconda2anaconda3/bin/python: bad interpreter: No such file or directory </code></pre> <p>I've tryed looking for the directory <code>/opt/anaconda1anaconda2anaconda3/bin/python:</code> but it simply doesn't exist. </p> <p>Furthermore, when I run python from the terminal it runs as normal with the following displayed at the top</p> <pre><code>Python 3.5.2 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:53:06) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux Type "help", "copyright", "credits" or "license" for more information. </code></pre> <p>for completeness my <code>.bashrc</code> file resembles:</p> <pre><code># # ~/.bashrc # # If not running interactively, don't do anything [[ $- != *i* ]] &amp;&amp; return alias ls='ls --color=auto' PS1='[\u@\h \W]\$ ' # added by Anaconda3 4.0.0 installer export PATH="/home/lukasz/anaconda3/bin:$PATH" # python startup for up keys export PYTHONSTARTUP=$HOME/.pythonstartup </code></pre> <p>I've tried following the <a href="http://stackoverflow.com/questions/35246386/conda-command-not-found">Conda command not found</a> and making the the appropriate changes but nothing, I've also attempted to <a href="http://stackoverflow.com/questions/33946829/conda-command-not-found-path-is-in-bashrc">Conda command not found, path is in .bashrc</a> but there really isn't a solution posted. </p> <p>I would like to try to fix this without having to remove Anaconda and reinstalling it.</p>
1
2016-10-05T22:10:27Z
39,884,767
<p>Something must have gone wrong during the installation, I suppose. The bad interpreter means that a script is looking for an interpreter that doesn't exist - as you rightfully pointed out.</p> <p>The problem is likely to be in the shebang <code>#!</code> statement of your conda script.</p> <blockquote> <p><em><a href="https://en.wikipedia.org/wiki/Shebang_(Unix)" rel="nofollow">From Wikipedia</a>: Under Unix-like operating systems, when a script with a shebang is run as a program, the program loader parses the rest of the script's initial line as an interpreter directive; the specified interpreter program is run instead, passing to it as an argument the path that was initially used when attempting to run the script.</em></p> </blockquote> <p>If you run</p> <pre><code>cat ~/anaconda3/bin/conda </code></pre> <p>You will probably get the following:</p> <pre><code>#!/opt/anaconda1anaconda2anaconda3/bin/python if __name__ == '__main__': import sys import conda.cli sys.exit(conda.cli.main()) </code></pre> <p>Changing the first line to point a correct interpreter, i.e., changing it to:</p> <pre><code>#!/home/lukasz/anaconda3/bin/python </code></pre> <p>Should make the <code>conda</code> command work.</p> <p>If you are sure that you installed everything properly, then I'd suggest maybe reaching out for <a href="https://www.continuum.io/support" rel="nofollow">support from the anaconda community.</a></p>
1
2016-10-05T22:38:04Z
[ "python", "linux", "anaconda" ]
Removing Duplicates conditional in Pandas based on all but on column?
39,884,561
<p>So I have a Pandas DataFrame loaded with a bunch of data, yet, there are some duplicates in the data. The way duplicates exist, make it hard to remove them. Imagine this:</p> <pre><code>1 |a |b |c |1232 2 | |b |c |1232 3 | |as |ac |89231 </code></pre> <p>Now I want the code to be able to remove row 2, because it's basically same as row 1, but its second column is empty (the second column has some empty artifacts based on the way data was scraped from the web), yet I don't want the code to remove 3 and 1. </p> <p>Any ideas?</p>
0
2016-10-05T22:16:52Z
39,885,121
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">drop_duplicates</a>. If your column names are, let's say: <code>['A', 'B', 'C', 'D', 'E']</code> and your data frame is <code>df</code> and <code>row 0</code> and <code>row 1</code> are not duplicated in column 'A' and column 'B', then you can do this:</p> <pre><code>df.drop_duplicates(['C', 'D','E'], keep='first') </code></pre>
0
2016-10-05T23:16:59Z
[ "python", "database", "algorithm", "csv", "pandas" ]
Use context manager as a function
39,884,579
<p>I'd like to make a function which would also act as context manager if called with <code>with</code> statement. Example usage would be:</p> <pre><code># Use as function set_active_language("en") # Use as context manager with set_active_language("en"): ... </code></pre> <p>This is very similar to how the standard function <code>open</code> is used.</p> <p>Here's the solution I came up with:</p> <pre><code>active_language = None # global variable to store active language class set_active_language(object): def __init__(self, language): global active_language self.previous_language = active_language active_language = language def __enter__(self): pass def __exit__(self, *args): global active_language active_language = self.previous_language </code></pre> <p>This code is not thread-safe, but this is not related to the problem. </p> <p>What I don't like about this solution is that class constructor pretends to be a simple function and is used only for its side effects.</p> <p>Is there a better way to do this?</p> <p>Note that I haven't tested this solution.</p> <p>Update: the reason why I don't want to split function and context manager into separate entities is is naming. The function and the context manager do the same thing, basically, so it seems reasonable to use one name for both. Naming the context processor would be problematic if I wanted to keep it separate. What should it be? <code>active_language</code>? This name may (and will) collide with variable name. <code>override_active_language</code> might work, though.</p>
2
2016-10-05T22:18:15Z
39,884,736
<p>Hopefully someone will prove me wrong, but I think the answer is <strong>no</strong>: there is no other way. And also, another short-coming of the method you chose is that it might misbehave when used along with other context managers in a <code>with a, b, c:</code> statement. The intended side-effect of the CM is executed on object construction, and not in the <code>__enter__</code> method as would be expected.</p> <p>To be able to do what you want, you would have to know from inside the class constructor whether it was initialized as a context manager in a <code>with</code> statement, or simply called as a function. As far as I can tell, there is no way to gather that, not even with the <code>inspect</code> module.</p>
0
2016-10-05T22:34:00Z
[ "python" ]
Use context manager as a function
39,884,579
<p>I'd like to make a function which would also act as context manager if called with <code>with</code> statement. Example usage would be:</p> <pre><code># Use as function set_active_language("en") # Use as context manager with set_active_language("en"): ... </code></pre> <p>This is very similar to how the standard function <code>open</code> is used.</p> <p>Here's the solution I came up with:</p> <pre><code>active_language = None # global variable to store active language class set_active_language(object): def __init__(self, language): global active_language self.previous_language = active_language active_language = language def __enter__(self): pass def __exit__(self, *args): global active_language active_language = self.previous_language </code></pre> <p>This code is not thread-safe, but this is not related to the problem. </p> <p>What I don't like about this solution is that class constructor pretends to be a simple function and is used only for its side effects.</p> <p>Is there a better way to do this?</p> <p>Note that I haven't tested this solution.</p> <p>Update: the reason why I don't want to split function and context manager into separate entities is is naming. The function and the context manager do the same thing, basically, so it seems reasonable to use one name for both. Naming the context processor would be problematic if I wanted to keep it separate. What should it be? <code>active_language</code>? This name may (and will) collide with variable name. <code>override_active_language</code> might work, though.</p>
2
2016-10-05T22:18:15Z
39,884,831
<p>Technically no, you cannot do this. But you can fake it well enough that people (who didn't overthink it) wouldn't notice.</p> <pre><code>def set_active_language(language): global active_language previous_language = active_language active_language = language class ActiveScope(object): def __enter__(self): pass def __exit__(self, *args): global active_language active_language = previous_language return ActiveScope() </code></pre> <p>When used as a function the <code>ActiveScope</code> class is just a slightly wasteful no-op.</p>
2
2016-10-05T22:46:34Z
[ "python" ]
Comparing scipy.stats.t.sf vs GSL using Cython
39,884,665
<p>I would like to calculate the p values of a large 2D numpy t values array. However, this takes long time and I would like to improve its speed. I tried using GSL. Although a single gsl_cdf_tdist_P is much much faster than scipy.stats.t.sf, when iterating over the ndarray, the process is very slow. I would like help to improve this. See the code below.</p> <p>GSL_Test.pyx</p> <pre><code>import cython cimport cython import numpy cimport numpy from cython_gsl cimport * DTYPE = numpy.float32 ctypedef numpy.float32_t DTYPE_t cdef get_gsl_p(double t, double nu): return (1 - gsl_cdf_tdist_P(t, nu)) * 2 @cython.boundscheck(False) @cython.wraparound(False) @cython.nonecheck(False) cdef get_gsl_p_for_2D_matrix(numpy.ndarray[DTYPE_t, ndim=2] t_matrix, int n): cdef unsigned int rows = t_matrix.shape[0] cdef numpy.ndarray[DTYPE_t, ndim=2] out = numpy.zeros((rows, rows), dtype='float32') cdef unsigned int row, col for row in range(rows): for col in range(rows): out[row, col] = get_gsl_p(t_matrix[row, col], n-2) return out def get_gsl_p_for_2D_matrix_def(numpy.ndarray[DTYPE_t, ndim=2] t_matrix, int n): return get_gsl_p_for_2D_matrix(t_matrix, n) </code></pre> <p>ipython</p> <pre><code>import GSL_Test import numpy import scipy.stats a = numpy.random.rand(3544, 3544).astype('float32') %timeit -n 1 GSL_Test.get_gsl_p_for_2D_matrix(a, 25) 1 loop, best of 3: 7.87 s per loop %timeit -n 1 scipy.stats.t.sf(a, 25)*2 1 loop, best of 3: 4.66 s per loop </code></pre> <p><strong>UPDATE:</strong> Adding cdef declarations I was able to reduce the computational time but not lower than scipy still. I modified the code to have the cdef declarations. </p> <pre><code>%timeit -n 1 GSL_Test.get_gsl_p_for_2D_matrix_def(a, 25) 1 loop, best of 3: 6.73 s per loop </code></pre>
0
2016-10-05T22:26:32Z
39,898,055
<p>You can get some small gain in raw performance by using a raw special function instead of <code>stats.t.sf</code>. Looking at the source, you find (<a href="https://github.com/scipy/scipy/blob/master/scipy/stats/_continuous_distns.py#L3849" rel="nofollow">https://github.com/scipy/scipy/blob/master/scipy/stats/_continuous_distns.py#L3849</a>)</p> <pre><code>def _sf(self, x, df): return sc.stdtr(df, -x) </code></pre> <p>So that you can use <code>stdtr</code> directly:</p> <pre><code>np.random.seed(1234) x = np.random.random((3740, 374)) t1 = stats.t.sf(x, 25) t2 = stdtr(25, -x) 1 loop, best of 3: 653 ms per loop 1 loop, best of 3: 562 ms per loop </code></pre> <p>If you do reach out for cython, the typed memoryview syntax often gives you faster code than the old ndarray syntax:</p> <pre><code>from scipy.special.cython_special cimport stdtr from numpy cimport npy_intp import numpy as np def tsf(double [:, ::1] x, int df=25): cdef double[:, ::1] out = np.empty_like(x) cdef npy_intp i, j cdef double tmp, xx for i in range(x.shape[0]): for j in range(x.shape[1]): xx = x[i, j] out[i, j] = stdtr(df, -xx) return np.asarray(out) </code></pre> <p>Here I'm also using the <code>cython_special</code> interface, which is only avaialble in the dev version of scipy (<a href="http://scipy.github.io/devdocs/special.cython_special.html#module-scipy.special.cython_special" rel="nofollow">http://scipy.github.io/devdocs/special.cython_special.html#module-scipy.special.cython_special</a>), but you can use GSL if you want.</p> <p>Finally, if you suspect a bottleneck in iterations, don't forget to inspect the output of <code>cython -a</code> to see if there's some python overhead in the hot loops.</p>
1
2016-10-06T14:00:46Z
[ "python", "numpy", "scipy", "cython", "gsl" ]
iterate through number of columns, with variable columns
39,884,769
<p>For example, let's consider this toy code </p> <pre><code>import numpy as np import numpy.random as rnd a = rnd.randint(0,10,(10,10)) k = (1,2) b = a[:,k] for col in np.arange(np.size(b,1)): b[:,col] = b[:,col]+col*100 </code></pre> <p>This code will work when the size of <code>k</code> is bigger than 1. However, with the size equal to 1, the extracted sub-matrix from <code>a</code> is transformed into a row vector, and applying the function in the <code>for</code> loop throws an error. Of course, I could fix this by checking the dimension of <code>b</code> and reshaping:</p> <pre><code>if np.dim(b) == 1: b = np.reshape(b, (np.size(b), 1)) </code></pre> <p>in order to obtain a column vector, but this is expensive. </p> <p>So, the question is: what is the best way to handle this situation? This seems like something that would arise quite often and I wonder what is the best strategy to deal with it. </p>
2
2016-10-05T22:38:07Z
39,885,674
<p>If you index with a list or tuple, the 2d shape is preserved:</p> <pre><code>In [638]: a=np.random.randint(0,10,(10,10)) In [639]: a[:,(1,2)].shape Out[639]: (10, 2) In [640]: a[:,(1,)].shape Out[640]: (10, 1) </code></pre> <p>And I think <code>b</code> iteration can be simplified to:</p> <pre><code>a[:,k] += np.arange(len(k))*100 </code></pre> <p>This sort of calculation will also be easier is <code>k</code> is always a list or tuple, and never a scalar (a scalar does not have a <code>len</code>).</p> <p><code>np.column_stack</code> ensures its inputs are 2d (and expands at the end if not) with:</p> <pre><code> if arr.ndim &lt; 2: arr = array(arr, copy=False, subok=True, ndmin=2).T </code></pre> <p><code>np.atleast_2d</code> does</p> <pre><code> elif len(ary.shape) == 1: result = ary[newaxis,:] </code></pre> <p>which of course could changed in this case to</p> <pre><code> if b.ndim==1: b = b[:,None] </code></pre> <p>Any ways, I think it is better to ensure the <code>k</code> is a tuple rather than adjust <code>b</code> shape after. But keep both options in your toolbox.</p>
0
2016-10-06T00:26:12Z
[ "python", "numpy", "for-loop", "matrix" ]
Communicate between two python app
39,884,815
<p>I have done two app's :</p> <ol> <li>The first one is a spider that extract all links from a website.<br></li> <li>The second one do some checks on each link sent by the first app.</li> </ol> <p>When the first app find a link, how can I send a notification or something else to the second app ?<br> The second app must listen continuously the data sent by the first app.</p> <p>I found few post speaking of <code>Queue</code> but I don't really understand how that work.</p> <p>Can someone explain me with a simple exemple how to communicate between the two app ?</p> <p>Thank's</p>
0
2016-10-05T22:44:09Z
39,884,866
<p>You want to save one file as a "module" to be imported by the other file. Here this can be implemented with the the <code>import</code> keyword. For example, if you name the second part of your application <code>listener.py</code>, you can type <code>import listener</code> in your other file (remember to put them in the same folder!) and call any method from the second file. <a href="https://docs.python.org/2/tutorial/modules.html" rel="nofollow">You can read more on Python modules here.</a></p>
0
2016-10-05T22:49:58Z
[ "python", "multithreading", "python-2.7", "queue" ]
Communicate between two python app
39,884,815
<p>I have done two app's :</p> <ol> <li>The first one is a spider that extract all links from a website.<br></li> <li>The second one do some checks on each link sent by the first app.</li> </ol> <p>When the first app find a link, how can I send a notification or something else to the second app ?<br> The second app must listen continuously the data sent by the first app.</p> <p>I found few post speaking of <code>Queue</code> but I don't really understand how that work.</p> <p>Can someone explain me with a simple exemple how to communicate between the two app ?</p> <p>Thank's</p>
0
2016-10-05T22:44:09Z
39,885,079
<p>There are all sorts of ways to accomplish inter-process communication, but by far the simplest is to use the filesystem. Have your spider write it's output to a temp file. When it's finished, move it into a folder that your second process polls periodically and when it finds work, then process it.</p> <p>The <code>spider</code> could like something like:</p> <pre><code>import tempfile, os tmpname = '' with tempfile.NamedTemporaryFile(delete=False) as tmp: tmpname = tmp.name tmp.write("spider output....\n") tgt = os.path.join('incoming', os.path.basename(tmpname)) os.rename(tmpname, tgt) </code></pre> <p>The second process could look something like this:</p> <pre><code>import time, os while 1: time.sleep(5) for item in os.listdir('incoming'): work_item = os.path.join('incoming', item) with open(work_item) as fin: # do something with item os.unlink(work_item) </code></pre>
0
2016-10-05T23:12:29Z
[ "python", "multithreading", "python-2.7", "queue" ]
Communicate between two python app
39,884,815
<p>I have done two app's :</p> <ol> <li>The first one is a spider that extract all links from a website.<br></li> <li>The second one do some checks on each link sent by the first app.</li> </ol> <p>When the first app find a link, how can I send a notification or something else to the second app ?<br> The second app must listen continuously the data sent by the first app.</p> <p>I found few post speaking of <code>Queue</code> but I don't really understand how that work.</p> <p>Can someone explain me with a simple exemple how to communicate between the two app ?</p> <p>Thank's</p>
0
2016-10-05T22:44:09Z
39,885,092
<p>A <a href="https://en.wikipedia.org/wiki/Queue_%28abstract_data_type%29" rel="nofollow">Queue</a> is just a container into which items may be put and retrieved, often in <a href="https://en.wikipedia.org/wiki/FIFO_%28computing_and_electronics%29" rel="nofollow">FIFO</a> order. The <a href="https://docs.python.org/2/library/queue.html" rel="nofollow"><code>Queue</code></a> module in Python 2 is just an implementation of one that supports synchronized access, meaning that it supports multiple threads using it (putting and getting things) at the same time.</p>
0
2016-10-05T23:13:55Z
[ "python", "multithreading", "python-2.7", "queue" ]
Converting and comparing 2 datetimes
39,884,856
<p>I need help trying to convert a string to datetime, then comparing it to see if it is less than 3 days old. I have tried both with the time class, as well as the datetime class, but I keep getting the same error:</p> <pre><code>TypeError: unsupported operand type(s) for -: 'str' and 'str' </code></pre> <p>here is the code I have tried:</p> <pre><code>def time_calculation(): time1 = "2:00 PM 5 Oct 2016" time2 = "2:00 PM 4 Oct 2016" time3 = "2:00 PM 1 Oct 2016" timeNow = time.strftime("%Y%m%d-%H%M%S") #newtime1 = time.strftime("%Y%m%d-%H%M%S", time.strptime(time1, "%I:%M %p %d %b %Y")) newtime1 = datetime.strptime(time1, "%I:%M %p %d %b %Y").strftime("%Y%m%d-%H%M%S") print("the new time1 is {}".format(newtime1)) #newtime2 = time.strftime("%Y%m%d-%H%M%S", time.strptime(time2, "%I:%M %p %d %b %Y")) newtime2 = datetime.strptime(time2, "%I:%M %p %d %b %Y").strftime("%Y%m%d-%H%M%S") print("the new time2 is {}".format(newtime2)) #newtime3 = time.strftime("%Y%m%d-%H%M%S", time.strptime(time3, "%I:%M %p %d %b %Y")) newtime3 = datetime.strptime(time3, "%I:%M %p %d %b %Y").strftime("%Y%m%d-%H%M%S") print("the new time3 is {}".format(newtime3)) timeList = [] timeList.append(newtime1) timeList.append(newtime2) timeList.append(newtime3) for ele in timeList: deltaTime = ele - timeNow if deltaTime.days &lt; 4: print("This time was less than 4 days old {}\n".format(ele.strftime("%Y%m%d-%H%M%S"))) </code></pre> <p>the commented out parts are what I did with time, while the others are with datetime. </p> <p>the error happens at the line where I try to compare the current time with each time in the list, but it takes them as strings instead of datetimes and won't subtract them so I can compare them. (In the for loop at the bottom.)</p>
0
2016-10-05T22:48:46Z
39,885,249
<p>Indeed, don't convert back to strings and instead work with <code>datetime</code> objects. As noted in the error message <code>str - str</code> isn't an operation that's defined (what does it mean to subtract a string from another?):</p> <pre><code>"s" - "s" # TypeError </code></pre> <p>Instead, initialize <code>timeNow</code> with <code>datetime.now()</code>, <code>datetime</code> instances support subtracting. As a second suggestion, subtract <code>ele</code> from <code>timeNow</code> and not <code>timeNow</code> from <code>ele</code>: </p> <pre><code>def time_calculation(): # snipped for brevity timeNow = datetime.now() # snipped for ele in timeList: deltaTime = timeNow - ele if deltaTime.days &lt; 4: print("This time was less than 4 days old {}\n".format(ele.strftime("%Y%m%d-%H%M%S"))) </code></pre> <p>Prints out:</p> <pre><code>time_calculation() the new time1 is 2016-10-05 14:00:00 the new time2 is 2016-10-04 14:00:00 the new time3 is 2016-10-01 14:00:00 This time was less than 4 days old 20161005-140000 This time was less than 4 days old 20161004-140000 </code></pre> <p>Which I'm guessing is what you were after.</p>
1
2016-10-05T23:31:53Z
[ "python", "python-3.x", "datetime" ]
In Python Spyder interactive plotting. How do I link plots so that when I zoom in on a plot it zooms in on the rest
39,884,875
<p>In Python Spyder interactive plotting. How do I link plots so that when I zoom in on one plot in one figure, it zooms all the other plots that are on the same figure and different figure to the same scale? They are all plotted vs time which is mSec.</p> <p>Here is a sample of my current code that is still in the works. (I know I am plotting the same thing twice, I am just testing few things.)</p> <pre><code>import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('data'.csv', delimiter=',', skiprows=1) # This uses array slicing/indexing to cut the correct columns into variables. mSec = data[:,0] Airspeed = data[:,10] AS_Cmd = data[:,25] airspeed = data[:,3] plt.rc('xtick', labelsize=15) #increase xaxis tick size plt.rc('ytick', labelsize=15) #increase yaxis tick size # Create a figure figsize = () fig1 = plt.figure(figsize= (20,20)) ax = fig1.add_subplot(211) ax.plot(mSec, Airspeed, label='Ground speed [m/s]', color = 'r') ax.plot(mSec, AS_Cmd, label='AS_Cmd') plt.legend(loc='best',prop={'size':13}) ax.set_ylim([-10,40]) ax1 = fig1.add_subplot(212) ax1.plot(mSec, Airspeed, label='Ground speed [m/s]', color = 'r') ax1.plot(mSec, AS_Cmd, label='AS_Cmd[m/s]') # Show the legend plt.legend(loc='lower left',prop={'size':8}) fig1.savefig('trans2.png', dpi=(200), bbox_inches='tight') #borderless on save </code></pre>
2
2016-10-05T22:50:41Z
39,885,682
<p><code>sharex</code> and <code>sharey</code> are your friends. Minimal example:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt fig1, (ax1, ax2) = plt.subplots(1,2,sharex=True, sharey=True) ax1.plot(np.random.rand(10)) ax2.plot(np.random.rand(11)) fig2 = plt.figure() ax3 = fig2.add_axes([0.1, 0.1, 0.8, 0.8], sharex=ax1, sharey=ax1) ax3.plot(np.random.rand(12)) </code></pre>
1
2016-10-06T00:27:11Z
[ "python", "matplotlib", "spyder" ]
Large amount of multiprocessing.Process causing deadlock
39,884,898
<p><strong>Context</strong></p> <p>I need to run a multiprocessing.Process inside a multiprocessing.ThreadPool. It seems weird at first but it is the only way I found to deals with segfault that could occurs because I am using a c++ shared library. If a segfault append, the process is killed and I can check the process.exitcode and deal with that.</p> <p><strong>Problem</strong></p> <p>After a while, a deadlock append when I am trying to join the process.</p> <p>Here is a simple version a my code:</p> <pre><code>import sys, time, multiprocessing from multiprocessing.pool import ThreadPool def main(): # Launch 8 workers pool = ThreadPool(8) it = pool.imap(run, range(500)) while True: try: it.next() except StopIteration: break def run(value): # Each worker launch it own Process process = multiprocessing.Process(target=run_and_might_segfault, args=(value,)) process.start() while process.is_alive(): sys.stdout.write('.') sys.stdout.flush() time.sleep(0.1) # Will never join after a while, because of a mystery deadlock process.join() # Deals with process.exitcode to log errors def run_and_might_segfault(value): # Load a shared library and do stuff (could throw c++ exception, segfault ...) print(value) if __name__ == '__main__': main() </code></pre> <p>And here is a possible output:</p> <pre><code>➜ ~ python m.py ..0 1 ........8 .9 .......10 ......11 ........12 13 ........14 ........16 ........................................................................................ </code></pre> <p>As you can see, <code>process.is_alive()</code> is alway true after few iterations, the process will never join.</p> <p>If I CTRL-C the script a get this stacktrace:</p> <pre><code>Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/multiprocessing/pool.py", line 680, in next item = self._items.popleft() IndexError: pop from an empty deque During handling of the above exception, another exception occurred: Traceback (most recent call last): File "m.py", line 30, in &lt;module&gt; main() File "m.py", line 9, in main it.next() File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5 /lib/python3.5/multiprocessing/pool.py", line 684, in next self._cond.wait(timeout) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5 /lib/python3.5/threading.py", line 293, in wait waiter.acquire() KeyboardInterrupt Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5 /lib/python3.5/multiprocessing/popen_fork.py", line 29, in poll pid, sts = os.waitpid(self.pid, flag) KeyboardInterrupt </code></pre> <p><strong>PS</strong> Using python 3.5.2 on macos.</p> <p>Every kind of help is appreciate, thanks.</p> <p><strong>Edit</strong></p> <p>I tried using python 2.7, and it is working well. May be a python 3.5 issue only?</p>
0
2016-10-05T22:53:16Z
40,045,511
<p>The problem is also reproduced on the latest build of CPython - <code>Python 3.7.0a0 (default:4e2cce65e522, Oct 13 2016, 21:55:44)</code>.</p> <p>If you <a href="http://podoliaka.org/2016/04/10/debugging-cpython-gdb/" rel="nofollow">attach</a> to one of the stuck processes with gdb, you'll see that it's trying to acquire a lock in <code>sys.stdout.flush()</code> call:</p> <pre><code>(gdb) py-list 263 import traceback 264 sys.stderr.write('Process %s:\n' % self.name) 265 traceback.print_exc() 266 finally: 267 util.info('process exiting with exitcode %d' % exitcode) &gt;268 sys.stdout.flush() 269 sys.stderr.flush() 270 271 return exitcode </code></pre> <p>Python level backtrace looks like this:</p> <pre><code> (gdb) py-bt Traceback (most recent call first): File "/home/rpodolyaka/src/cpython/Lib/multiprocessing/process.py", line 268, in _bootstrap sys.stdout.flush() File "/home/rpodolyaka/src/cpython/Lib/multiprocessing/popen_fork.py", line 74, in _launch code = process_obj._bootstrap() File "/home/rpodolyaka/src/cpython/Lib/multiprocessing/popen_fork.py", line 20, in __init__ self._launch(process_obj) File "/home/rpodolyaka/src/cpython/Lib/multiprocessing/context.py", line 277, in _Popen return Popen(process_obj) File "/home/rpodolyaka/src/cpython/Lib/multiprocessing/context.py", line 223, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "/home/rpodolyaka/src/cpython/Lib/multiprocessing/process.py", line 105, in start self._popen = self._Popen(self) File "deadlock.py", line 17, in run process.start() File "/home/rpodolyaka/src/cpython/Lib/multiprocessing/pool.py", line 119, in worker result = (True, func(*args, **kwds)) File "/home/rpodolyaka/src/cpython/Lib/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/rpodolyaka/src/cpython/Lib/threading.py", line 916, in _bootstrap_inner self.run() File "/home/rpodolyaka/src/cpython/Lib/threading.py", line 884, in _bootstrap self._bootstrap_inner() </code></pre> <p>At the interpreter level it looks like:</p> <pre><code>(gdb) frame 6 (gdb) list 287 return 0; 288 } 289 relax_locking = (_Py_Finalizing != NULL); 290 Py_BEGIN_ALLOW_THREADS 291 if (!relax_locking) 292 st = PyThread_acquire_lock(self-&gt;lock, 1); 293 else { 294 /* When finalizing, we don't want a deadlock to happen with daemon 295 * threads abruptly shut down while they owned the lock. 296 * Therefore, only wait for a grace period (1 s.). ... */ (gdb) p /x self-&gt;lock $1 = 0xd25ce0 (gdb) p /x self-&gt;owner $2 = 0x7f9bb2128700 </code></pre> <p>Note, that from the point of view of this particular child process the lock is still owned by one of threads in the parent process (<code>LWP 1105</code>):</p> <pre><code>(gdb) info threads Id Target Id Frame * 1 Thread 0x7f9bb5559440 (LWP 1102) "python" 0x00007f9bb5157577 in futex_abstimed_wait_cancelable (private=0, abstime=0x0, expected=0, futex_word=0xe4d340) at ../sysdeps/unix/sysv/linux/futex-internal.h:205 2 Thread 0x7f9bb312a700 (LWP 1103) "python" 0x00007f9bb4780253 in select () at ../sysdeps/unix/syscall-template.S:84 3 Thread 0x7f9bb2929700 (LWP 1104) "python" 0x00007f9bb4780253 in select () at ../sysdeps/unix/syscall-template.S:84 4 Thread 0x7f9bb2128700 (LWP 1105) "python" 0x00007f9bb4780253 in select () at ../sysdeps/unix/syscall-template.S:84 5 Thread 0x7f9bb1927700 (LWP 1106) "python" 0x00007f9bb4780253 in select () at ../sysdeps/unix/syscall-template.S:84 6 Thread 0x7f9bb1126700 (LWP 1107) "python" 0x00007f9bb4780253 in select () at ../sysdeps/unix/syscall-template.S:84 7 Thread 0x7f9bb0925700 (LWP 1108) "python" 0x00007f9bb4780253 in select () at ../sysdeps/unix/syscall-template.S:84 8 Thread 0x7f9b9bfff700 (LWP 1109) "python" 0x00007f9bb4780253 in select () at ../sysdeps/unix/syscall-template.S:84 9 Thread 0x7f9b9b7fe700 (LWP 1110) "python" 0x00007f9bb4780253 in select () at ../sysdeps/unix/syscall-template.S:84 10 Thread 0x7f9b9affd700 (LWP 1111) "python" 0x00007f9bb4780253 in select () at ../sysdeps/unix/syscall-template.S:84 11 Thread 0x7f9b9a7fc700 (LWP 1112) "python" 0x00007f9bb5157577 in futex_abstimed_wait_cancelable (private=0, abstime=0x0, expected=0, futex_word=0x7f9b80001ed0) at ../sysdeps/unix/sysv/linux/futex-internal.h:205 12 Thread 0x7f9b99ffb700 (LWP 1113) "python" 0x00007f9bb5157577 in futex_abstimed_wait_cancelable (private=0, abstime=0x0, expected=0, futex_word=0x7f9b84001bb0) at ../sysdeps/unix/sysv/linux/futex-internal.h:205 </code></pre> <p>So it's indeed a deadlock and it happens due to the fact that you perform writes and flushing on <code>sys.stdout</code> in multiple threads concurrently in the original process while also creating subprocesses - by the nature of <code>fork(2)</code> system call children inherit the parent memory including acquired locks: <code>fork()</code> calls must have been performed while the lock was acquired, and even when the parent process finally releases it, the children won't see that, as each of them now has its own memory space, that was copied on write.</p> <p>Thus, you need to be very careful when mixing multithreading with multiprocessing and make sure all the locks are properly released before <code>fork()</code>, if they are to be used in the children processes.</p> <p>It's very similar to what is described in <a href="http://bugs.python.org/issue6721" rel="nofollow">http://bugs.python.org/issue6721</a></p> <p>Note, that if you remove the interactions with <code>sys.stdout</code> from your snippet, it will work correctly.</p>
0
2016-10-14T14:21:46Z
[ "python", "multithreading", "multiprocessing", "deadlock" ]
How do I clear a ScatterPlotItem in PYQTGRAPH
39,884,931
<p>I am attempting to move a "cursor" around my graph using ScatterPlotItem and a '+' symbol as the cursor. The cursor updates its position perfectly but I cannot figure out how to clear the last instance. Here is the line that I use to plot the 'cursor'.</p> <pre><code>self.cursor2 = self.p2_3.addItem(pg.ScatterPlotItem([self.xx], [self.yy], pen=None, symbol='+', color = 'b')) </code></pre> <p>I tried self.cursor2.clear() but that didn't work. Any help is appreciated. </p>
0
2016-10-05T22:56:04Z
39,889,712
<p>When you call addItem you add the plotdataitem, in this case a scatterplotitem to your plotitem. To remove it you call removeItem in the same way. But you need to keep a reference to the scatterplotitem to do that.</p> <p>Note that addItem doesn't return anything i.e. your self.cursor2 is None.</p> <p>If you want to remove everything from your plot you could call</p> <pre><code>self.p2_3.clear() </code></pre> <p>otherwise to just remove the scatterplotitem you can do like this</p> <pre><code>import pyqtgraph as pg win = pg.GraphicsWindow() plotitem = win.addPlot() scatterplot = pg.ScatterPlotItem([2], [3], symbol='+', color = 'b') plotitem.addItem(scatterplot) plotitem.removeItem(scatterplot) </code></pre>
1
2016-10-06T07:11:33Z
[ "python", "python-2.7", "pyqtgraph" ]
Mask an image (np.ndarray) section which lies between two curves
39,885,113
<p>Borrowing this example from astropy:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from astropy.io import fits from astropy.wcs import WCS from astropy.utils.data import download_file fits_file = 'http://data.astropy.org/tutorials/FITS-images/HorseHead.fits' image_file = download_file(fits_file, cache=True) hdu = fits.open(image_file)[0] wcs = WCS(hdu.header) fig = plt.figure() ax = fig.add_subplot(111) plt.imshow(hdu.data, origin='lower', cmap='cubehelix') plt.xlabel('X') plt.ylabel('Y') x_array = np.arange(0, 1000) line_1 = 1 * x_array + 20 * np.sin(0.05*x_array) line_2 = x_array - 100 + 20 * np.sin(0.05*x_array) plt.plot(x_array, line_1, color='red') plt.plot(x_array, line_2, color='red') ax.set_xlim(0, hdu.shape[1]) ax.set_ylim(0, hdu.shape[0]) plt.show() </code></pre> <p>I would like to calculate the median pixel value (in y direction for example) which lies between the two curves:</p> <p><a href="http://i.stack.imgur.com/5QvFz.png" rel="nofollow"><img src="http://i.stack.imgur.com/5QvFz.png" alt="enter image description here"></a></p> <p>I believe the clever thing would be to create a mask for the region of interest.</p> <p>Is there a way to generate this mask without looping across the image pixels?</p> <p>Edit 1: Modified question improve understanding</p> <p>Edit 2: I changed the example to better represent the question title (curves instead of straight lines)</p>
2
2016-10-05T23:15:49Z
39,885,536
<p>A fairly straight forward way of generating such a mask would be to use the <code>numpy.mgrid</code> thingy that essentially gives you x and y-coordinate arrays (in that 2D case) that can then be used to compute the mask with the equation of the lines . </p> <p><strong>Edit :</strong> Provided you can express your mask using an equation (like <code>f(x,y)&lt;0</code> where f is any function you want) or a combination of those equations, you can do anything you want. Here is an example with your new mask along with some extra art pieces: </p> <pre><code>import numpy as np import matplotlib.pyplot as plt y,x=np.mgrid[0:1000,0:1000] #a wiggly ramp plt.subplot(221) mask0=(y &lt; x + 20 * np.sin(0.05*x)) &amp; (y &gt; x - 100 + 20 * np.sin(0.05*x)) plt.imshow(mask0,origin='lower',cmap='gray') #a ramp plt.subplot(222) mask1=(y &lt; x) &amp; (x &lt; y+100) plt.imshow(mask1,origin='lower',cmap='gray') #a disk plt.subplot(223) mask2=(200**2&gt;(x-500)**2+(y-500)**2) plt.imshow(mask2,origin='lower',cmap='gray') #a ying-yang attempt plt.subplot(224) mask3= (mask2 &amp; (0 &lt; np.sin(3.14*x/250)*100 + 500 - y) &amp; (30**2 &lt; (x-620)**2+(y-500)**2) )| (30**2 &gt; (x-380)**2+(y-500)**2) plt.imshow(mask3,origin='lower',cmap='gray') plt.show() </code></pre> <p>Output :</p> <p><a href="http://i.stack.imgur.com/VPK6w.png" rel="nofollow"><img src="http://i.stack.imgur.com/VPK6w.png" alt="Output"></a></p>
2
2016-10-06T00:08:49Z
[ "python", "numpy", "indexing", "mask", "scikit-image" ]
Mask an image (np.ndarray) section which lies between two curves
39,885,113
<p>Borrowing this example from astropy:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from astropy.io import fits from astropy.wcs import WCS from astropy.utils.data import download_file fits_file = 'http://data.astropy.org/tutorials/FITS-images/HorseHead.fits' image_file = download_file(fits_file, cache=True) hdu = fits.open(image_file)[0] wcs = WCS(hdu.header) fig = plt.figure() ax = fig.add_subplot(111) plt.imshow(hdu.data, origin='lower', cmap='cubehelix') plt.xlabel('X') plt.ylabel('Y') x_array = np.arange(0, 1000) line_1 = 1 * x_array + 20 * np.sin(0.05*x_array) line_2 = x_array - 100 + 20 * np.sin(0.05*x_array) plt.plot(x_array, line_1, color='red') plt.plot(x_array, line_2, color='red') ax.set_xlim(0, hdu.shape[1]) ax.set_ylim(0, hdu.shape[0]) plt.show() </code></pre> <p>I would like to calculate the median pixel value (in y direction for example) which lies between the two curves:</p> <p><a href="http://i.stack.imgur.com/5QvFz.png" rel="nofollow"><img src="http://i.stack.imgur.com/5QvFz.png" alt="enter image description here"></a></p> <p>I believe the clever thing would be to create a mask for the region of interest.</p> <p>Is there a way to generate this mask without looping across the image pixels?</p> <p>Edit 1: Modified question improve understanding</p> <p>Edit 2: I changed the example to better represent the question title (curves instead of straight lines)</p>
2
2016-10-05T23:15:49Z
39,886,055
<p>The code snippet below creates a mask, sets all values outside the mask to nan, and then uses NumPy's <code>nanmedian</code> to calculate the desired quantity along the direction indicated.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import gridspec from skimage.measure import grid_points_in_poly # Create test image N = 900 image = np.sin(np.linspace(0, 2 * np.pi, N * N).reshape((N, N)) ** 2) # Define the mask polygon poly = [[N, 0], [0, N], [100, N], [N, 100]] # Create the mask (True is inside the polygon) mask = grid_points_in_poly(image.shape, poly) # Set everything outside the mask to nan masked_image = image.copy() masked_image[~mask] = np.nan # Perform the required operation row_med = np.nanmedian(masked_image, axis=1) # The rest of the code is to visualize the result fig = plt.figure(figsize=(15, 10)) gs = gridspec.GridSpec(1, 3, width_ratios=(1, 1, 1/8)) ax0 = plt.subplot(gs[0]) ax1 = plt.subplot(gs[1]) ax2 = plt.subplot(gs[2]) ax0.imshow(image, cmap='gray') ax0.set_title('Input image') ax0.set_xlim(0, N) ax1.imshow(masked_image, cmap='gray') ax1.set_title('Masked image') ax1.set_xlim(0, N) ax2.plot(row_med, np.arange(N)) ax2.set_ylim([N, 0]) ax2.set_xlim([-1.5, 1.5]) ax2.set_title('Row median') plt.tight_layout() plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/axaZq.png" rel="nofollow"><img src="http://i.stack.imgur.com/axaZq.png" alt="Median along rows inside region of interest"></a></p>
4
2016-10-06T01:19:50Z
[ "python", "numpy", "indexing", "mask", "scikit-image" ]
How can I see the RGB channels of a given image with python?
39,885,178
<p>Imagine a I have an image and I want to split it and see the RGB channels. How can I do it using python?</p>
0
2016-10-05T23:21:49Z
39,885,418
<p>My favorite approach is using <a href="http://scikit-image.org/" rel="nofollow">scikit-image</a>. It is built on top of numpy/scipy and images are internally stored within numpy-arrays.</p> <p>Your question is a bit vague, so it's hard to answer. I don't know exactly what you want to do but will show you some code.</p> <h3>Test-image:</h3> <p>I will use <a href="http://www.colorwiki.com/images/0/0a/Photodisc.png" rel="nofollow">this test image</a>.</p> <h3>Code:</h3> <pre><code>import skimage.io as io import matplotlib.pyplot as plt # Read img = io.imread('Photodisc.png') # Split red = img[:, :, 0] green = img[:, :, 1] blue = img[:, :, 2] # Plot fig, axs = plt.subplots(2,2) cax_00 = axs[0,0].imshow(img) axs[0,0].xaxis.set_major_formatter(plt.NullFormatter()) # kill xlabels axs[0,0].yaxis.set_major_formatter(plt.NullFormatter()) # kill ylabels cax_01 = axs[0,1].imshow(red, cmap='Reds') fig.colorbar(cax_01, ax=axs[0,1]) axs[0,1].xaxis.set_major_formatter(plt.NullFormatter()) axs[0,1].yaxis.set_major_formatter(plt.NullFormatter()) cax_10 = axs[1,0].imshow(green, cmap='Greens') fig.colorbar(cax_10, ax=axs[1,0]) axs[1,0].xaxis.set_major_formatter(plt.NullFormatter()) axs[1,0].yaxis.set_major_formatter(plt.NullFormatter()) cax_11 = axs[1,1].imshow(blue, cmap='Blues') fig.colorbar(cax_11, ax=axs[1,1]) axs[1,1].xaxis.set_major_formatter(plt.NullFormatter()) axs[1,1].yaxis.set_major_formatter(plt.NullFormatter()) plt.show() # Plot histograms fig, axs = plt.subplots(3, sharex=True, sharey=True) axs[0].hist(red.ravel(), bins=10) axs[0].set_title('Red') axs[1].hist(green.ravel(), bins=10) axs[1].set_title('Green') axs[2].hist(blue.ravel(), bins=10) axs[2].set_title('Blue') plt.show() </code></pre> <h3>Output:</h3> <p><a href="http://i.stack.imgur.com/QrsKN.png" rel="nofollow"><img src="http://i.stack.imgur.com/QrsKN.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/RgIW2.png" rel="nofollow"><img src="http://i.stack.imgur.com/RgIW2.png" alt="enter image description here"></a></p> <h3>Comment</h3> <ul> <li>Output looks good: see for example the yellow flower, which has much green and red, but not much blue which is compatible with wikipedia's scheme from <a href="https://en.wikipedia.org/wiki/RGB_color_model" rel="nofollow">here</a>:</li> </ul> <p><a href="http://i.stack.imgur.com/afqqm.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/afqqm.jpg" alt="enter image description here"></a></p>
0
2016-10-05T23:54:07Z
[ "python", "image", "image-processing", "rgb" ]
Access folder that a custom python function resides in
39,885,180
<p>How do I access a folder that a python function resides in?</p> <p>For example, lets say that I have a N by 2 array of data. First column is the independent variable, and second is the dependent variable. I need to interpolate this data with different array of independent variable who's range is contained in the original independent variable. This procedure is used in multiple different codes with varying range of independent variables such that I do not want to copy this data file to multiple places. I would like to write a single function that achieves this, with the single copy of data inside the folder containing the function itself. </p> <p>My example attempts are:</p> <pre><code>import numpy as np from scipy.interpolate import splev, splrep def function(some_array): filepath = './file_path_in_the_function_folder.txt' some_data = np.loadtxt(filepath) interpolated_data = splev(some_array, splrep(some_data[:,0], some_data[:,1])) return interpolated_data </code></pre> <p>However, './' does not recognize the location of the function, rather it directs to the current working directory of the script that imports the function. How can I circumvent this problem?</p>
2
2016-10-05T23:22:35Z
39,885,367
<p>Like this: </p> <pre><code>import os my_dir = os.path.dirname(__file__) fname = 'file_path_in_the_function_folder.txt' filepath = os.path.join(my_dir, fname) </code></pre> <p>As explained in the <a href="https://docs.python.org/3/reference/datamodel.html?highlight=__file__" rel="nofollow">data model</a>, you can use the <code>__file__</code> name for getting the path of the current module. In python 3.4+ it's an absolute path, for earlier version you can't easily know if it's absolute or relative - but you usually needn't care, either.</p>
1
2016-10-05T23:48:04Z
[ "python" ]
urllib.request: Data Not Writing to Outfile
39,885,277
<p>I've got a script here which (ideally) iterates through multiple pages X of JSON data for each entity Y (in this case, multiple loans X for each team Y). The way that the api is constructed, I believe I must physically change a subdirectory within the URL in order to iterate through multiple entities. Here is the explicit documentation and URL:</p> <blockquote> <p>GET /teams/:id/loans </p> <p>Returns loans belonging to a particular team. Example <a href="http://api.kivaws.org/v1/teams/2/loans.json" rel="nofollow">http://api.kivaws.org/v1/teams/2/loans.json</a></p> <p>Parameters id(number) Required. The team ID for which to return loans. page(number) The page position of results to return. Default: 1 sort_by(string) The order by which to sort results. One of: oldest, newest Default: newest app_id(string) The application id in reverse DNS notation. ids_only(string) Return IDs only to make the return object smaller. One of: true, false Default: false Response<br> loan_listing – HTML , JSON , XML , RSS</p> <p>Status Production</p> </blockquote> <p>And here is my script, which does run and appear to extract the correct data, but <strong>doesn't seem to write any data to the outfile:</strong></p> <pre><code># -*- coding: utf-8 -*- import urllib.request as urllib import json import time # storing team loans dict. The key is the team id, en value is the list of lenders team_loans = {} url = "http://api.kivaws.org/v1/teams/" #teams_id range 1 - 11885 for i in range(1, 100): params = dict( id = i ) #i =1 try: handle = urllib.urlopen(str(url+str(i)+"/loans.json")) print(handle) except: print("Could not handle url") continue # reading response item_html = handle.read().decode('utf-8') # converting bytes to str data = str(item_html) # converting to json data = json.loads(data) # getting number of pages to crawl numPages = data['paging']['pages'] # deleting paging data data.pop('paging') # calling additional pages if numPages &gt;1: for pa in range(2,numPages+1,1): #pa = 2 handle = urllib.urlopen(str(url+str(i)+"/loans.json?page="+str(pa))) print("Pulling loan data from team " + str(i) + "...") # reading response item_html = handle.read().decode('utf-8') # converting bytes to str datatemp = str(item_html) # converting to json datatemp = json.loads(datatemp) #Pagings are redundant headers datatemp.pop('paging') # adding data to initial list for loan in datatemp['loans']: data['loans'].append(loan) time.sleep(2) # recording loans by team in dict team_loans[i] = data['loans'] if (data['loans']): print("===Data added to the team_loan dictionary===") else: print("!!!FAILURE to add data to team_loan dictionary!!!") # recorging data to file when 10 teams are read print("===Finished pulling from page " + str(i) + "===") if (int(i) % 10 == 0): outfile = open("team_loan.json", "w") print("===Now writing data to outfile===") json.dump(team_loans, outfile, sort_keys = True, indent = 2, ensure_ascii=True) outfile.close() else: print("!!!FAILURE to write data to outfile!!!") # compliance with API # of requests time.sleep(2) print ('Done! Check your outfile (team_loan.json)') </code></pre> <p>I know that may be a heady amount of code to throw in your faces, but it's a pretty sequential process.</p> <p>Again, this program is pulling the correct data, but it is <strong>not</strong> writing this data to the outfile. Can anyone understand why? </p>
0
2016-10-05T23:34:24Z
39,885,812
<p>For others who may read this post, the script does in face write data to an outfile. It was simply test code logic that was wrong. Ignore the print statements I have put into place.</p>
0
2016-10-06T00:46:46Z
[ "python", "json", "rest", "python-3.x", "urllib" ]
GtkFileChooserDialog does not act as modal
39,885,351
<p>I have a <a href="https://paste.gnome.org/pvxwgixip/lyrvkg" rel="nofollow">custom</a> <code>GtkFileChooserDialog</code> created with Glade. The <code>Modal</code> property is marked. I also have a <code>GtkFileChooserButton</code> that uses this <code>GtkFileChooserDialog</code> as its dialog:</p> <pre><code>class ImgChooserBttWithCapture(Gtk.FileChooserButton): """ The custom Gtk.FileChooserButton and Gtt.FileChooserDialog with a button for call capture app """ def __init__(self, cap_app_path): self.builder = Gtk.Builder.new_from_file( UIS_PATH + 'images_chooser_dialog.xml') self.chooser_dialog = self.builder.get_object('icd_photo_chsrdialog') super().__init__(dialog=self.chooser_dialog) self.cap_app_path = cap_app_path self.set_title('Selecione uma imagem') self.set_halign(Gtk.Align.START) self.set_valign(Gtk.Align.FILL) self.set_hexpand(True) self.set_tooltip_text('Clique para escolher uma nova imagem') self.set_local_only(False) handlers = {'onCaptureButtonClicked': self._on_capture_button_clicked} self.builder.connect_signals(handlers) def _on_capture_button_clicked(self, button): try: subprocess.call([self.cap_app_path]) except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError) as ex: self.builder.add_from_file(UIS_PATH + 'information_window.xml') msg_dialog = self.builder.get_object('iw_messagedialog') msg_dialog.set_title('Erro') msg_dialog.set_markup( '&lt;span size="12000"&gt;&lt;b&gt;Não foi possível abrir o aplicativo&lt;/b&gt;&lt;/span&gt;') msg_dialog.format_secondary_markup( 'O aplicativo de captura não está disponível.\nVerifique o caminho para o aplicativo de caputura em configurações.\n' + '&lt;span foreground="red"&gt;&lt;u&gt;' + str(ex) + '&lt;/u&gt;&lt;/span&gt;') msg_dialog.set_property('message-type', Gtk.MessageType.ERROR) msg_dialog.set_transient_for(self.chooser_dialog) self.builder.get_object('iw_message_image').set_from_file( 'views/uis/images/message_error.png') msg_dialog.run() msg_dialog.destroy() </code></pre> <p>But, when I click on the button, the dialog is not modal, that is, I can interact with the other window.</p>
0
2016-10-05T23:45:18Z
39,919,924
<p>Would <a href="http://stackoverflow.com/a/39873728/1981374">grabbing</a> the pointer work for you?</p> <pre><code>//pass all events to window apart LEAVE_NOTIFY_MASK MainWindow-&gt;set_events(GDK_EXPOSURE_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_MOTION_MASK | GDK_BUTTON1_MOTION_MASK | GDK_BUTTON2_MOTION_MASK | GDK_BUTTON3_MOTION_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_ENTER_NOTIFY_MASK | GDK_FOCUS_CHANGE_MASK | GDK_STRUCTURE_MASK | GDK_PROPERTY_CHANGE_MASK | GDK_VISIBILITY_NOTIFY_MASK | GDK_PROXIMITY_IN_MASK | GDK_PROXIMITY_OUT_MASK | GDK_SUBSTRUCTURE_MASK | GDK_SCROLL_MASK | GDK_TOUCH_MASK | GDK_SMOOTH_SCROLL_MASK | GDK_TOUCHPAD_GESTURE_MASK); MainWindow-&gt;set_modal(true); auto display = MainWindow-&gt;get_display(); auto window = MainWindow-&gt;get_window(); auto grabSuccess = display-&gt;get_default_seat()-&gt;grab(window, Gdk::SEAT_CAPABILITY_ALL, true); if(grabSuccess != Gdk::GRAB_SUCCESS) { std::clog&lt;&lt;"grab failed: "&lt;&lt;grabSuccess&lt;&lt;std::endl; } </code></pre>
0
2016-10-07T14:39:41Z
[ "python", "gtk", "gtk3", "pygobject" ]
Py installer, cannot add .txt files
39,885,354
<p>I'm fairly new with programming (and so with python) and the stackoverflow question/response system allowed me to resolve all my problems until now. However, I didn't find any post addressing directly my current issue, but have to admit that I don't really know what's wrong. Let me explain.</p> <p>I'm trying to make an executable file of a .py file using pyinstaller. There's no problem doing it with a simple .py program (using --onefile), but it does not work when it comes to a more complex program that uses other .py and .txt files. I know that I need to modify the spec file and tried many alternatives; adding hidden files for instance.</p> <p>Here's the files :</p> <ul> <li><strong>UpdatingStrategy.py</strong> (the target file to transform in executable)</li> <li>LPRfunctions.py (UpdatingStrategy.py imports functions from this file)</li> </ul> <p>The following .txt files are read by UpdatingStrategy.py</p> <ul> <li>Strategy_Observ.txt</li> <li>Strategy_Problems.txt</li> <li>Updating_Observ1.txt</li> <li>Updating_Observ2.txt</li> <li>Updating_Problems.txt</li> </ul> <p>Just to let you know, I'm using python3.5 and windows 10. Tell me if you need some extra information!</p> <p>Can someone tell me how to modify the spec file in order to make an executable file of UpdatingStrategy.py? And how to actually use the spec file properly? I have read the py installer documentation before but I lack so many key principles that I couldn't make it works.</p> <p>Thank you so much!</p>
0
2016-10-05T23:45:34Z
39,885,430
<p>after the line</p> <pre><code>a = Analysis( ... ) </code></pre> <p>add </p> <pre><code>a.datas += [ ("/absolute/path/to/some.txt","txt_files/some.txt","DATA"), ("/absolute/path/to/some2.txt","txt_files/some2.txt","DATA"), ("/absolute/path/to/some3.txt","txt_files/some3.txt","DATA"), ] </code></pre> <p>then in your program use the following to get the resource path of your txt files</p> <pre><code>def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.environ.get("_MEIPASS2",os.path.abspath(".")) return os.path.join(base_path, relative_path) ... txt_data = open(resource_path("txt_files/some.txt")).read() </code></pre> <p>make sure you build it like <code>python -m PyInstaller my_target.spec</code> ... do not call pyinstaller directly against your .py file after you have edited your spec file or it will overwrite your edited file...</p>
1
2016-10-05T23:54:45Z
[ "python", "python-3.x", "pyinstaller" ]
Beautifulsoup decompose()
39,885,359
<p>I'm trying to get rid of <code>&lt;script&gt;</code> tags and the content inside the tag utilizing beatifulsoup. I went to the documentation and seems to be a really simple function to call. More information about the function is <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#decompose" rel="nofollow">here</a>. Here is the content of the html page that I have parsed so far...</p> <pre><code>&lt;body class="pb-theme-normal pb-full-fluid"&gt; &lt;div class="pub_300x250 pub_300x250m pub_728x90 text-ad textAd text_ad text_ads text-ads text-ad-links" id="wp-adb-c" style="width: 1px !important; height: 1px !important; position: absolute !important; left: -10000px !important; top: -1000px !important; "&gt; &lt;/div&gt; &lt;div id="pb-f-a"&gt; &lt;/div&gt; &lt;div class="" id="pb-root"&gt; &lt;script&gt; (function(a){ TWP=window.TWP||{}; TWP.Features=TWP.Features||{}; TWP.Features.Page=TWP.Features.Page||{}; TWP.Features.Page.PostRecommends={}; TWP.Features.Page.PostRecommends.url="https://recommendation-hybrid.wpdigital.net/hybrid/hybrid-filter/hybrid.json?callback\x3d?"; TWP.Features.Page.PostRecommends.trackUrl="https://recommendation-hybrid.wpdigital.net/hybrid/hybrid-filter/tracker.json?callback\x3d?"; TWP.Features.Page.PostRecommends.profileUrl="https://usersegment.wpdigital.net/usersegments"; TWP.Features.Page.PostRecommends.canonicalUrl="" })(jQuery); &lt;/script&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>Imagine you have some web content like that and you have that in a BeautifulSoup object called <code>soup_html</code>. If I run <code>soup_html.script.decompose()</code> and them call the object <code>soup_html</code> the script tags still there. How I can get rid of the <code>&lt;script&gt;</code> and the content inside those tags?</p> <pre><code>markup = 'The html above' soup = BeautifulSoup(markup) html_body = soup.body soup.script.decompose() html_body </code></pre>
0
2016-10-05T23:46:26Z
39,904,439
<blockquote> <p><code>soup.script.decompose()</code></p> </blockquote> <p>This would remove a <em>single script element</em> from the "Soup" only. Instead, I think you meant to decompose all of them:</p> <pre><code>for script in soup("script"): script.decompose() </code></pre>
0
2016-10-06T19:44:19Z
[ "python", "python-3.x", "beautifulsoup" ]
Get python tcp server to send and recive messages once that are sent?
39,885,364
<p>I have been experimenting with network programing with python. To teach myself how to do this I have been playing with multiple versions of TCP chat servers and clients. My newest attempt has left me wondering what is wrong with the code I have just written. Only when a message has been sent from the client I have just created, does the other messages come in. I am not sure why this is happening. I have been searching online and I can't figure out why it is happening. All I do know is that it is not the servers mistake. I am certain that the problem is with the client I just created.</p> <pre><code>import socket, thread, threading, os def sendMsg(): Message = raw_input('[-]You:') s.send(Message) def recvMsg(): data = s.recv(buff) print(data) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = raw_input('[-]Target Ip-&gt; ') port = 5000 buff = 1024 try: s.connect((host, port)) except: print('[-]Failed to Connect') s.close() loop = True threads = [] while loop == True: try: t1 = threading.Thread(target=sendMsg()) threads.append(t1) t1.start() t2 = threading.Thread(target=recvMsg()) threads.append(t2) t2.start() except KeyboardInterrupt: print('\n') break s.close() os.system('clear') </code></pre> <p>Server code</p> <pre><code># Tcp Chat server import socket, select, os, time def broadcast_data (sock, message): for socket in CONNECTION_LIST: if socket != server_socket and socket != sock : try : socket.send(message) except : socket.close() CONNECTION_LIST.remove(socket) if __name__ == "__main__": CONNECTION_LIST = [] RECV_BUFFER = 4096 IP_MNG = '' PORT = 5000 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((IP_MNG, PORT)) server_socket.listen(10) CONNECTION_LIST.append(server_socket) print "[-]Connected To " + str(PORT) start = True while start == True: try: read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[]) for sock in read_sockets: if sock == server_socket: sockfd, addr = server_socket.accept() CONNECTION_LIST.append(sockfd) print "Client (%s, %s) connected" % addr broadcast_data(sockfd, "[-][%s:%s] entered room\n" % addr) else: try: data = sock.recv(RECV_BUFFER) if data: broadcast_data(sock, "\r" + '&lt;' + str(sock.getpeername()) + '&gt; ' + data) except: broadcast_data(sock, "Client (%s, %s) is offline" % addr) print "Client (%s, %s) is offline" % addr sock.close() CONNECTION_LIST.remove(sock) continue except KeyboardInterrupt: print('[-]Server Stopped') start = False server_socket.close() time.sleep(1) os.system('clear') </code></pre>
1
2016-10-05T23:47:33Z
39,936,234
<p>I am pretty new to socket programming, so this may be a shot in the darK:</p> <ul> <li>The client is generating a lot of threads reading and writing from a blocking socket. It looks like only a single operation can be performed at one time, a thread is blocking on a write or a thread is blocking on a read, since there is only one socket, all threads are operating on that single resource. You could have each thread you spawn open its own own socket connection write to it the read from it, which should address the issue. </li> <li>For the client, Are socket reads/writes thread safe?? <a href="http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid">Yes</a></li> <li><p>On the server should the <code>accept</code>ed connection be marked as non-blocking??</p> <p><code>sockfd, addr = server_socket.accept()</code></p> <p><code>sockfd.setblocking(0)</code></p></li> <li><p>On the server, do you need to manage when sockets are writable? It looks like sockets are written to as they become readable. I'd imagine that <code>socket.send</code> blocks during the readcall, so new connections aren't being handled during this time. <a href="https://pymotw.com/2/select/" rel="nofollow">Python module of the week</a> has awesome clear example of using <code>select</code> for non blocking servers</p></li> </ul>
0
2016-10-08T19:02:39Z
[ "python", "sockets", "tcp", "concurrency" ]
Pyinstaller not getting all modules - ImportError: No module named logilab.constraint
39,885,396
<p>I am trying to compile a python script into a .exe using Pyinstaller. I am using python 2.7, Pyinstaller 3.2 and windows 7.</p> <p>The script is using a module called "logilab", and another called "logilab.constraint".</p> <p>I have installed both modules succesfully using pip. The script runs fine, but when trying to run the .exe I get the following error:</p> <pre><code>Traceback (most recent call last): File "schedule_maker.py", line 1, in &lt;module&gt; ImportError: No module named logilab.constraint Failed to execute script schedule_maker </code></pre> <p>here is the Pyinstaller log:</p> <pre><code>490 INFO: PyInstaller: 3.2 490 INFO: Python: 2.7.11 490 INFO: Platform: Windows-7-6.1.7601-SP1 493 INFO: wrote c:\Scripts\Employee-Scheduler-master\schedule\schedule_maker.spe c 496 INFO: UPX is not available. 497 INFO: Extending PYTHONPATH with paths ['c:\\Scripts\\Employee-Scheduler-master\\schedule', 'C:\\Python27\\Lib\\site-packages', 'c:\\Scripts\\Employee-Scheduler-master\\schedule'] 498 INFO: checking Analysis 513 INFO: Building because pathex changed 514 INFO: Initializing module dependency graph... 519 INFO: Initializing module graph hooks... 595 INFO: running Analysis out00-Analysis.toc 608 INFO: Adding Microsoft.VC90.CRT to dependent assemblies of final executable required by C:\Python27\python.exe 692 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.21022.8_none_60a5df56e60dc5df.manifest 710 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.1_none_8550c6b5d18a9128.manifest 715 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.4148_none_f47e1bd6f6571810.manifest 727 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.4940_none_f47ed0f6f6564d90.manifest 812 INFO: Searching for assembly x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.307 29.4940_none ... 812 INFO: Found manifest C:\WINDOWS\WinSxS\Manifests\x86_microsoft.vc90.crt_1fc8 b3b9a1e18e3b_9.0.30729.4940_none_50916076bcb9a742.manifest 825 INFO: Searching for file msvcr90.dll 825 INFO: Found file C:\WINDOWS\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9 .0.30729.4940_none_50916076bcb9a742\msvcr90.dll 825 INFO: Searching for file msvcp90.dll 826 INFO: Found file C:\WINDOWS\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9 .0.30729.4940_none_50916076bcb9a742\msvcp90.dll 826 INFO: Searching for file msvcm90.dll 826 INFO: Found file C:\WINDOWS\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9 .0.30729.4940_none_50916076bcb9a742\msvcm90.dll 904 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.21022.8_none_60a5df56e60dc5df.manifest 907 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.1_none_8550c6b5d18a9128.manifest 908 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.4148_none_f47e1bd6f6571810.manifest 909 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.4940_none_f47ed0f6f6564d90.manifest 911 INFO: Adding redirect Microsoft.VC90.CRT version (9, 0, 21022, 8) -&gt; (9, 0, 30729, 4940) 4608 INFO: Caching module hooks... 4611 INFO: Analyzing c:\Scripts\Employee-Scheduler-master\schedule\schedule_make r.py 6958 INFO: Loading module hooks... 6958 INFO: Loading module hook "hook-logilab.py"... 6963 INFO: Loading module hook "hook-encodings.py"... 8536 INFO: Looking for ctypes DLLs 8536 INFO: Analyzing run-time hooks ... 8543 INFO: Looking for dynamic libraries 9572 INFO: Looking for eggs 9572 INFO: Using Python library C:\WINDOWS\system32\python27.dll 9572 INFO: Found binding redirects: [BindingRedirect(name=u'Microsoft.VC90.CRT', language=None, arch=u'x86', oldVers ion=(9, 0, 21022, 8), newVersion=(9, 0, 30729, 4940), publicKeyToken=u'1fc8b3b9a 1e18e3b')] 9582 INFO: Warnings written to c:\Scripts\Employee-Scheduler-master\schedule\bui ld\schedule_maker\warnschedule_maker.txt 9622 INFO: checking PYZ 9692 INFO: checking PKG 9695 INFO: Building because c:\Scripts\Employee-Scheduler-master\schedule\build\ schedule_maker\schedule_maker.exe.manifest changed 9697 INFO: Building PKG (CArchive) out00-PKG.pkg 9951 INFO: Redirecting Microsoft.VC90.CRT version (9, 0, 21022, 8) -&gt; (9, 0, 307 29, 4940) 11652 INFO: Bootloader C:\Python27\lib\site-packages\pyinstaller-3.2-py2.7.egg\P yInstaller\bootloader\Windows-32bit\run.exe 11654 INFO: checking EXE 11655 INFO: Rebuilding out00-EXE.toc because pkg is more recent 11657 INFO: Building EXE from out00-EXE.toc 11657 INFO: Appending archive to EXE c:\Scripts\Employee-Scheduler-master\schedu le\dist\schedule_maker.exe </code></pre> <p>I am using the following command to build:</p> <pre><code>pyinstaller --onefile schedule_maker.py </code></pre> <p>I tried adding the installation path for logilab.constraint in the command:</p> <pre><code>pyinstaller --onefile --paths=C:\Python27\Lib\site-packages\ schedule_maker.py </code></pre> <p>Any ideas? Am I missing something?</p>
0
2016-10-05T23:51:34Z
39,885,444
<p>on the first line of your script(schedule_maker.py) just add</p> <pre><code>import logilib import logilib.constraint </code></pre> <p>basically pyinstallers analysis probably didnt realize that you needed that package</p>
0
2016-10-05T23:56:53Z
[ "python", "python-2.7", "module", "pyinstaller" ]
Pyinstaller not getting all modules - ImportError: No module named logilab.constraint
39,885,396
<p>I am trying to compile a python script into a .exe using Pyinstaller. I am using python 2.7, Pyinstaller 3.2 and windows 7.</p> <p>The script is using a module called "logilab", and another called "logilab.constraint".</p> <p>I have installed both modules succesfully using pip. The script runs fine, but when trying to run the .exe I get the following error:</p> <pre><code>Traceback (most recent call last): File "schedule_maker.py", line 1, in &lt;module&gt; ImportError: No module named logilab.constraint Failed to execute script schedule_maker </code></pre> <p>here is the Pyinstaller log:</p> <pre><code>490 INFO: PyInstaller: 3.2 490 INFO: Python: 2.7.11 490 INFO: Platform: Windows-7-6.1.7601-SP1 493 INFO: wrote c:\Scripts\Employee-Scheduler-master\schedule\schedule_maker.spe c 496 INFO: UPX is not available. 497 INFO: Extending PYTHONPATH with paths ['c:\\Scripts\\Employee-Scheduler-master\\schedule', 'C:\\Python27\\Lib\\site-packages', 'c:\\Scripts\\Employee-Scheduler-master\\schedule'] 498 INFO: checking Analysis 513 INFO: Building because pathex changed 514 INFO: Initializing module dependency graph... 519 INFO: Initializing module graph hooks... 595 INFO: running Analysis out00-Analysis.toc 608 INFO: Adding Microsoft.VC90.CRT to dependent assemblies of final executable required by C:\Python27\python.exe 692 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.21022.8_none_60a5df56e60dc5df.manifest 710 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.1_none_8550c6b5d18a9128.manifest 715 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.4148_none_f47e1bd6f6571810.manifest 727 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.4940_none_f47ed0f6f6564d90.manifest 812 INFO: Searching for assembly x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.307 29.4940_none ... 812 INFO: Found manifest C:\WINDOWS\WinSxS\Manifests\x86_microsoft.vc90.crt_1fc8 b3b9a1e18e3b_9.0.30729.4940_none_50916076bcb9a742.manifest 825 INFO: Searching for file msvcr90.dll 825 INFO: Found file C:\WINDOWS\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9 .0.30729.4940_none_50916076bcb9a742\msvcr90.dll 825 INFO: Searching for file msvcp90.dll 826 INFO: Found file C:\WINDOWS\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9 .0.30729.4940_none_50916076bcb9a742\msvcp90.dll 826 INFO: Searching for file msvcm90.dll 826 INFO: Found file C:\WINDOWS\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9 .0.30729.4940_none_50916076bcb9a742\msvcm90.dll 904 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.21022.8_none_60a5df56e60dc5df.manifest 907 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.1_none_8550c6b5d18a9128.manifest 908 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.4148_none_f47e1bd6f6571810.manifest 909 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1f c8b3b9a1e18e3b_9.0.30729.4940_none_f47ed0f6f6564d90.manifest 911 INFO: Adding redirect Microsoft.VC90.CRT version (9, 0, 21022, 8) -&gt; (9, 0, 30729, 4940) 4608 INFO: Caching module hooks... 4611 INFO: Analyzing c:\Scripts\Employee-Scheduler-master\schedule\schedule_make r.py 6958 INFO: Loading module hooks... 6958 INFO: Loading module hook "hook-logilab.py"... 6963 INFO: Loading module hook "hook-encodings.py"... 8536 INFO: Looking for ctypes DLLs 8536 INFO: Analyzing run-time hooks ... 8543 INFO: Looking for dynamic libraries 9572 INFO: Looking for eggs 9572 INFO: Using Python library C:\WINDOWS\system32\python27.dll 9572 INFO: Found binding redirects: [BindingRedirect(name=u'Microsoft.VC90.CRT', language=None, arch=u'x86', oldVers ion=(9, 0, 21022, 8), newVersion=(9, 0, 30729, 4940), publicKeyToken=u'1fc8b3b9a 1e18e3b')] 9582 INFO: Warnings written to c:\Scripts\Employee-Scheduler-master\schedule\bui ld\schedule_maker\warnschedule_maker.txt 9622 INFO: checking PYZ 9692 INFO: checking PKG 9695 INFO: Building because c:\Scripts\Employee-Scheduler-master\schedule\build\ schedule_maker\schedule_maker.exe.manifest changed 9697 INFO: Building PKG (CArchive) out00-PKG.pkg 9951 INFO: Redirecting Microsoft.VC90.CRT version (9, 0, 21022, 8) -&gt; (9, 0, 307 29, 4940) 11652 INFO: Bootloader C:\Python27\lib\site-packages\pyinstaller-3.2-py2.7.egg\P yInstaller\bootloader\Windows-32bit\run.exe 11654 INFO: checking EXE 11655 INFO: Rebuilding out00-EXE.toc because pkg is more recent 11657 INFO: Building EXE from out00-EXE.toc 11657 INFO: Appending archive to EXE c:\Scripts\Employee-Scheduler-master\schedu le\dist\schedule_maker.exe </code></pre> <p>I am using the following command to build:</p> <pre><code>pyinstaller --onefile schedule_maker.py </code></pre> <p>I tried adding the installation path for logilab.constraint in the command:</p> <pre><code>pyinstaller --onefile --paths=C:\Python27\Lib\site-packages\ schedule_maker.py </code></pre> <p>Any ideas? Am I missing something?</p>
0
2016-10-05T23:51:34Z
39,909,502
<p>Apparently just installing the modules from their "setup.py" file was not enough, I had to </p> <pre><code>pip install --upgrade </code></pre> <p>on both of them. that fixed it.</p>
0
2016-10-07T04:39:42Z
[ "python", "python-2.7", "module", "pyinstaller" ]
Finding the same second elements in nested lists - recursive function
39,885,472
<p>I have nested lists looks like this;</p> <pre><code>[['CELTIC AMBASSASDOR', 'Warrenpoint'],['HAV SNAPPER', 'Silloth'],['BONAY', 'Antwerp'],['NINA', 'Antwerp'],['FRI SKIEN', 'Warrenpoint']] </code></pre> <p>and goes on. How can I find the lists that have same second elements, for example</p> <pre><code>['CELTIC AMBASSASDOR', 'Warrenpoint'] ['FRI SKIEN', 'Warrenpoint'] ['BONAY', 'Antwerp'] ['NINA', 'Antwerp'] </code></pre> <p>The list is too long (I'm reading it from a .csv file) and I can't determine to search which thing exactly (eg: I can't search for 'Antwerp' to find all Antwerps because I don't know all of the texts in csv file), so I thought I need a recursive function that will search until find the all nested lists seperated by second items. Couldn't figure out how to make the recursive function, if anyone has a better solution, much appreciated.</p>
-1
2016-10-05T23:59:57Z
39,885,526
<p>There's no need to use recursion here. Create a dictionary with a key of the second element and values of the whole sublist, then create a result that only includes the matches you're interested in:</p> <pre><code>import collections l = [['CELTIC AMBASSASDOR', 'Warrenpoint'],['HAV SNAPPER', 'Silloth'],['BONAY', 'Antwerp'],['NINA', 'Antwerp'],['FRI SKIEN', 'Warrenpoint']] d = collections.defaultdict(list) for item in l: d[item[1]].append(item) result = dict(item for item in d.items() if len(d[item[0]]) &gt; 1) </code></pre> <p>Result:</p> <pre><code>&gt;&gt;&gt; import pprint &gt;&gt;&gt; pprint.pprint(result) {'Antwerp': [['BONAY', 'Antwerp'], ['NINA', 'Antwerp']], 'Warrenpoint': [['CELTIC AMBASSASDOR', 'Warrenpoint'], ['FRI SKIEN', 'Warrenpoint']]} </code></pre>
2
2016-10-06T00:07:46Z
[ "python", "list", "recursion", "python-3.4", "nested-lists" ]
Finding the same second elements in nested lists - recursive function
39,885,472
<p>I have nested lists looks like this;</p> <pre><code>[['CELTIC AMBASSASDOR', 'Warrenpoint'],['HAV SNAPPER', 'Silloth'],['BONAY', 'Antwerp'],['NINA', 'Antwerp'],['FRI SKIEN', 'Warrenpoint']] </code></pre> <p>and goes on. How can I find the lists that have same second elements, for example</p> <pre><code>['CELTIC AMBASSASDOR', 'Warrenpoint'] ['FRI SKIEN', 'Warrenpoint'] ['BONAY', 'Antwerp'] ['NINA', 'Antwerp'] </code></pre> <p>The list is too long (I'm reading it from a .csv file) and I can't determine to search which thing exactly (eg: I can't search for 'Antwerp' to find all Antwerps because I don't know all of the texts in csv file), so I thought I need a recursive function that will search until find the all nested lists seperated by second items. Couldn't figure out how to make the recursive function, if anyone has a better solution, much appreciated.</p>
-1
2016-10-05T23:59:57Z
39,886,638
<pre><code>filter(lambda x:x[1] in set(filter(lambda x:zip(*l)[1].count(x)==2,zip(*l)[1])),l) </code></pre>
0
2016-10-06T02:38:00Z
[ "python", "list", "recursion", "python-3.4", "nested-lists" ]
What is the meaning of single quote(') in matlab, and how to change it to python
39,885,495
<pre><code>grad = (1/m * (h-y)' * X) + lambda * [0;theta(2:end)]'/m; cost = 1/(m) * sum(-y .* log(h) - (1-y) .* log(1-h)) + lambda/m/2*sum(theta(2:end).^2); </code></pre> <p>How to change this two lines to python? I tried to use the <code>zip</code> to do the same job as '. But it shows the error. </p>
1
2016-10-06T00:02:59Z
39,902,500
<p><strong>Short answer:</strong></p> <p>The <code>'</code> operator in MATLAB is the <em>matrix</em> (conjugate) transpose operator. It flips the matrix around dimensions and takes the complex conjugate of the matrix (the second part being what trips people up) The short answer is that the equivalent of <code>a'</code> in Python is <code>np.atleast_2d(a).T.conj()</code>.</p> <p><strong>Slightly longer answer:</strong></p> <p>Don't use <code>'</code> in MATLAB unless you <em>really</em> know what you are doing. Use <code>.'</code>, which is the ordinary transpose. It is the equivalent of <code>np.atleast_2d(a).T</code> in Python (no conjugate). If you are sure that the <code>a.ndim &gt;= 2</code> in python, then you can just use <code>a.T</code>. If you are sure that <code>a.ndim == 1</code> in Python, you can use <code>a[None].T</code>. If you are sure that <code>a.ndim == 0</code> in Python then transposing is pointless so just do whatever you want.</p> <p><strong>Very Long Answer:</strong></p> <p>The basic idea about a transpose is that it flips an array or matrix around one dimension So consider this:</p> <pre><code>&gt;&gt; a=[1,2,3,4,5,6] a = 1 2 3 4 5 6 &gt;&gt; a' ans = 1 2 3 4 5 6 &gt;&gt; b=[1,2,3;4,5,6] b = 1 2 3 4 5 6 &gt;&gt; b' ans = 1 4 2 5 3 6 </code></pre> <p>So it seems pretty clear, <code>'</code> does a transpose. But that is deceiving:</p> <pre><code>c=[1j,2j,3j,4j,5j,6j] c = Columns 1 through 3 0.000000000000000 + 1.000000000000000i 0.000000000000000 + 2.000000000000000i 0.000000000000000 + 3.000000000000000i Columns 4 through 6 0.000000000000000 + 4.000000000000000i 0.000000000000000 + 5.000000000000000i 0.000000000000000 + 6.000000000000000i &gt;&gt; c' ans = 0.000000000000000 - 1.000000000000000i 0.000000000000000 - 2.000000000000000i 0.000000000000000 - 3.000000000000000i 0.000000000000000 - 4.000000000000000i 0.000000000000000 - 5.000000000000000i 0.000000000000000 - 6.000000000000000i </code></pre> <p>Where did all those negatives come from? They weren't in the original array. The reason for this is described in the <a href="https://www.mathworks.com/help/matlab/ref/ctranspose.html">documentation</a>. The <code>'</code> operator in MATLAB isn't a normal transpose operator, the normal transpose operator is <code>.'</code>. The <code>'</code> operator does a <em>complex conjugate</em> transpose. It does the transpose of the matrix and does the complex conjugate of that matrix. </p> <p>The problem is that this is almost never what you actually want. It will result in code that seems to work as expected, but silently changes your FFT data, for example. So unless you are absolutely, positively sure your algorithm requires a complex conjugate transpose, use <code>.'</code>.</p> <p>As for Python, the Python transpose operator is <code>.T</code>. So you consider this:</p> <pre><code>&gt;&gt;&gt; a = np.array([[1, 2, 3, 4, 5, 6]]) &gt;&gt;&gt; print(a) [[1 2 3 4 5 6]] &gt;&gt;&gt; print(a.T) [[1] [2] [3] [4] [5] [6]] &gt;&gt;&gt; b = np.array([[1j, 2j, 3j, 4j, 5j, 6j]]) [[ 0.+1.j 0.+2.j 0.+3.j 0.+4.j 0.+5.j 0.+6.j]] &gt;&gt;&gt; (1j*np.ones((1,10))).T [[ 0.+1.j] [ 0.+2.j] [ 0.+3.j] [ 0.+4.j] [ 0.+5.j] [ 0.+6.j]] </code></pre> <p>Notice the lack of any negatives for the imaginary part. If you want to get the complex conjugate transpose, you need to use <code>np.conj(a)</code> or <code>a.conj()</code> to get the complex conjugate (either before or after doing the transpose). However, numpy has its own transpose pitfall:</p> <pre><code>&gt;&gt;&gt; c = np.array([1, 2, 3, 4, 5, 6]) &gt;&gt;&gt; print(c) [1 2 3 4 5 6] &gt;&gt;&gt; print(c.T) [1 2 3 4 5 6] </code></pre> <p>Huh? It didn't do anything. The reason is that <code>np.array([1, 2, 3, 4, 5, 6])</code> creates a 1D array. A transpose is flipping the array along a particular dimension. That is meaningless when there is only one dimension, so the transpose doesn't do anything. </p> <p>"But," you might object, "didn't a transpose of the 1D MATLAB matrix work?" The reason is more fundamental to how MATLAB and numpy store data. Consider Python:</p> <pre><code>&gt;&gt;&gt; np.array([[1, 2, 3], [4, 5, 6]]).ndim 2 &gt;&gt;&gt; np.array([1, 2, 3, 4, 5, 6]).ndim 1 &gt;&gt;&gt; np.array(1).ndim 0 </code></pre> <p>That seems reasonable. A 2D array has two dimensions, a 1D array has one dimension, and a scalar has zero dimensions. But try the same thing in MATLAB:</p> <pre><code>&gt;&gt; ndims([1,2,3;4,5,6]) ans = 2 &gt;&gt; ndims([1,2,3,4,5,6]) ans = 2 &gt;&gt; ndims(1) ans = 2 </code></pre> <p>Everything has 2 dimensions! MATLAB has no 1D or 0D data structures, everything in MATLAB <em>must</em> have at least 2 dimensions (although it may be possible to create your own effectively 1D or 0D class in MATLAB). So taking the transpose of your "1D" data structure in MATLAB worked becaused it wasn't actually 1D.</p> <p>Both the conjugate transpose and the 1D transpose issues come down to the basic data type MATLB and numpy use. MATLAB uses matrices, which inherently are at least 2D. nump, on the other hand, uses arrays, which can have any number of dimensions. MATLAB matrices use matrix mathematics as their normal operations (so <code>a * b</code> in MATLAB is a matrix product) while Python arrays use element-by-element mathematics as their normal operators (so <code>a * b</code> is an element-by-element product, equivalent of <code>a .* b</code> in MATLAB). MATLAB has element-by-element operators, and numpy arrays have matrix operators (although no matrix transpose yet, though adding one is being considered), so this mostly applies to the default operations.</p> <p>To avoid this issue in Python, there are several ways to get around it. Indexing with <code>None</code> in Python inserts additional dimensions. So for a 1D array <code>a</code>, <code>a[None]</code> will be a 2D array where the first dimension has a length of <code>1</code>. If you don't know ahead of time what the dimensionality of your array is, you can use <code>np.atleast_2d(a)</code>, which will make sure <code>a</code> has at least two dimensions. So 0D becomes 2D, 1D becomes 2D, 2D stays 2D, 3D stays 3D, 4D stays 4D, etc.</p> <p>That being said, numpy has a matrix class that works the same as MATLAB's in all these regards (it even has a conjugate transpose operator, <code>.H</code>). <strong>Don't use it</strong>. The python community has standardized around arrays, since in practice that is almost always what you want. That means that most Python tools expect arrays, and many will either malfunction if given matrices or will convert them to arrays. So just use arrays.</p>
8
2016-10-06T17:45:18Z
[ "python", "matlab", "matrix", "transpose" ]
Searching for value in a text file then printing the next line
39,885,496
<p>I am importing a txt file into Python 3, I am able to successfully print the item/line I am using as an identifier, however I am having difficulty printing the following line and retaining that value. </p> <p>I am using <code>'Anchor'</code> to find the line items which follow. The number of lines between each <code>'Anchor'</code> varies, meaning sometimes there is junk/noise between <code>'Anchor'</code>, however the depth and distance from shore are always the same number of lines from Anchor. I tried to add 1 to line, as the if function lets me know that it is an <code>'Anchor'</code> value, however I get the following: </p> <pre><code>TypeError: Can't convert 'int' object to str implicitly </code></pre> <p>The file looks similar to:</p> <pre><code>asfasdfasdf Anchor The depth is 30 Feet 5 miles from shore asdfasdsf Anchor The depth is 24 feet 8 miles from shore Anchor The depth is 21 feet 4 km from shore </code></pre> <p>Attempting with the following code:</p> <pre><code>f = open('test.txt', 'r', encoding='utf8') for line in f.readlines(): if 'Anchor' in line: print(line+1) f.close() </code></pre>
1
2016-10-06T00:03:02Z
39,885,610
<p>You could introduce a variable representing the state of the last line, like this:</p> <pre><code>previous_line_was_anchor = False for line in f.readlines(): if 'Anchor' in line: previous_line_was_anchor = True else: if previous_line_was_anchor: print line previous_line_was_anchor = False </code></pre>
0
2016-10-06T00:17:50Z
[ "python", "file", "python-3.x" ]
Searching for value in a text file then printing the next line
39,885,496
<p>I am importing a txt file into Python 3, I am able to successfully print the item/line I am using as an identifier, however I am having difficulty printing the following line and retaining that value. </p> <p>I am using <code>'Anchor'</code> to find the line items which follow. The number of lines between each <code>'Anchor'</code> varies, meaning sometimes there is junk/noise between <code>'Anchor'</code>, however the depth and distance from shore are always the same number of lines from Anchor. I tried to add 1 to line, as the if function lets me know that it is an <code>'Anchor'</code> value, however I get the following: </p> <pre><code>TypeError: Can't convert 'int' object to str implicitly </code></pre> <p>The file looks similar to:</p> <pre><code>asfasdfasdf Anchor The depth is 30 Feet 5 miles from shore asdfasdsf Anchor The depth is 24 feet 8 miles from shore Anchor The depth is 21 feet 4 km from shore </code></pre> <p>Attempting with the following code:</p> <pre><code>f = open('test.txt', 'r', encoding='utf8') for line in f.readlines(): if 'Anchor' in line: print(line+1) f.close() </code></pre>
1
2016-10-06T00:03:02Z
39,914,720
<p>I would highly recommend using <a href="https://docs.python.org/2/library/stdtypes.html?highlight=iterator#iterator-types" rel="nofollow">python iterators</a>.</p> <p>It looks like your problem would be more suited to a custom iteration, rather than using a <code>for .. in ..</code> loop:</p> <pre><code>lines = iter(f.readlines()) while True: try: if next(lines) == 'Anchor': print(next(lines)) except StopIteration: break </code></pre> <p>If you need to print additional lines after 'Anchor' just add more <code>print(next(lines))</code> calls.</p>
0
2016-10-07T10:09:00Z
[ "python", "file", "python-3.x" ]
Finding the max of each continguous subarray of a given size
39,885,520
<p>I'm trying to solve the following problem in Python</p> <blockquote> <p>Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.</p> </blockquote> <p>The idea is to use a double ended queue. This is my code:</p> <pre><code>def diff_sliding_window(arr, win): # max = -inf Q = [] win_maxes = [] # max of each window for i in range(win): print(Q) while len(Q) &gt; 0 and arr[i] &gt;= arr[len(Q) - 1]: # get rid of the index of the smaller element Q.pop() # removes last element Q.append(i) # print('&gt;&gt;', Q) for i in range(win, len(arr)): # win_maxes.append(arr[Q[0]]) print(arr[Q[0]]) while len(Q) &gt; 0 and Q[0] &lt;= i - win: Q.pop() while len(Q) &gt; 0 and arr[i] &gt;= arr[len(Q)-1]: Q.pop(0) Q.append(i) # win_maxes.append(arr[Q[0]]) print(arr[Q[0]]) </code></pre> <p>But I can't figure out why for the test cases:</p> <pre><code>t1 = [1, 3, -1, -3, 5, 3, 6, 7] t2 = [12, 1, 78, 90, 57, 89, 56] </code></pre> <p>that I'm not getting the correct results.</p> <hr> <p><strong>Update</strong>:</p> <p>I've made the changes that Matt Timmermans suggested, but I'm still not obtaining the proper output. For <code>t2</code>, and <code>win = 3</code></p> <pre><code>78 90 90 89 &lt;--- should be 90 89 </code></pre> <p>Here is my updated code:</p> <pre><code>from collections import deque def diff_sliding_window(arr, win): # max = -inf Q = deque() win_maxes = [] # max of each window for i in range(win): # print(Q) while len(Q) &gt; 0 and arr[i] &gt;= arr[Q[len(Q)-1]]: # get rid of the index of the smaller element Q.pop() # removes last element Q.append(i) # print('&gt;&gt;', Q) for i in range(win, len(arr)): # win_maxes.append(arr[Q[0]]) print(arr[Q[0]]) while len(Q) &gt; 0 and Q[0] &lt;= i - win: Q.pop() while len(Q) &gt; 0 and arr[i] &gt;= arr[Q[len(Q)-1]]: Q.popleft() Q.append(i) print(arr[Q[0]]) </code></pre>
0
2016-10-06T00:07:10Z
39,885,747
<p>What about this approach (which only needs one pass over the data):</p> <h3>Code</h3> <pre><code>def calc(xs, k): k_max = [] result = [] for ind, val in enumerate(xs): # update local maxes (all are active) for i in range(len(k_max)): if val &gt; k_max[i] : k_max[i] = val # one new sub-array starts k_max.append(val) if ind &gt;= (k-1): # one sub-array ends result.append(k_max[0]) k_max.pop(0) return result t1 = [1, 3, -1, -3, 5, 3, 6, 7] t2 = [12, 1, 78, 90, 57, 89, 56] print(calc(t1, 3)) print(calc(t2, 2)) </code></pre> <h3>Output</h3> <pre><code>[3, 3, 5, 5, 6, 7] [12, 78, 90, 90, 89, 89] </code></pre>
0
2016-10-06T00:37:47Z
[ "python", "algorithm", "data-structures", "queue" ]
Finding the max of each continguous subarray of a given size
39,885,520
<p>I'm trying to solve the following problem in Python</p> <blockquote> <p>Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.</p> </blockquote> <p>The idea is to use a double ended queue. This is my code:</p> <pre><code>def diff_sliding_window(arr, win): # max = -inf Q = [] win_maxes = [] # max of each window for i in range(win): print(Q) while len(Q) &gt; 0 and arr[i] &gt;= arr[len(Q) - 1]: # get rid of the index of the smaller element Q.pop() # removes last element Q.append(i) # print('&gt;&gt;', Q) for i in range(win, len(arr)): # win_maxes.append(arr[Q[0]]) print(arr[Q[0]]) while len(Q) &gt; 0 and Q[0] &lt;= i - win: Q.pop() while len(Q) &gt; 0 and arr[i] &gt;= arr[len(Q)-1]: Q.pop(0) Q.append(i) # win_maxes.append(arr[Q[0]]) print(arr[Q[0]]) </code></pre> <p>But I can't figure out why for the test cases:</p> <pre><code>t1 = [1, 3, -1, -3, 5, 3, 6, 7] t2 = [12, 1, 78, 90, 57, 89, 56] </code></pre> <p>that I'm not getting the correct results.</p> <hr> <p><strong>Update</strong>:</p> <p>I've made the changes that Matt Timmermans suggested, but I'm still not obtaining the proper output. For <code>t2</code>, and <code>win = 3</code></p> <pre><code>78 90 90 89 &lt;--- should be 90 89 </code></pre> <p>Here is my updated code:</p> <pre><code>from collections import deque def diff_sliding_window(arr, win): # max = -inf Q = deque() win_maxes = [] # max of each window for i in range(win): # print(Q) while len(Q) &gt; 0 and arr[i] &gt;= arr[Q[len(Q)-1]]: # get rid of the index of the smaller element Q.pop() # removes last element Q.append(i) # print('&gt;&gt;', Q) for i in range(win, len(arr)): # win_maxes.append(arr[Q[0]]) print(arr[Q[0]]) while len(Q) &gt; 0 and Q[0] &lt;= i - win: Q.pop() while len(Q) &gt; 0 and arr[i] &gt;= arr[Q[len(Q)-1]]: Q.popleft() Q.append(i) print(arr[Q[0]]) </code></pre>
0
2016-10-06T00:07:10Z
39,885,772
<p>Here's a simple solution using <code>itertools</code> and <code>tee</code>:</p> <pre><code>def nwise(iterable, n): ''' Step through the iterable in groups of n ''' ts = it.tee(iterable, n) for c, t in enumerate(ts): next(it.islice(t, c, c), None) return zip(*ts) def max_slide(ns, l): return [max(a) for a in nwise(ns, l)] &gt;&gt;&gt; max_slide([1, 3, -1, -3, 5, 3, 6, 7], 3) [3, 3, 5, 5, 6, 7] &gt;&gt;&gt; max_slide([12, 1, 78, 90, 57, 89, 56], 3) [78, 90, 90, 90, 89] </code></pre>
0
2016-10-06T00:41:08Z
[ "python", "algorithm", "data-structures", "queue" ]
Finding the max of each continguous subarray of a given size
39,885,520
<p>I'm trying to solve the following problem in Python</p> <blockquote> <p>Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.</p> </blockquote> <p>The idea is to use a double ended queue. This is my code:</p> <pre><code>def diff_sliding_window(arr, win): # max = -inf Q = [] win_maxes = [] # max of each window for i in range(win): print(Q) while len(Q) &gt; 0 and arr[i] &gt;= arr[len(Q) - 1]: # get rid of the index of the smaller element Q.pop() # removes last element Q.append(i) # print('&gt;&gt;', Q) for i in range(win, len(arr)): # win_maxes.append(arr[Q[0]]) print(arr[Q[0]]) while len(Q) &gt; 0 and Q[0] &lt;= i - win: Q.pop() while len(Q) &gt; 0 and arr[i] &gt;= arr[len(Q)-1]: Q.pop(0) Q.append(i) # win_maxes.append(arr[Q[0]]) print(arr[Q[0]]) </code></pre> <p>But I can't figure out why for the test cases:</p> <pre><code>t1 = [1, 3, -1, -3, 5, 3, 6, 7] t2 = [12, 1, 78, 90, 57, 89, 56] </code></pre> <p>that I'm not getting the correct results.</p> <hr> <p><strong>Update</strong>:</p> <p>I've made the changes that Matt Timmermans suggested, but I'm still not obtaining the proper output. For <code>t2</code>, and <code>win = 3</code></p> <pre><code>78 90 90 89 &lt;--- should be 90 89 </code></pre> <p>Here is my updated code:</p> <pre><code>from collections import deque def diff_sliding_window(arr, win): # max = -inf Q = deque() win_maxes = [] # max of each window for i in range(win): # print(Q) while len(Q) &gt; 0 and arr[i] &gt;= arr[Q[len(Q)-1]]: # get rid of the index of the smaller element Q.pop() # removes last element Q.append(i) # print('&gt;&gt;', Q) for i in range(win, len(arr)): # win_maxes.append(arr[Q[0]]) print(arr[Q[0]]) while len(Q) &gt; 0 and Q[0] &lt;= i - win: Q.pop() while len(Q) &gt; 0 and arr[i] &gt;= arr[Q[len(Q)-1]]: Q.popleft() Q.append(i) print(arr[Q[0]]) </code></pre>
0
2016-10-06T00:07:10Z
39,886,533
<p>It looks like you are trying to implement the O(n) algorithm for this problem, which would be better than the other two answers here at this time.</p> <p>But, your implementation is incorrect. Where you say <code>arr[i] &gt;= arr[len(Q)-1]</code>, you <em>should</em> say <code>arr[i] &gt;= arr[Q[len(Q)-1]]</code> or <code>arr[i] &gt;= arr[Q[-1]]</code>. You also swapped the <code>pop</code> and <code>pop(0)</code> cases in the second loop. It looks like it will be correct after you fix those.</p> <p>Also, though, your algorithm is not O(n), because you using <code>Q.pop(0)</code>, which takes O(k) time. Your total running time is therefore O(kn) instead. Using a deque for <code>Q</code> will fix this.</p> <p>Here it is all fixed, with some comments to show how it works:</p> <pre><code>from collections import deque def diff_sliding_window(arr, win): if win &gt; len(arr): return [] win_maxes = [] # max of each window #Q contains indexes of items in the window that are greater than #all items to the right of them. This always includes the last item #in the window Q = deque() #fill Q for initial window for i in range(win): #remove anything that isn't greater than the new item while len(Q) &gt; 0 and arr[i] &gt;= arr[Q[-1]]: Q.pop() Q.append(i) win_maxes.append(arr[Q[0]]) for i in range(win, len(arr)): #remove indexes (at most 1, really) left of window while len(Q) &gt; 0 and Q[0] &lt;= (i-win): Q.popleft() #remove anything that isn't greater than the new item while len(Q) &gt; 0 and arr[i] &gt;= arr[Q[-1]]: Q.pop() Q.append(i) win_maxes.append(arr[Q[0]]) return win_maxes </code></pre> <p>try it: <a href="https://ideone.com/kQ1qsQ" rel="nofollow">https://ideone.com/kQ1qsQ</a></p> <p>Proof that this is O(N): Each iteration of the inner loops removes an item from Q. Since there are only <code>len(arr)</code> added to Q in total, there can be at most <code>len(arr)</code> <em>total</em> iterations of the inner loops.</p>
1
2016-10-06T02:24:43Z
[ "python", "algorithm", "data-structures", "queue" ]
getting scalar form dataframe
39,885,537
<p>how to retrieve single scalar from a pandas dataframe column using filtering on another. I am using .value[0] but I would like something better.</p> <pre><code>df['Age_in_years'][ df['Sample_id'] == id_sample ].values[0] df.loc[df['Sample_id'] == id_sample, 'Age_in_years'].values[0] </code></pre>
0
2016-10-06T00:08:52Z
39,885,620
<p>You can call <code>idxmax()</code> on the condition series, which returns:</p> <blockquote> <p>Index of first occurrence of maximum of values.</p> </blockquote> <p>Which in this case is the <em>Index of the first True</em>, and then use <code>loc</code> to find the corresponding value: </p> <pre><code>df = pd.DataFrame({'id': [1,2,3,4,5,6], 'value': [2,2,2,3,3,3]}) df # id value #0 1 2 #1 2 2 #2 3 2 #3 4 3 #4 5 3 #5 6 3 df.loc[(df.value == 3).idxmax(), 'id'] # 4 </code></pre>
1
2016-10-06T00:19:20Z
[ "python", "pandas" ]
Combining paths using os.path.join
39,885,557
<p>I was wondering how you correctly use os.path. Basically what I'm trying to do is ask the user for a directory and after that, they type a letter (<code>N</code> in this case), and then a filename in the directory and it will combine the directory with the file.</p> <p>For example:</p> <pre><code>C:\Desktop </code></pre> <p>and</p> <pre><code>N hello </code></pre> <p>The final result produced would be C:\Desktop\hello.</p> <pre><code>import os import os.path import shutil from pathlib import Path </code></pre> <p>': directory = input() search_files() directory1=search_characteristics(directory) #print(directory1)</p> <p>What am I doing wrong?</p>
0
2016-10-06T00:11:51Z
39,885,803
<p>Here, this should work.</p> <pre><code>def search_characteristics(directory): interesting = input() interesting = interesting.split(" ") if (interesting[0] == 'N'): directory += (os.sep + interesting[1]) print(directory) elif interesting.startswith('E'): return os.path.splitext(directory,'') else: print("Error") return search_characteristics(directory) </code></pre> <p>If you have to use os.path.join then you can replace the line with os.sep with:</p> <pre><code>directory = os.path.join(directory, interesting[1]) </code></pre>
0
2016-10-06T00:45:34Z
[ "python", "python-3.4", "os.path" ]
How do I distribute all contents of root directory to a directory with that name
39,885,637
<p>I have a project named <code>myproj</code> structured like</p> <pre><code>/myproj __init__.py module1.py module2.py setup.py </code></pre> <p>my <code>setup.py</code> looks like this</p> <pre><code>from distutils.core import setup setup(name='myproj', version='0.1', description='Does projecty stuff', author='Me', author_email='me@domain.com', packages=['']) </code></pre> <p>But this places <code>module1.py</code> and <code>module2.py</code> in the install directory. </p> <hr> <p>How do I specify <code>setup</code> such that the directory <code>/myproj</code> and all of it's contents are dropped into the install directory?</p>
2
2016-10-06T00:20:38Z
39,885,719
<p>In your <code>myproj</code> root directory for this project, you want to move <code>module1.py</code> and <code>module2.py</code> into a directory named <code>myproj</code> under that, and if you wish to maintain Python &lt; 3.3 compatibility, add a <code>__init__</code>.py into there.</p> <pre><code>├── myproj │   ├── __init__.py │   ├── module1.py │   └── module2.py └── setup.py </code></pre> <p>You may also consider using <a href="https://setuptools.readthedocs.io/en/latest/" rel="nofollow"><code>setuptools</code></a> instead of just distutils. <code>setuptools</code> provide a lot more helper methods and additional attributes that make setting up this file a lot easier. This is the bare minimum <code>setup.py</code> I would construct for the above project:</p> <pre><code>from setuptools import setup, find_packages setup(name='myproj', version='0.1', description="My project", author='me', author_email='me@example.com', packages=find_packages(), ) </code></pre> <p>Running the installation you should see lines like this:</p> <pre><code>copying build/lib.linux-x86_64-2.7/myproj/__init__.py -&gt; build/bdist.linux-x86_64/egg/myproj copying build/lib.linux-x86_64-2.7/myproj/module1.py -&gt; build/bdist.linux-x86_64/egg/myproj copying build/lib.linux-x86_64-2.7/myproj/module2.py -&gt; build/bdist.linux-x86_64/egg/myproj </code></pre> <p>This signifies that the setup script has picked up the required source files. Run the python interpreter (preferably outside this project directory) to ensure that those modules can be imported (not due to relative import).</p> <p>On the other hand, if you wish to provide those modules at the root level, you definitely need to declare <a href="https://docs.python.org/distutils/setupscript.html#listing-individual-modules" rel="nofollow"><code>py_modules</code></a> explicitly.</p> <p>Finally, the <a href="https://packaging.python.org/" rel="nofollow">Python Packaging User Guide</a> is a good resource for more specific questions anyone may have about building distributable python packages.</p>
1
2016-10-06T00:32:25Z
[ "python", "distutils", "setup.py" ]
Interpolating 2 numpy arrays
39,885,723
<p>Is there any numpy or scipy or python function to interpolate between two 2D numpy array's? I have two 2D numpy arrays, and I want to apply changes to the first numpy array to make it similar to the second 2D array. The constraint is that I want the changes to be smooth. e.g., let the arrays be:</p> <pre><code>A [[1 1 1 1 1 1 1 1 1]] </code></pre> <p>and</p> <pre><code>B [[34 100 15 62 17 87 17 34 60]] </code></pre> <p>To make A similar to B, I could add 33 to the first grid cell of <code>A</code> and so on.. However, to make the changes smoother, I plan to compute a mean using a 2x2 window on array <code>B</code> and then apply the resulting changes to array <code>A</code>. Is there a built in numpy or scipy method to do this or follow this approach without using for loop.</p>
3
2016-10-06T00:33:07Z
39,898,561
<p>One way of smoothing could be to use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html" rel="nofollow">convolve2d</a>:</p> <pre><code>import numpy as np from scipy import signal B = np.array([[34, 100, 15], [62, 17, 87], [17, 34, 60]]) kernel = np.full((2, 2), .25) smoothed = signal.convolve2d(B, kernel) # [[ 8.5 33.5 28.75 3.75] # [ 24. 53.25 54.75 25.5 ] # [ 19.75 32.5 49.5 36.75] # [ 4.25 12.75 23.5 15. ]] </code></pre> <p>The above pads the matrix with zeros from all sides and then calculates the mean of each 2x2 window placing the value at the center of the window.</p> <p>If the matrices were actually larger, then using a 3x3 kernel (such as <code>np.full((3, 3), 1/9)</code>) and passing <code>mode='same'</code> to <code>convolve2d</code> would give a smoothed <code>B</code> with its shape preserved and elements "matching" the original. Otherwise you may need to decide what to do with the boundary values to make the shapes the same again.</p> <p>To move <code>A</code> towards the smoothed <code>B</code>, it can be set to a chosen affine combination of the matrices using standard arithmetic operations, for instance: <code>A = .2 * A + .8 * smoothed</code>.</p>
1
2016-10-06T14:22:31Z
[ "python", "numpy" ]
Interpolating 2 numpy arrays
39,885,723
<p>Is there any numpy or scipy or python function to interpolate between two 2D numpy array's? I have two 2D numpy arrays, and I want to apply changes to the first numpy array to make it similar to the second 2D array. The constraint is that I want the changes to be smooth. e.g., let the arrays be:</p> <pre><code>A [[1 1 1 1 1 1 1 1 1]] </code></pre> <p>and</p> <pre><code>B [[34 100 15 62 17 87 17 34 60]] </code></pre> <p>To make A similar to B, I could add 33 to the first grid cell of <code>A</code> and so on.. However, to make the changes smoother, I plan to compute a mean using a 2x2 window on array <code>B</code> and then apply the resulting changes to array <code>A</code>. Is there a built in numpy or scipy method to do this or follow this approach without using for loop.</p>
3
2016-10-06T00:33:07Z
40,050,430
<p>You've just described a Kalman Filtering / data fusion problem. You have an initial state <strong>A</strong> that has some errors and you have some observations <strong>B</strong> that also have some noise. You want to improve your estimate of state <strong>A</strong> by injecting some information from <strong>B</strong>, all while accounting for spatially correlated errors in both datasets. We don't have any prior information about the errors in <strong>A</strong> and <strong>B</strong>, so we can just make it up. Here's an implementation:</p> <pre><code>import numpy as np # Make a matrix of the distances between points in an array def dist(M): nx = M.shape[0] ny = M.shape[1] x = np.ravel(np.tile(np.arange(nx),(ny,1))).reshape((nx*ny,1)) y = np.ravel(np.tile(np.arange(ny),(nx,1))).reshape((nx*ny,1)) n,m = np.meshgrid(x,y) d = np.sqrt((n-n.T)**2+(m-m.T)**2) return d # Turn a distance matrix into a covariance matrix. Here is a linear covariance matrix. def covariance(d,scaling_factor): c = (-d/np.amax(d) + 1)*scaling_factor return c A = np.array([[1,1,1],[1,1,1],[1,1,1]]) # background state B = np.array([[34,100,15],[62,17,87],[17,34,60]]) # observations x = np.ravel(A).reshape((9,1)) # vector representation y = np.ravel(B).reshape((9,1)) # vector representation P_a = np.eye(9)*50 # background error covariance matrix (set to diagonal here) P_b = covariance(dist(B),2) # observation error covariance matrix (set to a function of distance here) # Compute the Kalman gain matrix K = P_a.dot(np.linalg.inv(P_a+P_b)) x_new = x + K.dot(y-x) A_new = x_new.reshape(A.shape) print(A) print(B) print(A_new) </code></pre> <p>Now, this method only works if your data are unbiased. So mean(A) must equal mean(B). But you'll still get okay results regardless. Also, you can play with the covariance matrices however you like. I'd recommend reading the Kalman filter wikipedia page for more details. </p> <p>By the way, the example above yields:</p> <pre><code>[[ 27.92920141 90.65490699 7.17920141] [ 55.92920141 7.65490699 79.17920141] [ 10.92920141 24.65490699 52.17920141]] </code></pre>
1
2016-10-14T19:09:24Z
[ "python", "numpy" ]
Why do I only print the first letters of each item in the list?
39,885,741
<p>I was wondering why I only print the first letter of each item I input. I would like for it to loop through the list and print each item that starts with one of the letters in the first_letters variable. </p> <pre><code>phrase = input('Enter a list: ') first_letters = ['A','B','C','D'] for name in phrase: if name[0] in first_letters: print(name) #['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot'] </code></pre>
-3
2016-10-06T00:36:19Z
39,885,773
<p>What @idjaw meant to say was the input which is a string is an <code>iterable</code>.</p> <p>Which means when you run the for loop on <code>name</code> it iterates over each letter in the string passed.</p> <p>If you'd want to read a list or store the input as a list, it'd be best to store the result as a space or comma separated input.</p> <p>eg. </p> <pre><code>results_from_input = "abc def ghi" results = results_from_input.split(" ") print(results) #['abc', 'def', 'ghi'] </code></pre> <p>then you can iterate over results.</p>
0
2016-10-06T00:41:27Z
[ "python" ]
Why do I only print the first letters of each item in the list?
39,885,741
<p>I was wondering why I only print the first letter of each item I input. I would like for it to loop through the list and print each item that starts with one of the letters in the first_letters variable. </p> <pre><code>phrase = input('Enter a list: ') first_letters = ['A','B','C','D'] for name in phrase: if name[0] in first_letters: print(name) #['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot'] </code></pre>
-3
2016-10-06T00:36:19Z
39,885,775
<p>If this is Python3, then the list you are entering is not actually a list but a string. So when you call,</p> <pre><code>for name in phrase: </code></pre> <p>you are calling each letter in that string. So the variable <code>name</code> is actually one letter so <code>name[0]</code> is equal to <code>name</code>.</p>
0
2016-10-06T00:41:40Z
[ "python" ]
Why do I only print the first letters of each item in the list?
39,885,741
<p>I was wondering why I only print the first letter of each item I input. I would like for it to loop through the list and print each item that starts with one of the letters in the first_letters variable. </p> <pre><code>phrase = input('Enter a list: ') first_letters = ['A','B','C','D'] for name in phrase: if name[0] in first_letters: print(name) #['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot'] </code></pre>
-3
2016-10-06T00:36:19Z
39,885,855
<p>Considering your input as: </p> <pre><code>Alpha, Bravo, Charlie, Delta, Echo, Foxtrot </code></pre> <p>This complicates handling your input a bit. Because you are now going to have to deal with a space and a comma between each word.</p> <p>Upon entering your user input, handle all spaces, and then use <code>split</code> to actually obtain a list of your entries. So: </p> <pre><code>phrase = input('Enter a list: ').replace(' ', '').split(',') </code></pre> <p>phrase will now be a list that looks like:</p> <pre><code>['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot'] </code></pre> <p>It would probably easier to just handle a space separated list like: </p> <pre><code>Alpha Bravo Charlie Delta Echo Foxtrot </code></pre> <p>Then, you can just call <code>split()</code> without that <code>replace</code> method, and utilize its default split-on-space: </p> <pre><code>phrase = input('Enter a list: ').split() </code></pre> <p>Now you are iterating over your list and you can now check the first letter of each word with your <code>first_letters</code> list.</p> <p>To ensure you always compare to the exact same casing, make sure you call <code>upper()</code> for each iteration in your list, to compare to the same case in your list:</p> <pre><code>phrase = input('Enter a list: ').replace(' ', '').split(',') first_letters = ['A','B','C','D'] for name in phrase: if name[0].upper() in first_letters: print(name) </code></pre> <p>Output: </p> <pre><code>Alpha Bravo Charlie Delta </code></pre>
0
2016-10-06T00:52:25Z
[ "python" ]
Why do I only print the first letters of each item in the list?
39,885,741
<p>I was wondering why I only print the first letter of each item I input. I would like for it to loop through the list and print each item that starts with one of the letters in the first_letters variable. </p> <pre><code>phrase = input('Enter a list: ') first_letters = ['A','B','C','D'] for name in phrase: if name[0] in first_letters: print(name) #['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot'] </code></pre>
-3
2016-10-06T00:36:19Z
39,886,184
<p>For input Alpha,Bravo,Charlie,Delta,Echo,Foxtrot</p> <p>If you are entering comma after each name you enter use .split(',') if you are just using space between names use .split()</p> <p>.split() looks for an empty space and splits the user input after space and .split(',') looks for comma and splits the user input after finding comma.</p> <pre><code>phrase = input('Enter a list: ').split(',') first_letters = ['A','B','C','D'] for name in phrase: if name[0].upper() in first_letters: print(name) </code></pre> <p>To see the list of names</p> <pre><code>print(phrase) </code></pre> <p>it will show you the names in a list form after using .split() or .split(',')</p> <p>['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot']</p> <p><strong>Output:</strong></p> <pre><code>Alpha Bravo Charlie Delta </code></pre> <p>If you want the correct names even when you use lowercase letters use this code </p> <pre><code>phrase = input('Enter a list: ').split(',') first_letters = ['A','B','C','D','a','b','c','d'] for name in phrase: if name[0] in first_letters: print(name) </code></pre> <p>For input Alpha,Bravo,Charlie,Delta,Echo,Foxtrot,alpha,bravo,charlie,delta,echo,foxtrot</p> <p><strong>Output:</strong></p> <pre><code>Alpha Bravo Charlie Delta alpha bravo charlie delta </code></pre>
0
2016-10-06T01:39:08Z
[ "python" ]
Most efficient way to determine overlapping timeseries in Python
39,885,770
<p>I am trying to determine what percentage of the time that two time series overlap using python's pandas library. The data is nonsynchronous so the times for each data point do not line up. Here is an example:</p> <p><strong>Time Series 1</strong></p> <pre><code>2016-10-05 11:50:02.000734 0.50 2016-10-05 11:50:03.000033 0.25 2016-10-05 11:50:10.000479 0.50 2016-10-05 11:50:15.000234 0.25 2016-10-05 11:50:37.000199 0.50 2016-10-05 11:50:49.000401 0.50 2016-10-05 11:50:51.000362 0.25 2016-10-05 11:50:53.000424 0.75 2016-10-05 11:50:53.000982 0.25 2016-10-05 11:50:58.000606 0.75 </code></pre> <p><strong>Time Series 2</strong></p> <pre><code>2016-10-05 11:50:07.000537 0.50 2016-10-05 11:50:11.000994 0.50 2016-10-05 11:50:19.000181 0.50 2016-10-05 11:50:35.000578 0.50 2016-10-05 11:50:46.000761 0.50 2016-10-05 11:50:49.000295 0.75 2016-10-05 11:50:51.000835 0.75 2016-10-05 11:50:55.000792 0.25 2016-10-05 11:50:55.000904 0.75 2016-10-05 11:50:57.000444 0.75 </code></pre> <p>Assuming the series holds its value until the next change what is the most efficient way to determine the percentage of time that they have the same value? </p> <p><strong>Example</strong></p> <p>Lets calculate the time that these series overlap starting at 11:50:07.000537 and ending at 2016-10-05 11:50:57.000444 0.75 since we have data for both series for that period. Time that there is overlap:</p> <ul> <li>11:50:10.000479 - 11:50:15.000234 (both have a value of 0.5) <strong>4.999755 seconds</strong></li> <li>11:50:37.000199 - 11:50:49.000295 (both have a value of 0.5) <strong>12.000096 seconds</strong></li> <li>11:50:53.000424 - 11:50:53.000982 (both have a value of 0.75) <strong>0.000558 seconds</strong></li> <li>11:50:55.000792 - 11:50:55.000904 (both have a value of 0.25) <strong>0.000112 seconds</strong></li> </ul> <p>The result (4.999755+12.000096+0.000558+0.000112) / 49.999907 = <strong>34%</strong></p> <p>One of the issues is my actual timeseries has much more data such as 1000 - 10000 observations and I need to run many more pairs. I thought about forward filling a series and then simply comparing the rows and dividing the total number of matches over the total number of rows but I do not think this would be very efficient.</p>
6
2016-10-06T00:40:44Z
39,886,191
<p>Cool problem. I brute forced this w/out using pandas or numpy, but I got your answer (thanks for working it out). I have not tested it on anything else. I also don't know how fast it is since it only goes through each dataframe once, but does not do any vectorization.</p> <pre><code>import pandas as pd ############################################################################# #Preparing the dataframes times_1 = ["2016-10-05 11:50:02.000734","2016-10-05 11:50:03.000033", "2016-10-05 11:50:10.000479","2016-10-05 11:50:15.000234", "2016-10-05 11:50:37.000199","2016-10-05 11:50:49.000401", "2016-10-05 11:50:51.000362","2016-10-05 11:50:53.000424", "2016-10-05 11:50:53.000982","2016-10-05 11:50:58.000606"] times_1 = [pd.Timestamp(t) for t in times_1] vals_1 = [0.50,0.25,0.50,0.25,0.50,0.50,0.25,0.75,0.25,0.75] times_2 = ["2016-10-05 11:50:07.000537","2016-10-05 11:50:11.000994", "2016-10-05 11:50:19.000181","2016-10-05 11:50:35.000578", "2016-10-05 11:50:46.000761","2016-10-05 11:50:49.000295", "2016-10-05 11:50:51.000835","2016-10-05 11:50:55.000792", "2016-10-05 11:50:55.000904","2016-10-05 11:50:57.000444"] times_2 = [pd.Timestamp(t) for t in times_2] vals_2 = [0.50,0.50,0.50,0.50,0.50,0.75,0.75,0.25,0.75,0.75] data_1 = pd.DataFrame({"time":times_1,"vals":vals_1}) data_2 = pd.DataFrame({"time":times_2,"vals":vals_2}) ############################################################################# shared_time = 0 #Keep running tally of shared time t1_ind = 0 #Pointer to row in data_1 dataframe t2_ind = 0 #Pointer to row in data_2 dataframe #Loop through both dataframes once, incrementing either the t1 or t2 index #Stop one before the end of both since do +1 indexing in loop while t1_ind &lt; len(data_1.time)-1 and t2_ind &lt; len(data_2.time)-1: #Get val1 and val2 val1,val2 = data_1.vals[t1_ind], data_2.vals[t2_ind] #Get the start and stop of the current time window t1_start,t1_stop = data_1.time[t1_ind], data_1.time[t1_ind+1] t2_start,t2_stop = data_2.time[t2_ind], data_2.time[t2_ind+1] #If the start of time window 2 is in time window 1 if val1 == val2 and (t1_start &lt;= t2_start &lt;= t1_stop): shared_time += (min(t1_stop,t2_stop)-t2_start).total_seconds() t1_ind += 1 #If the start of time window 1 is in time window 2 elif val1 == val2 and t2_start &lt;= t1_start &lt;= t2_stop: shared_time += (min(t1_stop,t2_stop)-t1_start).total_seconds() t2_ind += 1 #If there is no time window overlap and time window 2 is larger elif t1_start &lt; t2_start: t1_ind += 1 #If there is no time window overlap and time window 1 is larger else: t2_ind += 1 #How I calculated the maximum possible shared time (not pretty) shared_start = max(data_1.time[0],data_2.time[0]) shared_stop = min(data_1.time.iloc[-1],data_2.time.iloc[-1]) max_possible_shared = (shared_stop-shared_start).total_seconds() #Print output print "Shared time:",shared_time print "Total possible shared:",max_possible_shared print "Percent shared:",shared_time*100/max_possible_shared,"%" </code></pre> <p>Output:</p> <pre><code>Shared time: 17.000521 Total possible shared: 49.999907 Percent shared: 34.0011052421 % </code></pre>
3
2016-10-06T01:39:39Z
[ "python", "performance", "pandas", "vector", "time-series" ]
Most efficient way to determine overlapping timeseries in Python
39,885,770
<p>I am trying to determine what percentage of the time that two time series overlap using python's pandas library. The data is nonsynchronous so the times for each data point do not line up. Here is an example:</p> <p><strong>Time Series 1</strong></p> <pre><code>2016-10-05 11:50:02.000734 0.50 2016-10-05 11:50:03.000033 0.25 2016-10-05 11:50:10.000479 0.50 2016-10-05 11:50:15.000234 0.25 2016-10-05 11:50:37.000199 0.50 2016-10-05 11:50:49.000401 0.50 2016-10-05 11:50:51.000362 0.25 2016-10-05 11:50:53.000424 0.75 2016-10-05 11:50:53.000982 0.25 2016-10-05 11:50:58.000606 0.75 </code></pre> <p><strong>Time Series 2</strong></p> <pre><code>2016-10-05 11:50:07.000537 0.50 2016-10-05 11:50:11.000994 0.50 2016-10-05 11:50:19.000181 0.50 2016-10-05 11:50:35.000578 0.50 2016-10-05 11:50:46.000761 0.50 2016-10-05 11:50:49.000295 0.75 2016-10-05 11:50:51.000835 0.75 2016-10-05 11:50:55.000792 0.25 2016-10-05 11:50:55.000904 0.75 2016-10-05 11:50:57.000444 0.75 </code></pre> <p>Assuming the series holds its value until the next change what is the most efficient way to determine the percentage of time that they have the same value? </p> <p><strong>Example</strong></p> <p>Lets calculate the time that these series overlap starting at 11:50:07.000537 and ending at 2016-10-05 11:50:57.000444 0.75 since we have data for both series for that period. Time that there is overlap:</p> <ul> <li>11:50:10.000479 - 11:50:15.000234 (both have a value of 0.5) <strong>4.999755 seconds</strong></li> <li>11:50:37.000199 - 11:50:49.000295 (both have a value of 0.5) <strong>12.000096 seconds</strong></li> <li>11:50:53.000424 - 11:50:53.000982 (both have a value of 0.75) <strong>0.000558 seconds</strong></li> <li>11:50:55.000792 - 11:50:55.000904 (both have a value of 0.25) <strong>0.000112 seconds</strong></li> </ul> <p>The result (4.999755+12.000096+0.000558+0.000112) / 49.999907 = <strong>34%</strong></p> <p>One of the issues is my actual timeseries has much more data such as 1000 - 10000 observations and I need to run many more pairs. I thought about forward filling a series and then simply comparing the rows and dividing the total number of matches over the total number of rows but I do not think this would be very efficient.</p>
6
2016-10-06T00:40:44Z
39,986,401
<p><strong><em>setup</em></strong><br> create 2 time series</p> <pre><code>from StringIO import StringIO import pandas as pd txt1 = """2016-10-05 11:50:02.000734 0.50 2016-10-05 11:50:03.000033 0.25 2016-10-05 11:50:10.000479 0.50 2016-10-05 11:50:15.000234 0.25 2016-10-05 11:50:37.000199 0.50 2016-10-05 11:50:49.000401 0.50 2016-10-05 11:50:51.000362 0.25 2016-10-05 11:50:53.000424 0.75 2016-10-05 11:50:53.000982 0.25 2016-10-05 11:50:58.000606 0.75""" s1 = pd.read_csv(StringIO(txt1), sep='\s{2,}', engine='python', parse_dates=[0], index_col=0, header=None, squeeze=True).rename('s1').rename_axis(None) txt2 = """2016-10-05 11:50:07.000537 0.50 2016-10-05 11:50:11.000994 0.50 2016-10-05 11:50:19.000181 0.50 2016-10-05 11:50:35.000578 0.50 2016-10-05 11:50:46.000761 0.50 2016-10-05 11:50:49.000295 0.75 2016-10-05 11:50:51.000835 0.75 2016-10-05 11:50:55.000792 0.25 2016-10-05 11:50:55.000904 0.75 2016-10-05 11:50:57.000444 0.75""" s2 = pd.read_csv(StringIO(txt2), sep='\s{2,}', engine='python', parse_dates=[0], index_col=0, header=None, squeeze=True).rename('s2').rename_axis(None) </code></pre> <hr> <p><strong><em>TL;DR</em></strong></p> <pre><code>df = pd.concat([s1, s2], axis=1).ffill().dropna() overlap = df.index.to_series().diff().shift(-1) \ .fillna(0).groupby(df.s1.eq(df.s2)).sum() overlap.div(overlap.sum()) False 0.666657 True 0.333343 Name: duration, dtype: float64 </code></pre> <hr> <p><strong><em>explanation</em></strong></p> <p><strong><em>build base <code>pd.DataFrame</code> <code>df</code></em></strong> </p> <ul> <li>use <code>pd.concat</code> to align indexes</li> <li>use <code>ffill</code> to let values propagate forward</li> <li>use <code>dropna</code> to get rid of values of one series prior to the other starting</li> </ul> <hr> <pre><code>df = pd.concat([s1, s2], axis=1).ffill().dropna() df </code></pre> <p><a href="https://i.stack.imgur.com/Kkebu.png"><img src="https://i.stack.imgur.com/Kkebu.png" alt="enter image description here"></a></p> <p><strong><em>calculate <code>'duration'</code></em></strong><br> from current time stamp to next</p> <pre><code>df['duration'] = df.index.to_series().diff().shift(-1).fillna(0) df </code></pre> <p><a href="https://i.stack.imgur.com/1ZkA5.png"><img src="https://i.stack.imgur.com/1ZkA5.png" alt="enter image description here"></a></p> <p><strong><em>calculate overlap</em></strong> </p> <ul> <li><code>df.s1.eq(df.s2)</code> gives boolean series of when <code>s1</code> overlaps with <code>s2</code></li> <li>use <code>groupby</code> above boolean series to aggregate total duration when <code>True</code> and <code>False</code></li> </ul> <hr> <pre><code>overlap = df.groupby(df.s1.eq(df.s2)).duration.sum() overlap False 00:00:33.999548 True 00:00:17.000521 Name: duration, dtype: timedelta64[ns] </code></pre> <p><strong><em>percentage of time with same value</em></strong></p> <pre><code>overlap.div(overlap.sum()) False 0.666657 True 0.333343 Name: duration, dtype: float64 </code></pre>
6
2016-10-11T20:43:21Z
[ "python", "performance", "pandas", "vector", "time-series" ]
Variable shape tensor
39,885,928
<p>I need to get a tensor that is variable shape as I do not know the vector size before hand. So far I tried: </p> <pre><code>hashtag_len = tf.placeholder(tf.int32) train_hashtag = tf.placeholder(tf.int32, shape=[hashtag_len]) </code></pre> <p>but I get the error <code>TypeError: int() argument must be a string, a bytes-like object or a number, not 'Tensor'</code>. </p> <p>The only other way around this that I can think of is to pad the vector with enough zeros so that I can fit the intended vector inside a giant vector. Seems like tensorflow should have a better way of doing this.</p>
1
2016-10-06T01:03:04Z
39,886,448
<p>Use</p> <p><code>tf.placeholder(tf.int32)</code></p> <p>That creates placeholder of arbitrary shape</p>
2
2016-10-06T02:12:11Z
[ "python", "tensorflow" ]
Variable shape tensor
39,885,928
<p>I need to get a tensor that is variable shape as I do not know the vector size before hand. So far I tried: </p> <pre><code>hashtag_len = tf.placeholder(tf.int32) train_hashtag = tf.placeholder(tf.int32, shape=[hashtag_len]) </code></pre> <p>but I get the error <code>TypeError: int() argument must be a string, a bytes-like object or a number, not 'Tensor'</code>. </p> <p>The only other way around this that I can think of is to pad the vector with enough zeros so that I can fit the intended vector inside a giant vector. Seems like tensorflow should have a better way of doing this.</p>
1
2016-10-06T01:03:04Z
39,893,341
<p>If you want a VECTOR for sure, you should do the following:</p> <pre><code>train_hashtag = tf.placeholder(tf.int32, shape=[None]) </code></pre> <p>This shape describes vector of arbitrary length.</p>
3
2016-10-06T10:15:29Z
[ "python", "tensorflow" ]
The bin count displayed by pyplot hist doesn't match the actual counts?
39,885,949
<p>I have a list of ints--I call it 'hours1'--ranging from 0-23. Now this list is for 'hours' of a day in a 24 hour clock. I, however, want to transform it to a different time zone (move up 7 hours). This is simple enough, and I do it so that now I have 2 lists: hours1 and hours2.</p> <p>I use the following code to plot a histogram:</p> <pre><code>bins = range(24) plt.hist(hours,bins=bins, normed=0, facecolor='red', alpha=0.5) plt.axis([0, 23, 0, 1000]) </code></pre> <p>it works perfectly for hours1. For hours2 the last value (that of the bin for 23s) is too high. This is not a counting error/transformation error because when I count my hours2 list, I get 604 23s, which matches the what I expect (having 604 16s in hours1).</p> <p>so this is a very long winded way of saying, the height of the bins do not match what I get when I count the data myself...</p>
0
2016-10-06T01:05:46Z
39,887,514
<p>The issue was a binning one. In short, I wasn't paying attention/thinking about what I wanted to display. More specifically this was the correct code:</p> <pre><code>bins = range(25) plt.hist(hours, normed=0, facecolor='green', alpha=0.5, bins=bins) plt.axis([0, 24, 0, 1500]) </code></pre> <p>that is, there are 23 hours in a day, which means 24 seperate 'hour bins' counting 0. but the correct edge values for this are bins = range(25) (so that 23 gets placed in 23-24) and the correct axis is 0 to 24, (so bin 23 has width of 1). simple mistake, but i guess we've all bin there and done that?</p>
0
2016-10-06T04:26:11Z
[ "python", "matplotlib" ]
Preserving Rich Text Formatting in Excel via Python
39,885,978
<p>I'm trying to add rows to an Excel file via Python (need this to run and refresh daily). The Excel file is essentially a template, at the top of which has some cells for some of the words within a cell have specific formatting, i.e. cell value "That cat is <strong><em>fluffy</em></strong>". </p> <p>I can't quite find a way to get Python+Excel to work together to preserve that formatting - it takes the format of the first letter in the cell and applies it across the board. </p> <p>From what I can tell, this is an issue with preserving rich text, but I haven't been able to find a package that can preserve rich text, read and write excel files. </p> <p>I followed this thread to come up with the code below: <a href="http://stackoverflow.com/questions/2725852/writing-to-existing-workbook-using-xlwt">writing to existing workbook using xlwt</a></p> <p>But, it looks like that copy step from the xlutils package isn't preserving the rich text formatting.</p> <pre><code>import xlwt import xlrd from xlutils.copy import copy rb = xlrd.open_workbook(templateFile,formatting_info=True) r_sheet = rb.sheet_by_index(0) wb = copy(rb) w_sheet = wb.get_sheet(0) xlsfile = Infile insheet = xlrd.open_workbook(xlsfile,formatting_info=True).sheets()[0] outrow_idx = 10 for row_idx in xrange(insheet.nrows): for col_idx in xrange(insheet.ncols): w_sheet.write(outrow_idx, col_idx, insheet.cell_value(row_idx, col_idx)) outrow_idx += 1 wb.save(Outfile) </code></pre>
1
2016-10-06T01:09:14Z
39,885,996
<p>Please refer to this link over here, as it may help you with keeping the formatting</p> <p><a href="http://stackoverflow.com/questions/3723793/preserving-styles-using-pythons-xlrd-xlwt-and-xlutils-copy">Preserving styles using python&#39;s xlrd,xlwt, and xlutils.copy</a></p> <p>though it doesn't keep the cell comments</p>
0
2016-10-06T01:13:20Z
[ "python", "excel" ]
Django not connecting to MySQL properly, throws "ImportError: cannot import name 'NULL'"
39,886,028
<p>I want to use Django (using Python 3) with MySQL. To do so, I installed <a href="https://pypi.python.org/pypi/mysqlclient" rel="nofollow">mysqlclient</a>. To first test the waters with MySQL, I also created a new Django project and app, changed the DATABASES configuration in "settings.py" to settings I prepared in MySQL, and ensured that MySQL server is running (the database I created for testing does not have any tables within it at this point). </p> <p>But when I do </p> <pre><code>python manage.py runserver </code></pre> <p>in terminal command, I get the following error:</p> <pre><code>ImportError: No module named '_mysql_exceptions' ImportError: No module named '_mysql_exceptions' Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x103efaea0&gt; Traceback (most recent call last): File "/Users/shtryts/Django-1.10.1/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/shtryts/Django-1.10.1/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Users/shtryts/Django-1.10.1/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Users/shtryts/Django-1.10.1/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/shtryts/Django-1.10.1/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/shtryts/Django-1.10.1/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/shtryts/Django-1.10.1/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/shtryts/Django-1.10.1/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 665, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "/Users/shtryts/Django-1.10.1/django/contrib/auth/models.py", line 4, in &lt;module&gt; from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/shtryts/Django-1.10.1/django/contrib/auth/base_user.py", line 52, in &lt;module&gt; class AbstractBaseUser(models.Model): File "/Users/shtryts/Django-1.10.1/django/db/models/base.py", line 119, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/shtryts/Django-1.10.1/django/db/models/base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "/Users/shtryts/Django-1.10.1/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Users/shtryts/Django-1.10.1/django/db/__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Users/shtryts/Django-1.10.1/django/db/utils.py", line 211, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/shtryts/Django-1.10.1/django/db/utils.py", line 115, in load_backend return import_module('%s.base' % backend_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/Users/shtryts/Django-1.10.1/django/db/backends/mysql/base.py", line 31, in &lt;module&gt; from MySQLdb.converters import Thing2Literal, conversions # isort:skip File "/Users/shtryts/.virtualenvs/django/lib/python3.5/site-packages/MySQLdb/converters.py", line 35, in &lt;module&gt; from _mysql import string_literal, escape_sequence, escape_dict, escape, NULL ImportError: cannot import name 'NULL' </code></pre> <p>Should I be modifying a .py file within MySQLdb folder? If so, what should I do so that the Django project properly connects with the database?</p> <p>I'm testing in a virtualenv, Mac OS X 10.10.3. Thanks in advance for the help. (Also, I did not find a similar question as mine, but apologies if this has been addressed here before). </p> <p>EDIT: I failed to share my DATABASE setting, so here it is. </p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test1', 'USER': 'admin', 'PASSWORD': 'dbadmin', 'HOST': 'localhost', 'PORT': '3306', } } </code></pre> <p>Settings.py, the django project I created for testing purposes, mysqlclient installs, django framework, they're all inside virtualenv. Originally, mysqlclient (includes MySQLdb) was installed via "pip install" under the path /Library/Frameworks/Python.framework/Versions/3.5... I made a copy of the installed folders and placed them under the python site-package folder within virtualenv. From what I understand Django does not have a problem locating those folders and files.</p> <p>which pip output: /Users/shtryts/.virtualenvs/django/bin/pip. And my own code is in .virtualenvs/django/test/mySQLtest</p>
1
2016-10-06T01:16:51Z
39,887,369
<p>Ok, there are several problems here.</p> <p>First of all you cannot copy files from one python installation or virtual installation to another python installation or virtualenv. Please delete your current virtualenv and make a new one, detailed instructions are here: <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">http://docs.python-guide.org/en/latest/dev/virtualenvs/</a></p> <p>but briefly</p> <pre><code>rm -rf /Users/shtryts/.virtualenvs/django virtualenv /Users/shtryts/.virtualenvs/myvirtualenv </code></pre> <p>I recommend not using django as the name of the virtualenv. Use a name that shows which version of python is being used. Now <strong>activate</strong> the virtualenv before going to the next step.</p> <p>Then you should install all the requirements with pip such as</p> <pre><code>pip install django </code></pre> <p>Please note that 'MysqlDB' is not compatible with python 3x please see here for details: <a href="https://docs.djangoproject.com/en/1.10/ref/databases/#mysql-db-api-drivers" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/databases/#mysql-db-api-drivers</a></p> <p>Last but not least. one does not put one's own code inisde the django installation folders. instead in your home or workspace</p> <pre><code>django-admin starproject myproject </code></pre>
0
2016-10-06T04:10:41Z
[ "python", "mysql", "django" ]
How to search datetime index and place None-values to another variables whenever it is weekend Python
39,886,037
<p>Say that I have a pandas <code>df</code> which contains financial time-series data with datetime index. An example: </p> <pre><code>x = ['10-06-2016', '10-07-2016', '10-10-2016', '10-11-2016', '10-12-2016'] y = [0,1,2,3,4] </code></pre> <p>Note that I don't have time-series values on weekends, which is why '10-08-2016' and '10-09-2016' are not printed on dataframe index. </p> <p>I wish to create a new <code>y</code> vector which places <code>None</code> in spots where weekends are.</p> <p>So ideal output:</p> <pre><code>x = ['10-06-2016', '10-07-2016', '10-08-2016', '10-09-2016', '10-10-2016', '10-11-2016', '10-12-2016'] y = [0,1,None,None,2,3,4] </code></pre> <p>What's the best way to accomplish this? Since <code>x</code> is not printing the weekends, how do I search <code>x</code> is weekend and then insert <code>None</code> values to <code>y</code>?</p>
0
2016-10-06T01:17:44Z
39,886,270
<p>You can <code>reindex</code> the data frame which has a <code>datetimeIndex</code> with a wider range of date as follows, missing values will be filled with <code>NaN</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Value': y}, index=pd.to_datetime(x)) # Value #2016-10-06 0 #2016-10-07 1 #2016-10-10 2 #2016-10-11 3 #2016-10-12 4 df.reindex(pd.date_range(start = df.index.min(), end = df.index.max())) # Value #2016-10-06 0.0 #2016-10-07 1.0 #2016-10-08 NaN #2016-10-09 NaN #2016-10-10 2.0 #2016-10-11 3.0 #2016-10-12 4.0 </code></pre>
0
2016-10-06T01:48:42Z
[ "python", "datetime", "pandas" ]
Writing to Multiple Files
39,886,038
<p>I'm sure many of us are familiar with the python file IO pattern to write data to an outfile, as seen below;</p> <pre><code>outfile = open("myFile", "w") data.dump() outfile.close() </code></pre> <p>This is all supposing that we already have the file and can access it. Now, I want to create something a bit more complicated.</p> <p>Say I have a for-loop that iterates through an integer i. Say the range is 1 - 1000, and for the sake of saving space and headaches I want to write data I have been saving up in my loop every time that i % 100 == 0. This should write ten files:</p> <pre><code>for i in range (1, 1001): #scrape data from API and store in some structure ... if i % 100 == 0: #Create a new outfile, open it, and write the data to it ?... </code></pre> <p>How would I go about, in python, automatically creating new files with unique names, and opening and closing them for writing data?</p>
-2
2016-10-06T01:17:53Z
39,886,057
<pre><code>&gt;&gt;&gt; my_list = [] &gt;&gt;&gt; for i in range(1, 1001): ... # do something with the data... in this case, simply appending i to a list ... my_list.append(i) ... if i % 100 == 0: ... # create a new file name... it's that easy! ... file = fname + str(i) + ".txt" ... # create the new file with "w+" as open it ... with open(file, "w+") as f: ... for item in my_list: ... # write each element in my_list to file ... f.write("%s" % str(item)) ... print(file) ... file100.txt file200.txt file300.txt file400.txt file500.txt file600.txt file700.txt file800.txt file900.txt file1000.txt </code></pre> <p>Fill in the blanks, but a simple string concatenation would do the trick.</p>
1
2016-10-06T01:20:15Z
[ "python", "file-io" ]
Overwriting Google Drive API v3 Argparse in Python
39,886,041
<p>I'm trying to use the Google Drive API (v3) with Python to obtain and upload files to my Google Drive account. </p> <p>I used this guide to setup my authentication: <a href="https://developers.google.com/drive/v3/web/quickstart/python" rel="nofollow">https://developers.google.com/drive/v3/web/quickstart/python</a></p> <p>But for my program, I would like to take commandline input for username, filename, and output_filename. I modified the google doc code and did the following:</p> <pre><code> from __future__ import print_function import httplib2 import os from sys import argv from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage from apiclient.http import MediaIoBaseDownload, MediaIoBaseUpload import io try: import argparse parser = argparse.ArgumentParser(description="I want your name, the file ID, and the folder you want to dump output to") parser.add_argument('-u', '--username', help='User Name', required=True) parser.add_argument('-f', '--filename', help='File Name', required=True) parser.add_argument('-d', '--dirname', help = 'Directory Name', required=True) flags = parser.parse_args() except ImportError: flags = None SCOPES = 'https://www.googleapis.com/auth/drive' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Drive API Python Quickstart' ...#rest of the code is from the Google Drive Documentation (see above) def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'drive-python-quickstart.json') store = Storage(credential_path) credentials = store.get() #Credentials returns NONE if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if args: credentials = tools.run_flow(flow, store) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) print("check") return credentials </code></pre> <p>The problem is that in the get_credentials method, there is a line that says:</p> <pre><code>if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) </code></pre> <p>The run_flow method though uses a different argparser that google wrote (see: <a href="http://oauth2client.readthedocs.io/en/latest/source/oauth2client.tools.html" rel="nofollow">http://oauth2client.readthedocs.io/en/latest/source/oauth2client.tools.html</a>)</p> <p>So whenever I run this script with my own inputs with username, filename, etc. I keep getting an error that says "Unrecognized Arguments". </p> <p>How do I make my argparser over-write the one in run_flow?</p> <p>EDIT:</p> <p>Someone suggested using parse_known_args().</p> <p>Well, I modified my code to parse by saying args, flags = parser.parse_known_args() because that way, any misc. inputs would go into flags. </p> <p>The idea is that if I run the script and give it my 3 args, it should pull them into "args". </p> <p>But the problem with this again is that later on when I call the run_flow method in get_credentials, it throws an error saying:</p> <blockquote> <p>Usage: name.py [--auth_host_name AUTH_HOST_NAME] [--noauth_local_webserver] [--auth_host_port [AUTH_HOST_PORT ...]]] [--logging_level {DEBUG, INFO, WARNING, ERROR, CRITICAL}] Unrecognized arguments: -u shishy -f fname -d random_name</p> </blockquote> <p>I think it's still passing my command line input to the get_info method and the parser there has no idea what to do with it...</p>
0
2016-10-06T01:18:35Z
39,886,896
<p>I think there have been other questions about <code>argparse</code> and the <code>google api</code>, but I haven't used the latter.</p> <p>Parsers are independent and can't be over written. But they all (as a default anyways) use <code>sys.argv[1:]</code>. So if your code runs before the other one, you can edit <code>sys.argv</code> to remove the extra strings. Using <code>parse_known_args</code> is a handy way of separating your arguments from ones the other parser(s) should use.</p> <p>Often the parser is invoked from a <code>if __name__</code> block. That way imported modules don't do parsing, only ones used as scripts. But I don't if the google api makes this distinction.</p>
0
2016-10-06T03:08:25Z
[ "python", "google-drive-sdk", "argparse", "oauth2" ]
Overwriting Google Drive API v3 Argparse in Python
39,886,041
<p>I'm trying to use the Google Drive API (v3) with Python to obtain and upload files to my Google Drive account. </p> <p>I used this guide to setup my authentication: <a href="https://developers.google.com/drive/v3/web/quickstart/python" rel="nofollow">https://developers.google.com/drive/v3/web/quickstart/python</a></p> <p>But for my program, I would like to take commandline input for username, filename, and output_filename. I modified the google doc code and did the following:</p> <pre><code> from __future__ import print_function import httplib2 import os from sys import argv from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage from apiclient.http import MediaIoBaseDownload, MediaIoBaseUpload import io try: import argparse parser = argparse.ArgumentParser(description="I want your name, the file ID, and the folder you want to dump output to") parser.add_argument('-u', '--username', help='User Name', required=True) parser.add_argument('-f', '--filename', help='File Name', required=True) parser.add_argument('-d', '--dirname', help = 'Directory Name', required=True) flags = parser.parse_args() except ImportError: flags = None SCOPES = 'https://www.googleapis.com/auth/drive' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Drive API Python Quickstart' ...#rest of the code is from the Google Drive Documentation (see above) def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'drive-python-quickstart.json') store = Storage(credential_path) credentials = store.get() #Credentials returns NONE if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if args: credentials = tools.run_flow(flow, store) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) print("check") return credentials </code></pre> <p>The problem is that in the get_credentials method, there is a line that says:</p> <pre><code>if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) </code></pre> <p>The run_flow method though uses a different argparser that google wrote (see: <a href="http://oauth2client.readthedocs.io/en/latest/source/oauth2client.tools.html" rel="nofollow">http://oauth2client.readthedocs.io/en/latest/source/oauth2client.tools.html</a>)</p> <p>So whenever I run this script with my own inputs with username, filename, etc. I keep getting an error that says "Unrecognized Arguments". </p> <p>How do I make my argparser over-write the one in run_flow?</p> <p>EDIT:</p> <p>Someone suggested using parse_known_args().</p> <p>Well, I modified my code to parse by saying args, flags = parser.parse_known_args() because that way, any misc. inputs would go into flags. </p> <p>The idea is that if I run the script and give it my 3 args, it should pull them into "args". </p> <p>But the problem with this again is that later on when I call the run_flow method in get_credentials, it throws an error saying:</p> <blockquote> <p>Usage: name.py [--auth_host_name AUTH_HOST_NAME] [--noauth_local_webserver] [--auth_host_port [AUTH_HOST_PORT ...]]] [--logging_level {DEBUG, INFO, WARNING, ERROR, CRITICAL}] Unrecognized arguments: -u shishy -f fname -d random_name</p> </blockquote> <p>I think it's still passing my command line input to the get_info method and the parser there has no idea what to do with it...</p>
0
2016-10-06T01:18:35Z
39,887,497
<p>Nevermind, I figured it out. hpaulj had it right.</p> <p>In the get_credentials() method, right before it called run_flow(), I simply had to add a line saying:</p> <pre><code>flags=tools.argparser.parse_args(args=[]) credentials=tools.run_flow(flow, store, flags) </code></pre> <p>And at the beginning when I read the command line with my inputs, I simply used parser_known_flags() as hpaulj suggested!</p> <p>Thanks, shishy</p>
0
2016-10-06T04:23:57Z
[ "python", "google-drive-sdk", "argparse", "oauth2" ]
Can I use a decorator to loop through nested list?
39,886,054
<p>I am having to loop through a 2-dimensional grid (rows and columns) repeatedly to execute various functions at each cell in the grid. Each time I want to apply another to the cells, I have to code the nested loop...</p> <pre><code>for row in rows: for col in row: func(col) </code></pre> <p>So to avoid repeating myself, I started with this (old school - Python 2.7.x)</p> <pre><code>#version 1 grid = [[1,2,3,],[4,5,6],[7,8,9]] def loop(grid,func): results = [] for row in grid: for col in row: results.append(func(col)) return results def func(x): return x+1 results = loop(grid,func) </code></pre> <p>output:</p> <pre><code>[2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>To me, passing a function as argument into another function smelled of a decorator use case. But I haven't figured out how to make it work - passing the grid argument into any wrapper function is tripping me up.</p> <p>The only improvement I've made to the above is using <code>map</code></p> <pre><code>#version 2 def func(x): return x+1 def loop(grid,func): return map(func,[col for row in grid for col in row]) </code></pre> <p>So my question is can it be done using a decorator and how? (<strong>Etiquette alert</strong>: Which is the better way?)</p>
0
2016-10-06T01:19:47Z
39,886,168
<p>Sure, you can write a decorator to transform a function that works on a single element into one that works on a grid using a nested loop:</p> <pre><code>def gridfunc(func): def wrapper(grid): results = [] for row in grid: for col in row: results.append(func(col)) return results return wrapper @gridfunc def foo(x): return x+1 grid = [[1,2,3,],[4,5,6],[7,8,9]] results = foo(grid) </code></pre> <p>The only downside to this is that the original function <code>foo</code> is not (easily) available if you want to run it on a single value rather than a grid of them. If you want to be able to use both versions, you could use <code>gridfoo = gridfunc(foo)</code> instead of the <code>@decorator</code> syntax.</p>
0
2016-10-06T01:37:26Z
[ "python", "decorator" ]
I keep getting an attribute error 'int' object has no attribute 'dollars'
39,886,063
<p>Im working on this Money class and everything worked fine up until the multiplication. I keep getting an attribute error and can't figure out where I'm going wrong. The multiplication is of type float.</p> <pre><code>class Money: def __init__(self, d, c): self.dollars = d self.cents = c def __str__(self): return '${}.{:02d}'.format(self.dollars, self.cents) def __repr__(self): return 'Money({},{})'.format(repr(self.dollars), self.cents) def add(self, other): d = self.dollars + other.dollars c = self.cents + other.cents while c &gt; 99: d += 1 c -= 100 return Money(d,c) def subtract(self, other): d = self.dollars - other.dollars c = self.cents - other.cents while c &lt; 0: d -= 1 c += 100 return Money(d,c) def times(self, mult): d = self.dollars * mult.dollars c = self.cents * mult.cents while c &gt; 99: d *= 1 c *= 100 return Money(d,c) &gt;&gt;&gt; m2 = Money(10,10) &gt;&gt;&gt; m2.times(3) Traceback (most recent call last): File "&lt;pyshell#51&gt;", line 1, in &lt;module&gt; m2.times(3) File "/Users/kylerbolden/Desktop/hw2.py", line 67, in times d = float(self.dollars) * float(mult.dollars) AttributeError: 'int' object has no attribute 'dollars' </code></pre>
0
2016-10-06T01:22:08Z
39,886,163
<p>In <code>m2.times(3)</code>, you're passing the <code>int</code> <code>3</code> to the <code>times</code> method. In the times method, though, you're trying to multiply by <code>mult.dollars</code>, and not the <code>dollars</code> (<code>3</code>) that you actually passed. </p> <p><code>mult.dollars</code> doesn't work like <code>self.dollars</code> would. In fact, it's not a valid construct at all. </p> <p>Try</p> <pre><code>&gt;&gt;&gt; class Money: ... def __init__(self, d, c): ... self.dollars = d ... self.cents = c ... def times(self, mult): ... d = self.dollars * mult ... c = self.cents * mult ... while c &gt; 99: ... d *= 1 ... c *= 100 ... return Money(d, c) </code></pre> <p>You'll obviously have to modify the rest of your code, as well.</p> <p>It seems you want to return a new <code>Money</code> object instead of a balance with each of these methods, but to demonstrate the point I made above:</p> <pre><code>&gt;&gt;&gt; class Money: ... def __init__(self, d, c): ... self.dollars = d ... self.cents = c ... def times(self, mult): ... d = self.dollars * mult ... c = self.cents * mult ... while c &gt; 99: ... d *= 1 ... c *= 100 ... return (d,c) ... &gt;&gt;&gt; m2 = Money(10, 10) &gt;&gt;&gt; m2.times(3) (30, 30) </code></pre> <p>Edit: Okay, the above doesn't seem to be what you're looking for, but I'll leave it for people running into a similar error. What you need to fix in your code is the <code>mult</code> object that you're trying to pass. Your <code>add</code> and <code>subtract</code> methods all have the same parameters: <code>self</code> and <code>other</code>, where <code>other</code> is another instance of the <code>Money</code> class, I presume. So, you're trying to multiply, add, or subtract different balances, basically? In that case, change the <code>mult.dollars</code> and <code>mult.cents</code> to <code>other.dollars</code> and <code>other.cents</code> so that you can access those attributes for another <code>Money</code> object.</p> <p>After changing that:</p> <pre><code>&gt;&gt;&gt; class Money: ... def __init__(self, d, c): ... self.dollars = d ... self.cents = c ... def times(self, other): ... d = self.dollars * other.dollars ... c = self.cents * other.cents ... while c &gt; 99: ... d *= 1 ... c *= 100 ... return Money(d,c) ... &gt;&gt;&gt; m2 = Money(2, 3) &gt;&gt;&gt; m3 = Money(4, 5) &gt;&gt;&gt; m2.times(m3) Money(8,15) </code></pre> <p>Also, you might want to look into the <code>d *= 1</code> and <code>c *= 100</code> lines, but that should answer your initial question.</p>
3
2016-10-06T01:36:26Z
[ "python", "class", "attributes" ]
Django How I can pass request.user(current logged user) in forms when I use class based view?
39,886,067
<p>I wanted to pass request.user to show current user in a form with ModelMultipleChoiceField. I could figure out my problem thanks to here <a href="http://stackoverflow.com/a/25184373/6568309">http://stackoverflow.com/a/25184373/6568309</a>. I fixed my code like below.</p> <p><strong>but I could get solution with only function based view.</strong> well, I kept using class based views because I could use generic views and it was recommended in first place. <strong>Is it way to pass request.user like below with class based view(to use FormView or ModelFormView)? Additionally, Is is normal to mix function based views and class based views to meet your need in Django?</strong></p> <p>thank you in advance.</p> <p>forms.py</p> <pre><code>class CustomForm(forms.Form): username = forms.CharField(initial='testname',max_length=150) email = forms.EmailField() phone_number = forms.CharField(max_length=15) position = forms.CharField(max_length=15) uperall = forms.ModelMultipleChoiceField(queryset=None) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(CustomForm, self).__init__(*args, **kwargs) self.fields['uperall'].queryset = User.objects.filter(username=user.username) </code></pre> <p>urls.py</p> <pre><code>urlpatterns = [ url(r'^$', UserList.as_view(), name='index'), url(r'^create/$', UserCreate.as_view(), name='create'), url(r'^test/$', TestView.as_view(), name='test'), url(r'^test1/$', views.ftestview, name='test1'), ] </code></pre> <p>views.py</p> <pre><code>def ftestview(request): if request.method == 'POST': form = CustomForm(request.POST, user=request.user) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] phone_number = form.cleaned_data['phone_number'] position = form.cleaned_data['position'] with transaction.atomic(): user = User.objects.create(username=username,email=email) userinfo = UserInfo.objects.create(user=user,phone=phone_number,position=position) userinfo.save() user.save() return HttpResponseRedirect('/success') else: form = CustomForm(user=request.user) return render(request, 'manager/alltoall.html', { 'form': form }) </code></pre> <p>according to answer from levi thanksfully. I changed my code like below</p> <p>views.py</p> <pre><code>class TestView(FormView): form_class = CustomForm template_name = 'manager/alltoall.html' def get_form_kwargs(self): user = self.request.user form_kwargs = super(TestView, self).get_form_kwargs() form_kwargs.update({'initial': {'uperall': User.objects.filter(username=user.username)}}) return form_kwargs def form_valid(self, form): username = form.cleaned_data['username'] email = form.cleaned_data['email'] phone_number = form.cleaned_data['phone_number'] position = form.cleaned_data['position'] with transaction.atomic(): user = User.objects.create(username=username,email=email) userinfo = UserInfo.objects.create(user=user,phone=phone_number,position=position) userinfo.save() user.save() return super(TestView, self).form_valid(form) </code></pre> <p>but I got error like below.</p> <pre><code>Environment: Request Method: GET Request URL: http://127.0.0.1:8000/manager/test/ Django Version: 1.10.1 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'manager.apps.ManagerConfig', 'mptt'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Jaemyun\django_real\apa\apa\manager\templates\manager\alltoall.html, error at line 9 'NoneType' object has no attribute 'all' 1 : &lt;select multiple="multiple" data-field-name="groups"&gt; 2 : &lt;option value="volvo"&gt;Volvo&lt;/option&gt; 3 : &lt;option value="hyundai"&gt;Hyundai&lt;/option&gt; 4 : &lt;/select&gt; 5 : 6 : &lt;form action="." method="post"&gt; 7 : {% csrf_token %} 8 : &lt;table&gt; 9 : {{ form }} 10 : &lt;/table&gt; 11 : &lt;input type="submit" value="Submit" /&gt; 12 : &lt;/form&gt; Traceback: File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render() File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\template\response.py" in render 109. self.content = self.rendered_content File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\template\response.py" in rendered_content 86. content = template.render(context, self._request) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\template\base.py" in render 208. return self._render(context) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\template\base.py" in render 994. bit = node.render_annotated(context) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\template\base.py" in render 1050. return render_value_in_context(output, context) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\template\base.py" in render_value_in_context 1028. value = force_text(value) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\utils\encoding.py" in force_text 76. s = six.text_type(s) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\utils\html.py" in &lt;lambda&gt; 391. klass.__str__ = lambda self: mark_safe(klass_str(self)) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\forms\forms.py" in __str__ 123. return self.as_table() File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\forms\forms.py" in as_table 271. errors_on_separate_row=False) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\forms\forms.py" in _html_output 226. 'field': six.text_type(bf), File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\utils\html.py" in &lt;lambda&gt; 391. klass.__str__ = lambda self: mark_safe(klass_str(self)) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\forms\boundfield.py" in __str__ 43. return self.as_widget() File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\forms\boundfield.py" in as_widget 101. return force_text(widget.render(name, self.value(), attrs=attrs)) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\forms\widgets.py" in render 610. options = self.render_options(value) File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\forms\widgets.py" in render_options 560. for option_value, option_label in self.choices: File "C:\Users\Jaemyun\django_real\apa\myenv\lib\site-packages\django\forms\models.py" in __iter__ 1114. queryset = self.queryset.all() Exception Type: AttributeError at /manager/test/ Exception Value: 'NoneType' object has no attribute 'all' </code></pre>
0
2016-10-06T01:22:26Z
39,886,111
<p>You can override method <code>get_form_kwargs</code> from <code>FormView</code> class view in order to set inital data for your form. </p> <pre><code>class YouFormView(FormView): teplate_name = 'your template' form_class = YourForm def get_form_kwargs(self): user = self.request.user form_kwargs = super(YouFormView, self).get_form_kwargs() form_kwargs.update({ 'initial': { 'uperall': User.objects.filter(username=user.username) } }) return form_kwargs </code></pre> <p>About mixing views: I recommend stick to class based view. </p>
1
2016-10-06T01:28:19Z
[ "python", "django" ]
Is there a way to make selenium webdriver screenshot an entire page?
39,886,081
<p>The title is pretty self explanatory. I have a page with an iframe and two columns (left and right)</p> <p>Left has no scroll bar, while right has a scroll bar with a total of 600px to scroll. I need to screenshot the entirety of the right hand column. It doesn't matter if I get the entire page or not, as long as everything in the right hand column is in the screenshot.</p> <p>I am using Selenium 2 Webdriver + python</p>
0
2016-10-06T01:24:34Z
39,887,962
<p>There is workaround by following the steps described in <a href="http://www.ramandv.com/blog/angularjs-protractor-selenium-headless-end-end-testing/" rel="nofollow">http://www.ramandv.com/blog/angularjs-protractor-selenium-headless-end-end-testing/</a> and create a gaint virtual display for running your program.</p>
0
2016-10-06T05:11:24Z
[ "python", "selenium", "selenium-webdriver", "webdriver" ]
Python Curses: Exiting a program fast
39,886,252
<p>What is the best way to quickly exit a Python program with an infinite loop that uses curses module? </p> <p>I've tried adding nodelay() method coupled with this at the end of the loop: </p> <pre><code>if screen.getch() == ord('q'): break </code></pre> <p>However, it takes 2-3 seconds to make all the function calls on one iteration of the loop. And because of the application, it doesn't make sense to run the loop more often than every 5 second. This means that in order for my way of exiting the program to work, I sometimes have to press and hold 'q' for 2-8 seconds. </p> <p>My code looks like this:</p> <pre><code>import curses import time def main(screen): refresh_rate = 5 screen.nodelay(1) # Infinite loop. Displays information and updates it # every (refresh_rate) # of seconds while True: # Makes several http requests # and passes responses through multiple functions # Escape infinite loop if screen.getch() == ord('q'): break # Wait before going through the loop again time.sleep(refresh_rate) if __name__ == "__main__": curses.wrapper(main) </code></pre> <p>My other solution was to replace while True with:</p> <pre><code>loop = 1 while loop: #Loop code if screen.getch() == ord('q'): loop = -1 </code></pre> <p>This way, there is no need to press and hold 'q' to exit the program. But it can still take up to 8 seconds to exit after pressing 'q' once.</p> <p>For obvious reasons, this doesn't seem to be the best way of exiting the program. I am pretty sure there should be a better (faster) solution.</p> <p>Other than that, the program works fine. It's 2 files with more than 300 lines, so I am posting just the relevant parts of the code with my attempted solutions.</p>
0
2016-10-06T01:46:51Z
39,886,654
<p>What's probably happening is that your <code>'q'</code> is coming in between the <code>getch()</code> and the <code>sleep</code> calls. Given that <code>getch()</code> takes a fraction of a second to execute and <code>sleep</code> locks the program for 5 seconds, it's very likely that any time you press a key you're going to wait.</p> <p>The easiest way to exit any python script is to press <code>Ctrl-C</code> - it spawns a <code>KeyBoardInterrupt</code> exception that can be handled like:</p> <pre><code>try: while True: do_something() except KeyboardInterrupt: pass </code></pre> <p>Granted, if this is meant to be a user-facing application, that might not be sufficient. But it's also unlikely that any production application would operate without a full event loop and a UI that would allow them to exit.</p> <p>Last, if you want another way of doing what you're already doing, you can use: </p> <pre><code>import sys sys.stdin.read(1) </code></pre> <p>To read 1 bye of user input at a time. I'd go for the <code>Ctrl-C</code> route, if I were you.</p>
0
2016-10-06T02:40:14Z
[ "python", "ncurses", "python-curses" ]
Python Curses: Exiting a program fast
39,886,252
<p>What is the best way to quickly exit a Python program with an infinite loop that uses curses module? </p> <p>I've tried adding nodelay() method coupled with this at the end of the loop: </p> <pre><code>if screen.getch() == ord('q'): break </code></pre> <p>However, it takes 2-3 seconds to make all the function calls on one iteration of the loop. And because of the application, it doesn't make sense to run the loop more often than every 5 second. This means that in order for my way of exiting the program to work, I sometimes have to press and hold 'q' for 2-8 seconds. </p> <p>My code looks like this:</p> <pre><code>import curses import time def main(screen): refresh_rate = 5 screen.nodelay(1) # Infinite loop. Displays information and updates it # every (refresh_rate) # of seconds while True: # Makes several http requests # and passes responses through multiple functions # Escape infinite loop if screen.getch() == ord('q'): break # Wait before going through the loop again time.sleep(refresh_rate) if __name__ == "__main__": curses.wrapper(main) </code></pre> <p>My other solution was to replace while True with:</p> <pre><code>loop = 1 while loop: #Loop code if screen.getch() == ord('q'): loop = -1 </code></pre> <p>This way, there is no need to press and hold 'q' to exit the program. But it can still take up to 8 seconds to exit after pressing 'q' once.</p> <p>For obvious reasons, this doesn't seem to be the best way of exiting the program. I am pretty sure there should be a better (faster) solution.</p> <p>Other than that, the program works fine. It's 2 files with more than 300 lines, so I am posting just the relevant parts of the code with my attempted solutions.</p>
0
2016-10-06T01:46:51Z
39,891,775
<p>Given that you have nodelay already, the usual approach is to use napms with a small (20-50 milliseconds) time, and addressing your 5-seconds goal, to run the functions after several (10-25) repetitions of the getch/napms loop.</p> <p>Mixing curses and standard I/O doesn't really work well unless you take care to flush things when switching between the two.</p>
0
2016-10-06T08:58:33Z
[ "python", "ncurses", "python-curses" ]
Use a Dictionary generated from CSV to update values in .xlsx file using python
39,886,306
<p>Every day I am given an old Excel 95 file of data. It has columns up to the letter 'L' and hundreds of rows. Column 'B' is a customer reference number, it's unique to each customer. Column 'I' is a dollar value. </p> <p>Each morning I need to use this file to update another Excel file. I search for the customer reference number, and enter the dollar value. The columns for the Customer reference and Dollar value in the Destination file are 'D' and 'E' respectively. </p> <p>As I'm new to python I thought this would be a good project to automate. After research and installation of a few other modules (and reading the Automate the Boring stuff with python book) I haven't yet had any success. </p> <p>I'm saving the source file as a csv, then importing csv, then turning it into a dictionary in python. This works fine and I'm happy with it.</p> <p>My problem is trying to write the values to the destination file. I get no errors, the file saves at the end, but when I open it the values are not there. I'm not sure why. Any help is appreciated. </p> <pre><code>import os, csv, openpyxl os.chdir('nameOfMyDirectory') print('What is the name of the source file?') sourceFileName = input() print('What is the key column?') keyColumn = int(input()) print('What is the value column?') valueColumn = int(input()) source = csv.reader(open(sourceFileName + '.csv')) sourceDictionary = {} for row in source: key = row[keyColumn] sourceDictionary[key] = row[8] </code></pre> <p>Everthing above here seems to work, I can use the interactive shell to print the dollar values using the key column. I've included it incase I'm wrong and this needs to change too. </p> <p>Below is where the problem seems to be (I think)</p> <pre><code>print('What is the destination file name?') destinationFileName = input() wb = openpyxl.load_workbook(destinationFileName + '.xlsx') sheet = wb.get_sheet_by_name('nameOfMySheet') allRows = sheet.max_row for rowNum in range(2, allRows): #Start from row 2 and go to the end membershipID = sheet.cell(row=rowNum, column=4).value if membershipID in sourceDictionary: sheet.cell(row=rowNum, column=5).value = sourceDictionary[membershipID] wb.save('newFileName.xlsx') </code></pre> <p>The program runs and there are no errors. The new file is saved with the filename but the values are not updated, they are still blank.</p> <p>I wasn't sure if the openpyxl column = 4 value was one of those ones that started from 1 or 0, so I've tried counting from both, and both don't work.</p> <p>Any help is super appreciated. </p> <hr> <p>I've been asked to show some example data so here is a link to 2 google sheets that are identical to the source file csv and destination file xlsx. Hope this helps. <a href="https://drive.google.com/drive/folders/0Bz9zCfS5szC4RVFvdEg3VGF6T1U?usp=sharing" rel="nofollow">Link to sheets</a></p> <p>I'm trying to update the 'Destination File's Column E', with the 'Source Files Column I'. I use the customer ID column as the reference. </p>
1
2016-10-06T01:53:01Z
39,950,895
<p>Simply the problem is a type mismatch. The keys read in from csv are in <code>string</code> format and the values read in from the Excel sheet are <code>float</code> values. So the <code>if</code> statement to match the two always return <em>false</em>.</p> <p>To align the data types, adjust following line in second <code>for</code> loop where first you cast to integer and then to string:</p> <pre><code>membershipID = str(int(sheet.cell(row=rowNum, column=4).value)) </code></pre>
0
2016-10-10T03:26:54Z
[ "python", "python-3.x", "csv", "dictionary", "openpyxl" ]
How to change image format without writing it to disk using Python Pillow
39,886,326
<p>I got Pillow image that i got from the Internet:</p> <pre><code>response= urllib2.urlopen(&lt;url to gif image&gt;) img = Image.open(cStringIO.StringIO(response.read())) </code></pre> <p>I want to use it with tesserocr but it wont work with GIF images.</p> <p>If I save the image as PNG <code>img.save("tmp.png")</code> and load it <code>img = Image.open("tmp.png")</code> everything works.</p> <p>Is there a way to do this conversion without writing to disk?</p>
1
2016-10-06T01:56:12Z
39,899,744
<p>The solution was very simple:</p> <pre><code>response= urllib2.urlopen(&lt;url to gif image&gt;) img = Image.open(cStringIO.StringIO(response.read())) img = img.convert("RGB") </code></pre> <p>Note that you need to remove the alpha channel info to make image compatible with tesserocr</p>
0
2016-10-06T15:14:44Z
[ "python", "python-2.7", "pillow", "cstringio" ]
__main__.py Behavior Different Between Python 2 and 3
39,886,363
<p>I find it convenient to place my program entry point in a different file from <code>__main__.py</code>. Below are two example files located in the same package (<code>test_1</code>):</p> <p><code>__main__.py:</code></p> <pre><code>import sys from main import main as entry_point if __name__ == '__main__': script_name = sys.argv[ 0 ] print( "Script name: {}".format( script_name ) ) sys.exit( entry_point( sys.argv[ 1: ] ) ) </code></pre> <p><code>main.py:</code></p> <pre><code>import sys def main( args = None ): if args is None: args = sys.argv[ 1 : ] print( "Program arguments are: {}".format( str( args ) ) ) return len( args ) </code></pre> <p>When invoking the script with <code>python3 -m test_1 1 2 3 4</code>, I get the following error: "ImportError: No module named 'main'", but when invoked with <code>python2 -m test_1 1 2 3 4</code> I get the expected behavior of executing the script.</p> <p>Why does the importation work differently between python2 (2.7.12) and python3 (3.5.2) and what do I need to do to accomplish the behavior I am trying to achieve?</p>
0
2016-10-06T01:59:35Z
39,886,489
<p>For Python 3, the <code>__main__.py</code> needs to use an explicit relative import, so <code>from .main import main as entry_point</code> instead of <code>from main import main as entry_point</code>.</p>
0
2016-10-06T02:19:03Z
[ "python", "python-2.7", "python-3.x" ]
Input Validation loop / read file txt with Python
39,886,404
<p>My first issue is my file is not being read by the script and truthfully I do not know why.</p> <p>Second, the issue is my loop "y" or "Y" is not looping the question of account input for a user, it just continues to repeat until I hit "n" or "N" to exit....which works. (so I guess my loop works properly in that sense)</p> <p>My current situation I have a txt file that I need to read account numbers from. I need it to loop and continue to ask for validation of account numbers even if the account number is wrong.</p> <p>I would like the output to look like this</p> <p>------------My needed output----------------</p> <pre><code>&gt;&gt;&gt; Enter the account number to be validated: 456321 Account number 456321 is not valid. Enter another card number? Enter Y or N: Y Enter the account number to be validated: 5552012 Account number 5552012 is valid. Enter another card number? Enter Y or N: N &gt;&gt;&gt; </code></pre> <p>-----------End Needed output--------------</p> <p>-----------My output at the moment---------</p> <pre><code>&gt;&gt;&gt; ============ RESTART: G:\Software Design\accounts.py ============ Enter the account number to be validated: 4453221 Account number 4453221 is not valid Enter another card number? Enter Y or N: y Enter another card number? Enter Y or N: n &gt;&gt;&gt; </code></pre> <p>----------End current output-----------</p> <p>--------My Code----------</p> <pre><code>def main(): #setting loop control another = 'y' try: # open file READ ONLY charge_accounts.txt infile = open('charge_accounts.txt', 'r') # Setting accountNum variable accountNum = int(input('Enter the account number to be validated: ')) if accountNum in infile: accountNum = int(infile.readline(accountNum)) print('Account number ' + str(accountNum) + ' is valid') else: print('Account number ' + str(accountNum) + ' is not valid') # Loop controls for other account inputs while another == 'y' or another == 'Y': # Get another account another = input('Enter another card number? ' + 'Enter Y or N: ') if another == 'n' or another == 'N': break infile.close() # Extra credit +5 points ( catching errors ) except IOError: print('An error occured trying to read') print('the file', charge_accounts.txt) main() </code></pre>
-1
2016-10-06T02:07:14Z
39,886,514
<p>With regards to your loop, everything you want to be repeated needs to be inside of it. So think about what you've written, <code>while another == y:</code> the <em>body of the loop</em> will be repeated. So, my advice would be to think about <em>where you start looping</em>. </p> <p>Also, <code>accountNum in infile:</code> will always be false since you converted <code>accountNumb</code> to an <code>int</code>, and it needs to stay a string. Here is another head's up: </p> <pre><code>if accountNum in infile: accountNum = int(infile.readline(accountNum)) print('Account number ' + str(accountNum) + ' is valid') </code></pre> <p>Will not work like you think it will anyway. When you check if something is in a <code>file</code> object, it moves the stream position to the end. This means when you <code>readline</code> it will return an empty string! If you think about it, you don't really need the <code>readline</code> anyway.</p>
2
2016-10-06T02:22:42Z
[ "python", "loops", "readfile" ]
Argument 1 must be string, not datetime.datetime?
39,886,457
<p>I just took a Data Analysis course on Udacity. My code is:</p> <pre><code>enrollments_filename= '/Users/abc/Desktop/Udacity - Intro to Data Analysis/enrollments.csv' def open_file(filename): with open(filename, 'rb') as f: reader = unicodecsv.DictReader(f) return list(reader) enrollments = open_file(enrollments_filename) # Takes a date as a string, and returns a Python datetime object. # If there is no date given, returns None from datetime import datetime as dt def parse_date(date): if date == '': return None else: return dt.strptime(date, '%Y-%m-%d') # Takes a string which is either an empty string or represents an integer, # and returns an int or None. def parse_maybe_int(i): if i == '': return None else: return int(i) for enrollment in enrollments: enrollment['cancel_date'] = parse_date(enrollment['cancel_date']) enrollment['days_to_cancel'] = parse_maybe_int(enrollment['days_to_cancel']) enrollment['is_canceled'] = enrollment['is_canceled'] == 'True' enrollment['is_udacity'] = enrollment['is_udacity'] == 'True' enrollment['join_date'] = parse_date(enrollment['join_date']) enrollments[0] </code></pre> <p>Here is the error I got:</p> <pre><code>TypeError: strptime() argument 1 must be string, not datetime.datetime </code></pre> <p>Can anyone explain to me why? When I change <code>date</code> to <code>str(date)</code>, here is the error I got:</p> <pre><code>//anaconda/lib/python2.7/_strptime.pyc in _strptime(data_string, format) 333 if len(data_string) != found.end(): 334 raise ValueError("unconverted data remains: %s" % --&gt; 335 data_string[found.end():]) 336 337 year = None ValueError: unconverted data remains: 00:00:00 </code></pre> <p>The weird thing is, when I first ran the code, it works. But then I re-pressed the second time and it returned the error! Thanks very much!</p>
-1
2016-10-06T02:13:12Z
39,886,546
<p>I bet you ran this line twice in your shell/session:</p> <pre><code>enrollment['cancel_date'] = parse_date(enrollment['cancel_date']) </code></pre> <p>The first time works, but now enrollment['cancel_date'] is a date, not a string. Second time you ran it - error.</p>
0
2016-10-06T02:26:55Z
[ "python", "datetime" ]