samedi 27 juin 2015

calling a function on dataframe data

I am not sure what I am doing wrong here, I am simply trying to call a function with a if-then-else filter in it and apply to a dataframe.

In [7]:
df.dtypes

Out[7]:
Filler     float64
Spot       float64
Strike     float64
cp          object
mid        float64
vol        float64
usedvol    float64
dtype: object

In [8]:
df.head()

Out[8]:
          Filler  Spot  Strike cp  mid   vol  
    0       0.0   100      50  c   0.0   25.0   
    1       0.0   100      50  p   0.0   25.0   
    2       1.0   100      55  c   1.0   24.5  
    3       1.0   100      55  p   1.0   24.5   
    4       2.5   100      60  c   2.5   24.0 

I have the below function:

def badvert(df):
    if df['vol']>24.5:
        df['vol2'] = df['vol']*2
    else:
        df['vol2'] = df['vol']/2
    return(df['vol2'])

Which I call here:

df['vol2']=badvert(df)

Which generates this error message:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-bbf7a11a17c9> in <module>()
----> 1 df['vol2']=badvert(df)

<ipython-input-13-6132a4be33ca> in badvert(df)
      1 def badvert(df):
----> 2     if df['vol']>24.5:
      3         df['vol2'] = df['vol']*2
      4     else:
      5         df['vol2'] = df['vol']/2

C:\Users\camcompco\AppData\Roaming\Python\Python34\site-packages\pandas\core\generic.py in __nonzero__(self)
    712         raise ValueError("The truth value of a {0} is ambiguous. "
    713                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
--> 714                          .format(self.__class__.__name__))
    715 
    716     __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

My gut tells me that this is a simple "syntax" issue but I am at a loss. Any help would be greatly appreciated

In Django REST / OAuth2 toolkit what is the difference between TokenHasScope and TokenHasReadWriteScope?

In Django REST / OAuth2 toolkit what is the difference between TokenHasScope and TokenHasReadWriteScope?

For example in views.py:

from rest_framework import generics
from django.contrib.auth.models import User
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope, TokenHasScope
from oauth2.provider.views.mixins import ScopedResourceMixin

class UserView1(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    model = User

class UserView2(ScopedResourceMixin, viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasScope]
    required_scopes = ['what_is_this']
    model = User

What is the significance of the required_scopes value?

Reference: http://ift.tt/1Ho4RU3

MS WindowsServer 2012: Python request - SSL: UNKNOWN_PROTOCOL] unknown protocol

on MS Windows Server 2012, the Python script is doing https request into open github repository, see full log at

http://ift.tt/1CB2ztm

The problem is (Python 2.7.10) with Windows Server 2012 connection to https sites of github, which are open for public. On all other Windows servers (including CI testing on appveyor.com) this connection works.

Maybe this is issue related to Windows Server 2012. Any help please how to modify this line ?

update.fetch_url('http://ift.tt/1Ho4RDL', 'update.py')

tkinter child program not closed

I have 2 tkinter programs. The main program will have button to open the second program. The problem is when i try to close the child program, the main program is closed instead. I close the second program with command app.destroy(). How to fix this?
Thanks in advance.

All of the programs have this script

from Tkinter import *
import Tkinter as tk
import os

class SeaofBTCapp(tk.Tk):

    def __init__(self,*args,**kwargs):

        tk.Tk.__init__(self)
        container = tk.Frame(self, background="black")
        container.pack(side="top", fill="both", expand = True)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)



        self.frames = {}

        for F in (StartPage, PageCheck, PageUpdate, PageDigital, PageAnalog,
                  PageResult, PageHasil):

            frame = F(container, self)

            self.frames[F] = frame

            ##self.overrideredirect(1)

            self.geometry("800x480")
            self.title("IC Checker")
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

##frame class

app = SeaofBTCapp()
app.mainloop()

(Python) Vehicle number plates verification and file saving

My aim is to create code that can verify inputted number plates and verify them to the format: AA/11/AAA 2 letter, 2 numbers, 3 letters. If the entered plate is incorrect, it is saved to a file called 'invalidplates' which shows an array of all of the number plates that exceed the desired speed limit.

Here are the questions

a) On many major roads average speed checks are in place. Two sensors are placed a known distance apart and vehicle number plate recognition is used to identify a vehicle and the time it enters the section of road being monitored. The time is recorded when the vehicle leaves the monitored section. By using the time taken to travel the known distance, the average speed of a vehicle can be calculated. Create a program for calculating average speeds for a vehicle travelling through a section of road. Output a list of those vehicles exceeding the speed limit set for that section of road.

b)In the UK most vehicle registrations are in the format: • two letters • two numbers • three letters. For example, AZ01 XYZ. The vehicle number plate recognition system will provide this information as a string of characters. By identifying any vehicle registrations that do not match this pattern, a list of non-standard vehicle registrations and average speeds in excess of the speed limit should be compiled and saved. Create a program for saving a file with these non-standard registrations for those vehicles exceeding the speed limit set for that section of road.

c) The authorities have a file of known vehicle registrations and the vehicle’s owner. Those vehicles with standard registrations can be looked up in this file and a fine automatically sent out. A new file is created by comparing the information from the average speed recording system with the file of registered vehicles and their owners’ details. This new file should include the owner’s name and address details, the registration of the vehicle and the average speed of the vehicle in the section of road. Create a program for creating a file of details for vehicles exceeding the speed limit set for a section of road. You will need to create a suitable file with test data, including standard registrations and vehicle owner information.

Here is my code:

file = open("Speeders.txt", "w")
import random, string, time
Speeders = [] #Array

while True:
    try:
        Distance = float(input("Enter a known distance.(Metres ONLY)"))
        break
    except ValueError: #Allows ONLY numbers to be inputted, anything else is rejected
        print ("Invalid input (Numbers ONLY)")

while True:
    try:
        TimeTaken = float(input("Enter the time taken to pass the distance"))
        break
    except ValueError:#Allows ONLY numbers to be inputted, anything else is rejected
        print ("Invalid input (Numbers ONLY)")

while True:
    try:
        Limit = int(input("Enter the speed limit in metres per second"))
        break
    except ValueError:#Allows ONLY numbers to be inputted, anything else is rejected
        print ("Invalid input (Numbers ONLY)")

Speed = (Distance) / (TimeTaken)
print (("The speed of the vehicle was " + str(Speed) + " metres per second"))
while True:
    try:
        if (Speed) > (Limit):
            def NumPlate(self):
                plateFormat = ['L', 'L', 'N', 'N', 'L', 'L', 'L']
                NumPlate = []

                for i in plateFormat:
                    if i == 'L':
                        NumPlate.append(random.choice(string.ascii_letters[26:]))

                    elif i == 'N':
                        NumPlate.append(str(random.randint(0, 9)))
                        NumPlate.insert(4, " ")
                        NumPlate = str(input("Enter the vehicle's number plate."))
                        Speeders.append (NumPlate)
                        return  "".join(NumPlate)
                    break




        while True:
            reply = input('Enter Y to add another number plate N to print list: ')

            if reply == "Y":
                while True:
                    try:
                        Distance = float(input("Enter a known distance.(Metres ONLY)"))
                        break
                    except ValueError: #Allows ONLY numbers to be inputted, anything else is rejected
                        print ("Invalid input (Numbers ONLY)")

                while True:
                    try:
                        TimeTaken = float(input("Enter the time taken to pass the distance"))
                        break
                    except ValueError:#Allows ONLY numbers to be inputted, anything else is rejected
                        print ("Invalid input (Numbers ONLY)")

                while True:
                    try:
                        Limit = int(input("Enter the speed limit in metres per second"))
                        break
                    except ValueError:#Allows ONLY numbers to be inputted, anything else is rejected
                        print ("Invalid input (Numbers ONLY)")

                Speed = (Distance) / (TimeTaken)
                print (("The speed of the vehicle was " + str(Speed) + " metres per second"))

                if (Speed) > (Limit):
                        NumPlate = str(input("Enter the vehicle's number plate."))
                        Speeders.append (NumPlate)

                        while True:
                            reply = input('Enter Y to add another number plate N to print list: ')

                file.write("Here is a list of the Speeders' number plates on the roads\n")
                file.write("List" + str(Speeders))

            if reply == "N":
                for i in Speeders:
                    print("This is the list of current number plates that are speeding: " + str(Speeders))

Any help to improve/fix my code will be greatly appreciated :)

Who prepares input for R tasks

I am new to R.

Suppose to have some data that we have to parse for maybe building a representation in vectorial space of several items that will have to be clustered; it involves some text processing and manipulation. Other goals of the parsing might be to output a .csv, or a tab separated file. When doing this in Python, I would often use data structures such as dictionaries, sets, hash-maps.. such data structures seems not to be available on R.

I would like to know, do R users usually prepare/build their input data (that will be printed as a .csv or a tab separated file as above pointed out) with R itself, or do they usually rely on other programming languages more powerful for doing it, like Python?

At first glance, it seems to me that R is quite assuming that suitable input data are already available in right format, and we are not going to use R also for parsing some source to build a more structured input.

Need help on programming . Beginner Python

Sound level L in units of decibel (dB) is determined by L = 20 log10(p/p0) where p is the sound pressure of the sound (in Pascals, abbreviated Pa), and p0 is a reference sound pressure equal to 20 × 10–6 Pa (where L is 0 dB).

The following table gives descriptions for certain sound levels. Threshold of pain 130 dB Possible hearing damage 120 dB Jack hammer at 1 m 100 dB Traffic on a busy roadway at 10 m 90 dB Normal conversation 60 dB Calm library 30 dB Light leaf rustling 0 dB Write a program that reads a value and a unit, either dB or Pa, and then prints the closest description from the list above.

L=input('What can you hear outside')
L=L.upper()
if L == "JACKHAMMER":
   print(L)
from math import *
Pa=2
Pa=(Pa)
p0=(20*10)**(-6)(2)
p0=round(p0)
LdB = 20(log(Pa/p0)) 

so far i have this but there is an error

How to get n elements of a list not contained in another one?

I have two lists, of different size (either one can be larger than the other one), with some common elements. I would like to get n elements from the first list which are not in the second one.

I see two families of solutions (the example below is for n=3)

a = [i for i in range(2, 10)]
b = [i * 2 for i in range (1, 10)]
# [2, 3, 4, 5, 6, 7, 8, 9] [2, 4, 6, 8, 10, 12, 14, 16, 18]

# solution 1: generate the whole list, then slice
s1 = list(set(a) - set(b))
s2 = [i for i in a if i not in b]

for i in [s1, s2]:
    print (i[:3])

# solution 2: the simple loop solution
c = 0
s3 = []
for i in a:
    if i not in b:
        s3.append(i)
        c += 1
        if c == 3:
            break
print(s3)

All of the them are correct, the output is

[9, 3, 5]
[3, 5, 7]
[3, 5, 7]

(the first solution does not give the first 3 ones because set does not preserve the order - but this is OK in my case as I will have unsorted (even explicitly shuffled) lists anyway)

Are there the most pythonic and reasonably optimal ones?

The solution 1 first computes the difference, then slices - which I find quite inefficient (the sizes of my lists will be ~100k elements, I will be looking for the first 100 ones).

The solution 2 looks more optimal but it is ugly (which is a matter of taste, but I learned that when something looks ugly in Python, it means that there are usually more pythonic solution).

I will settle for solution 2 if there are no better alternatives.

Read Contents of txt file and display in Tkinter GUI Python

Hey i have successfully created a tkinter GUI in python which saves the Entered values in a text file...Here is the code-

from Tkinter import *
root = Tk()
def save():
    open("text.txt","w").close()
    text = e.get() + "\n" + e1.get() + "\n" +  e2.get() + "\n"
    with open("text.txt", "a") as f:
        f.write(text)
w1 = Label(root, text="Controller value")
w1.pack()
e = Entry(root)
e.pack()
w2 = Label(root, text="Velocity")
w2.pack()
e1 = Entry(root)
e1.pack()
w3 = Label(root, text="Desired Heading")
w3.pack()
e2 = Entry(root)
e2.pack()
toolbar = Frame(root)
b = Button(toolbar, text="save", width=9, command=save)
b.pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)
mainloop()

...

Now what i want to do is create 3 new Textboxes in the GUI which will Display the contents of the file..for eg- my text.txt file has the contents-

3

2

4

Now i want each of these 3 values to be displayed in 3 textboxes in the GUI.... Help me out please. Basically i want the first textbox in the GUI to display 3, second textbox 2 and third textbox 4...

how to add multiple attrs in Django forms

How can I add multiple attributes to an input tag in Django ?

Example: For adding a single attribute I can use this code

email = forms.EmailField(
        widget = forms.TextInput(attrs={'placeholder': 'Email'}))

But if I want to add 'class', 'size' and 'placeholder' attributes then what is the way of doing it in django forms?

video streaming using flask with raspi-camera

Sorry for my English skill. I want to make a web page which streams video and runs several functions. I am using python and flask server. But, there are some problems which I can't solve alone. I have a source code. It's almost perfect.

source code.

import time
from flask import Flask, render_template, Response
from camera import Camera

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(Camera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/test')
def test():
    return time.time() 

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True

and template

<html>
  <head>
    <title>Video Streaming Demonstration</title>
  </head>
  <body>
    <h1>Video Streaming Demonstration</h1>
    <img src="{{ url_for('video_feed') }}">
  </body>
</html>

In the source code, the function named gen() is using 'yield'. so, It will never end. It take all resource. I want to run another function like 'test' function while video is streaming.

Python - Error in my program

So I'm writing a python program that either sets the alarm off or doesn't, but can't seem to find my mistake for R1.

T = float(input("What is the temperature in F?"))

from math import *

e=2.71828182845904523536028747135266249775724709369995

R1 = ((33192)*e)**3583((1/T)-(1/40))

P1 = ((156300/R1) + 156,300)

P2 = ((156300/312600))

if P1 < P2:

    #print("The alarm will be sound")

else:

    #print("The alarm will not be sound")


 R1 = ((33192)*e)**3583((1/T)-(1/40))

TypeError: 'int' object is not callable

Best way to scan images like this in tesseract? which PIM?

So how should I parametrize tesseract to best scan images like

The worksheet type of worksheet I want to scan (borrow from Google Image search)

Is there anyway I can improve tesseract accuracy in parsing this? Or have it realize that it should read vertically. I am using pytesseract to read in the file? Can I modify the pim with pytesseract? Is there another python binding I should be using? Any help would be appreciated.

python graph-tool load csv file

I'm loading directed weighted graph from csv file into graph-tool graph in python. The organization of the input csv file is:

1,2,300

2,4,432

3,89,1.24

...

Where the fist two entries of a line identify source and target of an edge and the third number is the weight of the edge.

Currently I'm using:

g = gt.Graph()
e_weight = g.new_edge_property("float")
csv_network = open (in_file_directory+ '/'+network_input, 'r')
csv_data_n = csv_network.readlines()
for line in csv_data_n:
    edge = line.replace('\r\n','')
    edge = edge.split(delimiter)
    e = g.add_edge(edge[0], edge[1])
    e_weight[e] = float(edge[2])

However it takes quite long to load the data (I have network of 10 millions of nodes and it takes about 45 min). I have tried to make it faster by using g.add_edge_list, but this works only for unweighted graphs. Any suggestion how to make it faster?

Checking mail subject from Bash or Python

I have many cron jobs running on various servers, I want to check the status of the jobs via mail using command line. The only way seems to me is to extract the subject or body of the mail the jobs sent. cron will send mail regardless of the success or failure.

For example, upon success cron will send a mail with subject:

Done..succeeded

If failed:

Not done..Failed

The cron jobs run at specific times e.g. lets take 10:00, 16:00 and 22:30 everyday.

I have tried curl and urllib2 but could not get desired result. Also note that i can not make any modification to cron itself, the only option is to check the gmail.

So how can i check my gmail from bash or python to extarct the subject so that i get get an idea of the cron job?

How to create regular expression starting with different directory name in Python

Currently I am taking directory path as input from the user. The path will be different for each user(dir_name will be different)

/file/perm/perm13/user123/dir_name/ 

while the structure inside dir_name is same for all users given as below:

tar1 tar2 tar3 tar4 tar5 tar6 source

In each tar, three folders are there: build collateral fix in collateral: I have three different files

 _base.txt, _fullbase.txt and _skip.txt 

I also need corresponding .dot files from source/projectfiles/params/tar_base.dot | tar_fullbase.dot | tar_skip.dot

Here is what I need to do:
1. Take input from user 2. One by one- go into the targets. (tar1 -> tar2 -> tar3 ->tar4 ->tar5) 3. For each tar, search for collateral folder 4. and in collateral folder search for all three .txt files 5. for each .txt file search for corresponding .dot file

currently I do following: I take path for txt from the user

txtfilepath = raw_input (" Please provide file path for the desired txt")
dotfilepath = raw_input (" Please enter corresponding .dotfilepath")
<directory path>/<tar1>/collateral/<xyz_base.txt)

The regex:

platform = re.search("?<=/collateral/).(?="_(base|fullbase|skip)\.txt)",txtfilepath).group(0)

can some python geek help?

Error in scrapy while used command "scrapy crawl myproject"

C:\Python27\Scripts\stack>scrapy crawl myproject 'scrapy' is not recognized as an internal or external command, operable program or batch file.

Intra-package Reference

module_a is the main module of the package whereas module_b is just another module in package

package
|-------- __init__.py
|-------- module_a.py 
+-------- module_b.py 

How does from .module_b import Test differ from a direct import like from module_b import Test

Django Error: Key is not present in table "auth_user"

I created a custom user table in Django and it was working fine until I tried to save a new user to the database. I get the error:

insert or update on table "customer_email" violates foreign key constraint "customer_email_user_id_8eeb3a31aa9371c_fk_auth_user_id"
DETAIL:  Key (user_id)=(7) is not present in table "auth_user".

After a bit of looking around, I found this link which says I should drop the table django_admin_log and re-sync the database. I did this but the error persists. What I think is that the after re-syncing, the table django_admin_log is not being created. I tried to view the table using psql but it says no such table exists.

What could be wrong here? How do I fix this.

Edit When I run syncdb or sqlmigrate, it shows the following in console, but I don't think the table is being created or changes are actually coming into effect.

BEGIN;
CREATE TABLE "django_admin_log" ("id" serial NOT NULL PRIMARY KEY, "action_time" timestamp with time zone NOT NULL, "object_id" text NULL, "object_repr" varchar(200) NOT NULL, "action_flag" smallint NOT NULL CHECK ("action_flag" >= 0), "change_message" text NOT NULL, "content_type_id" integer NULL, "user_id" integer NOT NULL);
ALTER TABLE "django_admin_log" ADD CONSTRAINT "djan_content_type_id_697914295151027a_fk_django_content_type_id" FOREIGN KEY ("content_type_id") REFERENCES "django_content_type" ("id") DEFERRABLE  INITIALLY DEFERRED;
ALTER TABLE "django_admin_log" ADD CONSTRAINT "django_admin_log_user_id_52fdd58701c5f563_fk_userapp_user_id" FOREIGN KEY ("user_id") REFERENCES "userapp_user" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "django_admin_log_417f1b1c" ON "django_admin_log" ("content_type_id");
CREATE INDEX "django_admin_log_e8701ad4" ON "django_admin_log" ("user_id");

COMMIT;

Edit 2: I got the table to be created but the error still persists.

Edit 3: After further looking, I realised that the key is not in the table "auth_user" but in the table 'users', which is a custom model. So how do I fix this? I can set a meta class and set a db_table variable but that will mess up even more things..

How to change url path while switching pages via AJAX and Django?

I am following this answer to make smooth page switches: Rendering JSON objects using a Django template after an Ajax call

How do I make Django understand, that I'm on the other page already?

I want the list element to obtain 'active' class and to have /leaders/ in browser url path when I click on the link and load leaderboard template. Say i have:

leaderboard.html:

<li{% if path == leaders %} class="active"{% endif %}>  
   <a href="/leaders/">Leaderboard</a>
</li>

urls.py:

url(r'^leaders/$', 'index.views.leaderboard', name='leaders'),

view:

def leaderboard(request):
  ...
  if request.is_ajax():
    return_str = render_block_to_string('leaderboard.html', 'block_name', context)
    return HttpResponse(return_str)
  else:
    response = render_to_response('leaderboard.html', context)
    return response    

Edit: I've tried to use window.history.pushState, it changed url in browser, but did not tell anything to django.

How does flask's sqlalchemy extension discover models

The flask sqlalchemy API offers a very convenient function called create_all(...) that creates a database and each table corresponding to my defined models.

How does the API know which models I have defined? I never instantiate or register an instance of the model. They're just class definitions that inherit from db.Model.

Django - Time since model created

How du you calculate the time since a model was created? The model has the following field:

created_at = models.DateTimeField(auto_now_add=True)

This is what I tried:

from datetime import datetime, timedelta

@property
def time_since_created(self):
    return (datetime.now()-self.created_at).total_seconds()

But it did not work. Do anyone have any ideas?

How do I extract multiple float numbers from a string in Python?

regex= '<th scope="row" width="48%">52wk Range:</th><td class="yfnc_tabledata1"><span>(.+?)</span> - <span>(.+?)</span></td>'
    pattern = re.compile(regex)
LBUB = re.findall(pattern,htmltext)

I am trying to do basic data scraping in Python and perform some calculations on the returned real numbers. I have shown a small extract from the program so you can get the basic idea. I want it to read a html file and return certain numbers. The issue is that the real numbers are returned within a string variable like this...

[('90.77', '134.54')]

I want to extract the numbers from the variable so that they can be used as separate float variable. Does anybody know how to extract the two real numbers from within the string variable, basically getting rid of the ')], This is in Python 2.7.10

Unexpect string format behaviour [duplicate]

This question already has an answer here:

I'm seeing some unexpected behaviour with how str.format() handles bool types when specifying alignment. Here's the example:

>>> '{}'.format(bool(1))
True

>>> '{:<}'.format(bool(1))
1

Notice -- when I specified alignment, format switched to displaying an integer instead of True (I wanted to display the bool, not an integer). I can force the desired output by casting the bool to string thusly:

>>> '{:<}'.format(str(bool(1)))
True

My question is -- can anyone explain this edge case in str.format() ?

How to optimize a python script which runs for 4**k times?

Programming language: Python 3.4

I have written a program for the Bioinformatics 1 course from Coursera. The program is working all right, but is very slow for large datasets. I guess, it is because the loop is running for 4**k times, where k is the length of the sub-string that is passed into the function. Input: Strings Text and Pattern along with an integer d. Output: All starting positions where Pattern appears as a substring of Text with at most d mismatches.

This is my code:

def MotifCount(string1, substring, d):
    k = 4 ** (len(substring))
    codeArray = list(itertools.product(['A', 'C', 'G', 'T'], repeat=len(substring)))
    for i in range(k):
        codeArray2 = ''.join(list(codeArray[i]))
        HammingValue = HammingDistance(codeArray2, substring)
        if HammingValue <= d:
            for j in range(len(string1)):
                if(string1.find(codeArray2, j) == j):
                    print(j)



def HammingDistance(string_1, string_2):
    length_1 = len(string_1)
    length_2 = len(string_2)
    count = 0
    for i in range(length_1):
        if string_1[i] != string_2[i]:
            count += 1
    return count

Sample Input:

CGCCCGAATCCAGAACGCATTCCCATATTTCGGGACCACTGGCCTCCACGGTACGGACGTCAATCAAAT
ATTCTGGA
3

Output:

6 7 26 27

I want to optimize this code for bigger data sets. Is there any way to reduce the run time of the code?

python regex to split by comma or space (but leave strings as it is)

I need to split a string by space or by comma. But it should leave single or double quoted strings as it is. Even if it is apart by many spaces or a single space it makes no difference. For e.g.:

    """ 1,' unchanged 1' " unchanged  2 "   2.009,-2e15 """

should return

    """ 1,' unchanged 1'," unchanged  2 ",2.009,-2e15 """

There may be no or more spaces before and after a comma. Those spaces are to be ignored. In this particular context, as shown in the ex string, if two quoted or double quoted strings happen to be next to each other, they will have a space in between or a comma.

I have a previous question at python reg ex to include missing commas, however, for that to work a splitting comma should have a space after.

Python get variable from running script and pass to another Python script

I have a short but for me very important question:

I would like to write variables from an active python script that is already running to another python script. So I don't want something like this:

$ cat first.py second.py 
#first.py
def demo():
    some_list = []
    for i in 'string':
         some_list.append( i )
    return list

#second.py 
from first import demo

some_list = demo()
print some_list 

$python second.py
['s', 't', 'r', 'i', 'n', 'g']

I want my running script , e.g. "sent.py" to write constantly variables to some kind of "workspace", and then for example access those variables over another script, e.g. "get.py". And that without that I have to start both scripts together in a bash script.

So I am probably looking for a solution that is first passing python to bash an then to python again? I am very sorry, I am not so familiar with the terminology.

I hope it became clear what I mean, I did my best to explain it. I am kind of desperate and hope you can help. I have tried out and googled all kinds of stuff, but it just didn't work.

self in multiprocessing python

I have searched for how to do this and I don't find it. I suppose someone will put me a link to a google search, but I really don't know what exactly to look for. I'm trying to use Multiprocessing in python with a method of a class. This method has the "self" arg, but even if I pass it I get an error saying that I don't provide it:

Code:

def move_one_particle(self, moving_way):

def move(self, moving_way):
    for dummy_time in range(self.num_particles):
        p=mp.Process(target=self.move_one_particle, args=(moving_way))
        p.start()
        p.join()

output:

move_one_particle() takes exactly 2 arguments (1 given)

Set to list operation asymptotic complexity

What is the asymptotic complexity of the set to list operation? Is it O(1) or O(n)? I mean this one:

a = set()
for i in range(1000000):
    a.add(i)
a = list(a)

break out of a for loop and re-do it with updated list

This is my code:

for parseparent in allgroups:
  for groupPerm in self.permissions["groups"][parseparent]["permissions"]:
    if self.permissions["groups"][parseparent]["permissions"][groupPerm] and (groupPerm not in allgroups):
      allgroups.append(group)
      print("found a child- shall we do again?")

Firstly self.permissions["groups"][parseparent]["permissions"] will be a boolean value, thus my if statement is really reading like "If True and (groupPerm not in allgroups):". Normally the permission will not exist unless it is true, but sometimes they are set to False.

My problem is that if we reach the print statement, I need to re-run this loop because all groups will now have a new member of the list. There is no pre-defined limit of how far nested these could be, so I can't just do a set number of iterations like a range.

My solution is that when I get to print("found a child- shall we do again?"), i need to jump back to and re-do for parseparent in allgroups:. I thought about list comprehension, but I don't know how to do that in this case. most of the examples seem to be for a known, set amount of iterations.

basically, I suppose I am building lists from several dictionaries. here is an example, but only two levels deep (could be more):

allgroups starts out as []
master list = [dict1]
dict1 = {"dict2": True, "item1": True, "item2": False}
dict2 = {"dict3": True, "item4": True, "item5": False}
dict3 = {"Other": True, "item6": True, "item7": False}
dict4 = {"item9": False, "item8": True, "itemz": True}

once done, allgroups should contain [dict1, dict2, item1, dict3, item4, Other, item6] - ideally, I really want it to just contain the dictx items ([dict1, dict2, dict3]), but... this will server my purposes for now.

In a nutshell... start with the parent list, see if one of the items is another list (the child), then see if that child, in turn, has children; until no more subchildren are found.

What book do you recommend for learning advanced Python 3.x? [on hold]

I recently decided to give python, the language :D, a shot. I have already have some experience with other languages. Could you recommend me a book to read, most books i have found so far like "Learn Python the hard way" are either for ebginners or are written for Python 2.x.

How do I connect to a VM using WMI in python?

I'm trying to make a script in python which fetches several pieces of information (such as CPU name, network adapters) about machines in my network.

The script is currently working on my machine by using wmi.WMI() (or wmi.WMI('localhost')) to connect.

But now I want to see if it works for other machines as well. For this purpose, I've installed VMWare and set up a Virtual Machine (running Windows XP). I'd like to know how to connect to it.

I've read that you can simply use wmi.WMI([machine name or IP]) but putting in the IP ipconfig gives me does not seem to work. I get the error The RPC server is unavailable.

Could anybody help me please? Thank you in advance.

python programming with DVB-T usb stick

I would like to know where can I find register for a DVBT us b stick ( Avert V Volar HD Nano A867R) ?

Because I want to develop a python program with this dongle. I would like to use the register about this stick.

Thank you for your attention :)

How can I get the data from LocalStorage of a Chrome extension using Python?

I am using TimeStats extension on Chrome. And what I want to do now is to read the data in the LocalStorage (which contains all the information about the time I spent on each website) in a Python script and do later data processing.

I know that Ctrl+c and Ctrl+v would work in this case, but I am wondering are there any elegent and reliable ways to do that?

Thanks!

Accessing slice of 3D numpy array

I have a 3D numpy array of floating point numbers. Am I indexing the array improperly? I'd like to access slice 124 (index 123) but am seeing this error:

>>> arr.shape
(31, 285, 286)
>>> arr[:][123][:]
Runtime error 
Traceback (most recent call last):
  File "<string>", line 1, in <module>
IndexError: index 123 is out of bounds for axis 0 with size 31

What would be the cause of this error?

Set variable number/depth of if elif else statements

Say I had a list l = [1,2,3,...n] of indeterminate length, and I wanted to perform some if-elif statements according to the list contents, and the length of the list. So if the length was 3, we would have:

p = 2.1

if p >= l[0] and p <= l[1]:
   #do something
elif p >= l[1] and p<= l[2]:
   #do something
elif p >= l[len(l)]:
   #do something
elif p < l[0]:
   #do a final something and quit

So as I have mentioned, the list is of variable length in each case, it could be 32 for example, there is no upper limit in practice. So how do I create a case (a class, function, or whatever the standard method is) where this logic can be applied to any list or length n?

Some pointers would be nice, I haven't progressed to OOP yet, is this my cue to start?

How to load the math tesseract module?

So I am new to use tesseract and I want to load the math input module. Unfortunately, I do not know how to use it with the math module as found in this link. How do I made this properly load? Will it load the trained data by default? I've already added the trained data to the appropriate tessdata folder? i cannot figure out what the isocode for the lang parameter should be? is something like mat? There is very limited documentation on this issue and any help would be appreciated.

I am also coding this with pytesseract, but I am open to other modules if it does not support changing the trained dataset.

UnicodeEncodeError: Scraping data using Python and beautifulsoup4

I am trying to scrape data from the PGA website to get a list of all the golf courses in the USA. I want to scrape the data and input into a CSV file. My problem is after running my script I get this error. Can anyone help fix this error and how I can go about extracting the data?

Here is the error message:

File "/Users/AGB/Final_PGA2.py", line 44, in writer.writerow(row)

UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 35: ordinal not in range(128)

Script Below;

import csv import requests from bs4 import BeautifulSoup

courses_list = [] for i in range(906): # Number of pages plus one url = "http://ift.tt/1BWWYTt{}&searchbox=Course+Name&searchbox_zip=ZIP&distance=50&price_range=0&course_type=both&has_events=0".format(i) r = requests.get(url) soup = BeautifulSoup(r.content)

g_data2=soup.find_all("div",{"class":"views-field-nothing"})

for item in g_data2:
    try:
          name = item.contents[1].find_all("div",{"class":"views-field-title"})[0].text
          print name
    except:
          name=''
    try:
          address1=item.contents[1].find_all("div",{"class":"views-field-address"})[0].text
    except:
          address1=''
    try:
          address2=item.contents[1].find_all("div",{"class":"views-field-city-state-zip"})[0].text
    except:
          address2=''
    try:
          website=item.contents[1].find_all("div",{"class":"views-field-website"})[0].text
    except:
          website=''   
    try:
          Phonenumber=item.contents[1].find_all("div",{"class":"views-field-work-phone"})[0].text
    except:
          Phonenumber=''      

    course=[name,address1,address2,website,Phonenumber]

    courses_list.append(course)

with open ('PGA_Final.csv','a') as file: writer=csv.writer(file) for row in courses_list: writer.writerow(row)

How to isolate only the first space in a string using regex?

I have a foreign language to English dictionary that I'm trying to import into a sql database. This dictionary is in a text file and the lines look like this:

field1 field2 [romanization] /definition 1/definition 2/definition 3/

I'm using regex in python to identify the delimiters. So far I've been able to isolate every delimiter except for the space in-between field 1 and field 2.

(?<=\S)\s\[|\]\s/(?=[A-Za-z])|/
#(?<=\S)\s\[  is the opening square bracket after field 2
#\]\s/(?=[A-Za-z]) is the closing square bracket after the romanization
#/ is the forward slashes in-between definitions.
#????????? is the space between field 1 and field two

Gunicorn worker timeouts over and over?

I found this question with similar output: Gunicorn workers timeout no matter what. It's solution does not work.

~~~

So when I run foreman start web I get the following output:

17:53:46 web.1  | started with pid 31807
17:53:46 web.1  | [2015-06-26 17:53:46 -0400] [31807] [INFO] Starting gunicorn 19.3.0
17:53:46 web.1  | [2015-06-26 17:53:46 -0400] [31807] [INFO] Listening at: http://0.0.0.0:5000 (31807)
17:53:46 web.1  | [2015-06-26 17:53:46 -0400] [31807] [INFO] Using worker: sync
17:53:46 web.1  | [2015-06-26 17:53:46 -0400] [31810] [INFO] Booting worker with pid: 31810
17:54:26 web.1  | [2015-06-26 17:54:26 -0400] [31807] [CRITICAL] WORKER TIMEOUT (pid:31810)
17:54:26 web.1  | [2015-06-26 21:54:26 +0000] [31810] [INFO] Worker exiting (pid: 31810)
17:54:26 web.1  | [2015-06-26 17:54:26 -0400] [31821] [INFO] Booting worker with pid: 31821
17:54:57 web.1  | [2015-06-26 17:54:57 -0400] [31807] [CRITICAL] WORKER TIMEOUT (pid:31821)
17:54:57 web.1  | [2015-06-26 21:54:57 +0000] [31821] [INFO] Worker exiting (pid: 31821)
17:54:58 web.1  | [2015-06-26 17:54:58 -0400] [31831] [INFO] Booting worker with pid: 31831
17:55:29 web.1  | [2015-06-26 17:55:29 -0400] [31807] [CRITICAL] WORKER TIMEOUT (pid:31831)
...

and so on.

Loading it in a browser just connects and times out.

Procfile: web: gunicorn gettingstarted.wsgi --log-file -

wsgi.py:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gettingstarted.settings")

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise


application = get_wsgi_application()
application = DjangoWhiteNoise(application)

I will update this question with more information as time goes on.

Convert skimage.io to show it with tkinter

I started yesterday with python (to help a friend for her project).

She needs to use skimage for image processing and form detection, so I've tested to make a GUI (for the parameters) but I think skimage.io and PhotoImage from tkinter are incompatible.

img = io.imread("test.png")
canvas = Canvas(window, width=350, height=200)
canvas.create_image(0, 0, anchor=NW, image=img)
canvas.pack()

This doesn't work; how can I convert it?

Service Oriented App using Python/Django as a Front End

We are in the middle of re-thinking how we build applications at work and SOA has been thrown up as a possible solution to our issues. For some specific technical and philosophical reasons our front end team would rather not use a java script framework like Angular or Ember to build out the front end of the web applications (I'm not looking for arguments on this line of thought). Assuming that we do not use a java script framework would building a front end using Django/Flask/Bottle be something that could work?

Our front end engineers are very familiar with our current Django apps and templates and can easily work there way around them. We could consume the backend APIs inside views and just give the front end engineers what they need in the templates order to do their jobs. I realize this gets a bit sticky since there wouldn't be a clear separation between front and back as there would be with an Angular solution, but this does solve our underlying skill and philosophical issues that we have with adopting a java script only solution.

Is this completely absurd? Has anyone done this before? I know I can do this, but I guess the question I'm asking is if we should.

Django deployment with nginx issue

I am trying to deploy Django on my local machine . I am following this tutorial: http://ift.tt/1I00XNq

I am using fedora 21 so most things are same. I followed the tutorial word by word but I am unable to run Django without port and using the command runserver.

Here is the screenshot of what I am getting when I run localhost: http://ift.tt/1BWWYD1 Please suggest what to do.

Some Decoding Issue With String in Python

I'm trying to write the HTML Code string from Google into file in Python 3.4

#coding=utf-8
try:
    from urllib.request import Request, urlopen  # Python 3
except:
    from urllib2 import Request, urlopen  # Python 2

useragent = 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0'

#Generate URL
url = 'http://ift.tt/1Icd5wI'
query = str(input('Google It! :'))
full_url = url+query


#Request Data
data = Request(full_url)
data.add_header('User-Agent', useragent)
dataRequested = urlopen(data).read()
dataRequested = str(dataRequested.decode('utf-8'))


print(dataRequested)

#Write Data Into File
file = open('Google - '+query+'.html', 'w')
file.write(dataRequested)

It can print the string correctly, but when it write to file, it will show

file.write(dataRequested)
UnicodeEncodeError: 'cp950' codec can't encode character '\u200e' in position 97658: illegal multibyte sequence

I tried to change the decode way but it doesn't work. And i tried to replace \u200e too,but it will comes more encode charater error.

Convert unicode to an int or str in python 2.7

So I am storing some data that I have scraped from a website. A piece of that data is a number, thats type is unicode and I want to convert it into an int or a str and then into an int so I can add them together. I am using python 2.7 and the unicode is u'11:33:52' How can I turn it into an int

Distributed cluster of processes

I'm looking to build a distributed cluster of processes (a mesh or p2p network of processes - similar to how ElasticSearch handles nodes) that share data and state amongst themselves. I'll be doing this in Python. What's a good starting point to refer to for this. Each process in the cluster will be listening for requests and processing them and moving on to the next request. By spawning new processes it will scale horizontally. It will load a large data set to memory that it requires to handle these requests. I'd like the cluster to coordinate amongst itself how to distribute the data, how to shard it, how many replicas to keep, how frequently to rebalance to distribute the load when new workers join etc.

Is there an library/framework that would provide these features out of the box? Or will I have to build it myself? I'm reading through the Twisted documentation to see if it helps. Any ideas on how to go about this would be very helpful. Thank you.

Authentication token to only apply to one id

I am using this tutorial to incorporate authentication into my app: http://ift.tt/1a7sQjq

At the moment I have the following route:

@app.route('/checkin/venue/<int:venue_id>', methods = ['POST'])
@auth.login_required

My verify_password function is quite similar to that specified in the tutorial except I am accessing my own db.

The issue is that when I generate a token, it can be used across multiple venue_id's even though the token was generated using the credentials of a singlevenue.

Is there a way that I could pass the venue_id variable to the function verify_password(email_or_token, password) so when I call verify_auth_token I will be able to check that the venue_id encoded in the token actually corresponds to that made in the call:

@app.route('/checkin/venue/<int:venue_id>', methods = ['POST'])

Thanks for your help.

How to best catch sleep and resume events for OSX?

I want to make a timer that counts whenever the system (Mac OS X Yosemite) is on. My idea is to use python and listen for sleep and resume signals and increment a counter whenever the system is on. However, I haven't been able to find much information on how to do this.

  1. Would it be feasible to go about this problem with what I have detailed?
  2. Is there a better way to solve this problem?

Thanks!

Programming boilerplate subject [on hold]

Hi guys I'm a developer who spend lot of time reading books and trying every days to learn new things (Like every developer I guess). However when it's time to practice it's difficult to find idea to code. I'm looking for some kind of boilerplate subject that can be coded in many languages to practice them and in the same way practice stuffs like how units tests are write in the chosen language. Any help and advice will be appreciate

refresh a shell subprocess in python

I have a webpy code that sends "ps aux" data to a webpage using a subprocess.

import subprocess
ps = subprocess.Popen(('ps', 'aux'), stdout-subprocess.PIPE)
out = ps.communicate()[0]

(bunch of webpy stuff)
class index:
    def GET(self):
        return (output)
(more webpy to start the web server)

It sends the ps aux data across no problem however it does not refresh the ps aux data so i only get 1 continuous set rather than a changing set of data i am needing.

How do i refresh the subprocess to send new data every time I reload the webpage ?

lundi 11 mai 2015

pip install cryptography -> error...failed with exit status 1120

I am trying to install the cryptography module for python yet I keep getting errors and so far I have been able to solve each one as they come including:

  1. error: Unable to find vcvarsall.bat
  2. mysql-python install problem using virtualenv, windows, pip
  3. Installing lxml for Python 3.4 on Windows x 86 (32 bit) with Visual Studio C++ 2010 Express
  4. Failing to run pip install cryptography on Windows 7

However I have ran into an error that no matter how hard I look I find nothing so I decided I shall do what everyone else has done in the past and ask.

What do I need to do to get the error: command 'C:\\Program Files (x86)\\Microsoft\\Visual Studio\\14.0\\VC\\BIN\\amd64\\link.exe' failed with exit status 1120 error to go away so I can install the cryptographic module.

P.S. Yes I have tried easy_install


System Info

  • Windows 7 Home Premium - Service Pack 1 - 64-bit - AMD64x
  • Python 3.5.0a4

Setting up the environment

"C:\Program Files (x86)\Microsoft\Visual Studio\14.0\Common7\Tools\vsvars32.bat"
set INCLUDE=C:\ProgramData\Runtime\OpenSSL\include;%INCLUDE%
set LIB=C:\ProgramData\Runtime\OpenSSL\lib;C:\ProgramData\Runtime\OpenSSL\lib\VC\static;%LIB%


Checking the path

C:\PROGRA~1\Calibre2
C:\PROGRA~1\MICROS~1\120\Tools\Binn\
C:\PROGRA~1\MICROS~2\Dnvm\
C:\PROGRA~2\GNU\GnuPG\pub
C:\PROGRA~2\WI3CF2~1\8.1\WINDOW~1\
C:\PROGRA~3\Oracle\Java\javapath
C:\PROGRA~3\Runtime\JAVASC~1\nodejs
C:\PROGRA~3\Runtime\Perl\STRAWB~1\c\bin
C:\PROGRA~3\Runtime\Perl\STRAWB~1\perl\bin
C:\PROGRA~3\Runtime\Python\
C:\PROGRA~3\Runtime\Python\Scripts\
C:\PROGRA~3\Runtime\libxml2\bin
C:\PROGRA~3\Runtime\libxslt\bin
C:\Program Files (x86)\HTML Help Workshop
C:\Program Files (x86)\MSBuild\14.0\bin
C:\Program Files (x86)\Microsoft SDKs\F#\4.0\Framework\v4.0\
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\
C:\Program Files (x86)\Microsoft\Visual Studio\14.0\Common7\IDE\
C:\Program Files (x86)\Microsoft\Visual Studio\14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow
C:\Program Files (x86)\Microsoft\Visual Studio\14.0\Common7\Tools
C:\Program Files (x86)\Microsoft\Visual Studio\14.0\Team Tools\Performance Tools
C:\Program Files (x86)\Microsoft\Visual Studio\14.0\VC\BIN
C:\Program Files (x86)\Microsoft\Visual Studio\14.0\VC\VCPackages
C:\Program Files (x86)\Windows Kits\8.1\bin\x86
C:\ProgramData\Runtime\Gradle\bin
C:\ProgramData\Runtime\Lua\bin
C:\ProgramData\Runtime\OpenSSL/bin
C:\Users\Brandon\.dnx\bin
C:\Users\Brandon\AppData\Local\Android\sdk\platform-tools
C:\Windows
C:\Windows\Microsoft.NET\Framework\v4.0.30319
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Windows\system32
S:\xampp\php


pip install cryptography

Collecting cryptography
  Using cached cryptography-0.8.2.tar.gz
Requirement already satisfied (use --upgrade to upgrade): pyasn1 in c:\programdata\runtime\python\lib\site-packages (from cryptography)
Requirement already satisfied (use --upgrade to upgrade): six>=1.4.1 in c:\programdata\runtime\python\lib\site-packages (from cryptography)
Requirement already satisfied (use --upgrade to upgrade): setuptools in c:\programdata\runtime\python\lib\site-packages (from cryptography)
Requirement already satisfied (use --upgrade to upgrade): cffi>=0.8 in c:\programdata\runtime\python\lib\site-packages (from cryptography)
Requirement already satisfied (use --upgrade to upgrade): pycparser in c:\programdata\runtime\python\lib\site-packages (from cffi>=0.8->cryptography)
Installing collected packages: cryptography
  Running setup.py install for cryptography
    Complete output from command C:\ProgramData\Runtime\Python\python.exe -c "import setuptools, tokenize;__file__='S:\\Temp\\Local\\pip-build-j3dfyfa3\\cryptography\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record S:\Temp\Local\pip-igpv1y8a-record\install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.5
    creating build\lib.win-amd64-3.5\cryptography
    copying src\cryptography\exceptions.py -> build\lib.win-amd64-3.5\cryptography
    copying src\cryptography\fernet.py -> build\lib.win-amd64-3.5\cryptography
    copying src\cryptography\utils.py -> build\lib.win-amd64-3.5\cryptography
    copying src\cryptography\x509.py -> build\lib.win-amd64-3.5\cryptography
    copying src\cryptography\__about__.py -> build\lib.win-amd64-3.5\cryptography
    copying src\cryptography\__init__.py -> build\lib.win-amd64-3.5\cryptography
    creating build\lib.win-amd64-3.5\cryptography\hazmat
    copying src\cryptography\hazmat\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat
    creating build\lib.win-amd64-3.5\cryptography\hazmat\backends
    copying src\cryptography\hazmat\backends\interfaces.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends
    copying src\cryptography\hazmat\backends\multibackend.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends
    copying src\cryptography\hazmat\backends\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends
    creating build\lib.win-amd64-3.5\cryptography\hazmat\bindings
    copying src\cryptography\hazmat\bindings\utils.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings
    copying src\cryptography\hazmat\bindings\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings
    creating build\lib.win-amd64-3.5\cryptography\hazmat\primitives
    copying src\cryptography\hazmat\primitives\cmac.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives
    copying src\cryptography\hazmat\primitives\constant_time.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives
    copying src\cryptography\hazmat\primitives\hashes.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives
    copying src\cryptography\hazmat\primitives\hmac.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives
    copying src\cryptography\hazmat\primitives\padding.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives
    copying src\cryptography\hazmat\primitives\serialization.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives
    copying src\cryptography\hazmat\primitives\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives
    creating build\lib.win-amd64-3.5\cryptography\hazmat\backends\commoncrypto
    copying src\cryptography\hazmat\backends\commoncrypto\backend.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\commoncrypto
    copying src\cryptography\hazmat\backends\commoncrypto\ciphers.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\commoncrypto
    copying src\cryptography\hazmat\backends\commoncrypto\hashes.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\commoncrypto
    copying src\cryptography\hazmat\backends\commoncrypto\hmac.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\commoncrypto
    copying src\cryptography\hazmat\backends\commoncrypto\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\commoncrypto
    creating build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    copying src\cryptography\hazmat\backends\openssl\backend.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    copying src\cryptography\hazmat\backends\openssl\ciphers.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    copying src\cryptography\hazmat\backends\openssl\cmac.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    copying src\cryptography\hazmat\backends\openssl\dsa.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    copying src\cryptography\hazmat\backends\openssl\ec.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    copying src\cryptography\hazmat\backends\openssl\hashes.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    copying src\cryptography\hazmat\backends\openssl\hmac.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    copying src\cryptography\hazmat\backends\openssl\rsa.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    copying src\cryptography\hazmat\backends\openssl\utils.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    copying src\cryptography\hazmat\backends\openssl\x509.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    copying src\cryptography\hazmat\backends\openssl\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\backends\openssl
    creating build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\binding.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\cf.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\common_cryptor.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\common_digest.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\common_hmac.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\common_key_derivation.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\secimport.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\secitem.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\seckey.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\seckeychain.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\sectransform.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    copying src\cryptography\hazmat\bindings\commoncrypto\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\commoncrypto
    creating build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\aes.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\asn1.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\bignum.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\binding.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\bio.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\cmac.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\cms.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\conf.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\crypto.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\dh.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\dsa.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\ec.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\ecdh.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\ecdsa.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\engine.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\err.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\evp.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\hmac.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\nid.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\objects.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\opensslv.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\osrandom_engine.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\pem.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\pkcs12.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\pkcs7.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\rand.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\rsa.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\ssl.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\x509.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\x509name.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\x509v3.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\x509_vfy.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    copying src\cryptography\hazmat\bindings\openssl\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\openssl
    creating build\lib.win-amd64-3.5\cryptography\hazmat\primitives\asymmetric
    copying src\cryptography\hazmat\primitives\asymmetric\dh.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\asymmetric
    copying src\cryptography\hazmat\primitives\asymmetric\dsa.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\asymmetric
    copying src\cryptography\hazmat\primitives\asymmetric\ec.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\asymmetric
    copying src\cryptography\hazmat\primitives\asymmetric\padding.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\asymmetric
    copying src\cryptography\hazmat\primitives\asymmetric\rsa.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\asymmetric
    copying src\cryptography\hazmat\primitives\asymmetric\utils.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\asymmetric
    copying src\cryptography\hazmat\primitives\asymmetric\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\asymmetric
    creating build\lib.win-amd64-3.5\cryptography\hazmat\primitives\ciphers
    copying src\cryptography\hazmat\primitives\ciphers\algorithms.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\ciphers
    copying src\cryptography\hazmat\primitives\ciphers\base.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\ciphers
    copying src\cryptography\hazmat\primitives\ciphers\modes.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\ciphers
    copying src\cryptography\hazmat\primitives\ciphers\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\ciphers
    creating build\lib.win-amd64-3.5\cryptography\hazmat\primitives\interfaces
    copying src\cryptography\hazmat\primitives\interfaces\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\interfaces
    creating build\lib.win-amd64-3.5\cryptography\hazmat\primitives\kdf
    copying src\cryptography\hazmat\primitives\kdf\hkdf.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\kdf
    copying src\cryptography\hazmat\primitives\kdf\pbkdf2.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\kdf
    copying src\cryptography\hazmat\primitives\kdf\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\kdf
    creating build\lib.win-amd64-3.5\cryptography\hazmat\primitives\twofactor
    copying src\cryptography\hazmat\primitives\twofactor\hotp.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\twofactor
    copying src\cryptography\hazmat\primitives\twofactor\totp.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\twofactor
    copying src\cryptography\hazmat\primitives\twofactor\__init__.py -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\twofactor
    running egg_info
    writing entry points to src\cryptography.egg-info\entry_points.txt
    writing top-level names to src\cryptography.egg-info\top_level.txt
    writing requirements to src\cryptography.egg-info\requires.txt
    writing dependency_links to src\cryptography.egg-info\dependency_links.txt
    writing src\cryptography.egg-info\PKG-INFO

    warning: manifest_maker: standard file '-c' not found

    reading manifest file 'src\cryptography.egg-info\SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    no previously-included directories found matching 'docs\_build'
    warning: no previously-included files matching '*' found under directory 'vectors'
    writing manifest file 'src\cryptography.egg-info\SOURCES.txt'
    creating build\lib.win-amd64-3.5\cryptography\hazmat\bindings\__pycache__
    copying src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_15f8accfx62b488b1.c -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\__pycache__
    copying src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_89292e72x399b1113.c -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\__pycache__
    copying src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_c4c16865xffc7b1ce.c -> build\lib.win-amd64-3.5\cryptography\hazmat\bindings\__pycache__
    creating build\lib.win-amd64-3.5\cryptography\hazmat\primitives\src
    copying src\cryptography\hazmat\primitives\src\constant_time.c -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\src
    copying src\cryptography\hazmat\primitives\src\constant_time.h -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\src
    copying src\cryptography\hazmat\primitives\src\padding.c -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\src
    copying src\cryptography\hazmat\primitives\src\padding.h -> build\lib.win-amd64-3.5\cryptography\hazmat\primitives\src
    running build_ext

    building '_Cryptography_cffi_89292e72x399b1113' extension
    creating build\temp.win-amd64-3.5
    creating build\temp.win-amd64-3.5\Release
    creating build\temp.win-amd64-3.5\Release\src
    creating build\temp.win-amd64-3.5\Release\src\cryptography
    creating build\temp.win-amd64-3.5\Release\src\cryptography\hazmat
    creating build\temp.win-amd64-3.5\Release\src\cryptography\hazmat\bindings
    creating build\temp.win-amd64-3.5\Release\src\cryptography\hazmat\bindings\__pycache__

    C:\Program Files (x86)\Microsoft\Visual Studio\14.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\ProgramData\Runtime\Python\include -IC:\ProgramData\Runtime\Python\include /Tcsrc\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_89292e72x399b1113.c /Fobuild\temp.win-amd64-3.5\Release\src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_89292e72x399b1113.obj
    _Cryptography_cffi_89292e72x399b1113.c
    src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_89292e72x399b1113.c(2539): warning C4048: different array subscripts: 'unsigned char (*)[0]' and 'unsigned char (*)[32]'
    src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_89292e72x399b1113.c(2540): warning C4048: different array subscripts: 'unsigned char (*)[0]' and 'unsigned char (*)[32]'
    src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_89292e72x399b1113.c(2567): warning C4048: different array subscripts: 'unsigned char (*)[0]' and 'unsigned char (*)[48]'
    C:\Program Files (x86)\Microsoft\Visual Studio\14.0\VC\BIN\amd64\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:C:\ProgramData\Runtime\Python\libs /LIBPATH:C:\ProgramData\Runtime\Python\PCbuild\amd64 libeay32mt.lib ssleay32mt.lib advapi32.lib crypt32.lib gdi32.lib user32.lib ws2_32.lib /EXPORT:PyInit__Cryptography_cffi_89292e72x399b1113 build\temp.win-amd64-3.5\Release\src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_89292e72x399b1113.obj /OUT:build\lib.win-amd64-3.5\cryptography\_Cryptography_cffi_89292e72x399b1113.cp35-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.5\Release\src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_89292e72x399b1113.cp35-win_amd64.lib /MANIFESTFILE:build\temp.win-amd64-3.5\Release\src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_89292e72x399b1113.cp35-win_amd64.pyd.manifest_Cryptography_cffi_89292e72x399b1113.obj : warning LNK4197: export 'PyInit__Cryptography_cffi_89292e72x399b1113' specified multiple times; using first specification
        Creating library build\temp.win-amd64-3.5\Release\src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_89292e72x399b1113.cp35-win_amd64.lib and object build\temp.win-amd64-3.5\Release\src\cryptography\hazmat\bindings\__pycache__\_Cryptography_cffi_89292e72x399b1113.cp35-win_amd64.exp
        libeay32mt.lib(cryptlib.obj) : error LNK2019: unresolved external symbol sscanf referenced in function OPENSSL_cpuid_setup
        libeay32mt.lib(v3_utl.obj) : error LNK2001: unresolved external symbol sscanf
        libeay32mt.lib(cryptlib.obj) : error LNK2019: unresolved external symbol _vsnwprintf referenced in function OPENSSL_showfatal
        libeay32mt.lib(cryptlib.obj) : error LNK2019: unresolved external symbol _vsnprintf referenced in function OPENSSL_showfatal
        ssleay32mt.lib(t1_enc.obj) : error LNK2001: unresolved external symbol __iob_func
        libeay32mt.lib(txt_db.obj) : error LNK2001: unresolved external symbol __iob_func
        libeay32mt.lib(gost_eng.obj) : error LNK2001: unresolved external symbol __iob_func
        libeay32mt.lib(ui_openssl.obj) : error LNK2001: unresolved external symbol __iob_func
        ssleay32mt.lib(s3_srvr.obj) : error LNK2001: unresolved external symbol __iob_func
        ssleay32mt.lib(d1_both.obj) : error LNK2001: unresolved external symbol __iob_func
        libeay32mt.lib(cryptlib.obj) : error LNK2001: unresolved external symbol __iob_func
        libeay32mt.lib(eng_openssl.obj) : error LNK2001: unresolved external symbol __iob_func
        libeay32mt.lib(pem_lib.obj) : error LNK2001: unresolved external symbol __iob_func
        libeay32mt.lib(e_capi.obj) : error LNK2001: unresolved external symbol __iob_func
        ssleay32mt.lib(s3_srvr.obj) : error LNK2019: unresolved external symbol fprintf referenced in function ssl3_accept
        ssleay32mt.lib(d1_both.obj) : error LNK2001: unresolved external symbol fprintf
        ssleay32mt.lib(t1_enc.obj) : error LNK2001: unresolved external symbol fprintf
        libeay32mt.lib(txt_db.obj) : error LNK2001: unresolved external symbol fprintf
        libeay32mt.lib(eng_openssl.obj) : error LNK2001: unresolved external symbol fprintf
        libeay32mt.lib(pem_lib.obj) : error LNK2001: unresolved external symbol fprintf
        libeay32mt.lib(gost_eng.obj) : error LNK2001: unresolved external symbol fprintf
        libeay32mt.lib(ui_openssl.obj) : error LNK2001: unresolved external symbol fprintf
        libeay32mt.lib(gost_eng.obj) : error LNK2019: unresolved external symbol printf referenced in function bind_gost
        libeay32mt.lib(pqueue.obj) : error LNK2001: unresolved external symbol printf
        libeay32mt.lib(e_cswift.obj) : error LNK2019: unresolved external symbol sprintf referenced in function cswift_mod_exp
        libeay32mt.lib(dso_win32.obj) : error LNK2001: unresolved external symbol sprintf
        build\lib.win-amd64-3.5\cryptography\_Cryptography_cffi_89292e72x399b1113.cp35-win_amd64.pyd : fatal error LNK1120: 7 unresolved externals

    error: command 'C:\\Program Files (x86)\\Microsoft\\Visual Studio\\14.0\\VC\\BIN\\amd64\\link.exe' failed with exit status 1120

    ----------------------------------------
    Command "C:\ProgramData\Runtime\Python\python.exe -c "import setuptools, tokenize;__file__='S:\\Temp\\Local\\pip-build-j3dfyfa3\\cryptography\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record S:\Temp\Local\pip-igpv1y8a-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in S:\Temp\Local\pip-build-j3dfyfa3\cryptography

Windows user creation error due to special characters or signs

I want to create a local user in windows which the user name contains "@". Lets say this way I want to use somebody's email address and create a local windows account with his email address like "foo(at)bar.com". Is there any work around to bypass the windows error for the "@" and "." issue? I've tried this with the windows GUI and command line but still getting the same error, My Os is Windows 2008 R2.

How to open a file WinAPI, (Visual c++)

really simple, open a file using winapi, like this guy https://www.youtube.com/watch?v=6jR78lp8Ar0 . but he is doing in windows form application, i would like to know for win32 console application

USB-Printer printing progress information

I need to write a program that finds all connected USB-printers of a Windows PC and send a file to a selected printer from this list. These two points are no problem and work pretty fine

First point

        var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer");
        i = 1;
        foreach (var printer in printerQuery.Get())
        {
            var name = printer.GetPropertyValue("Name");
            var status = printer.GetPropertyValue("Status");
            var isDefault = printer.GetPropertyValue("Default");
            var isNetworkPrinter = printer.GetPropertyValue("Network");
            var PortName = printer.GetPropertyValue("PortName");
            bool Connected = (bool)printer.GetPropertyValue("WorkOffline");
            var Caption = printer.GetPropertyValue("Caption");

            string s = "Name: " + name;
            string nbr = "";
            if (i.ToString().Length < 2) nbr = "0";
            nbr += i.ToString();
            listBoxUSBInfo.Items.Add(nbr + ": " + s);
            listBoxUSBInfo.Items.Add("      Status: " + status);
            listBoxUSBInfo.Items.Add("      Default: " + isDefault);
            listBoxUSBInfo.Items.Add("      Network: " + isNetworkPrinter);
            listBoxUSBInfo.Items.Add("      PortName: " + PortName);
            if ( Connected) listBoxUSBInfo.Items.Add("      Connected: True");
            if (!Connected) listBoxUSBInfo.Items.Add("      Connected: False");
            listBoxUSBInfo.Items.Add("      Caption: " + Caption);

            i++;
        }

Second point

Is quite easy:

The class "RawPrinterHelper" is well known in this forum, I think

RawPrinterHelper.SendFileToPrinter("PrinterName", "FileName");

But now my problem.

I must print very large files (more than 100.000 pages) and the operator wants to see, how many pages are currently printed. Is it possible to get this information? For example every 3 seconds, so that I can display at on the screen.

Netbeans Become very Slow when pc are connected through internet

i am using netbeans IDE 7.3.1 . but when ever i run a java web based project and connect internet to my pc, then my browser and netbeans IDE both become very slow . how can i resolve this issue ? is there any solution ? is there hardware issue regarding slowness ??

Delphi: Creating and Reading a text file is causing an I/O 32 error. Should this be prevented using sleep?

I am currently working on a program that needs to be able to report whether or not Windows has been activated.

function TSoftwareReport.getLicenceInfo : String;
var
  Activated : String;
  LicenceFile : TextFile;
begin
  // redirect command output to txt file
  ShellExecute(0,nil,'cmd.exe', '/C cscript %windir%\system32\slmgr.vbs/xpr > C:\Activated.txt', nil, SW_HIDE);
  //Read the file
  Sleep(1000);
  AssignFile(LicenceFile, 'C:\Activated.txt');
  Reset(LicenceFile);
  while not Eof(LicenceFile) do
  begin
    ReadLn(LicenceFile,Activated);
    if AnsiContainsText(Activated, 'Permanently') then
    begin
      Activated := 'Permanent';
      Break;
    end;
  end;
  //cleanup file
  CloseFile(LicenceFile);
  DelDir('C:\Activated.txt');
  Result := Activated;
end;

Currently I am using the ShellExecute and redirecting the output to a text file, that I then want to read in order to find out if Windows has been activated.

The problem I am having is that when I go to do the ShellExecute line followed by the AssignFile line I get an I/O 32 error. I suspect that this is due to ShellExecute not closing the file before I attempt to access it with "AssignFile". Which is why I now have the Sleep() line in. The problem with this is that I don't know how long I should be sleeping for as performance will be different across machines.

I tried writing code that would try running the AssignFile line and if that fails, then sleep() and try again but now I'm throwing exceptions on purpose. The whole thing just feels hacky and badly written. I already feel bad about having to redirect the output from shellexecute to a text file.

So the question is, Should I be using sleep, and if so how do I decide how long to sleep for? Should I be using an alternative?

Git on Windows not working with remote because of "SSL protocol" errors

tl;dr

Git on Windows stops connecting to github because of mysterious "SSL protocol" errors. Halp!

The Issue

I'm developing on Windows, using a private GitHub repo for source control. When I first boot my system, I'm able to access the remote repo without issue - pull, push, fetch, etc. all work just fine.

After some amount of time(*), this stops, and I get the following error:

fatal: unable to access 'http://ift.tt/1JC7YVi': Unknown SSL protocol error in connection to github.com:443

(*) The amount of time seems variable - I've witnessed as little as an hour or two, up to a whole day. Usually after coming back from the system sleeping, it seems to be an issue, but I don't know if it's caused by a time delay or by the system sleeping.

Checking via cURL, I get

λ curl -v "http://ift.tt/1JC7YVi"
*   Trying 192.30.252.130...
* Connected to github.com (192.30.252.130) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: C:\Program Files (x86)\Git\bin\curl-ca-bundle.crt
  CApath: none
* TLSv1.0, TLS handshake, Client hello (1):
* Unknown SSL protocol error in connection to github.com:443
* Closing connection 0
curl: (35) Unknown SSL protocol error in connection to github.com:443

Using set GIT_CURL_VERBOSE=1 with git pull shows similar information. Sometimes it succeeds (see below), but most of the time it fails.

Further Notes

There's a little bit of a sporadic nature to it - sometimes I can get requests to succeed, but once it starts exploding, it's generally broken 9 out of 10 requests or more.

A successful cURL request looks like:

λ curl -v "http://ift.tt/1JC7YVi"
*   Trying 192.30.252.130...
* Connected to github.com (192.30.252.130) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: C:\Program Files (x86)\Git\bin\curl-ca-bundle.crt
  CApath: none
* TLSv1.0, TLS handshake, Client hello (1):
* TLSv1.0, TLS handshake, Server hello (2):
* TLSv1.0, TLS handshake, CERT (11):
* TLSv1.0, TLS handshake, Server finished (14):
* TLSv1.0, TLS handshake, Client key exchange (16):
* TLSv1.0, TLS change cipher, Client hello (1):
* TLSv1.0, TLS handshake, Finished (20):
* TLSv1.0, TLS change cipher, Client hello (1):
* TLSv1.0, TLS handshake, Finished (20):
* SSL connection using TLSv1.0 / AES128-SHA
* Server certificate:
*        subject: businessCategory=Private Organization; 1.3.6.1.4.1.311.60.2.1.3=US; 1.3.6.1.4.1.311.60.2.1.2=Delaware; serialNumber=5157550; street=548 4th Street; postalCode=94107; C=US; ST=California; L=San Francisco; O=GitHub, Inc.; CN=github.com
*        start date: 2014-04-08 00:00:00 GMT
*        expire date: 2016-04-12 12:00:00 GMT
*        subjectAltName: github.com matched
*        issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert SHA2 Extended Validation Server CA
*        SSL certificate verify ok.
> GET /our-team/private-repo.git/ HTTP/1.1
> User-Agent: curl/7.41.0
> Host: github.com
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Server: GitHub.com
< Date: Mon, 11 May 2015 15:19:43 GMT
< Content-Type: text/html
< Content-Length: 178
< Location: http://ift.tt/1Pe36wi
< Vary: Accept-Encoding
< X-Served-By: 76f8aa18dab86a06db6e70a0421dc28c
<
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>
* Connection #0 to host github.com left intact

The Question

I've googled a good bit on trying to find this (over the course of several weeks, so I don't have links), but most suggestions seem to point at certificate errors or OpenSSL version mismatches / bugs (which wouldn't be sporadic like this AFAIK).

What might be causing this failure, and how can I resolve it?

Relevant Software:

λ git --version
git version 1.9.5.msysgit.1

λ curl --version
curl 7.41.0 (i386-pc-win32) libcurl/7.41.0 OpenSSL/0.9.8zf zlib/1.2.8
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL libz

assembly - Calling dll functions

I wish to know how can I call a function of a .dll from assembly code, how do I get the address, and where the value returned from the function is stored. Thanks in advance.

import comma separated text data to java database table

I have several large MS Access databases (e.g. 1gb each file), which I want to import to JavaDB Derby database so that whole application can be switched to Java platform. I'm using Windows 7 64 bit/ Netbeans 8.0 (which no more supports JDBC-ODBC). I am using "ucanaccess" to connect to such a large MS access database, now the problem is that the system either takes infinitely long or stops responding, while trying to connet to the MS access database. Is there any other faster and more efficient way to import/ convert such large Access databases (almost 200 databases, 1gb each).

How to execute code during windows form [C++]

I was wondering how I'd Execute my network code during the form is running because if I put it in the comment area where it says "Code To Execute here" it will run AFTER the form exists but not DURING when it's running.

#include "Mouse.h"
#include <SFML\System.hpp>
#include <SFML\Network.hpp>
#include <SFML\Audio.hpp>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <Windows.h>

using namespace std;
using namespace System;
using namespace System::Windows::Forms;

[STAThread]

int main(array<String^>^ arg) {
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);

    Administration::Mouse form;
    Application::Run(%form)

    /* code i wanted to execute goes here */

}

Thanks in Advance

How to kill a process in python 2.5 on windows 64bit platform?

I have a python script by which i am opening three executable files as follows:

Aa=subprocess.Popen([r"..\location\learning\A.exe"])
Bb=subprocess.Popen([r"..\location\learning\new\B.bat"])
Cc=subprocess.Popen([r"..\location\learning\new\B.bat"])

All the three files are getting opened. Now,next step i want kill these three opened modules.So, firstly i tried to kill "Aa" as follows:

PROCESS_TERMINATE= 1
k = ctypes.windll.kernel32klll
handle = k.OpenProcess(PROCESS_TERMINATE, False,Aa.pid)
k.TerminateProcess(handle, -1)
k.CloseHandle(handle)

But after adding these piece of lines the three modules 'Aa','Bb' and 'Cc' they don't gets opened.So,i want to know some clean solution so that firstly all the three modules gets executed and then after a while they get closed itself. As,i am using python 2.5 on windows 64 bit platform so kindly suggest solution accordingly.

For loop reading file names with spaces

I'm trying to scan files in directorys for text inside, but whenever I come across a file that has the ' - Copy' added to the end of it from windows, the program will not read it. I've tried using quotes within the name being passed, but no dice.

FOR /R %%F in (*.CDP) do (
    for /f "tokens=*" %%a in (%%~nxF) do (

I've been using this code and have no issues with the typical files Im seeing. however if its something like dummy_file - Copy, I will get an error from the program saying 'System cannot find the file dummy_file.' period included. If I use

FOR /R %%F in (*.CDP) do (
        for /f "tokens=*" %%a in ("%%~nxF") do (

Then the second for loop gets skipped, and the program proceeds on. I thought this would made the loop take it as a string literal, but apparently the for loop has its own way of reading things.

Is it possible to accept files in this loop that have a - Copy in them? Will I be able to use dummy_file - Copy.cdp here?

Windows Phone 8.1 Development - Get data from a list to populate answers on a page

I'm attempting to build a sort of quiz for Windows Phone 8.1 using C# and XAML, and I want to add questions and answers to a list/array, and then on the page each line from that list/array populates the buttons and textblocks on the page.

I originally wanted to do this from a text file instead of a list or array but this seemed a lot more complicated than I first thought.

I'm wondering if anyone can point me in the right direction?

Thanks.

Alternative of subInACL to grant permissions to a service ?

Here I have a scenario where I can use subInACL to grant START/STOP/PAUSE permissions to MSSQLSERVER and SQLSERVERAGENT with "NT AUTHORITY\NETWORK SERVICE" account .

subinacl.exe /service MSSQLSERVER /grant="NT AUTHORITY\MSSQLSERVER"=PTO

subinacl.exe /service SQLSERVERAGENT /grant="NT AUTHORITY\SQLSERVERAGENT"=PTO

The above two commands work fine and resolve the Access Denied issue when I start/stop the service using xp_servicecontrol .

However I was looking for an alternative to do the same without having to donwload subInACL and then use it . Any help on this will be much appreciated!

C# Windows Store App can't seem to execute Bat.file

I'm in the middle of creating a POS app, which is meant to run in Kiosk mode on a device with no keyboard (both normal and on-screen).

Therefore it is very important for me, to be able to do 2 things from inside the app.

  1. Shutdown Windows

and

  1. Restart Windows

To my understanding it's not possible to access process.Start - Hence I created 2 batch files, which is working perfect when double-clicked on my desktop.

c# file not found exeption after app starts on startup

I have problem with my app. When i run it by myself all works perfect. But when my app start from startup I have System.IO.FileNotFoundException. I add my app on startup by following code:

RegistryKey wowNode = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run", true);

wowNode.SetValue("myApp", System.Reflection.Assembly.GetEntryAssembly().Location);

and when my app start after reboot I have System.IO.FileNotFoundException all files are in the same directory with .exe file

Can someone help me with this?

code I use for read file:

names = File.ReadAllLines("name.txt");

Frame navigation issue while using Drawer Layout in windows phone 8.1

I am developing a Windows Phone App 8.1 using a third party DrawerLayout. My problem is when I have design the page using draweralayout. I need to pass the same layout to each other pages in my application. but when i use bold Frame.navigate(typeof(Page1)); the application is crashed. I am unable to debug the problem. please help!!!

My Xaml Code is

<Grid x:Name="Rootlayout">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <!-- title bar-->
    <Grid x:Name="TitleBar" Height="50" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" Background="SkyBlue">
        <Image  Source="/Assets/fs-logo.png" Height="50" HorizontalAlignment="Left" Margin="10,0,0,0"/>
    </Grid>
    <!--Drawer Layout-->
    <drawer:DrawerLayout x:Name="DrawerLayout" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">
        <!--Main Layout-->
        <Grid x:Name="mainLayout" Background="White" >
            <ScrollViewer>
                <Grid Margin="5">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <Image x:Name="mainImage" Grid.Row="0" Source="{Binding }"></Image>
                    <GridView x:Name="grdView" Grid.Row="1" ItemsSource="{Binding }" ItemContainerStyle="{StaticResource GridViewItemContainer}" Tapped="grdView_Tapped" >
                        <GridView.ItemTemplate>
                            <DataTemplate>
                                <Border BorderThickness="1" BorderBrush="Blue">
                                <Grid Height="{Binding Size}"
                                      Width="{Binding Size}">
                                    <Image Height="120" Width="150" Source="{Binding sImageURL}" Stretch="Fill">

                                    </Image>
                                    <TextBlock Text="{Binding Name}" HorizontalAlignment="Center" VerticalAlignment="Bottom" Foreground="Black" FontSize="18"/>
                                </Grid>
                                </Border>
                            </DataTemplate>
                        </GridView.ItemTemplate>
                        <GridView.ItemsPanel>
                            <ItemsPanelTemplate>
                                <ItemsWrapGrid Orientation="Horizontal"></ItemsWrapGrid>
                            </ItemsPanelTemplate>
                        </GridView.ItemsPanel>
                    </GridView>
                </Grid>
            </ScrollViewer>
        </Grid>
        <!--Drawer Layout-->
        <Grid x:Name="listFragment" FlowDirection="LeftToRight" >
            <ListView x:Name="listItem" SelectionChanged="listItem_SelectionChanged">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" FontSize="20" Foreground="Black" Margin="10" VerticalAlignment="Center" HorizontalAlignment="Left"/>      
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </drawer:DrawerLayout>
    <Image Grid.Row="1" Grid.Column="0" Height="50" Width="50" Source="/Assets/appbar.right.png" Tapped="chevlon_Tapped">

    </Image>
</Grid>

My MainPage.cs

 public sealed partial class MainPage : Page
{
    private NavigationHelper navigationHelper;
    private ObservableDictionary defaultViewModel = new ObservableDictionary();

    List<Services.Company> companyData;
    List<Services.Category> categoryData;

    public MainPage()
    {
        this.InitializeComponent();

        Loaded += MainPage_Loaded;
        this.navigationHelper = new NavigationHelper(this);
        this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
        this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
        this.NavigationCacheMode = NavigationCacheMode.Required;
    }

   async void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
       await  Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();


      // SetGridViewItemSize();        
            //throw new NotImplementedException();
    }
   /// <summary>
   /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>.
   /// </summary>
   public NavigationHelper NavigationHelper
   {
       get { return this.navigationHelper; }
   }

   /// <summary>
   /// Gets the view model for this <see cref="Page"/>.
   /// This can be changed to a strongly typed view model.
   /// </summary>
   public ObservableDictionary DefaultViewModel
   {
       get { return this.defaultViewModel; }
   }

   private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
   {
       if (e.PageState != null)
       {

          // this.DefaultViewModel["MainPage"] = (MainPage)e.PageState["MainPage"];
           // Restore scroll offset
           var index = (int)e.PageState["FirstVisibleItemIndex"];
           var container = grdView.ContainerFromIndex(index);
           grdView.ScrollIntoView(container);



       }
       else
       {
           //Load Data for the First time

           DrawerLayout.InitializeDrawerLayout();
           var company = await Services.CompCatInfo.GetCompaniesAsync(App.compId);
           companyData = company.ToList();
           if (companyData.Count > 0)
           {
               mainImage.Source = new BitmapImage(new Uri(companyData.ElementAt(0).LogoImgUrl, UriKind.Absolute));
           }
           var category = await Services.CompCatInfo.GetCategoriesAsync(App.compId);
           categoryData = category.ToList();

           SetGridViewItemSize();
           if (categoryData.Count > 0)
           {
               grdView.ItemsSource = categoryData;
           }


       }

   }
   private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
   {
       var isp = (ItemsWrapGrid)grdView.ItemsPanelRoot;
       int firstVisibleItem = isp.FirstVisibleIndex;
       e.PageState["FirstVisibleItemIndex"] = firstVisibleItem;
      // e.PageState["HomePage"] = this.Frame.CurrentSourcePageType;
       // This must be serializable according to the SuspensionManager
       //e.PageState["MainPage"] = this.DefaultViewModel["MainPage"];
   }
   private void SetGridViewItemSize()
   {
       //var viewModel = (DataContext as ViewModel1);

       var width = Math.Truncate((grdView.ActualWidth - 10));
       var height = Math.Truncate((grdView.ActualHeight - 10));

       // total left + right margin for each tile (ItemContainerStyle)
       var margin = 10;
       var twoColumnGridPortrait = (width / 2) - margin;
     //  var threeColumnGridPortrait = (width / 3) - margin;
       var twoColumnGridLandscape = (height / 2) - margin;
       var threeColumnGridLandscape = (height / 3) - margin;
       double portrait;
       double landscape;
       portrait = twoColumnGridPortrait;
       landscape = threeColumnGridLandscape;

       Application.Current.Resources["GridViewItemPortrait"] = Math.Round(portrait, 2);
       Application.Current.Resources["GridViewItemLandscape"] = Math.Round(landscape, 2);

       if (DisplayInformation.GetForCurrentView().CurrentOrientation == DisplayOrientations.Portrait)
       {
           Measure((double)Application.Current.Resources["GridViewItemPortrait"]);
       }
       else
       {
           Measure((double)Application.Current.Resources["GridViewItemLandscape"]);
       }
      // throw new NotImplementedException();
   }

   private void Measure(double size)
   {
       for (int i = 0; i < categoryData.Count; i++)
       {
           var item = categoryData[i];
           item.Size = size;
       }
       //throw new NotImplementedException();
   }
   #region NavigationHelper registration
   /// <summary>
    /// Invoked when this page is about to be displayed in a Frame.
    /// </summary>
    /// <param name="e">Event data that describes how this page was reached.
    /// This parameter is typically used to configure the page.</param>
    protected override void OnNavigatedTo(NavigationEventArgs e)
   {
       this.navigationHelper.OnNavigatedTo(e);




        //if (e.NavigationMode == NavigationMode.New)
        //{
        //    DrawerLayout.InitializeDrawerLayout();
        //    var company = await Services.CompCatInfo.GetCompaniesAsync(App.compId);
        //    companyData = company.ToList();
        //    if (companyData.Count > 0)
        //    {
        //        mainImage.Source = new BitmapImage(new Uri(companyData.ElementAt(0).LogoImgUrl, UriKind.Absolute));
        //    }
        //    var category = await Services.CompCatInfo.GetCategoriesAsync(App.compId);
        //    categoryData = category.ToList();
        //    SetGridViewItemSize();
        //    grdView.ItemsSource = categoryData;
        //}
        //else 
        //{
        //   // this.Frame.Content = e.Content;

        //}
        // TODO: Prepare page for display here.

        // TODO: If your application contains multiple pages, ensure that you are
        // handling the hardware Back button by registering for the
        // Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
        // If you are using the NavigationHelper provided by some templates,
        // this event is handled for you.
    }

    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        this.navigationHelper.OnNavigatedFrom(e);
    }

   #endregion

    private void chevlon_Tapped(object sender, TappedRoutedEventArgs e)
    {
        string[] list = new string[] { "Services","Solutions","Technologies","About Us"};
        listItem.ItemsSource = list.ToList();
        if(DrawerLayout.IsDrawerOpen)
        {
            DrawerLayout.CloseDrawer();
        }
        else
        {
            DrawerLayout.OpenDrawer();
        }
    }

    private void listItem_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (listItem.SelectedItem != null)
        {
            var selecteditem = listItem.SelectedValue as string;
           // DetailsTxtBlck.Text = "SelectedItem is: " + selecteditem;
            DrawerLayout.CloseDrawer();
            listItem.SelectedItem = null;
        }

    }

    private void grdView_Tapped(object sender, TappedRoutedEventArgs e)
    {
        DrawerLayout.CloseDrawer();
        if(e.OriginalSource.GetType().ToString()=="Windows.UI.Xaml.Controls.Image"||e.OriginalSource.GetType().ToString()=="Windows.UI.Xaml.Controls.TextBlock")
        {
            var catObj = (sender as GridView).SelectedItem as Services.Category;
            ////Frame rootFrame = Window.Current.Content as Frame;
            ////rootFrame.Navigate(typeof(Page2),catObj);
           Frame.Navigate(typeof(Page2),catObj);

        }

    }
}