qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
55,494,430
Plz suggest how to create dictionary from the following file contetns ``` 2,20190327.1.csv.gz 3,20190327.23.csv.gz 4,20190327.21302.csv.gz 2,20190327.24562.csv.gz ``` my required output is ``` {2:20190327.1.csv.gz:982, 3:20190327.23.csv.gz, 4:20190327.21302.csv.gz, 2:20190327.24562.csv.gz} ``` I am new to python and I tried below code but It is not working. Please suggest ``` from __future__ import print_function import csv file = '/tmp/.fileA' with open(file) as fh: rd = csv.DictReader(fh, delimiter=',') for row in rd: print(row) ```
2019/04/03
[ "https://Stackoverflow.com/questions/55494430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3619226/" ]
You could use `$"color".isin("GREEN","RED","YELLOW")` Code example: ``` val df2 = df.withColumn("Ind", when($"color".isin("GREEN","RED","YELLOW"), 1).otherwise(0)) df2.show(false) ``` Outputs: ``` +------+---+ | color|Ind| +------+---+ | RED| 1| | GREEN| 1| |YELLOW| 1| | PINK| 0| +------+---+ ``` A quick search revealed a similar question already answered in stack-overflow: [Spark SQL - IN clause](https://stackoverflow.com/a/40218776/2613150)
You should be able to check the column against a list with: ``` val result = df.withColumn("Ind", when($"color".in("GREEN", "RED", "YELLOW"), 1).otherwise(0)) ```
3,902,608
I'm pretty new to python and am trying to grab the ropes and decided a fun way to learn would be to make a cheesy MUD type game. My goal for the piece of code I'm going to show is to have three randomly selected enemies(from a list) be presented for the "hero" to fight. The issue I am running into is that python is copying from list to list by reference, not value (I think), because of the code shown below... ``` import random #ene = [HP,MAXHP,loDMG,hiDMG] enemies = [[8,8,1,5,"Ene1"],[9,9,3,6,"Ene2"],[15,15,2,8,"Ene3"]] genENE = [] #skews # of ene's to be gen, favoring 1,2, and 3 eneAppears = 3 for i in range(0,eneAppears): num = random.randint(5,5) if num <= 5: genENE.insert(i,enemies[0]) elif num >= 6 and num <=8: genENE.insert(i,enemies[1]) else: genENE.insert(i,enemies[2]) #genENE = [[8,8,1,5,"Ene1"],[9,9,3,6,"Ene2"],[15,15,2,8,"Ene3"]] for i in range(0,eneAppears): if eneAppears == 1: print "A " + genENE[0][4] + " appears!" else: while i < eneAppears: print "A " + genENE[i][4] + " appears!" i = eneAppears genENE[1][0] = genENE[1][0] - 1 print genENE ``` Basically I have a "master" list of enemies that I use to copy whatever one I want over into an index of another list during my first "for" loop. Normally the randomly generated numbers are 1 through 10, but the problem I'm having is more easily shown by forcing the same enemy to be inserted into my "copy" list several times. Basically when I try to subtract a value of an enemy with the same name in my "copy" list, they all subtract that value (see last two lines of code). I've done a lot of searching and cannot find a way to *copy* just a single index from one list to another. Any suggestions? Thanks!
2010/10/10
[ "https://Stackoverflow.com/questions/3902608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/471561/" ]
Change ``` genENE.insert(i,enemies[0]) ``` to ``` genENE.insert(i,enemies[0][:]) ``` This will force the list to be copied rather than referenced. Also, I would use append rather than insert in this instance.
`they all subtract that value` What do you mean do they all? If you mean both lists, you're problem is because you're only referencing the list NOT creating a second one.
58,931,845
My Airflow DAGs mainly consist of PythonOperators, and I would like to use my Python IDEs debug tools to develop python "inside" airflow. - I rely on Airflow's database connectors, which I think would be ugly to move "out" of airflow for development. I have been using Airflow for a bit, and have so far only achieved development and debugging via the CLI. Which is starting to get tiresome. Does anyone know of a nice way to set up PyCharm, or another IDE, that enables me to use the IDE's debug toolset when running `airflow test ..`?
2019/11/19
[ "https://Stackoverflow.com/questions/58931845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152989/" ]
It might be somewhat of a hack, but I found one way to set up PyCharm: * Use `which airflow` to the local airflow environment - which in my case is just a pipenv * Add a new run configuration in PyCharm * Set the python "Script path" to said airflow script * Set Parameters to test a task: `test dag_x task_y 2019-11-19` This have only been validated with the **SequentialExecutor**, which might be important. It sucks that I have to change test parameters in the run configuration for every new debug/development task, but so far this is pretty useful for setting breakpoints and stepping through code while "inside" the local airflow environment.
I debug `airflow test dag_id task_id`, run on a vagrant machine, using PyCharm. You should be able to use the same method, even if you're running airflow directly on localhost. [Pycharm's documentation on this subject](https://www.jetbrains.com/help/pycharm/remote-debugging-with-product.html#remote-debug-config) should show you how to create an appropriate "Python Remote Debug" configuration. When you run this config, it waits to be contacted by the bit of code that you've added someplace (for example in one of your operators). And then you can debug as normal, with breakpoints set in Pycharm.
58,931,845
My Airflow DAGs mainly consist of PythonOperators, and I would like to use my Python IDEs debug tools to develop python "inside" airflow. - I rely on Airflow's database connectors, which I think would be ugly to move "out" of airflow for development. I have been using Airflow for a bit, and have so far only achieved development and debugging via the CLI. Which is starting to get tiresome. Does anyone know of a nice way to set up PyCharm, or another IDE, that enables me to use the IDE's debug toolset when running `airflow test ..`?
2019/11/19
[ "https://Stackoverflow.com/questions/58931845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152989/" ]
Might be a little late to the party, but been looking for a solution to this as well. Wanted to be able to debug code as close to "production mode" as possible (so nothing with test etc). Found a solution in the form of the "Python Debug Server". It works the other way around: Your IDE listens and the connection is made from the remote script to your editor. Just add a new run configuration of type "Python Debug Server". You'll get a screen telling you to `pip install pydevd-pycharm` remotely. At that same page you can fill in your local IP and a port on which the debugger should be available and optional path mappings. After that, just add the proposed 2 lines of code to where you want your debug session to start. Run the configuration to activate the listener and if all is well your editor should break as soon as the location of the `settrace`-call is reached. [![airflow remote debug](https://i.stack.imgur.com/S8gIm.png)](https://i.stack.imgur.com/S8gIm.png) Edit/Note: If you stop the configuration in your editor, airflow **will continue with the task**, be sure to realise that.
It might be somewhat of a hack, but I found one way to set up PyCharm: * Use `which airflow` to the local airflow environment - which in my case is just a pipenv * Add a new run configuration in PyCharm * Set the python "Script path" to said airflow script * Set Parameters to test a task: `test dag_x task_y 2019-11-19` This have only been validated with the **SequentialExecutor**, which might be important. It sucks that I have to change test parameters in the run configuration for every new debug/development task, but so far this is pretty useful for setting breakpoints and stepping through code while "inside" the local airflow environment.
58,931,845
My Airflow DAGs mainly consist of PythonOperators, and I would like to use my Python IDEs debug tools to develop python "inside" airflow. - I rely on Airflow's database connectors, which I think would be ugly to move "out" of airflow for development. I have been using Airflow for a bit, and have so far only achieved development and debugging via the CLI. Which is starting to get tiresome. Does anyone know of a nice way to set up PyCharm, or another IDE, that enables me to use the IDE's debug toolset when running `airflow test ..`?
2019/11/19
[ "https://Stackoverflow.com/questions/58931845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152989/" ]
Might be a little late to the party, but been looking for a solution to this as well. Wanted to be able to debug code as close to "production mode" as possible (so nothing with test etc). Found a solution in the form of the "Python Debug Server". It works the other way around: Your IDE listens and the connection is made from the remote script to your editor. Just add a new run configuration of type "Python Debug Server". You'll get a screen telling you to `pip install pydevd-pycharm` remotely. At that same page you can fill in your local IP and a port on which the debugger should be available and optional path mappings. After that, just add the proposed 2 lines of code to where you want your debug session to start. Run the configuration to activate the listener and if all is well your editor should break as soon as the location of the `settrace`-call is reached. [![airflow remote debug](https://i.stack.imgur.com/S8gIm.png)](https://i.stack.imgur.com/S8gIm.png) Edit/Note: If you stop the configuration in your editor, airflow **will continue with the task**, be sure to realise that.
I debug `airflow test dag_id task_id`, run on a vagrant machine, using PyCharm. You should be able to use the same method, even if you're running airflow directly on localhost. [Pycharm's documentation on this subject](https://www.jetbrains.com/help/pycharm/remote-debugging-with-product.html#remote-debug-config) should show you how to create an appropriate "Python Remote Debug" configuration. When you run this config, it waits to be contacted by the bit of code that you've added someplace (for example in one of your operators). And then you can debug as normal, with breakpoints set in Pycharm.
58,931,845
My Airflow DAGs mainly consist of PythonOperators, and I would like to use my Python IDEs debug tools to develop python "inside" airflow. - I rely on Airflow's database connectors, which I think would be ugly to move "out" of airflow for development. I have been using Airflow for a bit, and have so far only achieved development and debugging via the CLI. Which is starting to get tiresome. Does anyone know of a nice way to set up PyCharm, or another IDE, that enables me to use the IDE's debug toolset when running `airflow test ..`?
2019/11/19
[ "https://Stackoverflow.com/questions/58931845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152989/" ]
For VSCode, the following debug configuration attaches the builtin debugger ``` { "name": "Airflow Test - Example", "type": "python", "request": "launch", "program": "`pyenv which airflow`", // or path to airflow "console": "integratedTerminal", "args": [ // exact formulation may depend on airflow 1.0 vs 2.0 "test", "mydag", "mytask", "`date +%Y-%m-%dT00:00:00`", // current date "-sd", "path/to/mydag" // providing the subdirectory makes this faster ] } ``` I'd assume there are similar configs that work for other IDEs
I debug `airflow test dag_id task_id`, run on a vagrant machine, using PyCharm. You should be able to use the same method, even if you're running airflow directly on localhost. [Pycharm's documentation on this subject](https://www.jetbrains.com/help/pycharm/remote-debugging-with-product.html#remote-debug-config) should show you how to create an appropriate "Python Remote Debug" configuration. When you run this config, it waits to be contacted by the bit of code that you've added someplace (for example in one of your operators). And then you can debug as normal, with breakpoints set in Pycharm.
58,931,845
My Airflow DAGs mainly consist of PythonOperators, and I would like to use my Python IDEs debug tools to develop python "inside" airflow. - I rely on Airflow's database connectors, which I think would be ugly to move "out" of airflow for development. I have been using Airflow for a bit, and have so far only achieved development and debugging via the CLI. Which is starting to get tiresome. Does anyone know of a nice way to set up PyCharm, or another IDE, that enables me to use the IDE's debug toolset when running `airflow test ..`?
2019/11/19
[ "https://Stackoverflow.com/questions/58931845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152989/" ]
Might be a little late to the party, but been looking for a solution to this as well. Wanted to be able to debug code as close to "production mode" as possible (so nothing with test etc). Found a solution in the form of the "Python Debug Server". It works the other way around: Your IDE listens and the connection is made from the remote script to your editor. Just add a new run configuration of type "Python Debug Server". You'll get a screen telling you to `pip install pydevd-pycharm` remotely. At that same page you can fill in your local IP and a port on which the debugger should be available and optional path mappings. After that, just add the proposed 2 lines of code to where you want your debug session to start. Run the configuration to activate the listener and if all is well your editor should break as soon as the location of the `settrace`-call is reached. [![airflow remote debug](https://i.stack.imgur.com/S8gIm.png)](https://i.stack.imgur.com/S8gIm.png) Edit/Note: If you stop the configuration in your editor, airflow **will continue with the task**, be sure to realise that.
For VSCode, the following debug configuration attaches the builtin debugger ``` { "name": "Airflow Test - Example", "type": "python", "request": "launch", "program": "`pyenv which airflow`", // or path to airflow "console": "integratedTerminal", "args": [ // exact formulation may depend on airflow 1.0 vs 2.0 "test", "mydag", "mytask", "`date +%Y-%m-%dT00:00:00`", // current date "-sd", "path/to/mydag" // providing the subdirectory makes this faster ] } ``` I'd assume there are similar configs that work for other IDEs
55,515,401
I have a python script that dynamically create task (airflow operator) and DAG basing on a JSON file that maps every option desired. The script also dedicated function to create any operator needed. Sometimes i want to activate some conditional options based on the mapping... for example in a bigqueryOperator sometimes i need a time\_partitioning and a destination\_table, but i don't want to set on every mapped task. I've tried to read documentation about BaseOperator, but i can't see any java-like set method. Function that return the operator for example the bigQuery one ```py def bqOperator(mappedTask): try: return BigQueryOperator( task_id=mappedTask.get('task_id'), sql=mappedTask.get('sql'), ##destination_dataset_table=project+'.'+dataset+'.'+mappedTask.get('target'), write_disposition=mappedTask.get('write_disposition'), allow_large_results=mappedTask.get('allow_large_results'), ##time_partitioning=mappedTask.get('time_partitioning'), use_legacy_sql=mappedTask.get('use_legacy_sql'), dag=dag, ) except Exception as e: error = 'Error creating BigQueryOperator for task : ' + mappedTask.get('task_id') logger.error(error) raise Exception(error) ``` mappedTask inside json file without partitioning ``` { "task_id": "TEST_TASK_ID", "sql": "some fancy query", "type": "bqOperator", "dependencies": [], "write_disposition": "WRITE_APPEND", "allow_large_results": true, "createDisposition": "CREATE_IF_NEEDED", "use_legacy_sql": false }, ``` mappedTask inside json file with partitioning ``` { "task_id": "TEST_TASK_ID_PARTITION", "sql": "some fancy query", "type": "bqOperator", "dependencies": [], "write_disposition": "WRITE_APPEND", "allow_large_results": true, "createDisposition": "CREATE_IF_NEEDED", "use_legacy_sql": false, "targetTable": "TARGET_TABLE", "time_partitioning": { "field": "DATE_TO_PART", "type": "DAY" } }, ```
2019/04/04
[ "https://Stackoverflow.com/questions/55515401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4626682/" ]
Change `bqOperator` as below to handle that case, basically it would pass None when it won't find that field in your json: ``` def bqOperator(mappedTask): try: return BigQueryOperator( task_id=mappedTask.get('task_id'), sql=mappedTask.get('sql'), destination_dataset_table="{}.{}.{}".format(project, dataset, mappedTask.get('target')) if mappedTask.get('target', None) else None, write_disposition=mappedTask.get('write_disposition'), allow_large_results=mappedTask.get('allow_large_results'), time_partitioning=mappedTask.get('time_partitioning', None), use_legacy_sql=mappedTask.get('use_legacy_sql'), dag=dag, ) except Exception as e: error = 'Error creating BigQueryOperator for task : ' + mappedTask.get('task_id') logger.error(error) raise Exception(error) ```
There is no private methods or fields in python, so you can directly set and get fields like ```py op.use_legacy_sql = True ``` Given that I strongly discourage from doing this, as this a real code smell. Instead you could modify you factory class to apply some defaults to your json data. Or even better, apply defaults on json itself. Than save and use updated json. This will make things more predictable.
63,979,298
So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out? [![enter image description here](https://i.stack.imgur.com/951Bj.png)](https://i.stack.imgur.com/951Bj.png) [![enter image description here](https://i.stack.imgur.com/ye3ru.png)](https://i.stack.imgur.com/ye3ru.png) [![enter image description here](https://i.stack.imgur.com/FFx2n.png)](https://i.stack.imgur.com/FFx2n.png) **IN SHORT**: How to tell Django that it is html and it has to simply join it in the code.(Not to use as text.) *Details* Python 3.8.2 Django 2.2.7 Edit: Haven't read the official documentation then.
2020/09/20
[ "https://Stackoverflow.com/questions/63979298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13935716/" ]
It looks like all standard types (button, image, text, etc) are intercepter by ToolbarItem and converted into appropriate internal representation. But custom view (eg. shape based)... is not. So see below a demo of possible approach. Demo prepared & tested with Xcode 12 / iOS 14. [![demo](https://i.stack.imgur.com/o0ZR8.gif)](https://i.stack.imgur.com/o0ZR8.gif) ``` ToolbarItem(placement: .bottomBar) { ShapeButton(shape: Rectangle(), color: .red) { print(">> works") } } ``` and simple custom Shape-based button ``` struct ShapeButton<S:Shape>: View { var shape: S var color: Color var action: () -> () @GestureState private var tapped = false var body: some View { shape .fill(color).opacity(tapped ? 0.4 : 1) .animation(.linear(duration: 0.15), value: tapped) .frame(width: 18, height: 18) .gesture(DragGesture(minimumDistance: 0) .updating($tapped) { value, state, _ in state = true } .onEnded { _ in action() }) } } ```
If you drop into UIKit it's working for me. ``` struct ButtonRepresentation: UIViewRepresentable { let sfSymbolName: String let titleColor: UIColor let action: () -> () func makeUIView(context: Context) -> UIButton { let b = UIButton() let largeConfig = UIImage.SymbolConfiguration(scale: .large) let image = UIImage(systemName: sfSymbolName, withConfiguration: largeConfig) b.setImage(image, for: .normal) b.tintColor = titleColor b.addTarget(context.coordinator, action: #selector(context.coordinator.didTapButton(_:)), for: .touchUpInside) return b } func updateUIView(_ uiView: UIButton, context: Context) {} func makeCoordinator() -> Coordinator { return Coordinator(action: action) } typealias UIViewType = UIButton class Coordinator { let action: () -> () @objc func didTapButton(_ sender: UIButton) { self.action() } init(action: @escaping () -> ()) { self.action = action } } } ``` Then you can add separate ButtonRepresentations with different colors. ``` .toolbar { ToolbarItem(placement: .cancellationAction) { ButtonRepresentation(sfSymbolName: closeIcon, titleColor: closeIconColor) { presentationMode.wrappedValue.dismiss() } } ```
63,979,298
So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out? [![enter image description here](https://i.stack.imgur.com/951Bj.png)](https://i.stack.imgur.com/951Bj.png) [![enter image description here](https://i.stack.imgur.com/ye3ru.png)](https://i.stack.imgur.com/ye3ru.png) [![enter image description here](https://i.stack.imgur.com/FFx2n.png)](https://i.stack.imgur.com/FFx2n.png) **IN SHORT**: How to tell Django that it is html and it has to simply join it in the code.(Not to use as text.) *Details* Python 3.8.2 Django 2.2.7 Edit: Haven't read the official documentation then.
2020/09/20
[ "https://Stackoverflow.com/questions/63979298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13935716/" ]
It looks like all standard types (button, image, text, etc) are intercepter by ToolbarItem and converted into appropriate internal representation. But custom view (eg. shape based)... is not. So see below a demo of possible approach. Demo prepared & tested with Xcode 12 / iOS 14. [![demo](https://i.stack.imgur.com/o0ZR8.gif)](https://i.stack.imgur.com/o0ZR8.gif) ``` ToolbarItem(placement: .bottomBar) { ShapeButton(shape: Rectangle(), color: .red) { print(">> works") } } ``` and simple custom Shape-based button ``` struct ShapeButton<S:Shape>: View { var shape: S var color: Color var action: () -> () @GestureState private var tapped = false var body: some View { shape .fill(color).opacity(tapped ? 0.4 : 1) .animation(.linear(duration: 0.15), value: tapped) .frame(width: 18, height: 18) .gesture(DragGesture(minimumDistance: 0) .updating($tapped) { value, state, _ in state = true } .onEnded { _ in action() }) } } ```
The simplest solution I've found is to ditch `Button` and use `.onTapGesture` instead. ``` struct ContentView: View { var body: some View { NavigationView { Text("Hello World!") .toolbar { // To be colored RED ToolbarItem(placement: .bottomBar) { Label("Icon One", systemImage: "stop.fill") .foregroundColor(.red) .onTapGesture { // Respond to tap } } // To be colored BLACK ToolbarItem(placement: .bottomBar) { Label("Icon One", systemImage: "play.fill") .foregroundColor(.black) .onTapGesture { // Respond to tap } } } } } } ``` Output: [![enter image description here](https://i.stack.imgur.com/Fk7Wa.png)](https://i.stack.imgur.com/Fk7Wa.png)
63,979,298
So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out? [![enter image description here](https://i.stack.imgur.com/951Bj.png)](https://i.stack.imgur.com/951Bj.png) [![enter image description here](https://i.stack.imgur.com/ye3ru.png)](https://i.stack.imgur.com/ye3ru.png) [![enter image description here](https://i.stack.imgur.com/FFx2n.png)](https://i.stack.imgur.com/FFx2n.png) **IN SHORT**: How to tell Django that it is html and it has to simply join it in the code.(Not to use as text.) *Details* Python 3.8.2 Django 2.2.7 Edit: Haven't read the official documentation then.
2020/09/20
[ "https://Stackoverflow.com/questions/63979298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13935716/" ]
Yep, I've been struggling with the same thing. It looks that `Buttons` are using system tint color and its style overall. Here is my take: ``` content .toolbar { ToolbarItem(placement: .navigationBarLeading) { HStack { StyledButton(image: .system("arrow.left")) { ... } Spacer(minLength: 0) // important to not fell button to default styling } } } ``` The idea is to not display Button only, but together with other UI elements. Looks like a SwiftUI bug to me. (Or just trying to out-smart you.)
It looks like all standard types (button, image, text, etc) are intercepter by ToolbarItem and converted into appropriate internal representation. But custom view (eg. shape based)... is not. So see below a demo of possible approach. Demo prepared & tested with Xcode 12 / iOS 14. [![demo](https://i.stack.imgur.com/o0ZR8.gif)](https://i.stack.imgur.com/o0ZR8.gif) ``` ToolbarItem(placement: .bottomBar) { ShapeButton(shape: Rectangle(), color: .red) { print(">> works") } } ``` and simple custom Shape-based button ``` struct ShapeButton<S:Shape>: View { var shape: S var color: Color var action: () -> () @GestureState private var tapped = false var body: some View { shape .fill(color).opacity(tapped ? 0.4 : 1) .animation(.linear(duration: 0.15), value: tapped) .frame(width: 18, height: 18) .gesture(DragGesture(minimumDistance: 0) .updating($tapped) { value, state, _ in state = true } .onEnded { _ in action() }) } } ```
63,979,298
So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out? [![enter image description here](https://i.stack.imgur.com/951Bj.png)](https://i.stack.imgur.com/951Bj.png) [![enter image description here](https://i.stack.imgur.com/ye3ru.png)](https://i.stack.imgur.com/ye3ru.png) [![enter image description here](https://i.stack.imgur.com/FFx2n.png)](https://i.stack.imgur.com/FFx2n.png) **IN SHORT**: How to tell Django that it is html and it has to simply join it in the code.(Not to use as text.) *Details* Python 3.8.2 Django 2.2.7 Edit: Haven't read the official documentation then.
2020/09/20
[ "https://Stackoverflow.com/questions/63979298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13935716/" ]
It looks like all standard types (button, image, text, etc) are intercepter by ToolbarItem and converted into appropriate internal representation. But custom view (eg. shape based)... is not. So see below a demo of possible approach. Demo prepared & tested with Xcode 12 / iOS 14. [![demo](https://i.stack.imgur.com/o0ZR8.gif)](https://i.stack.imgur.com/o0ZR8.gif) ``` ToolbarItem(placement: .bottomBar) { ShapeButton(shape: Rectangle(), color: .red) { print(">> works") } } ``` and simple custom Shape-based button ``` struct ShapeButton<S:Shape>: View { var shape: S var color: Color var action: () -> () @GestureState private var tapped = false var body: some View { shape .fill(color).opacity(tapped ? 0.4 : 1) .animation(.linear(duration: 0.15), value: tapped) .frame(width: 18, height: 18) .gesture(DragGesture(minimumDistance: 0) .updating($tapped) { value, state, _ in state = true } .onEnded { _ in action() }) } } ```
Sadly this trick only works on iOS. But on the bright side it also works for Menu as well: ``` Menu { Button("A title") {} } label : { HStack { Label("Star"), systemImage: "star") .labelStyle(.iconOnly) .foregroundColor(.red) Spacer(minLength: 0) } } ```
63,979,298
So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out? [![enter image description here](https://i.stack.imgur.com/951Bj.png)](https://i.stack.imgur.com/951Bj.png) [![enter image description here](https://i.stack.imgur.com/ye3ru.png)](https://i.stack.imgur.com/ye3ru.png) [![enter image description here](https://i.stack.imgur.com/FFx2n.png)](https://i.stack.imgur.com/FFx2n.png) **IN SHORT**: How to tell Django that it is html and it has to simply join it in the code.(Not to use as text.) *Details* Python 3.8.2 Django 2.2.7 Edit: Haven't read the official documentation then.
2020/09/20
[ "https://Stackoverflow.com/questions/63979298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13935716/" ]
Yep, I've been struggling with the same thing. It looks that `Buttons` are using system tint color and its style overall. Here is my take: ``` content .toolbar { ToolbarItem(placement: .navigationBarLeading) { HStack { StyledButton(image: .system("arrow.left")) { ... } Spacer(minLength: 0) // important to not fell button to default styling } } } ``` The idea is to not display Button only, but together with other UI elements. Looks like a SwiftUI bug to me. (Or just trying to out-smart you.)
If you drop into UIKit it's working for me. ``` struct ButtonRepresentation: UIViewRepresentable { let sfSymbolName: String let titleColor: UIColor let action: () -> () func makeUIView(context: Context) -> UIButton { let b = UIButton() let largeConfig = UIImage.SymbolConfiguration(scale: .large) let image = UIImage(systemName: sfSymbolName, withConfiguration: largeConfig) b.setImage(image, for: .normal) b.tintColor = titleColor b.addTarget(context.coordinator, action: #selector(context.coordinator.didTapButton(_:)), for: .touchUpInside) return b } func updateUIView(_ uiView: UIButton, context: Context) {} func makeCoordinator() -> Coordinator { return Coordinator(action: action) } typealias UIViewType = UIButton class Coordinator { let action: () -> () @objc func didTapButton(_ sender: UIButton) { self.action() } init(action: @escaping () -> ()) { self.action = action } } } ``` Then you can add separate ButtonRepresentations with different colors. ``` .toolbar { ToolbarItem(placement: .cancellationAction) { ButtonRepresentation(sfSymbolName: closeIcon, titleColor: closeIconColor) { presentationMode.wrappedValue.dismiss() } } ```
63,979,298
So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out? [![enter image description here](https://i.stack.imgur.com/951Bj.png)](https://i.stack.imgur.com/951Bj.png) [![enter image description here](https://i.stack.imgur.com/ye3ru.png)](https://i.stack.imgur.com/ye3ru.png) [![enter image description here](https://i.stack.imgur.com/FFx2n.png)](https://i.stack.imgur.com/FFx2n.png) **IN SHORT**: How to tell Django that it is html and it has to simply join it in the code.(Not to use as text.) *Details* Python 3.8.2 Django 2.2.7 Edit: Haven't read the official documentation then.
2020/09/20
[ "https://Stackoverflow.com/questions/63979298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13935716/" ]
If you drop into UIKit it's working for me. ``` struct ButtonRepresentation: UIViewRepresentable { let sfSymbolName: String let titleColor: UIColor let action: () -> () func makeUIView(context: Context) -> UIButton { let b = UIButton() let largeConfig = UIImage.SymbolConfiguration(scale: .large) let image = UIImage(systemName: sfSymbolName, withConfiguration: largeConfig) b.setImage(image, for: .normal) b.tintColor = titleColor b.addTarget(context.coordinator, action: #selector(context.coordinator.didTapButton(_:)), for: .touchUpInside) return b } func updateUIView(_ uiView: UIButton, context: Context) {} func makeCoordinator() -> Coordinator { return Coordinator(action: action) } typealias UIViewType = UIButton class Coordinator { let action: () -> () @objc func didTapButton(_ sender: UIButton) { self.action() } init(action: @escaping () -> ()) { self.action = action } } } ``` Then you can add separate ButtonRepresentations with different colors. ``` .toolbar { ToolbarItem(placement: .cancellationAction) { ButtonRepresentation(sfSymbolName: closeIcon, titleColor: closeIconColor) { presentationMode.wrappedValue.dismiss() } } ```
Sadly this trick only works on iOS. But on the bright side it also works for Menu as well: ``` Menu { Button("A title") {} } label : { HStack { Label("Star"), systemImage: "star") .labelStyle(.iconOnly) .foregroundColor(.red) Spacer(minLength: 0) } } ```
63,979,298
So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out? [![enter image description here](https://i.stack.imgur.com/951Bj.png)](https://i.stack.imgur.com/951Bj.png) [![enter image description here](https://i.stack.imgur.com/ye3ru.png)](https://i.stack.imgur.com/ye3ru.png) [![enter image description here](https://i.stack.imgur.com/FFx2n.png)](https://i.stack.imgur.com/FFx2n.png) **IN SHORT**: How to tell Django that it is html and it has to simply join it in the code.(Not to use as text.) *Details* Python 3.8.2 Django 2.2.7 Edit: Haven't read the official documentation then.
2020/09/20
[ "https://Stackoverflow.com/questions/63979298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13935716/" ]
Yep, I've been struggling with the same thing. It looks that `Buttons` are using system tint color and its style overall. Here is my take: ``` content .toolbar { ToolbarItem(placement: .navigationBarLeading) { HStack { StyledButton(image: .system("arrow.left")) { ... } Spacer(minLength: 0) // important to not fell button to default styling } } } ``` The idea is to not display Button only, but together with other UI elements. Looks like a SwiftUI bug to me. (Or just trying to out-smart you.)
The simplest solution I've found is to ditch `Button` and use `.onTapGesture` instead. ``` struct ContentView: View { var body: some View { NavigationView { Text("Hello World!") .toolbar { // To be colored RED ToolbarItem(placement: .bottomBar) { Label("Icon One", systemImage: "stop.fill") .foregroundColor(.red) .onTapGesture { // Respond to tap } } // To be colored BLACK ToolbarItem(placement: .bottomBar) { Label("Icon One", systemImage: "play.fill") .foregroundColor(.black) .onTapGesture { // Respond to tap } } } } } } ``` Output: [![enter image description here](https://i.stack.imgur.com/Fk7Wa.png)](https://i.stack.imgur.com/Fk7Wa.png)
63,979,298
So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out? [![enter image description here](https://i.stack.imgur.com/951Bj.png)](https://i.stack.imgur.com/951Bj.png) [![enter image description here](https://i.stack.imgur.com/ye3ru.png)](https://i.stack.imgur.com/ye3ru.png) [![enter image description here](https://i.stack.imgur.com/FFx2n.png)](https://i.stack.imgur.com/FFx2n.png) **IN SHORT**: How to tell Django that it is html and it has to simply join it in the code.(Not to use as text.) *Details* Python 3.8.2 Django 2.2.7 Edit: Haven't read the official documentation then.
2020/09/20
[ "https://Stackoverflow.com/questions/63979298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13935716/" ]
The simplest solution I've found is to ditch `Button` and use `.onTapGesture` instead. ``` struct ContentView: View { var body: some View { NavigationView { Text("Hello World!") .toolbar { // To be colored RED ToolbarItem(placement: .bottomBar) { Label("Icon One", systemImage: "stop.fill") .foregroundColor(.red) .onTapGesture { // Respond to tap } } // To be colored BLACK ToolbarItem(placement: .bottomBar) { Label("Icon One", systemImage: "play.fill") .foregroundColor(.black) .onTapGesture { // Respond to tap } } } } } } ``` Output: [![enter image description here](https://i.stack.imgur.com/Fk7Wa.png)](https://i.stack.imgur.com/Fk7Wa.png)
Sadly this trick only works on iOS. But on the bright side it also works for Menu as well: ``` Menu { Button("A title") {} } label : { HStack { Label("Star"), systemImage: "star") .labelStyle(.iconOnly) .foregroundColor(.red) Spacer(minLength: 0) } } ```
63,979,298
So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out? [![enter image description here](https://i.stack.imgur.com/951Bj.png)](https://i.stack.imgur.com/951Bj.png) [![enter image description here](https://i.stack.imgur.com/ye3ru.png)](https://i.stack.imgur.com/ye3ru.png) [![enter image description here](https://i.stack.imgur.com/FFx2n.png)](https://i.stack.imgur.com/FFx2n.png) **IN SHORT**: How to tell Django that it is html and it has to simply join it in the code.(Not to use as text.) *Details* Python 3.8.2 Django 2.2.7 Edit: Haven't read the official documentation then.
2020/09/20
[ "https://Stackoverflow.com/questions/63979298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13935716/" ]
Yep, I've been struggling with the same thing. It looks that `Buttons` are using system tint color and its style overall. Here is my take: ``` content .toolbar { ToolbarItem(placement: .navigationBarLeading) { HStack { StyledButton(image: .system("arrow.left")) { ... } Spacer(minLength: 0) // important to not fell button to default styling } } } ``` The idea is to not display Button only, but together with other UI elements. Looks like a SwiftUI bug to me. (Or just trying to out-smart you.)
Sadly this trick only works on iOS. But on the bright side it also works for Menu as well: ``` Menu { Button("A title") {} } label : { HStack { Label("Star"), systemImage: "star") .labelStyle(.iconOnly) .foregroundColor(.red) Spacer(minLength: 0) } } ```
7,451,347
I'm programming an iOS application which needs to communicate with a python app in a very effecient way thru UDP sockets. In the middle I have a bonjour service which serves as a bridge for my iOS app and host python app to communicate. I'm building my own protocol which is a simple C structure. The code that I had already as packing strings into NSKeyedArchiver entities which by their turn would be packed in NSData and sent. In the other side there is a NSKeyedUnarchiver. The problem is that it can't understand the C struct i'm sending. Is there a way of putting a C structure inside a NSKeyedArchiver? How should I modify my middle service to remove this?
2011/09/16
[ "https://Stackoverflow.com/questions/7451347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/933104/" ]
Yes, it is possible. Read the [Archives and Serializations Programming Guide](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Archiving/Archiving.html), everything is explained here with samples, including this case, especially the part [Encoding and decoding C Data Types](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Archiving/Articles/codingctypes.html#//apple_ref/doc/uid/20001294-BBCBDHBI) :)
Rather than use NSData - and if the struct contains simple data items, rather than objects pointers you can use NSValue ``` NSValue valueFromStruct = [[NSValue value:&aStruct withObjCType:@encode(YourStructType)] retain]; ``` As NSValue conforms to the NSCoding protocol you can use the methods that you want to use.
68,382,302
I am using a MacOS 10.15 and Python version 3.7.7 I wanted to upgrade pip so I ran `pip install --upgrade pip`, but it turns out my pip was gone (it shows `ImportError: No module named pip` when I want to use `pip install ...`) I tried several methods like `python3 -m ensurepip`, but it returns ``` Looking in links: /var/folders/sc/f0txnv0j71l2mvss7psclh_h0000gn/T/tmpchwk90o3 Requirement already satisfied: setuptools in ./anaconda3/lib/python3.7/site-packages (49.6.0.post20200814) Requirement already satisfied: pip in ./anaconda3/lib/python3.7/site-packages (20.2.2) ``` and `pip install` still does not work and returns the same error message. I also tried `easy_install pip` and other methods but pip still does not work. Can anyone help me with this? --- Update: Using the method from @cshelly, it works on my computer!
2021/07/14
[ "https://Stackoverflow.com/questions/68382302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14438351/" ]
Try the following: ```sh python3 -m pip --upgrade pip ``` The `-m` flag will run a library module as a script.
The pip used by python3 is called pip3. Since you're using python3, you want to do `pip3 install --upgrade pip`.
68,382,302
I am using a MacOS 10.15 and Python version 3.7.7 I wanted to upgrade pip so I ran `pip install --upgrade pip`, but it turns out my pip was gone (it shows `ImportError: No module named pip` when I want to use `pip install ...`) I tried several methods like `python3 -m ensurepip`, but it returns ``` Looking in links: /var/folders/sc/f0txnv0j71l2mvss7psclh_h0000gn/T/tmpchwk90o3 Requirement already satisfied: setuptools in ./anaconda3/lib/python3.7/site-packages (49.6.0.post20200814) Requirement already satisfied: pip in ./anaconda3/lib/python3.7/site-packages (20.2.2) ``` and `pip install` still does not work and returns the same error message. I also tried `easy_install pip` and other methods but pip still does not work. Can anyone help me with this? --- Update: Using the method from @cshelly, it works on my computer!
2021/07/14
[ "https://Stackoverflow.com/questions/68382302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14438351/" ]
Try the following: ```sh python3 -m pip --upgrade pip ``` The `-m` flag will run a library module as a script.
Since it says no module named pip, thus pip is not installed in your system So you may try ``` curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py ``` to download pip directly then you can use execute it using - ``` python3 get-pip.py ``` For details you may refer - <https://www.geeksforgeeks.org/how-to-install-pip-in-macos/> PS: You may need to use **sudo** to make use of administrative privileges.
62,451,944
``` class TempClass(): def __init__(self,*args): for i in range(len(args)): self.number1=args[0] self.number2=args[1] print(self.number1,self.number2) temp1=TempClass(10,20) ``` output: 10 20 ``` class TempClass2(): def __init__(self,*args): for i in range(len(args)): self.number1=args[0] self.number2=args[1] print(self.number1) print(self.number1[0],self.number2) temp2=TempClass2([10,20],40) ``` output : [10, 20] ``` class TempClass3(): def __init__(self,*args): for i in range(len(args)): self.number1[0]=args[0] self.number1[1]=args[1] print(self.number1) temp3=TempClass3(10,20) ``` output: AttributeError: 'TempClass3' object has no attribute 'number1' My question is in TempClass3 I tried to create a list by passing parameters to construct. why is it not possible?? Note: I tried doing this while learning OOps concepts in python.. please suggest me if my question itself is meaningless.
2020/06/18
[ "https://Stackoverflow.com/questions/62451944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5985980/" ]
You first need to initialize `self.number1` with `[None] * 2` (or similar) before using it. However, I would use `args` directly: ``` class TempClass3(): def __init__(self,*args): self.number1 = list(args) print(self.number1) temp3=TempClass3(10,20) ```
When you are calling self.number1[0]=args[0], you are asking python to first open the list self.number1 which doesn't exist, then find an element in this non-existent list. If it doesn't exist but you pass it a value, like self.number1=args[0], python will create self.number1 and define self.number1 as args[0]. You could fix this by adding the line self.number1 = [0,0] at the start of tempclass3 so that the list already exists.
62,451,944
``` class TempClass(): def __init__(self,*args): for i in range(len(args)): self.number1=args[0] self.number2=args[1] print(self.number1,self.number2) temp1=TempClass(10,20) ``` output: 10 20 ``` class TempClass2(): def __init__(self,*args): for i in range(len(args)): self.number1=args[0] self.number2=args[1] print(self.number1) print(self.number1[0],self.number2) temp2=TempClass2([10,20],40) ``` output : [10, 20] ``` class TempClass3(): def __init__(self,*args): for i in range(len(args)): self.number1[0]=args[0] self.number1[1]=args[1] print(self.number1) temp3=TempClass3(10,20) ``` output: AttributeError: 'TempClass3' object has no attribute 'number1' My question is in TempClass3 I tried to create a list by passing parameters to construct. why is it not possible?? Note: I tried doing this while learning OOps concepts in python.. please suggest me if my question itself is meaningless.
2020/06/18
[ "https://Stackoverflow.com/questions/62451944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5985980/" ]
You first need to initialize `self.number1` with `[None] * 2` (or similar) before using it. However, I would use `args` directly: ``` class TempClass3(): def __init__(self,*args): self.number1 = list(args) print(self.number1) temp3=TempClass3(10,20) ```
In this code: ``` class TempClass3(): def __init__(self,*args): for i in range(len(args)): self.number1[0]=args[0] self.number1[1]=args[1] print(self.number1) ``` you're attempting to access a list called `self.number1` that doesn't exist yet. Instead you want to do something like: ``` class TempClass3(): def __init__(self,*args): self.number1 = [] # create an empty list we can append to self.number1.append(args[0]) self.number1.append(args[1]) print(self.number1) ``` or maybe: ``` class TempClass3(): def __init__(self,*args): self.number1 = [args[0], args[1]] # create a list with two elements print(self.number1) ``` or, if you just want all the args instead of only the first two, simply: ``` class TempClass3(): def __init__(self,*args): self.number1 = list(args) # create a list from the contents of a tuple print(self.number1) ```
53,107,475
I am trying to install kdb on the jupyter-notebook. First I download the 64-bit windows version on <https://ondemand.kx.com/> and also download the licence in the email. Then I open it using window command prompt. I set QHOME and PATH using the following code in command prompt: ``` setx QHOME "C:\q" setx PATH "%PATH%;C:\q\w64" exit ``` I can run q properly in windows command. However, when I open Anaconda3 prompt, to run the q, by typing: ``` activate base q ``` The error appears ``` python.exe: can't open file 'C:\Users\Cecil': [Errno 2] No such file or directory ``` My directory path in Anaconda is ``` (base) C:\Users\Cecil M> ``` And when I open the jupyter-book, the kernel is dead Is there any step missing here. I have downloaded relative packages, such as kx kdb, kx embedpy, kx jupyterq.
2018/11/01
[ "https://Stackoverflow.com/questions/53107475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10105915/" ]
You didn't give us the requirements for the individual filenames, but here is an example that uses a sequential number for each given filename. ``` count = 0 for item in all_news: count += 1 filename = '{}.txt'.format(count) with open(filename, 'w') as f_out: f.write('{}\n'.format(item)) ```
You have to open a new file on each element of the list, and you will need a counter to ensure have separated filenames (or a second list). ``` counter=0 for item in all_news: with open('your_file_'+str(counter)+'.txt', 'w') as f: f.write("%s\n" % item) counter = counter + 1 ``` This will write each element in files like `you_file_0.txt`, `your_file_1.txt`, etc *(I'm just elaborating what ShadowRanger already commented above).*
53,107,475
I am trying to install kdb on the jupyter-notebook. First I download the 64-bit windows version on <https://ondemand.kx.com/> and also download the licence in the email. Then I open it using window command prompt. I set QHOME and PATH using the following code in command prompt: ``` setx QHOME "C:\q" setx PATH "%PATH%;C:\q\w64" exit ``` I can run q properly in windows command. However, when I open Anaconda3 prompt, to run the q, by typing: ``` activate base q ``` The error appears ``` python.exe: can't open file 'C:\Users\Cecil': [Errno 2] No such file or directory ``` My directory path in Anaconda is ``` (base) C:\Users\Cecil M> ``` And when I open the jupyter-book, the kernel is dead Is there any step missing here. I have downloaded relative packages, such as kx kdb, kx embedpy, kx jupyterq.
2018/11/01
[ "https://Stackoverflow.com/questions/53107475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10105915/" ]
Something like this? ``` all_news = ['a', 'b', 'c'] for item in all_news: # every file will get the item name # if there aren't repeated items with open(f'{item}.txt', 'w') as f: f.write("%s\n" % item) ``` If in the list are more items with the same name: ``` for count, item in enumerate(all_news, 1): # every file will get the the index as name with open(f'{count}.txt', 'w') as f: f.write("%s\n" % item) ```
You have to open a new file on each element of the list, and you will need a counter to ensure have separated filenames (or a second list). ``` counter=0 for item in all_news: with open('your_file_'+str(counter)+'.txt', 'w') as f: f.write("%s\n" % item) counter = counter + 1 ``` This will write each element in files like `you_file_0.txt`, `your_file_1.txt`, etc *(I'm just elaborating what ShadowRanger already commented above).*
33,340,749
I have registered on Google Developers Console, but my project is not a billed project. I did the steps of “initialized environment.” and “Build and Run ”as the web pages <https://github.com/GoogleCloudPlatform/datalab/wiki/Development-Environment> and <https://github.com/GoogleCloudPlatform/datalab/wiki/Build-and-Run> describe. But when i run code in Notebook deployed on my local linux server,i run into the following error: Create and run a SQL query ========================== bq.Query('SELECT \* FROM [cloud-datalab-samples:httplogs.logs\_20140615] LIMIT 3').results() -------------------------------------------------------------------------------------------- Exception Traceback (most recent call last) in () 1 # Create and run a SQL query ----> 2 bq.Query('SELECT \* FROM [cloud-datalab-samples:httplogs.logs\_20140615] LIMIT 3').results() /usr/local/lib/python2.7/dist-packages/gcp/bigquery/\_query.pyc in results(self, use\_cache) 130 """ 131 if not use\_cache or (self.\_results is None): --> 132 self.execute(use\_cache=use\_cache) 133 return self.\_results.results 134 /usr/local/lib/python2.7/dist-packages/gcp/bigquery/\_query.pyc in execute(self, table\_name, table\_mode, use\_cache, priority, allow\_large\_results) 343 """ 344 job = self.execute\_async(table\_name=table\_name, table\_mode=table\_mode, use\_cache=use\_cache, --> 345 priority=priority, allow\_large\_results=allow\_large\_results) 346 self.\_results = job.wait() 347 return self.\_results /usr/local/lib/python2.7/dist-packages/gcp/bigquery/\_query.pyc in execute\_async(self, table\_name, table\_mode, use\_cache, priority, allow\_large\_results) 307 allow\_large\_results=allow\_large\_results) 308 except Exception as e: --> 309 raise e 310 if 'jobReference' not in query\_result: 311 raise Exception('Unexpected query response.') **Exception: Failed to send HTTP request.** Step by step,I find the place which throws the exception: if headers is None: headers = {} ``` headers['user-agent'] = 'GoogleCloudDataLab/1.0' # Add querystring to the URL if there are any arguments. if args is not None: qs = urllib.urlencode(args) url = url + '?' + qs # Setup method to POST if unspecified, and appropriate request headers # if there is data to be sent within the request. if data is not None: if method is None: method = 'POST' if data != '': # If there is a content type specified, use it (and the data) as-is. # Otherwise, assume JSON, and serialize the data object. if 'Content-Type' not in headers: data = json.dumps(data) headers['Content-Type'] = 'application/json' headers['Content-Length'] = str(len(data)) else: if method == 'POST': headers['Content-Length'] = '0' # If the method is still unset, i.e. it was unspecified, and there # was no data to be POSTed, then default to GET request. if method is None: method = 'GET' # Create an Http object to issue requests. Associate the credentials # with it if specified to perform authorization. # # TODO(nikhilko): # SSL cert validation seemingly fails, and workarounds are not amenable # to implementing in library code. So configure the Http object to skip # doing so, in the interim. http = httplib2.Http() http.disable_ssl_certificate_validation = True if credentials is not None: http = credentials.authorize(http) try: response, content = http.request(url,method=method,body=data,headers=headers) if 200 <= response.status < 300: if raw_response: return content return json.loads(content) else: raise RequestException(response.status, content) except ValueError: raise Exception('Failed to process HTTP response.') except httplib2.HttpLib2Error: raise Exception('Failed to send HTTP request.') ``` I wonder whether it is my configuration error or The cloud datalab does not support deploy&run locally.That is to say,we cannot run code in notebooks on local datalab server. Please give me some ideas.The question has disturbed me for one week!Thank you!
2015/10/26
[ "https://Stackoverflow.com/questions/33340749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5488148/" ]
If you are looking to run Datalab container locally instead of running it in Google Cloud, that is also possible as described here: <https://github.com/GoogleCloudPlatform/datalab/wiki/Build-and-Run> However, that is developer setup for building/changing Datalab code and not currently geared towards a data scientist / developer looking to use Datalab as a tool. I.e. it is more complex to set up compared to just deploying Datalab to a billing-enabled cloud project. Even with locally running container, you will likely want to have a Google Cloud project to run BigQuery queries etc
If your project does not have billing enabled you cannot run queries against BigQuery, which is what it looks like you are trying to do.
33,340,749
I have registered on Google Developers Console, but my project is not a billed project. I did the steps of “initialized environment.” and “Build and Run ”as the web pages <https://github.com/GoogleCloudPlatform/datalab/wiki/Development-Environment> and <https://github.com/GoogleCloudPlatform/datalab/wiki/Build-and-Run> describe. But when i run code in Notebook deployed on my local linux server,i run into the following error: Create and run a SQL query ========================== bq.Query('SELECT \* FROM [cloud-datalab-samples:httplogs.logs\_20140615] LIMIT 3').results() -------------------------------------------------------------------------------------------- Exception Traceback (most recent call last) in () 1 # Create and run a SQL query ----> 2 bq.Query('SELECT \* FROM [cloud-datalab-samples:httplogs.logs\_20140615] LIMIT 3').results() /usr/local/lib/python2.7/dist-packages/gcp/bigquery/\_query.pyc in results(self, use\_cache) 130 """ 131 if not use\_cache or (self.\_results is None): --> 132 self.execute(use\_cache=use\_cache) 133 return self.\_results.results 134 /usr/local/lib/python2.7/dist-packages/gcp/bigquery/\_query.pyc in execute(self, table\_name, table\_mode, use\_cache, priority, allow\_large\_results) 343 """ 344 job = self.execute\_async(table\_name=table\_name, table\_mode=table\_mode, use\_cache=use\_cache, --> 345 priority=priority, allow\_large\_results=allow\_large\_results) 346 self.\_results = job.wait() 347 return self.\_results /usr/local/lib/python2.7/dist-packages/gcp/bigquery/\_query.pyc in execute\_async(self, table\_name, table\_mode, use\_cache, priority, allow\_large\_results) 307 allow\_large\_results=allow\_large\_results) 308 except Exception as e: --> 309 raise e 310 if 'jobReference' not in query\_result: 311 raise Exception('Unexpected query response.') **Exception: Failed to send HTTP request.** Step by step,I find the place which throws the exception: if headers is None: headers = {} ``` headers['user-agent'] = 'GoogleCloudDataLab/1.0' # Add querystring to the URL if there are any arguments. if args is not None: qs = urllib.urlencode(args) url = url + '?' + qs # Setup method to POST if unspecified, and appropriate request headers # if there is data to be sent within the request. if data is not None: if method is None: method = 'POST' if data != '': # If there is a content type specified, use it (and the data) as-is. # Otherwise, assume JSON, and serialize the data object. if 'Content-Type' not in headers: data = json.dumps(data) headers['Content-Type'] = 'application/json' headers['Content-Length'] = str(len(data)) else: if method == 'POST': headers['Content-Length'] = '0' # If the method is still unset, i.e. it was unspecified, and there # was no data to be POSTed, then default to GET request. if method is None: method = 'GET' # Create an Http object to issue requests. Associate the credentials # with it if specified to perform authorization. # # TODO(nikhilko): # SSL cert validation seemingly fails, and workarounds are not amenable # to implementing in library code. So configure the Http object to skip # doing so, in the interim. http = httplib2.Http() http.disable_ssl_certificate_validation = True if credentials is not None: http = credentials.authorize(http) try: response, content = http.request(url,method=method,body=data,headers=headers) if 200 <= response.status < 300: if raw_response: return content return json.loads(content) else: raise RequestException(response.status, content) except ValueError: raise Exception('Failed to process HTTP response.') except httplib2.HttpLib2Error: raise Exception('Failed to send HTTP request.') ``` I wonder whether it is my configuration error or The cloud datalab does not support deploy&run locally.That is to say,we cannot run code in notebooks on local datalab server. Please give me some ideas.The question has disturbed me for one week!Thank you!
2015/10/26
[ "https://Stackoverflow.com/questions/33340749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5488148/" ]
If you are looking to run Datalab container locally instead of running it in Google Cloud, that is also possible as described here: <https://github.com/GoogleCloudPlatform/datalab/wiki/Build-and-Run> However, that is developer setup for building/changing Datalab code and not currently geared towards a data scientist / developer looking to use Datalab as a tool. I.e. it is more complex to set up compared to just deploying Datalab to a billing-enabled cloud project. Even with locally running container, you will likely want to have a Google Cloud project to run BigQuery queries etc
Follow the steps in the quickstart guide titled [Run Cloud Datalab locally](https://cloud.google.com/datalab/docs/quickstarts/quickstart-local) to run datalab locally without setting up a datalab dev environment.
32,260,538
So i have this script in python. It uses models from django to get some (to be precise: a lot of) data from database. A quick 'summary' of what i want to achieve (it might be not so important, so you can as well get it just by looking at the code): There are objects of A type. For each A object there are related objects of B type (1 to many). For each B object there are related objects of C type (1 to many). For each C object there is one related object that is particularly interesting for me- let's call it D (1 to 1 relation). For each A object in database(not many) i need to get all B objects related to it and all the D objects related to it to create a summary of the A object. Each summary is a separate worksheet (i am using **openpyxl**). The code i wrote is valid (meaning: it does what i want it to do), but there's problem with garbage collection, so the process gets killed. I have tried not using prefetching, since time is not that much of a concern, but it doesn't really help. Abstract code: ``` a_objects = A.objects.all() wb = Workbook() for a_object in a_objects: ws = wb.create_sheet() ws.title = a.name summary_dictionary = {} << 1 >> b_objects = B.objects.filter(a_object=a_object) for b_object in b_objects: c_objects = C.objects.filter(b_object=b_object) for c_object in c_objects: # Here i put a value in dictionary, or alter it, # depending on whether c_object.d_object has unique fields for current a_object # Key is a tuple of 3 floats (taken from d_object) # Value is array of 3 small integers (between 0 and 100) summary_dictionary = sorted(summary_dictionary.items(), key=operator.itemgetter(0)) for summary_item in summary_dictionary: ws.append([summary_item[0][0], summary_item[0][1], summary_item[0][2], summary_item[1][0], summary_item[1][1], summary_item[1][2], sum(summary_item[1])]) wb.save("someFile.xlsx") ``` While theoretically the whole xlsx file could be huge - possibly over 1GB, if all the d\_objects values were unique, i estimate it to be a lot under 100 MB even at the end of the script. There's about 650 MB free memory in system while script is being executed. There are about 80 A objects and the script is killed after 6 or 7 of them. I used "top" to monitor memory usage and didn't notice any memory being freed, which is weird, because, let's say: 3rd a\_object had 1000 b\_objects related to it and each b\_object had 30 c\_objects related to it and 4th a\_object had only 100 b\_objects related to it and each b\_object had only 2 c\_objects related to it. A lot of memory should be freed some time after <<1>> in 4th iteration, right? My point is that what i thought this program should behave like, is that it would run as long as the following can fit into memory: - the whole summary - a single set of all b\_objects and its c\_objects and its d\_objects for any a\_object in database. What am i missing then?
2015/08/27
[ "https://Stackoverflow.com/questions/32260538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915216/" ]
Alright so my main problem was that I couldn't get the \_id of the document I inserted without not being able to check whether if it was updated/found or inserted. However I learned that you can generate your own Id's. ``` id = mongoose.Types.ObjectId(); Chatrooms.findOneAndUpdate({Roomname: room.Roomname},{ $setOnInsert: {_id: id, status: true, userNum: 1}}, {new: true, upsert: true}, function(err, doc) { if(err) console.log(err); if(doc === null) { // inserted document logic // _id available for inserted document via id } else if(doc.status) { // found document logic } }); ``` **Update** Mongoose API v4.4.8 passRawResult: if true, passes the raw result from the MongoDB driver as the third callback parameter.
I'm afraid Using **FindOneAndUpdate** can't do what you whant because it doesn't has middleware and setter and it mention it the docs: Although values are cast to their appropriate types when using the findAndModify helpers, the following are not applied: * defaults * Setters * validators * middleware <http://mongoosejs.com/docs/api.html> search it in the findOneAndUpdate if you want to get the docs before update and the docs after update you can do it this way : ``` Model.findOne({ name: 'borne' }, function (err, doc) { if (doc){ console.log(doc);//this is ur document before update doc.name = 'jason borne'; doc.save(callback); // you can use your own callback to get the udpated doc } }) ``` hope it helps you
32,260,538
So i have this script in python. It uses models from django to get some (to be precise: a lot of) data from database. A quick 'summary' of what i want to achieve (it might be not so important, so you can as well get it just by looking at the code): There are objects of A type. For each A object there are related objects of B type (1 to many). For each B object there are related objects of C type (1 to many). For each C object there is one related object that is particularly interesting for me- let's call it D (1 to 1 relation). For each A object in database(not many) i need to get all B objects related to it and all the D objects related to it to create a summary of the A object. Each summary is a separate worksheet (i am using **openpyxl**). The code i wrote is valid (meaning: it does what i want it to do), but there's problem with garbage collection, so the process gets killed. I have tried not using prefetching, since time is not that much of a concern, but it doesn't really help. Abstract code: ``` a_objects = A.objects.all() wb = Workbook() for a_object in a_objects: ws = wb.create_sheet() ws.title = a.name summary_dictionary = {} << 1 >> b_objects = B.objects.filter(a_object=a_object) for b_object in b_objects: c_objects = C.objects.filter(b_object=b_object) for c_object in c_objects: # Here i put a value in dictionary, or alter it, # depending on whether c_object.d_object has unique fields for current a_object # Key is a tuple of 3 floats (taken from d_object) # Value is array of 3 small integers (between 0 and 100) summary_dictionary = sorted(summary_dictionary.items(), key=operator.itemgetter(0)) for summary_item in summary_dictionary: ws.append([summary_item[0][0], summary_item[0][1], summary_item[0][2], summary_item[1][0], summary_item[1][1], summary_item[1][2], sum(summary_item[1])]) wb.save("someFile.xlsx") ``` While theoretically the whole xlsx file could be huge - possibly over 1GB, if all the d\_objects values were unique, i estimate it to be a lot under 100 MB even at the end of the script. There's about 650 MB free memory in system while script is being executed. There are about 80 A objects and the script is killed after 6 or 7 of them. I used "top" to monitor memory usage and didn't notice any memory being freed, which is weird, because, let's say: 3rd a\_object had 1000 b\_objects related to it and each b\_object had 30 c\_objects related to it and 4th a\_object had only 100 b\_objects related to it and each b\_object had only 2 c\_objects related to it. A lot of memory should be freed some time after <<1>> in 4th iteration, right? My point is that what i thought this program should behave like, is that it would run as long as the following can fit into memory: - the whole summary - a single set of all b\_objects and its c\_objects and its d\_objects for any a\_object in database. What am i missing then?
2015/08/27
[ "https://Stackoverflow.com/questions/32260538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915216/" ]
Version 4.1.10 of Mongoose has an option called `passRawResult` which if set to `true` causes the `raw` parameter to be passed. Leaving out this option seems to default to `false` and cause `raw` to always be `undefined`: > > passRawResult: if true, passes the raw result from the MongoDB driver > as the third callback parameter > > > <http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate>
I'm afraid Using **FindOneAndUpdate** can't do what you whant because it doesn't has middleware and setter and it mention it the docs: Although values are cast to their appropriate types when using the findAndModify helpers, the following are not applied: * defaults * Setters * validators * middleware <http://mongoosejs.com/docs/api.html> search it in the findOneAndUpdate if you want to get the docs before update and the docs after update you can do it this way : ``` Model.findOne({ name: 'borne' }, function (err, doc) { if (doc){ console.log(doc);//this is ur document before update doc.name = 'jason borne'; doc.save(callback); // you can use your own callback to get the udpated doc } }) ``` hope it helps you
32,260,538
So i have this script in python. It uses models from django to get some (to be precise: a lot of) data from database. A quick 'summary' of what i want to achieve (it might be not so important, so you can as well get it just by looking at the code): There are objects of A type. For each A object there are related objects of B type (1 to many). For each B object there are related objects of C type (1 to many). For each C object there is one related object that is particularly interesting for me- let's call it D (1 to 1 relation). For each A object in database(not many) i need to get all B objects related to it and all the D objects related to it to create a summary of the A object. Each summary is a separate worksheet (i am using **openpyxl**). The code i wrote is valid (meaning: it does what i want it to do), but there's problem with garbage collection, so the process gets killed. I have tried not using prefetching, since time is not that much of a concern, but it doesn't really help. Abstract code: ``` a_objects = A.objects.all() wb = Workbook() for a_object in a_objects: ws = wb.create_sheet() ws.title = a.name summary_dictionary = {} << 1 >> b_objects = B.objects.filter(a_object=a_object) for b_object in b_objects: c_objects = C.objects.filter(b_object=b_object) for c_object in c_objects: # Here i put a value in dictionary, or alter it, # depending on whether c_object.d_object has unique fields for current a_object # Key is a tuple of 3 floats (taken from d_object) # Value is array of 3 small integers (between 0 and 100) summary_dictionary = sorted(summary_dictionary.items(), key=operator.itemgetter(0)) for summary_item in summary_dictionary: ws.append([summary_item[0][0], summary_item[0][1], summary_item[0][2], summary_item[1][0], summary_item[1][1], summary_item[1][2], sum(summary_item[1])]) wb.save("someFile.xlsx") ``` While theoretically the whole xlsx file could be huge - possibly over 1GB, if all the d\_objects values were unique, i estimate it to be a lot under 100 MB even at the end of the script. There's about 650 MB free memory in system while script is being executed. There are about 80 A objects and the script is killed after 6 or 7 of them. I used "top" to monitor memory usage and didn't notice any memory being freed, which is weird, because, let's say: 3rd a\_object had 1000 b\_objects related to it and each b\_object had 30 c\_objects related to it and 4th a\_object had only 100 b\_objects related to it and each b\_object had only 2 c\_objects related to it. A lot of memory should be freed some time after <<1>> in 4th iteration, right? My point is that what i thought this program should behave like, is that it would run as long as the following can fit into memory: - the whole summary - a single set of all b\_objects and its c\_objects and its d\_objects for any a\_object in database. What am i missing then?
2015/08/27
[ "https://Stackoverflow.com/questions/32260538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915216/" ]
As of 8 August 2019 (Mongoose Version 5.6.9), the property to set is "rawResult" and not "passRawResult": ``` M.findOneAndUpdate({}, obj, {new: true, upsert: true, rawResult:true}, function(err, d) { if(err) console.log(err); console.log(d); }); ``` Output: ``` { lastErrorObject: { n: 1, updatedExisting: false, upserted: 5d4befa6b44b48c3f2d21c75 }, value: { _id: 5d4befa6b44b48c3f2d21c75, rating: 4, review: 'QQQ' }, ok: 1 } ``` Notice also the result is returned as the second parameter and not the third parameter of the callback. The document can be retrieved by d.value.
I'm afraid Using **FindOneAndUpdate** can't do what you whant because it doesn't has middleware and setter and it mention it the docs: Although values are cast to their appropriate types when using the findAndModify helpers, the following are not applied: * defaults * Setters * validators * middleware <http://mongoosejs.com/docs/api.html> search it in the findOneAndUpdate if you want to get the docs before update and the docs after update you can do it this way : ``` Model.findOne({ name: 'borne' }, function (err, doc) { if (doc){ console.log(doc);//this is ur document before update doc.name = 'jason borne'; doc.save(callback); // you can use your own callback to get the udpated doc } }) ``` hope it helps you
32,260,538
So i have this script in python. It uses models from django to get some (to be precise: a lot of) data from database. A quick 'summary' of what i want to achieve (it might be not so important, so you can as well get it just by looking at the code): There are objects of A type. For each A object there are related objects of B type (1 to many). For each B object there are related objects of C type (1 to many). For each C object there is one related object that is particularly interesting for me- let's call it D (1 to 1 relation). For each A object in database(not many) i need to get all B objects related to it and all the D objects related to it to create a summary of the A object. Each summary is a separate worksheet (i am using **openpyxl**). The code i wrote is valid (meaning: it does what i want it to do), but there's problem with garbage collection, so the process gets killed. I have tried not using prefetching, since time is not that much of a concern, but it doesn't really help. Abstract code: ``` a_objects = A.objects.all() wb = Workbook() for a_object in a_objects: ws = wb.create_sheet() ws.title = a.name summary_dictionary = {} << 1 >> b_objects = B.objects.filter(a_object=a_object) for b_object in b_objects: c_objects = C.objects.filter(b_object=b_object) for c_object in c_objects: # Here i put a value in dictionary, or alter it, # depending on whether c_object.d_object has unique fields for current a_object # Key is a tuple of 3 floats (taken from d_object) # Value is array of 3 small integers (between 0 and 100) summary_dictionary = sorted(summary_dictionary.items(), key=operator.itemgetter(0)) for summary_item in summary_dictionary: ws.append([summary_item[0][0], summary_item[0][1], summary_item[0][2], summary_item[1][0], summary_item[1][1], summary_item[1][2], sum(summary_item[1])]) wb.save("someFile.xlsx") ``` While theoretically the whole xlsx file could be huge - possibly over 1GB, if all the d\_objects values were unique, i estimate it to be a lot under 100 MB even at the end of the script. There's about 650 MB free memory in system while script is being executed. There are about 80 A objects and the script is killed after 6 or 7 of them. I used "top" to monitor memory usage and didn't notice any memory being freed, which is weird, because, let's say: 3rd a\_object had 1000 b\_objects related to it and each b\_object had 30 c\_objects related to it and 4th a\_object had only 100 b\_objects related to it and each b\_object had only 2 c\_objects related to it. A lot of memory should be freed some time after <<1>> in 4th iteration, right? My point is that what i thought this program should behave like, is that it would run as long as the following can fit into memory: - the whole summary - a single set of all b\_objects and its c\_objects and its d\_objects for any a\_object in database. What am i missing then?
2015/08/27
[ "https://Stackoverflow.com/questions/32260538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915216/" ]
Alright so my main problem was that I couldn't get the \_id of the document I inserted without not being able to check whether if it was updated/found or inserted. However I learned that you can generate your own Id's. ``` id = mongoose.Types.ObjectId(); Chatrooms.findOneAndUpdate({Roomname: room.Roomname},{ $setOnInsert: {_id: id, status: true, userNum: 1}}, {new: true, upsert: true}, function(err, doc) { if(err) console.log(err); if(doc === null) { // inserted document logic // _id available for inserted document via id } else if(doc.status) { // found document logic } }); ``` **Update** Mongoose API v4.4.8 passRawResult: if true, passes the raw result from the MongoDB driver as the third callback parameter.
I don't know how this got completely off track, but there as always been a "third" argument response to all `.XXupdate()` methods, which is basically the raw response from the driver. This always tells you whether the document is "upserted" or not: ```js Chatrooms.findOneAndUpdate( { "Roomname": room.Roomname }, { "$setOnInsert": { "status": true, "userNum": 1 }}, { "new": true, "upsert": true }, function(err, doc,raw) { if(err) console.log(err); // Check if upserted if ( raw.lasErrorObject.n == 1 && !raw.lastErrorObject.updatedExisting ) { console.log("upserted: %s", raw.lastErrorObject.upserted); } console.log("DOC " + doc) if (doc.status) { // FOUND ROOM SATTUS IS TRUE LOGIC console.log(doc); // return callback(true) } }); ``` Which will tell you the `_id` of the document that was just upserted. From something like this in the "raw" response: ```js { lastErrorObject: { updatedExisting: false, n: 1, upserted: 55e12c65f6044f57c8e09a46 }, value: { _id: 55e12c65f6044f57c8e09a46, status: true, userNum: 1 __v: 0 }, ok: 1 } ``` --- Complete reproducible listing: ```js var async = require('async'), mongoose = require('mongoose'), Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/test'); var testSchema = new Schema({ name: String }); var Test = mongoose.model('Test', testSchema, 'test'); async.series( [ function(callback) { Test.remove({},callback); }, function(callback) { async.eachSeries( ["first","second"], function(it,callback) { console.log(it); Test.findOneAndUpdate( { "name": "Bill" }, { "$set": { "name": "Bill" } }, { "new": true, "upsert": true }, function(err,doc,raw) { console.log(raw), console.log(doc), callback(err); } ); }, callback ); } ], function(err) { if (err) throw err; mongoose.disconnect(); } ); ``` Which outputs: ```js first { lastErrorObject: { updatedExisting: false, n: 1, upserted: 55e2a92328f7d03a06a2dd6b }, value: { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 }, ok: 1 } { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 } second { lastErrorObject: { updatedExisting: true, n: 1 }, value: { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 }, ok: 1 } { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 } ```
32,260,538
So i have this script in python. It uses models from django to get some (to be precise: a lot of) data from database. A quick 'summary' of what i want to achieve (it might be not so important, so you can as well get it just by looking at the code): There are objects of A type. For each A object there are related objects of B type (1 to many). For each B object there are related objects of C type (1 to many). For each C object there is one related object that is particularly interesting for me- let's call it D (1 to 1 relation). For each A object in database(not many) i need to get all B objects related to it and all the D objects related to it to create a summary of the A object. Each summary is a separate worksheet (i am using **openpyxl**). The code i wrote is valid (meaning: it does what i want it to do), but there's problem with garbage collection, so the process gets killed. I have tried not using prefetching, since time is not that much of a concern, but it doesn't really help. Abstract code: ``` a_objects = A.objects.all() wb = Workbook() for a_object in a_objects: ws = wb.create_sheet() ws.title = a.name summary_dictionary = {} << 1 >> b_objects = B.objects.filter(a_object=a_object) for b_object in b_objects: c_objects = C.objects.filter(b_object=b_object) for c_object in c_objects: # Here i put a value in dictionary, or alter it, # depending on whether c_object.d_object has unique fields for current a_object # Key is a tuple of 3 floats (taken from d_object) # Value is array of 3 small integers (between 0 and 100) summary_dictionary = sorted(summary_dictionary.items(), key=operator.itemgetter(0)) for summary_item in summary_dictionary: ws.append([summary_item[0][0], summary_item[0][1], summary_item[0][2], summary_item[1][0], summary_item[1][1], summary_item[1][2], sum(summary_item[1])]) wb.save("someFile.xlsx") ``` While theoretically the whole xlsx file could be huge - possibly over 1GB, if all the d\_objects values were unique, i estimate it to be a lot under 100 MB even at the end of the script. There's about 650 MB free memory in system while script is being executed. There are about 80 A objects and the script is killed after 6 or 7 of them. I used "top" to monitor memory usage and didn't notice any memory being freed, which is weird, because, let's say: 3rd a\_object had 1000 b\_objects related to it and each b\_object had 30 c\_objects related to it and 4th a\_object had only 100 b\_objects related to it and each b\_object had only 2 c\_objects related to it. A lot of memory should be freed some time after <<1>> in 4th iteration, right? My point is that what i thought this program should behave like, is that it would run as long as the following can fit into memory: - the whole summary - a single set of all b\_objects and its c\_objects and its d\_objects for any a\_object in database. What am i missing then?
2015/08/27
[ "https://Stackoverflow.com/questions/32260538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915216/" ]
Version 4.1.10 of Mongoose has an option called `passRawResult` which if set to `true` causes the `raw` parameter to be passed. Leaving out this option seems to default to `false` and cause `raw` to always be `undefined`: > > passRawResult: if true, passes the raw result from the MongoDB driver > as the third callback parameter > > > <http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate>
I don't know how this got completely off track, but there as always been a "third" argument response to all `.XXupdate()` methods, which is basically the raw response from the driver. This always tells you whether the document is "upserted" or not: ```js Chatrooms.findOneAndUpdate( { "Roomname": room.Roomname }, { "$setOnInsert": { "status": true, "userNum": 1 }}, { "new": true, "upsert": true }, function(err, doc,raw) { if(err) console.log(err); // Check if upserted if ( raw.lasErrorObject.n == 1 && !raw.lastErrorObject.updatedExisting ) { console.log("upserted: %s", raw.lastErrorObject.upserted); } console.log("DOC " + doc) if (doc.status) { // FOUND ROOM SATTUS IS TRUE LOGIC console.log(doc); // return callback(true) } }); ``` Which will tell you the `_id` of the document that was just upserted. From something like this in the "raw" response: ```js { lastErrorObject: { updatedExisting: false, n: 1, upserted: 55e12c65f6044f57c8e09a46 }, value: { _id: 55e12c65f6044f57c8e09a46, status: true, userNum: 1 __v: 0 }, ok: 1 } ``` --- Complete reproducible listing: ```js var async = require('async'), mongoose = require('mongoose'), Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/test'); var testSchema = new Schema({ name: String }); var Test = mongoose.model('Test', testSchema, 'test'); async.series( [ function(callback) { Test.remove({},callback); }, function(callback) { async.eachSeries( ["first","second"], function(it,callback) { console.log(it); Test.findOneAndUpdate( { "name": "Bill" }, { "$set": { "name": "Bill" } }, { "new": true, "upsert": true }, function(err,doc,raw) { console.log(raw), console.log(doc), callback(err); } ); }, callback ); } ], function(err) { if (err) throw err; mongoose.disconnect(); } ); ``` Which outputs: ```js first { lastErrorObject: { updatedExisting: false, n: 1, upserted: 55e2a92328f7d03a06a2dd6b }, value: { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 }, ok: 1 } { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 } second { lastErrorObject: { updatedExisting: true, n: 1 }, value: { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 }, ok: 1 } { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 } ```
32,260,538
So i have this script in python. It uses models from django to get some (to be precise: a lot of) data from database. A quick 'summary' of what i want to achieve (it might be not so important, so you can as well get it just by looking at the code): There are objects of A type. For each A object there are related objects of B type (1 to many). For each B object there are related objects of C type (1 to many). For each C object there is one related object that is particularly interesting for me- let's call it D (1 to 1 relation). For each A object in database(not many) i need to get all B objects related to it and all the D objects related to it to create a summary of the A object. Each summary is a separate worksheet (i am using **openpyxl**). The code i wrote is valid (meaning: it does what i want it to do), but there's problem with garbage collection, so the process gets killed. I have tried not using prefetching, since time is not that much of a concern, but it doesn't really help. Abstract code: ``` a_objects = A.objects.all() wb = Workbook() for a_object in a_objects: ws = wb.create_sheet() ws.title = a.name summary_dictionary = {} << 1 >> b_objects = B.objects.filter(a_object=a_object) for b_object in b_objects: c_objects = C.objects.filter(b_object=b_object) for c_object in c_objects: # Here i put a value in dictionary, or alter it, # depending on whether c_object.d_object has unique fields for current a_object # Key is a tuple of 3 floats (taken from d_object) # Value is array of 3 small integers (between 0 and 100) summary_dictionary = sorted(summary_dictionary.items(), key=operator.itemgetter(0)) for summary_item in summary_dictionary: ws.append([summary_item[0][0], summary_item[0][1], summary_item[0][2], summary_item[1][0], summary_item[1][1], summary_item[1][2], sum(summary_item[1])]) wb.save("someFile.xlsx") ``` While theoretically the whole xlsx file could be huge - possibly over 1GB, if all the d\_objects values were unique, i estimate it to be a lot under 100 MB even at the end of the script. There's about 650 MB free memory in system while script is being executed. There are about 80 A objects and the script is killed after 6 or 7 of them. I used "top" to monitor memory usage and didn't notice any memory being freed, which is weird, because, let's say: 3rd a\_object had 1000 b\_objects related to it and each b\_object had 30 c\_objects related to it and 4th a\_object had only 100 b\_objects related to it and each b\_object had only 2 c\_objects related to it. A lot of memory should be freed some time after <<1>> in 4th iteration, right? My point is that what i thought this program should behave like, is that it would run as long as the following can fit into memory: - the whole summary - a single set of all b\_objects and its c\_objects and its d\_objects for any a\_object in database. What am i missing then?
2015/08/27
[ "https://Stackoverflow.com/questions/32260538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915216/" ]
As of 8 August 2019 (Mongoose Version 5.6.9), the property to set is "rawResult" and not "passRawResult": ``` M.findOneAndUpdate({}, obj, {new: true, upsert: true, rawResult:true}, function(err, d) { if(err) console.log(err); console.log(d); }); ``` Output: ``` { lastErrorObject: { n: 1, updatedExisting: false, upserted: 5d4befa6b44b48c3f2d21c75 }, value: { _id: 5d4befa6b44b48c3f2d21c75, rating: 4, review: 'QQQ' }, ok: 1 } ``` Notice also the result is returned as the second parameter and not the third parameter of the callback. The document can be retrieved by d.value.
I don't know how this got completely off track, but there as always been a "third" argument response to all `.XXupdate()` methods, which is basically the raw response from the driver. This always tells you whether the document is "upserted" or not: ```js Chatrooms.findOneAndUpdate( { "Roomname": room.Roomname }, { "$setOnInsert": { "status": true, "userNum": 1 }}, { "new": true, "upsert": true }, function(err, doc,raw) { if(err) console.log(err); // Check if upserted if ( raw.lasErrorObject.n == 1 && !raw.lastErrorObject.updatedExisting ) { console.log("upserted: %s", raw.lastErrorObject.upserted); } console.log("DOC " + doc) if (doc.status) { // FOUND ROOM SATTUS IS TRUE LOGIC console.log(doc); // return callback(true) } }); ``` Which will tell you the `_id` of the document that was just upserted. From something like this in the "raw" response: ```js { lastErrorObject: { updatedExisting: false, n: 1, upserted: 55e12c65f6044f57c8e09a46 }, value: { _id: 55e12c65f6044f57c8e09a46, status: true, userNum: 1 __v: 0 }, ok: 1 } ``` --- Complete reproducible listing: ```js var async = require('async'), mongoose = require('mongoose'), Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/test'); var testSchema = new Schema({ name: String }); var Test = mongoose.model('Test', testSchema, 'test'); async.series( [ function(callback) { Test.remove({},callback); }, function(callback) { async.eachSeries( ["first","second"], function(it,callback) { console.log(it); Test.findOneAndUpdate( { "name": "Bill" }, { "$set": { "name": "Bill" } }, { "new": true, "upsert": true }, function(err,doc,raw) { console.log(raw), console.log(doc), callback(err); } ); }, callback ); } ], function(err) { if (err) throw err; mongoose.disconnect(); } ); ``` Which outputs: ```js first { lastErrorObject: { updatedExisting: false, n: 1, upserted: 55e2a92328f7d03a06a2dd6b }, value: { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 }, ok: 1 } { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 } second { lastErrorObject: { updatedExisting: true, n: 1 }, value: { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 }, ok: 1 } { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 } ```
32,260,538
So i have this script in python. It uses models from django to get some (to be precise: a lot of) data from database. A quick 'summary' of what i want to achieve (it might be not so important, so you can as well get it just by looking at the code): There are objects of A type. For each A object there are related objects of B type (1 to many). For each B object there are related objects of C type (1 to many). For each C object there is one related object that is particularly interesting for me- let's call it D (1 to 1 relation). For each A object in database(not many) i need to get all B objects related to it and all the D objects related to it to create a summary of the A object. Each summary is a separate worksheet (i am using **openpyxl**). The code i wrote is valid (meaning: it does what i want it to do), but there's problem with garbage collection, so the process gets killed. I have tried not using prefetching, since time is not that much of a concern, but it doesn't really help. Abstract code: ``` a_objects = A.objects.all() wb = Workbook() for a_object in a_objects: ws = wb.create_sheet() ws.title = a.name summary_dictionary = {} << 1 >> b_objects = B.objects.filter(a_object=a_object) for b_object in b_objects: c_objects = C.objects.filter(b_object=b_object) for c_object in c_objects: # Here i put a value in dictionary, or alter it, # depending on whether c_object.d_object has unique fields for current a_object # Key is a tuple of 3 floats (taken from d_object) # Value is array of 3 small integers (between 0 and 100) summary_dictionary = sorted(summary_dictionary.items(), key=operator.itemgetter(0)) for summary_item in summary_dictionary: ws.append([summary_item[0][0], summary_item[0][1], summary_item[0][2], summary_item[1][0], summary_item[1][1], summary_item[1][2], sum(summary_item[1])]) wb.save("someFile.xlsx") ``` While theoretically the whole xlsx file could be huge - possibly over 1GB, if all the d\_objects values were unique, i estimate it to be a lot under 100 MB even at the end of the script. There's about 650 MB free memory in system while script is being executed. There are about 80 A objects and the script is killed after 6 or 7 of them. I used "top" to monitor memory usage and didn't notice any memory being freed, which is weird, because, let's say: 3rd a\_object had 1000 b\_objects related to it and each b\_object had 30 c\_objects related to it and 4th a\_object had only 100 b\_objects related to it and each b\_object had only 2 c\_objects related to it. A lot of memory should be freed some time after <<1>> in 4th iteration, right? My point is that what i thought this program should behave like, is that it would run as long as the following can fit into memory: - the whole summary - a single set of all b\_objects and its c\_objects and its d\_objects for any a\_object in database. What am i missing then?
2015/08/27
[ "https://Stackoverflow.com/questions/32260538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915216/" ]
Alright so my main problem was that I couldn't get the \_id of the document I inserted without not being able to check whether if it was updated/found or inserted. However I learned that you can generate your own Id's. ``` id = mongoose.Types.ObjectId(); Chatrooms.findOneAndUpdate({Roomname: room.Roomname},{ $setOnInsert: {_id: id, status: true, userNum: 1}}, {new: true, upsert: true}, function(err, doc) { if(err) console.log(err); if(doc === null) { // inserted document logic // _id available for inserted document via id } else if(doc.status) { // found document logic } }); ``` **Update** Mongoose API v4.4.8 passRawResult: if true, passes the raw result from the MongoDB driver as the third callback parameter.
Version 4.1.10 of Mongoose has an option called `passRawResult` which if set to `true` causes the `raw` parameter to be passed. Leaving out this option seems to default to `false` and cause `raw` to always be `undefined`: > > passRawResult: if true, passes the raw result from the MongoDB driver > as the third callback parameter > > > <http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate>
32,260,538
So i have this script in python. It uses models from django to get some (to be precise: a lot of) data from database. A quick 'summary' of what i want to achieve (it might be not so important, so you can as well get it just by looking at the code): There are objects of A type. For each A object there are related objects of B type (1 to many). For each B object there are related objects of C type (1 to many). For each C object there is one related object that is particularly interesting for me- let's call it D (1 to 1 relation). For each A object in database(not many) i need to get all B objects related to it and all the D objects related to it to create a summary of the A object. Each summary is a separate worksheet (i am using **openpyxl**). The code i wrote is valid (meaning: it does what i want it to do), but there's problem with garbage collection, so the process gets killed. I have tried not using prefetching, since time is not that much of a concern, but it doesn't really help. Abstract code: ``` a_objects = A.objects.all() wb = Workbook() for a_object in a_objects: ws = wb.create_sheet() ws.title = a.name summary_dictionary = {} << 1 >> b_objects = B.objects.filter(a_object=a_object) for b_object in b_objects: c_objects = C.objects.filter(b_object=b_object) for c_object in c_objects: # Here i put a value in dictionary, or alter it, # depending on whether c_object.d_object has unique fields for current a_object # Key is a tuple of 3 floats (taken from d_object) # Value is array of 3 small integers (between 0 and 100) summary_dictionary = sorted(summary_dictionary.items(), key=operator.itemgetter(0)) for summary_item in summary_dictionary: ws.append([summary_item[0][0], summary_item[0][1], summary_item[0][2], summary_item[1][0], summary_item[1][1], summary_item[1][2], sum(summary_item[1])]) wb.save("someFile.xlsx") ``` While theoretically the whole xlsx file could be huge - possibly over 1GB, if all the d\_objects values were unique, i estimate it to be a lot under 100 MB even at the end of the script. There's about 650 MB free memory in system while script is being executed. There are about 80 A objects and the script is killed after 6 or 7 of them. I used "top" to monitor memory usage and didn't notice any memory being freed, which is weird, because, let's say: 3rd a\_object had 1000 b\_objects related to it and each b\_object had 30 c\_objects related to it and 4th a\_object had only 100 b\_objects related to it and each b\_object had only 2 c\_objects related to it. A lot of memory should be freed some time after <<1>> in 4th iteration, right? My point is that what i thought this program should behave like, is that it would run as long as the following can fit into memory: - the whole summary - a single set of all b\_objects and its c\_objects and its d\_objects for any a\_object in database. What am i missing then?
2015/08/27
[ "https://Stackoverflow.com/questions/32260538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915216/" ]
As of 8 August 2019 (Mongoose Version 5.6.9), the property to set is "rawResult" and not "passRawResult": ``` M.findOneAndUpdate({}, obj, {new: true, upsert: true, rawResult:true}, function(err, d) { if(err) console.log(err); console.log(d); }); ``` Output: ``` { lastErrorObject: { n: 1, updatedExisting: false, upserted: 5d4befa6b44b48c3f2d21c75 }, value: { _id: 5d4befa6b44b48c3f2d21c75, rating: 4, review: 'QQQ' }, ok: 1 } ``` Notice also the result is returned as the second parameter and not the third parameter of the callback. The document can be retrieved by d.value.
Version 4.1.10 of Mongoose has an option called `passRawResult` which if set to `true` causes the `raw` parameter to be passed. Leaving out this option seems to default to `false` and cause `raw` to always be `undefined`: > > passRawResult: if true, passes the raw result from the MongoDB driver > as the third callback parameter > > > <http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate>
26,975,539
I thought that the standalone PsychoPy install could coexist happily if Python was installed separately on the PC to but I can't get it to, nor can I find any docs. (I'm using Windows 7) I have the lastest standalone version installed and the shortcut to run it is ``` "D:\Program Files (x86)\PsychoPy2\pythonw.exe" "D:\Program Files (x86)\PsychoPy2\Lib\site-packages\PsychoPy-1.81.02-py2.7.egg\psychopy\app\psychopyApp.py" ``` This works fine if my system env variables for PYTHONHOME & PYTHONPATH aren't set but I also use Python for other apps and need them setting to point to the other version of Python I have installed natively. When these env vars are set, Psychopy fails to load and gives no error messages at all. Can anyone advise how I get them to play together nicely? (I thought it used to work last year, has something changed?) [ I've tried a full uninstall of psychopy and freshly installed the latest standalone version v1.81.02
2014/11/17
[ "https://Stackoverflow.com/questions/26975539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/765827/" ]
It is not a button documented by Qt. You can detect this by catching events and checking event type: <http://qt-project.org/doc/qt-5/qevent.html#Type-enum> There are different types as `QEvent::EnterWhatsThisMode` `QEvent::WhatsThisClicked` and so on. I achieved something similar to what are you looking for using event filter in mainwindow. ``` if(event->type() == QEvent::EnterWhatsThisMode) qDebug() << "click"; ``` I saw "click" when I clicked on `?` button.
Based on Chernobyl's answer, this is how I did it in Python (PySide): ``` def event(self, event): if event.type() == QtCore.QEvent.EnterWhatsThisMode: print "click" return True return QtGui.QDialog.event(self, event) ``` That is, you reimplement `event` when app enters 'WhatsThisMode'. Otherwise, pass along control back to the base class. It almost works. The only wrinkle is that the mouse cursor is still turned into the 'Forbidden' shape. Based on [another post](https://stackoverflow.com/a/26978238/1886357), I got rid of that by adding: ``` QtGui.QWhatsThis.leaveWhatsThisMode() ``` As the line right before the print command in the previous.
26,975,539
I thought that the standalone PsychoPy install could coexist happily if Python was installed separately on the PC to but I can't get it to, nor can I find any docs. (I'm using Windows 7) I have the lastest standalone version installed and the shortcut to run it is ``` "D:\Program Files (x86)\PsychoPy2\pythonw.exe" "D:\Program Files (x86)\PsychoPy2\Lib\site-packages\PsychoPy-1.81.02-py2.7.egg\psychopy\app\psychopyApp.py" ``` This works fine if my system env variables for PYTHONHOME & PYTHONPATH aren't set but I also use Python for other apps and need them setting to point to the other version of Python I have installed natively. When these env vars are set, Psychopy fails to load and gives no error messages at all. Can anyone advise how I get them to play together nicely? (I thought it used to work last year, has something changed?) [ I've tried a full uninstall of psychopy and freshly installed the latest standalone version v1.81.02
2014/11/17
[ "https://Stackoverflow.com/questions/26975539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/765827/" ]
The other answers were a bit misleading for me, focusing only on catching the question mark event, but not explaining the normal usage. When this button is clicked and *WhatsThisMode* is triggered, the elements of the dialog are supposed to give info about themselves. And if mouse hovers over an element that supports this info then the pointer will become a pointing arrow with a question mark (on Windows at least), with a tooltip message displayed on mouse click. Here's how to achieve it in PySide: ``` someWidget.setWhatsThis("Help on widget") ``` QWhatsThis documentation for [PySide](https://srinikom.github.io/pyside-docs/PySide/QtGui/QWhatsThis.html "PySide QWhatsThis docs") and [Qt5](http://doc.qt.io/qt-5/qwhatsthis.html "Qt5 WhatsThis docs") is also available.
It is not a button documented by Qt. You can detect this by catching events and checking event type: <http://qt-project.org/doc/qt-5/qevent.html#Type-enum> There are different types as `QEvent::EnterWhatsThisMode` `QEvent::WhatsThisClicked` and so on. I achieved something similar to what are you looking for using event filter in mainwindow. ``` if(event->type() == QEvent::EnterWhatsThisMode) qDebug() << "click"; ``` I saw "click" when I clicked on `?` button.
26,975,539
I thought that the standalone PsychoPy install could coexist happily if Python was installed separately on the PC to but I can't get it to, nor can I find any docs. (I'm using Windows 7) I have the lastest standalone version installed and the shortcut to run it is ``` "D:\Program Files (x86)\PsychoPy2\pythonw.exe" "D:\Program Files (x86)\PsychoPy2\Lib\site-packages\PsychoPy-1.81.02-py2.7.egg\psychopy\app\psychopyApp.py" ``` This works fine if my system env variables for PYTHONHOME & PYTHONPATH aren't set but I also use Python for other apps and need them setting to point to the other version of Python I have installed natively. When these env vars are set, Psychopy fails to load and gives no error messages at all. Can anyone advise how I get them to play together nicely? (I thought it used to work last year, has something changed?) [ I've tried a full uninstall of psychopy and freshly installed the latest standalone version v1.81.02
2014/11/17
[ "https://Stackoverflow.com/questions/26975539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/765827/" ]
The other answers were a bit misleading for me, focusing only on catching the question mark event, but not explaining the normal usage. When this button is clicked and *WhatsThisMode* is triggered, the elements of the dialog are supposed to give info about themselves. And if mouse hovers over an element that supports this info then the pointer will become a pointing arrow with a question mark (on Windows at least), with a tooltip message displayed on mouse click. Here's how to achieve it in PySide: ``` someWidget.setWhatsThis("Help on widget") ``` QWhatsThis documentation for [PySide](https://srinikom.github.io/pyside-docs/PySide/QtGui/QWhatsThis.html "PySide QWhatsThis docs") and [Qt5](http://doc.qt.io/qt-5/qwhatsthis.html "Qt5 WhatsThis docs") is also available.
Based on Chernobyl's answer, this is how I did it in Python (PySide): ``` def event(self, event): if event.type() == QtCore.QEvent.EnterWhatsThisMode: print "click" return True return QtGui.QDialog.event(self, event) ``` That is, you reimplement `event` when app enters 'WhatsThisMode'. Otherwise, pass along control back to the base class. It almost works. The only wrinkle is that the mouse cursor is still turned into the 'Forbidden' shape. Based on [another post](https://stackoverflow.com/a/26978238/1886357), I got rid of that by adding: ``` QtGui.QWhatsThis.leaveWhatsThisMode() ``` As the line right before the print command in the previous.
59,598,620
I am creating my first Django project. I have successfully installed Django version 2.1. When I created the project, the project was successfully launched at the url 127.0.0.1:8000. Then I ran the command **python manage.py startapp products**. Products folder was also successfully created in the project. Then inside the products folder, I opened: **views.py** ``` from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') ``` then **products/urls**: ``` from django.urls import path from . import views urlpatterns = [ path('', views.index) ] ``` Inside the main project folder, I opened **urls.py** and I modified the code: ``` from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')) ] ``` Then the url **<http://127.0.0.1:8000/products/>** was not opening on browser. Browser is giving the "Unable to connect" error. I am using the PyCharm IDE. I will really appreciate your answer.
2020/01/05
[ "https://Stackoverflow.com/questions/59598620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12655703/" ]
In you **settings.py** add the app to the **INSTALLED\_APPS** list as: ```py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products' # <-- your product app ] ``` And modify **ALLOWED\_HOSTS** list as: ```py ALLOWED_HOSTS = ['localhost', '127.0.0.1'] ``` Then run the application: `python manage.py runserver 127.0.0.1:8080`.
Check if you had ran the command below: `python manage.py runserver` If you had run the above command and the error persists, try to run on the global address 0.0.0.0 ``` python manage.py runserver 0.0.0.0:8000 ``` OR on a different port ``` python manage.py runserver 0.0.0.0:8001 ```
46,368,459
I have different types of `ISO 8601` formatted date strings, using `datetime library`, i want to obtain a `datetime object` from these strings. Example of the input strings: 1. `2017-08-01` (1st august 2017) 2. `2017-09` (september of 2017) 3. `2017-W20` (20th week) 4. `2017-W37-2` (tuesday of 37th week) I am able to obtain the 1st, 2nd and 4th examples, but for 3rd, I get a traceback while trying. I am using datetime.datetime.strptime function for them in try-except blocks, as follows: ``` try : d1 = datetime.datetime.strptime(date,'%Y-%m-%d') except : try : d1 = datetime.datetime.strptime(date,'%Y-%m') except : try : d1 = datetime.datetime.strptime(date,'%G-W%V') except : print('Not going through') ``` When i tried the 3rd try block on terminal, here's the error i got ``` >>> dstr '2017-W38' >>> dt.strptime(dstr,'%G-W%V') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\tushar.aggarwal\Desktop\Python\Python3632\lib\_strptime.py", line 565, in _strptime_datetime tt, fraction = _strptime(data_string, format) File "C:\Users\tushar.aggarwal\Desktop\Python\Python3632\lib\_strptime.py", line 483, in _strptime raise ValueError("ISO year directive '%G' must be used with " ValueError: ISO year directive '%G' must be used with the ISO week directive '%V' and a weekday directive ('%A', '%a', '%w', or '%u'). ``` And this is how i got the 4th case working : ``` >>> dstr '2017-W38-2' >>> dt.strptime(dstr,'%G-W%V-%u') datetime.datetime(2017, 9, 19, 0, 0) ``` Here is the reference for my code : [strptime documentation](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) There are many questions on SO regarding date parsing from `ISO 8601` formats, but I couldn't find one addressing my issue. Moreover the questions involved are very old and take older versions of python where `%G`, `%V` directives in `strptime` are not available.
2017/09/22
[ "https://Stackoverflow.com/questions/46368459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6374328/" ]
You can escape the Twig tags (as described [here](https://twig.symfony.com/doc/2.x/templates.html#escaping)) using `{{ '{{' }}`, `{{ '}}' }}`, `{{ '{%' }}` and `{{ '%}' }}`. ``` $input = '<h1>{{ pageTitle }}</h1> <div class="row"> {% for product in products %} <span class="mep"></span> {% endfor %} </div>'; $search = "/({{|}}|{%|%})/"; $replace = "{{ '$1' }}"; echo preg_replace($search, $replace, $input); ```
My regex solution (better solution still welcome): ``` $input = '<h1>{{ pageTitle }}</h1> <div class="row"> {% for product in products %} <span class="mep"></span> {% endfor %} </div>'; $search = '/({{.+}})|({%.+%})/si'; $replace = ''; echo preg_replace($input, $search, $replace); ```
31,768,128
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. /tmp/tmpbSjX8k/pip.zip/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. Collecting pip Downloading pip-7.1.0-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 181kB/s Installing collected packages: pip Found existing installation: pip 1.4.1 Uninstalling pip-1.4.1: Successfully uninstalled pip-1.4.1 Successfully installed pip-7.1.0 Monas-MacBook-Pro:CS764 mona$ pip --version -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory ```
2015/08/02
[ "https://Stackoverflow.com/questions/31768128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2414957/" ]
I'm guessing you have two python installs, or two pip installs, one of which has been partially removed. Why do you use `sudo`? Ideally you should be able to install and run everything from your user account instead of using root. If you mix root and your local account together you are more likely to run into permissions issues (e.g. see the warning it gives about "parent directory is not owned by the current user"). What do you get if you run this? ``` $ head -n1 /usr/local/bin/pip ``` This will show you which python binary `pip` is trying to use. If it's pointing `/usr/local/opt/python/bin/python2.7`, then try running this: ``` $ ls -al /usr/local/opt/python/bin/python2.7 ``` If this says "No such file or directory", then pip is trying to use a python binary that has been removed. Next, try this: ``` $ which python $ which python2.7 ``` To see the path of the python binary that's actually working. Since it looks like pip was successfully installed somewhere, it could be that `/usr/local/bin/pip` is part of an older installation of pip that's higher up on the `PATH`. To test that, you may try moving the non-functioning `pip` binary out of the way like this (might require `sudo`): ``` $ mv /usr/local/bin/pip /usr/local/bin/pip.old ``` Then try running your `pip --version` command again. Hopefully it picks up the correct version and runs successfully.
For me, on centOS 7 I had to remove the old pip link from /bin by ```sh rm /bin/pip2.7 rm /bin/pip ``` then relink it with ```sh sudo ln -s /usr/local/bin/pip2.7 /bin/pip2.7 ``` Then if ```sh /usr/local/bin/pip2.7 ``` Works, this should work
31,768,128
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. /tmp/tmpbSjX8k/pip.zip/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. Collecting pip Downloading pip-7.1.0-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 181kB/s Installing collected packages: pip Found existing installation: pip 1.4.1 Uninstalling pip-1.4.1: Successfully uninstalled pip-1.4.1 Successfully installed pip-7.1.0 Monas-MacBook-Pro:CS764 mona$ pip --version -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory ```
2015/08/02
[ "https://Stackoverflow.com/questions/31768128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2414957/" ]
I made the same error using sudo for my installation. (oops) ``` brew install python brew linkapps python brew link --overwrite python ``` This brought everything back to normal.
This error typically pops up every time there is an iOS upgrade. Try ``` xcode-select --install ``` This will install the latest xcode version and that should fix it
31,768,128
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. /tmp/tmpbSjX8k/pip.zip/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. Collecting pip Downloading pip-7.1.0-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 181kB/s Installing collected packages: pip Found existing installation: pip 1.4.1 Uninstalling pip-1.4.1: Successfully uninstalled pip-1.4.1 Successfully installed pip-7.1.0 Monas-MacBook-Pro:CS764 mona$ pip --version -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory ```
2015/08/02
[ "https://Stackoverflow.com/questions/31768128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2414957/" ]
In case it helps anyone, the solution mentioned in this other question worked for me when pip stopped working today after upgrading it: [Pip broken after upgrading](https://stackoverflow.com/questions/26302805/pip-broken-after-upgrading) It seems that it's an issue when a previously cached location changes, so you can refresh the cache with this command: ``` hash -r ```
I got same problem. If I run `brew link --overwrite python2`. There was still `zsh: /usr/local/bin//fab: bad interpreter: /usr/local/opt/python/bin/python2.7: no such file or directory`. ``` cd /usr/local/opt/ mv python2 python ``` Solved it! Now we can use python2 version fabric. === 2018/07/25 updated There is convinient way to use python2 version fab when your os python linked to python3. `.sh` for your command. ``` # fab python2 cd /usr/local/opt rm python ln -s python2 python # use the fab cli ... # link to python3 cd /usr/local/opt rm python ln -s python3 python ``` Hope this helps.
31,768,128
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. /tmp/tmpbSjX8k/pip.zip/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. Collecting pip Downloading pip-7.1.0-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 181kB/s Installing collected packages: pip Found existing installation: pip 1.4.1 Uninstalling pip-1.4.1: Successfully uninstalled pip-1.4.1 Successfully installed pip-7.1.0 Monas-MacBook-Pro:CS764 mona$ pip --version -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory ```
2015/08/02
[ "https://Stackoverflow.com/questions/31768128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2414957/" ]
Editing the first line of this file worked to me: `MBP-de-Jose:~ josejunior$ which python3` ``` /usr/local/Cellar/python/3.7.3/bin/python3 ``` `MBP-de-Jose:~ josejunior$` before ``` #!/usr/local/opt/python/bin/python3.7 ``` after ``` #!/usr/local/Cellar/python/3.7.3/bin/python3 ```
This error typically pops up every time there is an iOS upgrade. Try ``` xcode-select --install ``` This will install the latest xcode version and that should fix it
31,768,128
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. /tmp/tmpbSjX8k/pip.zip/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. Collecting pip Downloading pip-7.1.0-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 181kB/s Installing collected packages: pip Found existing installation: pip 1.4.1 Uninstalling pip-1.4.1: Successfully uninstalled pip-1.4.1 Successfully installed pip-7.1.0 Monas-MacBook-Pro:CS764 mona$ pip --version -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory ```
2015/08/02
[ "https://Stackoverflow.com/questions/31768128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2414957/" ]
In case it helps anyone, the solution mentioned in this other question worked for me when pip stopped working today after upgrading it: [Pip broken after upgrading](https://stackoverflow.com/questions/26302805/pip-broken-after-upgrading) It seems that it's an issue when a previously cached location changes, so you can refresh the cache with this command: ``` hash -r ```
This error typically pops up every time there is an iOS upgrade. Try ``` xcode-select --install ``` This will install the latest xcode version and that should fix it
31,768,128
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. /tmp/tmpbSjX8k/pip.zip/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. Collecting pip Downloading pip-7.1.0-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 181kB/s Installing collected packages: pip Found existing installation: pip 1.4.1 Uninstalling pip-1.4.1: Successfully uninstalled pip-1.4.1 Successfully installed pip-7.1.0 Monas-MacBook-Pro:CS764 mona$ pip --version -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory ```
2015/08/02
[ "https://Stackoverflow.com/questions/31768128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2414957/" ]
To simplify to operation, we can use the below command to reinstall version 2: `brew install python@2` Then on my mac, it looks as below: ``` ▶ python -V Python 2.7.10 ▶ python2 -V Python 2.7.14 ▶ python3 -V Python 3.6.5 ▶ pip2 -V pip 9.0.3 from /usr/local/lib/python2.7/site-packages (python 2.7) ▶ pip3 -V pip 9.0.3 from /usr/local/lib/python3.6/site-packages (python 3.6) ▶ pip --version pip 9.0.3 from /usr/local/lib/python2.7/site-packages (python 2.7) ```
I had the same issue. I have both Python 2.7 & 3.6 installed. Python 2.7 had `virtualenv` working, but after installing Python3, virtualenv kept looking for version 2.7 and couldn't find it. Doing `pip install virtualenv` installed the Python3 version of virtualenv. Then, for each command, if I want to use Python2, I would use `virtualenv --python=python2.7 somecommand`
31,768,128
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. /tmp/tmpbSjX8k/pip.zip/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. Collecting pip Downloading pip-7.1.0-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 181kB/s Installing collected packages: pip Found existing installation: pip 1.4.1 Uninstalling pip-1.4.1: Successfully uninstalled pip-1.4.1 Successfully installed pip-7.1.0 Monas-MacBook-Pro:CS764 mona$ pip --version -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory ```
2015/08/02
[ "https://Stackoverflow.com/questions/31768128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2414957/" ]
Only solution in OSX and its variant. ``` ln -s /usr/local/bin/python /usr/local/opt/python/bin/python2.7 ```
``` sudo /usr/bin/easy_install pip ``` this command worked out for me
31,768,128
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. /tmp/tmpbSjX8k/pip.zip/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. Collecting pip Downloading pip-7.1.0-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 181kB/s Installing collected packages: pip Found existing installation: pip 1.4.1 Uninstalling pip-1.4.1: Successfully uninstalled pip-1.4.1 Successfully installed pip-7.1.0 Monas-MacBook-Pro:CS764 mona$ pip --version -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory ```
2015/08/02
[ "https://Stackoverflow.com/questions/31768128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2414957/" ]
I had the same issue, virtualenv was pointing to an old python path. Fixing the path resolved the issue: ``` $ virtualenv -p python2.7 env -bash: /usr/local/bin/virtualenv: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory $ which python2.7 /opt/local/bin/python2.7 # needed to change to correct python path $ head /usr/local/bin/virtualenv #!/usr/local/opt/python/bin/python2.7 <<<< REMOVED THIS LINE #!/opt/local/bin/python2.7 <<<<< REPLACED WITH CORRECT PATH # now it works: $ virtualenv -p python2.7 env Running virtualenv with interpreter /opt/local/bin/python2.7 New python executable in env/bin/python Installing setuptools, pip...done. ```
You could have two different versions of Python and pip. Try to: `pip2 install --upgrade pip` and then `pip2 install -r requirements.txt` Or `pip3` if you are on newer Python version.
31,768,128
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. /tmp/tmpbSjX8k/pip.zip/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. Collecting pip Downloading pip-7.1.0-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 181kB/s Installing collected packages: pip Found existing installation: pip 1.4.1 Uninstalling pip-1.4.1: Successfully uninstalled pip-1.4.1 Successfully installed pip-7.1.0 Monas-MacBook-Pro:CS764 mona$ pip --version -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory ```
2015/08/02
[ "https://Stackoverflow.com/questions/31768128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2414957/" ]
I'm guessing you have two python installs, or two pip installs, one of which has been partially removed. Why do you use `sudo`? Ideally you should be able to install and run everything from your user account instead of using root. If you mix root and your local account together you are more likely to run into permissions issues (e.g. see the warning it gives about "parent directory is not owned by the current user"). What do you get if you run this? ``` $ head -n1 /usr/local/bin/pip ``` This will show you which python binary `pip` is trying to use. If it's pointing `/usr/local/opt/python/bin/python2.7`, then try running this: ``` $ ls -al /usr/local/opt/python/bin/python2.7 ``` If this says "No such file or directory", then pip is trying to use a python binary that has been removed. Next, try this: ``` $ which python $ which python2.7 ``` To see the path of the python binary that's actually working. Since it looks like pip was successfully installed somewhere, it could be that `/usr/local/bin/pip` is part of an older installation of pip that's higher up on the `PATH`. To test that, you may try moving the non-functioning `pip` binary out of the way like this (might require `sudo`): ``` $ mv /usr/local/bin/pip /usr/local/bin/pip.old ``` Then try running your `pip --version` command again. Hopefully it picks up the correct version and runs successfully.
In my case, I decided to remove the homebrew python installation from my mac as I already had two other versions of python installed on my mac through MacPorts. This caused the error message. Reinstalling python through brew solved my issue.
31,768,128
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. /tmp/tmpbSjX8k/pip.zip/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. Collecting pip Downloading pip-7.1.0-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 181kB/s Installing collected packages: pip Found existing installation: pip 1.4.1 Uninstalling pip-1.4.1: Successfully uninstalled pip-1.4.1 Successfully installed pip-7.1.0 Monas-MacBook-Pro:CS764 mona$ pip --version -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory ```
2015/08/02
[ "https://Stackoverflow.com/questions/31768128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2414957/" ]
Because I had both python 2 and 3 installed on Mac OSX I was having all sorts of errors. I used which to find the location of my python2.7 file (/usr/local/bin/python2.7) ``` which python2.7 ``` Then I symlinked my real python2.7 install location with the one the script expected: ``` ln -s /usr/local/bin/python2.7 /usr/local/opt/python/bin/python2.7 ```
You could have two different versions of Python and pip. Try to: `pip2 install --upgrade pip` and then `pip2 install -r requirements.txt` Or `pip3` if you are on newer Python version.
10,529,461
I just noticed the problem with process terminate (from `multiprocessing` library) method on Linux. I have application working with `multiprocessing` library but... when I call `terminate` function on Windows everything works great, on the other hand Linux fails with this solution. As a replacement of process killing I was forced to use ``` os.system('kill -9 {}'.format(pid)) ``` I know this isn't too smart, but it works. So I just wondering why this code works on Windows, but on Linux fails. Example: ```python from multiprocessing import Process import os process=Process(target=foo,args=('bar',)) pid=process.pid process.terminate() # works on Windows only ... os.sytem('kill -9 {}'.format(pid)) # my replacements on Linux ``` My configuration: python 3.2.0 build 88445; Linux-2.6.32-Debian-6.0.4 This is a sample from my code. I hope it will be sufficient. ```python def start_test(timestamp,current_test_suite,user_ip): global_test_table[timestamp] = current_test_suite setattr(global_test_table[timestamp], "user_ip", user_ip) test_cases = global_test_table[timestamp].test_cases_table test_cases = test_cases*int(global_test_table[timestamp].count + 1) global_test_table[timestamp].test_cases_table = test_cases print(test_cases) print(global_test_table[timestamp].test_cases_table) case_num = len(test_cases) Report.basecounter = Report.casecounter = case_num setattr(global_test_table[timestamp], "case_num", case_num) setattr(global_test_table[timestamp], "user_current_test", 0) try: dbobj=MySQLdb.connect(*dbconnector) dbcursor=dbobj.cursor() dbcursor.execute(sqlquery_insert_progress.format(progress_timestamp = str(timestamp), user_current_test = global_test_table[timestamp].user_current_tes$ except :... for i in range(case_num): user_row = global_test_table[timestamp] current_test_from_tests_table = user_row.test_cases_table[i] unittest.TextTestRunner(verbosity=2).run(suite(CommonGUI.get_address(CommonGUI,current_test_from_tests_table[1], current_test_from_tests_table[2], user$ global_test_table[timestamp].user_current_test = i + 1 try: dbobj=MySQLdb.connect(*dbconnector) dbcursor=dbobj.cursor() dbcursor.execute(sqlquery_update_progress.format(progress_timestamp = str(timestamp), user_current_test = global_test_table[timestamp].user_current$ except :... @cherrypy.expose() def start_test_page(self, **test_suite): timestamp = str(time.time()) user_ip = cherrypy.request.remote.ip if on_server(): sys.stdout=sys.stderr=open("/var/log/cherrypy/test_gui/{file}.log".format(file=timestamp),"a") current_test_suite = self.parse_result(**test_suite) #global_test_table[timestamp] = current_test_suite #setattr(global_test_table[timestamp], "user_ip", user_ip) user_test_process = Process(target=start_test, args=(timestamp,current_test_suite,user_ip)) users_process_table[timestamp] = user_test_process user_test_process.start() return '''{"testsuite_id" : "''' + str(timestamp) + '''"}''' @cherrypy.expose() def stop_test(self, timestamp): if timestamp in users_process_table: if on_server(): user_process_pid = users_process_table[timestamp].pid os.system("kill -9 " + str(user_process_pid)) else: users_process_table[timestamp].terminate() del users_process_table[timestamp] else: return "No process exists" ```
2012/05/10
[ "https://Stackoverflow.com/questions/10529461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/611982/" ]
From the [docs](http://docs.python.org/py3k/library/multiprocessing.html#multiprocessing.Process.terminate): > > terminate() > > > Terminate the process. On Unix this is done using the > SIGTERM signal; on Windows TerminateProcess() is used. Note that exit > handlers and finally clauses, etc., will not be executed. > > > Note that descendant processes of the process will not be terminated – > they will simply become orphaned. > > > So it looks like you have to make sure that your process handles the SIGTERM signal correctly. Use [`signal.signal`](http://docs.python.org/py3k/library/signal.html#signal.signal) to set a signal handler. To set a SIGTERM signal handler that simply exist the process, use: ``` import signal import sys signal.signal(signal.SIGTERM, lambda signum, stack_frame: sys.exit(1)) ``` **EDIT** A Python process normally terminates on SIGTERM, I don't know why your multiprocessing process doesn't terminate on SIGTERM.
Not exactly a direct answer to your question, but since you are dealing with the threads this could be helpful as well for debugging those threads: <https://stackoverflow.com/a/10165776/1019572> I recently found a bug in cherrypy using this code.
3,182,009
I'm trying to upload an image (just a random picture for now) to my MediaWiki site, but I keep getting this error: > > "Unrecognized value for parameter 'action': upload" > > > Here's what I did (site url and password changed): ``` Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import wikitools >>> import poster >>> wiki = wikitools.wiki.Wiki("mywikiurl/api.php") >>> wiki.login(username="admin", password="mypassword") True >>> screenshotPage = wikitools.wikifile.File(wiki=wiki, title="screenshot") >>> screenshotPage.upload(fileobj=open("/Users/jeff/Pictures/02273_magensbay_1280x800.jpg", "r"), ignorewarnings=True) Traceback (most recent call last): File "", line 1, in File "/Library/Python/2.6/site-packages/wikitools/wikifile.py", line 228, in upload res = req.query() File "/Library/Python/2.6/site-packages/wikitools/api.py", line 143, in query raise APIError(data['error']['code'], data['error']['info']) wikitools.api.APIError: (u'unknown_action', u"Unrecognized value for parameter 'action': upload") >>> ``` From what I could find on google, the current MediaWiki doesn't support uploading files. But that's ridiculous... there must be some way, right? I'm not married to the wikitools package—any way of doing it is appreciated. EDIT: I set $wgEnableUploads = true in my LocalSettings.php, and I can upload files manually, just not through python. EDIT: I think wikitools gets an edit token automatically. I've attached the upload method. Before it does the API request it calls self.getToken('edit'), which should take care of it I think? I'll play around with it a little though to see if manually adding that in fixes things. ``` def upload(self, fileobj=None, comment='', url=None, ignorewarnings=False, watch=False): """Upload a file, requires the "poster" module fileobj - A file object opened for reading comment - The log comment, used as the inital page content if the file doesn't already exist on the wiki url - A URL to upload the file from, if allowed on the wiki ignorewarnings - Ignore warnings about duplicate files, etc. watch - Add the page to your watchlist """ if not api.canupload and fileobj: raise UploadError("The poster module is required for file uploading") if not fileobj and not url: raise UploadError("Must give either a file object or a URL") if fileobj and url: raise UploadError("Cannot give a file and a URL") params = {'action':'upload', 'comment':comment, 'filename':self.unprefixedtitle, 'token':self.getToken('edit') # There's no specific "upload" token } if url: params['url'] = url else: params['file'] = fileobj if ignorewarnings: params['ignorewarnings'] = '' if watch: params['watch'] = '' req = api.APIRequest(self.site, params, write=True, multipart=bool(fileobj)) res = req.query() if 'upload' in res and res['upload']['result'] == 'Success': self.wikitext = '' self.links = [] self.templates = [] self.exists = True return res ``` Also this is my first question so somebody let me know if you can't post other peoples' code or something. Thanks!
2010/07/05
[ "https://Stackoverflow.com/questions/3182009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383971/" ]
You need at least MediaWiki 1.16 (which is currently in begta) to be able to upload files via the API. Or you can try [mwclient](http://mwclient.sf.net/), which automatically falls back to uploading via Special:Upload if an older version of MediaWiki is used (with reduced functionality, such as no error handling etc.)
Maybe you have to "obtain a token" first? > > To upload files, a token is required. This token is identical to the edit token and is the same regardless of target filename, but changes at every login. Unlike other tokens, it cannot be obtained directly, so one must obtain and use an edit token instead. > > > See here for details: <http://www.mediawiki.org/wiki/API:Edit_-_Uploading_files>
3,182,009
I'm trying to upload an image (just a random picture for now) to my MediaWiki site, but I keep getting this error: > > "Unrecognized value for parameter 'action': upload" > > > Here's what I did (site url and password changed): ``` Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import wikitools >>> import poster >>> wiki = wikitools.wiki.Wiki("mywikiurl/api.php") >>> wiki.login(username="admin", password="mypassword") True >>> screenshotPage = wikitools.wikifile.File(wiki=wiki, title="screenshot") >>> screenshotPage.upload(fileobj=open("/Users/jeff/Pictures/02273_magensbay_1280x800.jpg", "r"), ignorewarnings=True) Traceback (most recent call last): File "", line 1, in File "/Library/Python/2.6/site-packages/wikitools/wikifile.py", line 228, in upload res = req.query() File "/Library/Python/2.6/site-packages/wikitools/api.py", line 143, in query raise APIError(data['error']['code'], data['error']['info']) wikitools.api.APIError: (u'unknown_action', u"Unrecognized value for parameter 'action': upload") >>> ``` From what I could find on google, the current MediaWiki doesn't support uploading files. But that's ridiculous... there must be some way, right? I'm not married to the wikitools package—any way of doing it is appreciated. EDIT: I set $wgEnableUploads = true in my LocalSettings.php, and I can upload files manually, just not through python. EDIT: I think wikitools gets an edit token automatically. I've attached the upload method. Before it does the API request it calls self.getToken('edit'), which should take care of it I think? I'll play around with it a little though to see if manually adding that in fixes things. ``` def upload(self, fileobj=None, comment='', url=None, ignorewarnings=False, watch=False): """Upload a file, requires the "poster" module fileobj - A file object opened for reading comment - The log comment, used as the inital page content if the file doesn't already exist on the wiki url - A URL to upload the file from, if allowed on the wiki ignorewarnings - Ignore warnings about duplicate files, etc. watch - Add the page to your watchlist """ if not api.canupload and fileobj: raise UploadError("The poster module is required for file uploading") if not fileobj and not url: raise UploadError("Must give either a file object or a URL") if fileobj and url: raise UploadError("Cannot give a file and a URL") params = {'action':'upload', 'comment':comment, 'filename':self.unprefixedtitle, 'token':self.getToken('edit') # There's no specific "upload" token } if url: params['url'] = url else: params['file'] = fileobj if ignorewarnings: params['ignorewarnings'] = '' if watch: params['watch'] = '' req = api.APIRequest(self.site, params, write=True, multipart=bool(fileobj)) res = req.query() if 'upload' in res and res['upload']['result'] == 'Success': self.wikitext = '' self.links = [] self.templates = [] self.exists = True return res ``` Also this is my first question so somebody let me know if you can't post other peoples' code or something. Thanks!
2010/07/05
[ "https://Stackoverflow.com/questions/3182009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383971/" ]
I got so frustrated with all these troubles that I made my own simple routines using poster and the python standard cookielib and httplib2. It is located here: <https://github.com/gandrewstone/mediawiki_python_bot>
Maybe you have to "obtain a token" first? > > To upload files, a token is required. This token is identical to the edit token and is the same regardless of target filename, but changes at every login. Unlike other tokens, it cannot be obtained directly, so one must obtain and use an edit token instead. > > > See here for details: <http://www.mediawiki.org/wiki/API:Edit_-_Uploading_files>
3,182,009
I'm trying to upload an image (just a random picture for now) to my MediaWiki site, but I keep getting this error: > > "Unrecognized value for parameter 'action': upload" > > > Here's what I did (site url and password changed): ``` Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import wikitools >>> import poster >>> wiki = wikitools.wiki.Wiki("mywikiurl/api.php") >>> wiki.login(username="admin", password="mypassword") True >>> screenshotPage = wikitools.wikifile.File(wiki=wiki, title="screenshot") >>> screenshotPage.upload(fileobj=open("/Users/jeff/Pictures/02273_magensbay_1280x800.jpg", "r"), ignorewarnings=True) Traceback (most recent call last): File "", line 1, in File "/Library/Python/2.6/site-packages/wikitools/wikifile.py", line 228, in upload res = req.query() File "/Library/Python/2.6/site-packages/wikitools/api.py", line 143, in query raise APIError(data['error']['code'], data['error']['info']) wikitools.api.APIError: (u'unknown_action', u"Unrecognized value for parameter 'action': upload") >>> ``` From what I could find on google, the current MediaWiki doesn't support uploading files. But that's ridiculous... there must be some way, right? I'm not married to the wikitools package—any way of doing it is appreciated. EDIT: I set $wgEnableUploads = true in my LocalSettings.php, and I can upload files manually, just not through python. EDIT: I think wikitools gets an edit token automatically. I've attached the upload method. Before it does the API request it calls self.getToken('edit'), which should take care of it I think? I'll play around with it a little though to see if manually adding that in fixes things. ``` def upload(self, fileobj=None, comment='', url=None, ignorewarnings=False, watch=False): """Upload a file, requires the "poster" module fileobj - A file object opened for reading comment - The log comment, used as the inital page content if the file doesn't already exist on the wiki url - A URL to upload the file from, if allowed on the wiki ignorewarnings - Ignore warnings about duplicate files, etc. watch - Add the page to your watchlist """ if not api.canupload and fileobj: raise UploadError("The poster module is required for file uploading") if not fileobj and not url: raise UploadError("Must give either a file object or a URL") if fileobj and url: raise UploadError("Cannot give a file and a URL") params = {'action':'upload', 'comment':comment, 'filename':self.unprefixedtitle, 'token':self.getToken('edit') # There's no specific "upload" token } if url: params['url'] = url else: params['file'] = fileobj if ignorewarnings: params['ignorewarnings'] = '' if watch: params['watch'] = '' req = api.APIRequest(self.site, params, write=True, multipart=bool(fileobj)) res = req.query() if 'upload' in res and res['upload']['result'] == 'Success': self.wikitext = '' self.links = [] self.templates = [] self.exists = True return res ``` Also this is my first question so somebody let me know if you can't post other peoples' code or something. Thanks!
2010/07/05
[ "https://Stackoverflow.com/questions/3182009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383971/" ]
You need at least MediaWiki 1.16 (which is currently in begta) to be able to upload files via the API. Or you can try [mwclient](http://mwclient.sf.net/), which automatically falls back to uploading via Special:Upload if an older version of MediaWiki is used (with reduced functionality, such as no error handling etc.)
I was having similar trouble, and I was getting a raise APIError(data['error']['code'], data['error']['info']) wikitools.api.APIError: (u'verification-error', u'This file did not pass file verification') However, I found that the target page needs to be the same type as the file, and you should open the file for binary: ``` testImage = wikitools.wikifile.File(wiki=site, title="Image:test_snapshot.jpg") testImage.upload(fileobj=open("somefile.jpg", "rb"), ignorewarnings=True) ```
3,182,009
I'm trying to upload an image (just a random picture for now) to my MediaWiki site, but I keep getting this error: > > "Unrecognized value for parameter 'action': upload" > > > Here's what I did (site url and password changed): ``` Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import wikitools >>> import poster >>> wiki = wikitools.wiki.Wiki("mywikiurl/api.php") >>> wiki.login(username="admin", password="mypassword") True >>> screenshotPage = wikitools.wikifile.File(wiki=wiki, title="screenshot") >>> screenshotPage.upload(fileobj=open("/Users/jeff/Pictures/02273_magensbay_1280x800.jpg", "r"), ignorewarnings=True) Traceback (most recent call last): File "", line 1, in File "/Library/Python/2.6/site-packages/wikitools/wikifile.py", line 228, in upload res = req.query() File "/Library/Python/2.6/site-packages/wikitools/api.py", line 143, in query raise APIError(data['error']['code'], data['error']['info']) wikitools.api.APIError: (u'unknown_action', u"Unrecognized value for parameter 'action': upload") >>> ``` From what I could find on google, the current MediaWiki doesn't support uploading files. But that's ridiculous... there must be some way, right? I'm not married to the wikitools package—any way of doing it is appreciated. EDIT: I set $wgEnableUploads = true in my LocalSettings.php, and I can upload files manually, just not through python. EDIT: I think wikitools gets an edit token automatically. I've attached the upload method. Before it does the API request it calls self.getToken('edit'), which should take care of it I think? I'll play around with it a little though to see if manually adding that in fixes things. ``` def upload(self, fileobj=None, comment='', url=None, ignorewarnings=False, watch=False): """Upload a file, requires the "poster" module fileobj - A file object opened for reading comment - The log comment, used as the inital page content if the file doesn't already exist on the wiki url - A URL to upload the file from, if allowed on the wiki ignorewarnings - Ignore warnings about duplicate files, etc. watch - Add the page to your watchlist """ if not api.canupload and fileobj: raise UploadError("The poster module is required for file uploading") if not fileobj and not url: raise UploadError("Must give either a file object or a URL") if fileobj and url: raise UploadError("Cannot give a file and a URL") params = {'action':'upload', 'comment':comment, 'filename':self.unprefixedtitle, 'token':self.getToken('edit') # There's no specific "upload" token } if url: params['url'] = url else: params['file'] = fileobj if ignorewarnings: params['ignorewarnings'] = '' if watch: params['watch'] = '' req = api.APIRequest(self.site, params, write=True, multipart=bool(fileobj)) res = req.query() if 'upload' in res and res['upload']['result'] == 'Success': self.wikitext = '' self.links = [] self.templates = [] self.exists = True return res ``` Also this is my first question so somebody let me know if you can't post other peoples' code or something. Thanks!
2010/07/05
[ "https://Stackoverflow.com/questions/3182009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383971/" ]
You need at least MediaWiki 1.16 (which is currently in begta) to be able to upload files via the API. Or you can try [mwclient](http://mwclient.sf.net/), which automatically falls back to uploading via Special:Upload if an older version of MediaWiki is used (with reduced functionality, such as no error handling etc.)
I got so frustrated with all these troubles that I made my own simple routines using poster and the python standard cookielib and httplib2. It is located here: <https://github.com/gandrewstone/mediawiki_python_bot>
3,182,009
I'm trying to upload an image (just a random picture for now) to my MediaWiki site, but I keep getting this error: > > "Unrecognized value for parameter 'action': upload" > > > Here's what I did (site url and password changed): ``` Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import wikitools >>> import poster >>> wiki = wikitools.wiki.Wiki("mywikiurl/api.php") >>> wiki.login(username="admin", password="mypassword") True >>> screenshotPage = wikitools.wikifile.File(wiki=wiki, title="screenshot") >>> screenshotPage.upload(fileobj=open("/Users/jeff/Pictures/02273_magensbay_1280x800.jpg", "r"), ignorewarnings=True) Traceback (most recent call last): File "", line 1, in File "/Library/Python/2.6/site-packages/wikitools/wikifile.py", line 228, in upload res = req.query() File "/Library/Python/2.6/site-packages/wikitools/api.py", line 143, in query raise APIError(data['error']['code'], data['error']['info']) wikitools.api.APIError: (u'unknown_action', u"Unrecognized value for parameter 'action': upload") >>> ``` From what I could find on google, the current MediaWiki doesn't support uploading files. But that's ridiculous... there must be some way, right? I'm not married to the wikitools package—any way of doing it is appreciated. EDIT: I set $wgEnableUploads = true in my LocalSettings.php, and I can upload files manually, just not through python. EDIT: I think wikitools gets an edit token automatically. I've attached the upload method. Before it does the API request it calls self.getToken('edit'), which should take care of it I think? I'll play around with it a little though to see if manually adding that in fixes things. ``` def upload(self, fileobj=None, comment='', url=None, ignorewarnings=False, watch=False): """Upload a file, requires the "poster" module fileobj - A file object opened for reading comment - The log comment, used as the inital page content if the file doesn't already exist on the wiki url - A URL to upload the file from, if allowed on the wiki ignorewarnings - Ignore warnings about duplicate files, etc. watch - Add the page to your watchlist """ if not api.canupload and fileobj: raise UploadError("The poster module is required for file uploading") if not fileobj and not url: raise UploadError("Must give either a file object or a URL") if fileobj and url: raise UploadError("Cannot give a file and a URL") params = {'action':'upload', 'comment':comment, 'filename':self.unprefixedtitle, 'token':self.getToken('edit') # There's no specific "upload" token } if url: params['url'] = url else: params['file'] = fileobj if ignorewarnings: params['ignorewarnings'] = '' if watch: params['watch'] = '' req = api.APIRequest(self.site, params, write=True, multipart=bool(fileobj)) res = req.query() if 'upload' in res and res['upload']['result'] == 'Success': self.wikitext = '' self.links = [] self.templates = [] self.exists = True return res ``` Also this is my first question so somebody let me know if you can't post other peoples' code or something. Thanks!
2010/07/05
[ "https://Stackoverflow.com/questions/3182009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383971/" ]
I got so frustrated with all these troubles that I made my own simple routines using poster and the python standard cookielib and httplib2. It is located here: <https://github.com/gandrewstone/mediawiki_python_bot>
I was having similar trouble, and I was getting a raise APIError(data['error']['code'], data['error']['info']) wikitools.api.APIError: (u'verification-error', u'This file did not pass file verification') However, I found that the target page needs to be the same type as the file, and you should open the file for binary: ``` testImage = wikitools.wikifile.File(wiki=site, title="Image:test_snapshot.jpg") testImage.upload(fileobj=open("somefile.jpg", "rb"), ignorewarnings=True) ```
29,922,373
I'm doing a fair amount of parallel processing in Python using the multiprocessing module. I know certain objects CAN be pickle (thus passed as arguments in multi-p) and others can't. E.g. ``` class abc(): pass a=abc() pickle.dumps(a) 'ccopy_reg\n_reconstructor\np1\n(c__main__\nabc\np2\nc__builtin__\nobject\np3\nNtRp4\n.' ``` But I have some larger classes in my code (a dozen methods, or so), and this happens: ``` a=myBigClass() pickle.dumps(a) Traceback (innermost last): File "<stdin>", line 1, in <module> File "/usr/apps/Python279/python-2.7.9-rhel5-x86_64/lib/python2.7/copy_reg.py", line 70, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle file objects ``` It's not a file object, but at other times, I'll get other messages that say basically: "I can't pickle this". So what's the rule? Number of bytes? Depth of hierarchy? Phase of the moon?
2015/04/28
[ "https://Stackoverflow.com/questions/29922373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1415450/" ]
From the [docs](https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled): > > The following types can be pickled: > > > * `None`, `True`, and `False` > * integers, long integers, floating point numbers, complex numbers > * normal and Unicode strings > * tuples, lists, sets, and dictionaries containing only picklable objects > * functions defined at the top level of a module > + built-in functions defined at the top level of a module > * classes that are defined at the top level of a module > * instances of such classes whose `__dict__` or the result of calling `__getstate__()` is picklable (see section The pickle protocol for details). > > > Attempts to pickle unpicklable objects will raise the `PicklingError` > exception; when this happens, an unspecified number of bytes may have > already been written to the underlying file. Trying to pickle a highly > recursive data structure may exceed the maximum recursion depth, a > `RuntimeError` will be raised in this case. You can carefully raise this > limit with `sys.setrecursionlimit()`. > > >
The general rule of thumb is that "logical" objects can be pickled, but "resource" objects (files, locks) can't, because it makes no sense to persist/clone them.
29,922,373
I'm doing a fair amount of parallel processing in Python using the multiprocessing module. I know certain objects CAN be pickle (thus passed as arguments in multi-p) and others can't. E.g. ``` class abc(): pass a=abc() pickle.dumps(a) 'ccopy_reg\n_reconstructor\np1\n(c__main__\nabc\np2\nc__builtin__\nobject\np3\nNtRp4\n.' ``` But I have some larger classes in my code (a dozen methods, or so), and this happens: ``` a=myBigClass() pickle.dumps(a) Traceback (innermost last): File "<stdin>", line 1, in <module> File "/usr/apps/Python279/python-2.7.9-rhel5-x86_64/lib/python2.7/copy_reg.py", line 70, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle file objects ``` It's not a file object, but at other times, I'll get other messages that say basically: "I can't pickle this". So what's the rule? Number of bytes? Depth of hierarchy? Phase of the moon?
2015/04/28
[ "https://Stackoverflow.com/questions/29922373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1415450/" ]
From the [docs](https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled): > > The following types can be pickled: > > > * `None`, `True`, and `False` > * integers, long integers, floating point numbers, complex numbers > * normal and Unicode strings > * tuples, lists, sets, and dictionaries containing only picklable objects > * functions defined at the top level of a module > + built-in functions defined at the top level of a module > * classes that are defined at the top level of a module > * instances of such classes whose `__dict__` or the result of calling `__getstate__()` is picklable (see section The pickle protocol for details). > > > Attempts to pickle unpicklable objects will raise the `PicklingError` > exception; when this happens, an unspecified number of bytes may have > already been written to the underlying file. Trying to pickle a highly > recursive data structure may exceed the maximum recursion depth, a > `RuntimeError` will be raised in this case. You can carefully raise this > limit with `sys.setrecursionlimit()`. > > >
In addition to icedtrees' answer, also coming straight from the [docs](https://docs.python.org/3.5/library/pickle.html#pickle-inst), you can customize and control how class instances are pickled and unpicked, using the special methods: `object.__getnewargs_ex__()`, `object.__getnewargs__()`, `object.__getstate__()`, `object.__setstate__(state)`
29,922,373
I'm doing a fair amount of parallel processing in Python using the multiprocessing module. I know certain objects CAN be pickle (thus passed as arguments in multi-p) and others can't. E.g. ``` class abc(): pass a=abc() pickle.dumps(a) 'ccopy_reg\n_reconstructor\np1\n(c__main__\nabc\np2\nc__builtin__\nobject\np3\nNtRp4\n.' ``` But I have some larger classes in my code (a dozen methods, or so), and this happens: ``` a=myBigClass() pickle.dumps(a) Traceback (innermost last): File "<stdin>", line 1, in <module> File "/usr/apps/Python279/python-2.7.9-rhel5-x86_64/lib/python2.7/copy_reg.py", line 70, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle file objects ``` It's not a file object, but at other times, I'll get other messages that say basically: "I can't pickle this". So what's the rule? Number of bytes? Depth of hierarchy? Phase of the moon?
2015/04/28
[ "https://Stackoverflow.com/questions/29922373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1415450/" ]
I'm the `dill` author. There's a fairly comprehensive list of what pickles and what doesn't as part of `dill`. It can be run per version of Python 2.5–3.4, and adjusted for what pickles with `dill` or what pickles with `pickle` by changing one flag. See [here](https://github.com/uqfoundation/dill/blob/master/tests/test_objects.py) and [here](https://github.com/uqfoundation/dill/blob/master/dill/_objects.py). The root of the rules for what pickles is (off the top of my head): 1. Can you capture the state of the object by reference (i.e. a function defined in `__main__` versus an imported function)? [*Then, yes*] 2. Does a generic `__getstate__` and `__setstate__` rule exist for the given object type? [*Then, yes*] 3. Does it depend on a `Frame` object (i.e. rely on the GIL and global execution stack)? Iterators are now an exception to this, by "replaying" the iterator on unpickling. [*Then, no*] 4. Does the object instance point to the wrong class path (i.e. due to being defined in a closure, in C-bindings, or other `__init__` path manipulations)? [*Then, no*] 5. Is it considered dangerous by Python to allow this? [*Then, no*] So, (5) is less prevalent now than it used to be, but still has some lasting effects in the language for `pickle`. `dill`, for the most part, removes (1), (2), and (5) – but is still fairly effected by (3) and (4). I might be forgetting something else, but I think in general those are the underlying rules. Certain modules like `multiprocessing` register some objects that are important for their functioning. `dill` registers the majority of objects in the language. The `dill` fork of `multiprocessing` is required because `multiprocessing` uses `cPickle`, and `dill` can only augment the pure-Python pickling registry. You could, if you have the patience, go through all the relevant `copy_reg` functions in `dill`, and apply them to the `cPickle` module and you'd get a much more pickle-capable `multiprocessing`. I've found a simple (read: one liner) way to do this for `pickle`, but not `cPickle`.
From the [docs](https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled): > > The following types can be pickled: > > > * `None`, `True`, and `False` > * integers, long integers, floating point numbers, complex numbers > * normal and Unicode strings > * tuples, lists, sets, and dictionaries containing only picklable objects > * functions defined at the top level of a module > + built-in functions defined at the top level of a module > * classes that are defined at the top level of a module > * instances of such classes whose `__dict__` or the result of calling `__getstate__()` is picklable (see section The pickle protocol for details). > > > Attempts to pickle unpicklable objects will raise the `PicklingError` > exception; when this happens, an unspecified number of bytes may have > already been written to the underlying file. Trying to pickle a highly > recursive data structure may exceed the maximum recursion depth, a > `RuntimeError` will be raised in this case. You can carefully raise this > limit with `sys.setrecursionlimit()`. > > >
29,922,373
I'm doing a fair amount of parallel processing in Python using the multiprocessing module. I know certain objects CAN be pickle (thus passed as arguments in multi-p) and others can't. E.g. ``` class abc(): pass a=abc() pickle.dumps(a) 'ccopy_reg\n_reconstructor\np1\n(c__main__\nabc\np2\nc__builtin__\nobject\np3\nNtRp4\n.' ``` But I have some larger classes in my code (a dozen methods, or so), and this happens: ``` a=myBigClass() pickle.dumps(a) Traceback (innermost last): File "<stdin>", line 1, in <module> File "/usr/apps/Python279/python-2.7.9-rhel5-x86_64/lib/python2.7/copy_reg.py", line 70, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle file objects ``` It's not a file object, but at other times, I'll get other messages that say basically: "I can't pickle this". So what's the rule? Number of bytes? Depth of hierarchy? Phase of the moon?
2015/04/28
[ "https://Stackoverflow.com/questions/29922373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1415450/" ]
I'm the `dill` author. There's a fairly comprehensive list of what pickles and what doesn't as part of `dill`. It can be run per version of Python 2.5–3.4, and adjusted for what pickles with `dill` or what pickles with `pickle` by changing one flag. See [here](https://github.com/uqfoundation/dill/blob/master/tests/test_objects.py) and [here](https://github.com/uqfoundation/dill/blob/master/dill/_objects.py). The root of the rules for what pickles is (off the top of my head): 1. Can you capture the state of the object by reference (i.e. a function defined in `__main__` versus an imported function)? [*Then, yes*] 2. Does a generic `__getstate__` and `__setstate__` rule exist for the given object type? [*Then, yes*] 3. Does it depend on a `Frame` object (i.e. rely on the GIL and global execution stack)? Iterators are now an exception to this, by "replaying" the iterator on unpickling. [*Then, no*] 4. Does the object instance point to the wrong class path (i.e. due to being defined in a closure, in C-bindings, or other `__init__` path manipulations)? [*Then, no*] 5. Is it considered dangerous by Python to allow this? [*Then, no*] So, (5) is less prevalent now than it used to be, but still has some lasting effects in the language for `pickle`. `dill`, for the most part, removes (1), (2), and (5) – but is still fairly effected by (3) and (4). I might be forgetting something else, but I think in general those are the underlying rules. Certain modules like `multiprocessing` register some objects that are important for their functioning. `dill` registers the majority of objects in the language. The `dill` fork of `multiprocessing` is required because `multiprocessing` uses `cPickle`, and `dill` can only augment the pure-Python pickling registry. You could, if you have the patience, go through all the relevant `copy_reg` functions in `dill`, and apply them to the `cPickle` module and you'd get a much more pickle-capable `multiprocessing`. I've found a simple (read: one liner) way to do this for `pickle`, but not `cPickle`.
The general rule of thumb is that "logical" objects can be pickled, but "resource" objects (files, locks) can't, because it makes no sense to persist/clone them.
29,922,373
I'm doing a fair amount of parallel processing in Python using the multiprocessing module. I know certain objects CAN be pickle (thus passed as arguments in multi-p) and others can't. E.g. ``` class abc(): pass a=abc() pickle.dumps(a) 'ccopy_reg\n_reconstructor\np1\n(c__main__\nabc\np2\nc__builtin__\nobject\np3\nNtRp4\n.' ``` But I have some larger classes in my code (a dozen methods, or so), and this happens: ``` a=myBigClass() pickle.dumps(a) Traceback (innermost last): File "<stdin>", line 1, in <module> File "/usr/apps/Python279/python-2.7.9-rhel5-x86_64/lib/python2.7/copy_reg.py", line 70, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle file objects ``` It's not a file object, but at other times, I'll get other messages that say basically: "I can't pickle this". So what's the rule? Number of bytes? Depth of hierarchy? Phase of the moon?
2015/04/28
[ "https://Stackoverflow.com/questions/29922373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1415450/" ]
I'm the `dill` author. There's a fairly comprehensive list of what pickles and what doesn't as part of `dill`. It can be run per version of Python 2.5–3.4, and adjusted for what pickles with `dill` or what pickles with `pickle` by changing one flag. See [here](https://github.com/uqfoundation/dill/blob/master/tests/test_objects.py) and [here](https://github.com/uqfoundation/dill/blob/master/dill/_objects.py). The root of the rules for what pickles is (off the top of my head): 1. Can you capture the state of the object by reference (i.e. a function defined in `__main__` versus an imported function)? [*Then, yes*] 2. Does a generic `__getstate__` and `__setstate__` rule exist for the given object type? [*Then, yes*] 3. Does it depend on a `Frame` object (i.e. rely on the GIL and global execution stack)? Iterators are now an exception to this, by "replaying" the iterator on unpickling. [*Then, no*] 4. Does the object instance point to the wrong class path (i.e. due to being defined in a closure, in C-bindings, or other `__init__` path manipulations)? [*Then, no*] 5. Is it considered dangerous by Python to allow this? [*Then, no*] So, (5) is less prevalent now than it used to be, but still has some lasting effects in the language for `pickle`. `dill`, for the most part, removes (1), (2), and (5) – but is still fairly effected by (3) and (4). I might be forgetting something else, but I think in general those are the underlying rules. Certain modules like `multiprocessing` register some objects that are important for their functioning. `dill` registers the majority of objects in the language. The `dill` fork of `multiprocessing` is required because `multiprocessing` uses `cPickle`, and `dill` can only augment the pure-Python pickling registry. You could, if you have the patience, go through all the relevant `copy_reg` functions in `dill`, and apply them to the `cPickle` module and you'd get a much more pickle-capable `multiprocessing`. I've found a simple (read: one liner) way to do this for `pickle`, but not `cPickle`.
In addition to icedtrees' answer, also coming straight from the [docs](https://docs.python.org/3.5/library/pickle.html#pickle-inst), you can customize and control how class instances are pickled and unpicked, using the special methods: `object.__getnewargs_ex__()`, `object.__getnewargs__()`, `object.__getstate__()`, `object.__setstate__(state)`
65,346,545
I have two dense matrices with the sizes (2500, 208) and (208, 2500). I want to calculate their product. It works fine and fast when it is a single process but when it is in a multiprocessing block, the processes stuck in there for hours. I do sparse matrices multiplication with even larger sizes but I have no problem. My code looks like this: ``` with Pool(processes=agents) as pool: result = pool.starmap(run_func, args) def run_func(args): #Do stuff. Including large sparse matrices multiplication. C = np.matmul(A,B) # or A.dot(B) or even using BLASS library directly dgemm(1, A, B) #Never go after the line above! ``` Note that when the function `run_func` is executed in a single process, then it works fine. When I do multiprocessing on my local machine, it works fine. When I go for a multiprocessing on HPC, it stucks. I allocate my resources like this: `srun -v --nodes=1 --time 7-0:0 --cpus-per-task=2 --nodes=1 --mem-per-cpu=20G python3 -u run.py 2` Where the last parameter is the number of `agents` in the code above. Here is the LAPACK library details supported on the HPC (obtained from numpy): ``` libraries = ['mkl_rt', 'pthread'] library_dirs = ['**/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['**/include'] blas_opt_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['**lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['**/include'] lapack_mkl_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['**/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['**/include'] lapack_opt_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['**/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['**/include'] ``` Compared to my local machine, all python packages and python version on HPC are the same. Any leads on what is going on?
2020/12/17
[ "https://Stackoverflow.com/questions/65346545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13575728/" ]
All you need to do is pass the function 'add transaction' from 'Page 2' to 'Page 3'. You have to make sure that the function 'add transaction' accepts 'Trans' as a parameter and it also calls setState for Page 2. In Page 3 you have to pass your 'Trans(true, -50)' as the parameter to the 'add transaction' function that is received from 'Page 2'. The 'add transaction' function may be run in the onPressed method of RaisedButton on 'Page 3'. Please see the code below : ``` import 'package:flutter/material.dart'; import 'dart:math' as math; final Color darkBlue = const Color.fromARGB(255, 18, 32, 47); void main() { runApp(MyApp()); } extension Ex on double { double toPrecision(int n) => double.parse(toStringAsFixed(n)); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue), debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: const Text("Flutter Demo App"), ), body: Center( child: MyWidget(), ), ), ); } } class MyWidget extends StatefulWidget { _MyWidgetState createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { void _addTransaction(Trans transaction) { setState(() { transactions.add(transaction); }); } final List<Trans> transactions = [ const Trans(myBool: false, myDouble: 20), const Trans(myBool: true, myDouble: -50), const Trans(myBool: false, myDouble: 110), const Trans(myBool: false, myDouble: 35.5), ]; @override Widget build(BuildContext context) { return Column( children: [ Container( height: MediaQuery.of(context).size.height * .7, child: Scrollbar( showTrackOnHover: true, child: ListView.builder( itemCount: transactions.length, itemBuilder: (context, index) { return ListTile( title: transactions[index], ); }, ), ), ), RaisedButton( onPressed: () { final rnd = math.Random(); _addTransaction( Trans( myBool: rnd.nextBool(), myDouble: rnd.nextDouble().toPrecision(2) + rnd.nextInt(100), ), ); }, child: const Text("Add Transaction"), ), RaisedButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => Page3(addTran: _addTransaction), ), ); }, child: const Text("Page 3"), ), ], ); } } class Trans extends StatelessWidget { final myBool; final myDouble; const Trans({Key key, this.myBool, this.myDouble}) : super(key: key); @override Widget build(BuildContext context) { return Row( children: [ Text("Transaction: ${myBool.toString()} ${myDouble.toString()}") ], ); } } class Page3 extends StatefulWidget { final Function addTran; const Page3({Key key, this.addTran}) : super(key: key); @override _Page3State createState() => _Page3State(); } class _Page3State extends State<Page3> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Page 3"), ), body: Center( child: RaisedButton( onPressed: () => widget.addTran( const Trans(myBool: true, myDouble: 50), ), child: const Text("Add Transaction"), ), ), ); } } ``` Note : even though in my example code above the widget 'Page 3' is in the same file. You may make a separate library for 'Page 3' as usual by importing material.dart.
Usually there are two methods of widget interaction: callbacks (when one widget provides a callback and other one call it back) or streams (when one widget provides a stream controller and other one uses those controller to send events to stream). Callbacks and events are processed by widget-initiator. 1. Create a `ValueSetter` parameter in `Page3` widget and create it like: ```dart // in Page2 final page3 = Page3(callback: (trans) { transactions.add(trans); } // in Page3 onPressed: () { widget.callback(Trans(...)); // if Page3 us stateful } ``` 2. Create a `StreamController<Trans> state member in` Page2`and pass it as parameter to`Page3`. ```dart // in Page2 @override void initState() { super.initState(); controller.stream.listen((trans) { transactions.add(trans); }); } // in Page3 onPressed: () { widget.controller.add(Trans(...)); } ```
45,597,031
I've looked at several other questions and none of them seem to help with my solution. I think I'm just not very intelligent sadly. Basic question I know. I decided to learn python and I'm making a basic app with tkinter to learn. Basically it's an app that stores and displays people's driving licence details (name and expiry date). One of the abilities I want it to have is a name lookup. To begin with, I need to figure out how to put a textbox into my window! I will post the relevant (well, what I think is relevant!) code below: ``` class search(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Enter a name to display that individual's details", font=LARGE_FONT) label.pack(pady=10,padx=10) label1 = tk.Label(console, text="Name:").pack() searchbox = tk.Entry(console) searchbox.pack() button1 = tk.Button(self, text="SEARCH", command=lambda: controller.show_frame(main))#not created yet button1.pack() button2 = tk.Button(self, text="HOME", command=lambda: controller.show_frame(main)) button2.pack() ``` and of course at the top I have ``` import tkinter as tk ``` When I try and run this I get "typeobject "search" has no attribute 'tk'". It worked fine - the search window would open when I click the relevant button on the home window. Until I tried to add the Entry box. What am I doing wrong here? I'm an utter newbie so I'm prepared to face my stupidity Also apologies if the formatting of this question is awful, I'm a newbie posting here as well. Putting everything into correct "code" format is a real pain
2017/08/09
[ "https://Stackoverflow.com/questions/45597031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140751/" ]
I'm guessing you're running into problems since you didn't specify a layout manager and passed `console` instead of `self`: ``` import tkinter as tk class Search(tk.Frame): def __init__(self, parent=None, controller=None): tk.Frame.__init__(self, parent) self.pack() # specify layout manager label1 = tk.Label(self, text="Enter a name to display that individual's details") label1.pack(pady=10, padx=10) label2 = tk.Label(self, text="Name:") label2.pack() searchbox = tk.Entry(self) searchbox.pack() button1 = tk.Button(self, text="SEARCH", command=lambda: controller.show_frame(main)) button1.pack() button2 = tk.Button(self, text="HOME", command=lambda: controller.show_frame(main)) button2.pack() # Just cobble up the rest for example purposes: main = None class Controller: def show_frame(self, frame=None): pass app = Search(controller=Controller()) app.mainloop() ```
First of all, using `from tkinter import *` is a more efficient way of importing Tkinters libraries without having to import specific things when needed. To answer your question though, here is the code for entering a text box. `t1 = Text(self)` To insert text into the text box: `t1.insert()` An example of this would be `t1.insert(END, 'This is text')` If you haven't got it already, t1 is the variable I'm assigning to the text box, although you can choose whatever variable you want. I highly recommend effbots tutorial on tkinter, I found it extremely useful. Here is the link: <http://effbot.org/tkinterbook/tkinter-application-windows.htm> Best of luck!
17,964,475
Hey I'm trying to install some packages from a `requires` file on a new virtual environment (2.7.4), but I keep running into the following error: ``` CertificateError: hostname 'pypi.python.org' doesn't match either of '*.addvocate.com', 'addvocate.com' ``` I cannot seem to find anything helpful on the error when I search. What is going wrong here? Who in the world is `addvocate.com` and what are they doing here?
2013/07/31
[ "https://Stackoverflow.com/questions/17964475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2637052/" ]
The issue is being documented on the python status site at <http://status.python.org/incidents/jj8d7xn41hr5>
When I try to connect to pypi I get the following error: ``` pypi.python.org uses an invalid security certificate. The certificate is only valid for the following names: *.addvocate.com , addvocate.com ``` So either pypi is using the wrong ssl certificate or somehow my connection is being routed to the wrong server. In the meantime I have resorted to downloading directly from source URLs. See <http://www.pip-installer.org/en/latest/usage.html#pip-install>
17,964,475
Hey I'm trying to install some packages from a `requires` file on a new virtual environment (2.7.4), but I keep running into the following error: ``` CertificateError: hostname 'pypi.python.org' doesn't match either of '*.addvocate.com', 'addvocate.com' ``` I cannot seem to find anything helpful on the error when I search. What is going wrong here? Who in the world is `addvocate.com` and what are they doing here?
2013/07/31
[ "https://Stackoverflow.com/questions/17964475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2637052/" ]
When I try to connect to pypi I get the following error: ``` pypi.python.org uses an invalid security certificate. The certificate is only valid for the following names: *.addvocate.com , addvocate.com ``` So either pypi is using the wrong ssl certificate or somehow my connection is being routed to the wrong server. In the meantime I have resorted to downloading directly from source URLs. See <http://www.pip-installer.org/en/latest/usage.html#pip-install>
Changing your DNS settings should solve it for now. For my Ubuntu 12.04 Amazon AWS Instance I did the following: ``` sudo pico /etc/dhcp/dhclient.conf supersede domain-name-servers 8.8.8.8, 8.8.4.4; ``` Save the file and it was fine after a few seconds.
17,964,475
Hey I'm trying to install some packages from a `requires` file on a new virtual environment (2.7.4), but I keep running into the following error: ``` CertificateError: hostname 'pypi.python.org' doesn't match either of '*.addvocate.com', 'addvocate.com' ``` I cannot seem to find anything helpful on the error when I search. What is going wrong here? Who in the world is `addvocate.com` and what are they doing here?
2013/07/31
[ "https://Stackoverflow.com/questions/17964475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2637052/" ]
The issue is being documented on the python status site at <http://status.python.org/incidents/jj8d7xn41hr5>
I had the same error, I fixed it by downgrading my pip version to 1.2.1: easy\_install pip==1.2.1
17,964,475
Hey I'm trying to install some packages from a `requires` file on a new virtual environment (2.7.4), but I keep running into the following error: ``` CertificateError: hostname 'pypi.python.org' doesn't match either of '*.addvocate.com', 'addvocate.com' ``` I cannot seem to find anything helpful on the error when I search. What is going wrong here? Who in the world is `addvocate.com` and what are they doing here?
2013/07/31
[ "https://Stackoverflow.com/questions/17964475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2637052/" ]
I had the same error, I fixed it by downgrading my pip version to 1.2.1: easy\_install pip==1.2.1
Changing your DNS settings should solve it for now. For my Ubuntu 12.04 Amazon AWS Instance I did the following: ``` sudo pico /etc/dhcp/dhclient.conf supersede domain-name-servers 8.8.8.8, 8.8.4.4; ``` Save the file and it was fine after a few seconds.
17,964,475
Hey I'm trying to install some packages from a `requires` file on a new virtual environment (2.7.4), but I keep running into the following error: ``` CertificateError: hostname 'pypi.python.org' doesn't match either of '*.addvocate.com', 'addvocate.com' ``` I cannot seem to find anything helpful on the error when I search. What is going wrong here? Who in the world is `addvocate.com` and what are they doing here?
2013/07/31
[ "https://Stackoverflow.com/questions/17964475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2637052/" ]
The issue is being documented on the python status site at <http://status.python.org/incidents/jj8d7xn41hr5>
Changing your DNS settings should solve it for now. For my Ubuntu 12.04 Amazon AWS Instance I did the following: ``` sudo pico /etc/dhcp/dhclient.conf supersede domain-name-servers 8.8.8.8, 8.8.4.4; ``` Save the file and it was fine after a few seconds.
48,174,011
I'm running apache2 web server on raspberry pi3 model B. I'm setting up smart home running with Pi's and Uno's. I have a php scrypt that executes python program>index.php. It has rwxrwxrwx >I'll change that late becouse i don't fully need it. And i want to real-time display print from python script. `exec('sudo python3 piUno.py')` Let's say that output is "Hello w" How can i import/get printed data from .py?
2018/01/09
[ "https://Stackoverflow.com/questions/48174011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8882678/" ]
shell\_exec returns the output of your script. so use ``` $cmd = escapeshellcmd('sudo python3 piUno.py'); $output = shell_exec($cmd); echo $output; ``` should work! let me know if it doesn't edit: oh hey! your question got me looking at doc to check myself and exec actually returns the last line of output if you need only the last output. ``` $output = exec('sudo python3 piUno.py'); echo $output; ``` or, you can set a second parameter to exec() to store all output lines in an array (1 entry per line) as this ``` $output = array(); exec('sudo python3 piUno.py',$output); var_dump($output); ``` aight! this was fun!
First make sure you have permissions to **write read execute for web user**. You can you user `sudo sudo chmod 777 /path/to/your/directory/file.xyz` For php file and file you want to run. `$output = exec('sudo pytho3 piUno'); echo $output;` **Credits ---> Ralph Thomas Hopper**
14,346,177
I'm trying to use factory\_boy to help generate some MongoEngine documents for my tests. I'm having trouble defining `EmbeddedDocumentField` objects. Here's my MongoEngine `Document`: ```py class Comment(EmbeddedDocument): content = StringField() name = StringField(max_length=120) class Post(Document): title = StringField(required=True) tags = ListField(StringField(), required=True) comments = ListField(EmbeddedDocumentField(Comment)) ``` Here's my partially completed factory\_boy `Factory`: ```py class CommentFactory(factory.Factory): FACTORY_FOR = Comment content = "Platinum coins worth a trillion dollars are great" name = "John Doe" class BlogFactory(factory.Factory): FACTORY_FOR = Blog title = "On Using MongoEngine with factory_boy" tags = ['python', 'mongoengine', 'factory-boy', 'django'] comments = [factory.SubFactory(CommentFactory)] # this doesn't work ``` Any ideas how to specify the `comments` field? The problem is that factory-boy attempts to create the `Comment` EmbeddedDocument.
2013/01/15
[ "https://Stackoverflow.com/questions/14346177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/387163/" ]
I'm not sure if this is what you want but I just started looking at this problem and this seems to work: ``` from mongoengine import EmbeddedDocument, Document, StringField, ListField, EmbeddedDocumentField import factory class Comment(EmbeddedDocument): content = StringField() name = StringField(max_length=120) class Post(Document): title = StringField(required=True) tags = ListField(StringField(), required=True) comments = ListField(EmbeddedDocumentField(Comment)) class CommentFactory(factory.Factory): FACTORY_FOR = Comment content = "Platinum coins worth a trillion dollars are great" name = "John Doe" class PostFactory(factory.Factory): FACTORY_FOR = Post title = "On Using MongoEngine with factory_boy" tags = ['python', 'mongoengine', 'factory-boy', 'django'] comments = factory.LazyAttribute(lambda a: [CommentFactory()]) >>> b = PostFactory() >>> b.comments[0].content 'Platinum coins worth a trillion dollars are great' ``` I wouldn't be surprised if I'm missing something though.
The way that I'm doing it right now is to prevent the Factories based on EmbeddedDocuments from building. So, I've setup up an EmbeddedDocumentFactory, like so: ``` class EmbeddedDocumentFactory(factory.Factory): ABSTRACT_FACTORY = True @classmethod def _prepare(cls, create, **kwargs): return super(EmbeddedDocumentFactory, cls)._prepare(False, **kwargs) ``` Then I inherit from that to create factories for EmbeddedDocuments: ``` class CommentFactory(EmbeddedDocumentFactory): FACTORY_FOR = Comment content = "Platinum coins worth a trillion dollars are great" name = "John Doe" ``` This may not be the best solution, so I'll wait on someone else to respond before accepting this as the answer.
66,517,764
### What is the pythonic way to remove all the parts of string upto and including dot from a set ``` theSet={'products.add_product','products.add_category','books.view_books','cats.change_cats'} #desired output newSet = {'add_product','add_category','view_books', 'change_cats'} ```
2021/03/07
[ "https://Stackoverflow.com/questions/66517764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8047262/" ]
You can use `yearmon`function from `zoo`. Then search for string Jun with R `grepl` function in Date column and apply desired condition with `case_when`from `dplyr` package. ``` library(zoo) library(dplyr) # your data Date <- c("2000-01", "2000-02", "2000-03", "2000-04", "2000-05", "2000-06", "2000-07", "2000-08", "2000-09", "2000-10", "2000-11", "2000-12", "2001-01", "2001-02", "2001-03", "2001-04", "2001-05", "2001-06", "2001-07", "2001-08", "2001-09", "2001-10", "2001-11", "2001-12", "2000-01", "2000-02") Permno <- c(10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10030, 10030) Value <- c("Big, Growth", "Small, Value", "Neutral, Neutral", "Big, Value", "Big, Value", "Big, Value", "Big, Value", "Big, Value", "Small, Value", "Small, Neutral", "Neutral, Neutral", "Big, Growth", "Small, Value", "Neutral, Neutral", "Big, Value", "Big, Value", "Small, Value", "Small, Neutral", "Neutral, Neutral", "Big, Growth", "Small, Value", "Neutral, Neutral", "Big, Value", "Small, Neutral", "Neutral, Neutral", "Small, Neutral") df <- data.frame(Date, Permno, Value) # code for your desired output df1 <- df %>% mutate(Date = as.yearmon(Date), Hold = case_when(grepl("Jun", Date) ~ Value)) # Output: > df1 Date Permno Value Hold 1 Jan 2000 10026 Big, Growth <NA> 2 Feb 2000 10026 Small, Value <NA> 3 Mar 2000 10026 Neutral, Neutral <NA> 4 Apr 2000 10026 Big, Value <NA> 5 May 2000 10026 Big, Value <NA> 6 Jun 2000 10026 Big, Value Big, Value 7 Jul 2000 10026 Big, Value <NA> 8 Aug 2000 10026 Big, Value <NA> 9 Sep 2000 10026 Small, Value <NA> 10 Oct 2000 10026 Small, Neutral <NA> 11 Nov 2000 10026 Neutral, Neutral <NA> 12 Dec 2000 10026 Big, Growth <NA> 13 Jan 2001 10026 Small, Value <NA> 14 Feb 2001 10026 Neutral, Neutral <NA> 15 Mar 2001 10026 Big, Value <NA> 16 Apr 2001 10026 Big, Value <NA> 17 May 2001 10026 Small, Value <NA> 18 Jun 2001 10026 Small, Neutral Small, Neutral 19 Jul 2001 10026 Neutral, Neutral <NA> 20 Aug 2001 10026 Big, Growth <NA> 21 Sep 2001 10026 Small, Value <NA> 22 Oct 2001 10026 Neutral, Neutral <NA> 23 Nov 2001 10026 Big, Value <NA> 24 Dec 2001 10026 Small, Neutral <NA> 25 Jan 2000 10030 Neutral, Neutral <NA> 26 Feb 2000 10030 Small, Neutral <NA> ```
Why not simply this? ``` FF5_class$HOLD <- ifelse(substr(FF5_class$Date, 6,7) =="06", FF5_class$Value, NA) Date Permno Value HOLD 1 2000-01 10026 Big, Growth <NA> 2 2000-02 10026 Small, Value <NA> 3 2000-03 10026 Neutral, Neutral <NA> 4 2000-04 10026 Big, Value <NA> 5 2000-05 10026 Big, Value <NA> 6 2000-06 10026 Big, Value Big, Value 7 2000-07 10026 Big, Value <NA> 8 2000-08 10026 Big, Value <NA> 9 2000-09 10026 Small, Value <NA> 10 2000-10 10026 Small, Neutral <NA> 11 2000-11 10026 Neutral, Neutral <NA> 12 2000-12 10026 Big, Growth <NA> 13 2001-01 10026 Small, Value <NA> 14 2001-02 10026 Neutral, Neutral <NA> 15 2001-03 10026 Big, Value <NA> 16 2001-04 10026 Big, Value <NA> 17 2001-05 10026 Small, Value <NA> 18 2001-06 10026 Small, Neutral Small, Neutral 19 2001-07 10026 Neutral, Neutral <NA> 20 2001-08 10026 Big, Growth <NA> 21 2001-09 10026 Small, Value <NA> 22 2001-10 10026 Neutral, Neutral <NA> 23 2001-11 10026 Big, Value <NA> 24 2001-12 10026 Small, Neutral <NA> 25 2000-01 10030 Neutral, Neutral <NA> 26 2000-02 10030 Small, Neutral <NA> ``` dput(FF5\_class) used ``` FF5_class <- structure(list(Date = c("2000-01", "2000-02", "2000-03", "2000-04", "2000-05", "2000-06", "2000-07", "2000-08", "2000-09", "2000-10", "2000-11", "2000-12", "2001-01", "2001-02", "2001-03", "2001-04", "2001-05", "2001-06", "2001-07", "2001-08", "2001-09", "2001-10", "2001-11", "2001-12", "2000-01", "2000-02"), Permno = c(10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10026, 10030, 10030), Value = c("Big, Growth", "Small, Value", "Neutral, Neutral", "Big, Value", "Big, Value", "Big, Value", "Big, Value", "Big, Value", "Small, Value", "Small, Neutral", "Neutral, Neutral", "Big, Growth", "Small, Value", "Neutral, Neutral", "Big, Value", "Big, Value", "Small, Value", "Small, Neutral", "Neutral, Neutral", "Big, Growth", "Small, Value", "Neutral, Neutral", "Big, Value", "Small, Neutral", "Neutral, Neutral", "Small, Neutral" ), HOLD = c(NA, NA, NA, NA, NA, "Big, Value", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Small, Neutral", NA, NA, NA, NA, NA, NA, NA, NA)), row.names = c(NA, -26L), class = "data.frame") ```
3,434,048
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
2010/08/08
[ "https://Stackoverflow.com/questions/3434048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388350/" ]
Since you're working on windows with VB, it's worth mentioning that [IronPython](http://ironpython.net/) might be one option. Since both VB and IronPython can interact through .NET, you could wrap up your script in an assembly and expose a function which you call with the required arguments.
Have you taken a look at the [getopt module](http://docs.python.org/library/getopt.html)? It's designed to make working with command line options easier. See also the examples at [Dive Into Python](http://www.faqs.org/docs/diveintopython/kgp_commandline.html). If you are working with Python 2.7 (and not lower), than you can also have a look at the [argparse module](http://docs.python.org/library/argparse.html#module-argparse) which should make it even easier.
3,434,048
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
2010/08/08
[ "https://Stackoverflow.com/questions/3434048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388350/" ]
If you are using Python <2.7 I would suggest [optparse](http://docs.python.org/library/optparse.html). optparse is deprecated though, and in 2.7 you should use [argparse](http://docs.python.org/library/argparse.html#module-argparse) It makes passing named parameters a breeze.
you can do something fun like call it as ``` thepyscript.py "x = 12,y = 'hello world', z = 'jam'" ``` and inside your script, parse do: ``` stuff = arg[1].split(',') for item in stuff: exec(item) #or eval(item) depending on how complex you get #Exec can be a lot of fun :) In fact with this approach you could potentially #send functions to your script. #If this is more than you need, then i'd stick w/ arg/optparse ```
3,434,048
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
2010/08/08
[ "https://Stackoverflow.com/questions/3434048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388350/" ]
you can do something fun like call it as ``` thepyscript.py "x = 12,y = 'hello world', z = 'jam'" ``` and inside your script, parse do: ``` stuff = arg[1].split(',') for item in stuff: exec(item) #or eval(item) depending on how complex you get #Exec can be a lot of fun :) In fact with this approach you could potentially #send functions to your script. #If this is more than you need, then i'd stick w/ arg/optparse ```
What do you think about creating a python script setting these variables from the gui side? When starting the python app you just start this script and you have your vars. [Execfile](http://docs.python.org/library/functions.html#execfile)
3,434,048
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
2010/08/08
[ "https://Stackoverflow.com/questions/3434048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388350/" ]
Have you taken a look at the [getopt module](http://docs.python.org/library/getopt.html)? It's designed to make working with command line options easier. See also the examples at [Dive Into Python](http://www.faqs.org/docs/diveintopython/kgp_commandline.html). If you are working with Python 2.7 (and not lower), than you can also have a look at the [argparse module](http://docs.python.org/library/argparse.html#module-argparse) which should make it even easier.
What do you think about creating a python script setting these variables from the gui side? When starting the python app you just start this script and you have your vars. [Execfile](http://docs.python.org/library/functions.html#execfile)
3,434,048
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
2010/08/08
[ "https://Stackoverflow.com/questions/3434048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388350/" ]
If you are using Python <2.7 I would suggest [optparse](http://docs.python.org/library/optparse.html). optparse is deprecated though, and in 2.7 you should use [argparse](http://docs.python.org/library/argparse.html#module-argparse) It makes passing named parameters a breeze.
If your script is not called too often, you can use a configuration file. [The .ini style is easily readable by ConfigParser](http://docs.python.org/library/configparser.html): ``` [Section_1] foo1=1 foo2=2 foo3=5 ... [Section_2] bar1=1 bar2=2 bar3=3 ... ``` If you have a serious amount of variables, it might be the right way to go.
3,434,048
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
2010/08/08
[ "https://Stackoverflow.com/questions/3434048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388350/" ]
If you are using Python <2.7 I would suggest [optparse](http://docs.python.org/library/optparse.html). optparse is deprecated though, and in 2.7 you should use [argparse](http://docs.python.org/library/argparse.html#module-argparse) It makes passing named parameters a breeze.
Have you taken a look at the [getopt module](http://docs.python.org/library/getopt.html)? It's designed to make working with command line options easier. See also the examples at [Dive Into Python](http://www.faqs.org/docs/diveintopython/kgp_commandline.html). If you are working with Python 2.7 (and not lower), than you can also have a look at the [argparse module](http://docs.python.org/library/argparse.html#module-argparse) which should make it even easier.
3,434,048
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
2010/08/08
[ "https://Stackoverflow.com/questions/3434048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388350/" ]
Since you're working on windows with VB, it's worth mentioning that [IronPython](http://ironpython.net/) might be one option. Since both VB and IronPython can interact through .NET, you could wrap up your script in an assembly and expose a function which you call with the required arguments.
If your script is not called too often, you can use a configuration file. [The .ini style is easily readable by ConfigParser](http://docs.python.org/library/configparser.html): ``` [Section_1] foo1=1 foo2=2 foo3=5 ... [Section_2] bar1=1 bar2=2 bar3=3 ... ``` If you have a serious amount of variables, it might be the right way to go.
3,434,048
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
2010/08/08
[ "https://Stackoverflow.com/questions/3434048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388350/" ]
Since you're working on windows with VB, it's worth mentioning that [IronPython](http://ironpython.net/) might be one option. Since both VB and IronPython can interact through .NET, you could wrap up your script in an assembly and expose a function which you call with the required arguments.
What do you think about creating a python script setting these variables from the gui side? When starting the python app you just start this script and you have your vars. [Execfile](http://docs.python.org/library/functions.html#execfile)
3,434,048
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
2010/08/08
[ "https://Stackoverflow.com/questions/3434048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388350/" ]
If you are using Python <2.7 I would suggest [optparse](http://docs.python.org/library/optparse.html). optparse is deprecated though, and in 2.7 you should use [argparse](http://docs.python.org/library/argparse.html#module-argparse) It makes passing named parameters a breeze.
Since you're working on windows with VB, it's worth mentioning that [IronPython](http://ironpython.net/) might be one option. Since both VB and IronPython can interact through .NET, you could wrap up your script in an assembly and expose a function which you call with the required arguments.
3,434,048
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
2010/08/08
[ "https://Stackoverflow.com/questions/3434048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388350/" ]
If you are using Python <2.7 I would suggest [optparse](http://docs.python.org/library/optparse.html). optparse is deprecated though, and in 2.7 you should use [argparse](http://docs.python.org/library/argparse.html#module-argparse) It makes passing named parameters a breeze.
What do you think about creating a python script setting these variables from the gui side? When starting the python app you just start this script and you have your vars. [Execfile](http://docs.python.org/library/functions.html#execfile)
5,574,649
I need a scalable `NoSql` solution to store data as *arrays* for many fields & time stamps, where the key is a combination of a `field` and a `timestamp`. Data would be stored in the following scheme: **KEY** --> "FIELD\_NAME.YYYYMMDD.HHMMSS" **VALUE** --> [v1, v2, v3, v4, v5, v6] (v1..v6 are just `floats`) For instance, suppose that: **FIELD\_NAME** = "TOMATO" **TIME\_STAMP** = "20060316.184356" **VALUES** = [72.34, -22.83, -0.938, 0.265, -2047.23] I need to be able to retrieve **VALUE** (the entire array) given the combination of `FIELD_NAME` & `TIME_STAMP`. The query **VALUES**["*TOMATO.20060316.184356*"] would return the vector [72.34, -22.83, -0.938, 0.265, -2047.23]. Reads of arrays should be as fast as possible. Yet, I also need a way to store (in-place) a scalar value within an array . Suppose that I want to assign the 1st element of `TOMATO` on timestamp `2006/03/16.18:43:56` to be `500.867`. In such a case, I need to have a fast mechanism to do so -- something like: **VALUES**["*TOMATO.20060316.184356*"][0] = 500.867 (this would update on disk) Any idea which `NoSql` solution would work best for this(big plus if it has `python` interface)? I am looking for a fast yet a powerful solution. my data needs would grow to about 20[TB].
2011/04/07
[ "https://Stackoverflow.com/questions/5574649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
Sounds like MongoDB would be a good fit. [PyMongo](http://api.mongodb.org/python/1.10+/index.html) is the api.
Your data is highly structured and regular; what benefit do you see in NoSQL vs a more traditional database? I think [MySQL Cluster](http://dev.mysql.com/downloads/cluster/) sounds tailor-made for your problem. **Edit:** @user540009: I agree that there are serious slowdowns on single-machine or mirrored instances of MySQL larger than half a terabyte, and no-one wants to have to deal with manual sharding; MySQL Cluster is meant to deal with this, and I have read of (though not personally played with) implementations up to 110 terabytes.
12,672,629
> > **Possible Duplicate:** > > [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) > > > I am parsing an XML file that gives me the time in the respective isoformat: ``` tc1 = 2012-09-28T16:41:12.9976565 tc2 = 2012-09-28T23:57:44.6636597 ``` But it is being treated as a string when I retrieve this from the XML file. I have two such time values and i need to do a diff between the two so as to find delta. But since it is a string I can not directly do tc2-tc1. But since they are already in isoformat for datetime, how do i get python to recognize it as datetime? thanks.
2012/10/01
[ "https://Stackoverflow.com/questions/12672629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/966739/" ]
You can use the [python-dateutil `parse()` function](http://labix.org/python-dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2), it's more flexible than strptime. Hope this help you.
Use the [`datetime` module](http://docs.python.org/library/datetime.html). ``` td = datetime.strptime('2012-09-28T16:41:12.997656', '%Y-%m-%dT%H:%M:%S.%f') - datetime.strptime('2012-09-28T23:57:44.663659', '%Y-%m-%dT%H:%M:%S.%f') print td # => datetime.timedelta(-1, 60208, 333997) ``` There is only one small problem: Your microseconds are one digit to long for `%f` to handle. So I've removed the last digits from your input strings.
12,672,629
> > **Possible Duplicate:** > > [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) > > > I am parsing an XML file that gives me the time in the respective isoformat: ``` tc1 = 2012-09-28T16:41:12.9976565 tc2 = 2012-09-28T23:57:44.6636597 ``` But it is being treated as a string when I retrieve this from the XML file. I have two such time values and i need to do a diff between the two so as to find delta. But since it is a string I can not directly do tc2-tc1. But since they are already in isoformat for datetime, how do i get python to recognize it as datetime? thanks.
2012/10/01
[ "https://Stackoverflow.com/questions/12672629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/966739/" ]
Use the [`datetime.strptime`](http://docs.python.org/library/datetime.html#strftime-strptime-behavior) method: ``` import datetime datetime.datetime.strptime(your_string, "%Y-%m-%dT%H:%M:%S.%f") ``` The link provided presents the different format directives. Note that the microseconds are limited to the range `[0,999999]`, meaning that a `ValueError` will be raised with your example (you're using 1/10us): you need to truncate your string to drop the final character.
Use the [`datetime` module](http://docs.python.org/library/datetime.html). ``` td = datetime.strptime('2012-09-28T16:41:12.997656', '%Y-%m-%dT%H:%M:%S.%f') - datetime.strptime('2012-09-28T23:57:44.663659', '%Y-%m-%dT%H:%M:%S.%f') print td # => datetime.timedelta(-1, 60208, 333997) ``` There is only one small problem: Your microseconds are one digit to long for `%f` to handle. So I've removed the last digits from your input strings.
12,672,629
> > **Possible Duplicate:** > > [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) > > > I am parsing an XML file that gives me the time in the respective isoformat: ``` tc1 = 2012-09-28T16:41:12.9976565 tc2 = 2012-09-28T23:57:44.6636597 ``` But it is being treated as a string when I retrieve this from the XML file. I have two such time values and i need to do a diff between the two so as to find delta. But since it is a string I can not directly do tc2-tc1. But since they are already in isoformat for datetime, how do i get python to recognize it as datetime? thanks.
2012/10/01
[ "https://Stackoverflow.com/questions/12672629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/966739/" ]
Use the [`datetime.strptime`](http://docs.python.org/library/datetime.html#strftime-strptime-behavior) method: ``` import datetime datetime.datetime.strptime(your_string, "%Y-%m-%dT%H:%M:%S.%f") ``` The link provided presents the different format directives. Note that the microseconds are limited to the range `[0,999999]`, meaning that a `ValueError` will be raised with your example (you're using 1/10us): you need to truncate your string to drop the final character.
You can use the [python-dateutil `parse()` function](http://labix.org/python-dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2), it's more flexible than strptime. Hope this help you.
42,044,619
I'm working on a project of my own, and I'm at a point where i don't know anymore what to do.. I'm trying to implement some sounds into my project where i press some tact. switches and they should make sounds.. I'm a complete newbie with python so i found a piece of code doing something similar... ``` import os from time import sleep import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.IN) GPIO.setup(24, GPIO.IN) GPIO.setup(25, GPIO.IN) while True: if (GPIO.input(23) == False): os.system('mpg123 -q binary-language-moisture-evaporators.mp3 &') if (GPIO.input(24) == False): os.system('mpg123 -q power-converters.mp3 &') if (GPIO.input(25)== False): os.system('mpg123 -q vader.mp3 &') sleep(0.1); ``` I want the 1st sound to run in a continuous loop while `input(23)==false` and if one of the other two buttons is pressed it stops the first one and plays the other, only once, and returns to checking if `input(23)==false` I need this to be done to finish my project, but I don't have the need really to learn python from scratch (at least for now). at least some guidelines would be greatly appreciated.
2017/02/04
[ "https://Stackoverflow.com/questions/42044619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7516655/" ]
Based on <https://github.com/Unitech/pm2/blob/master/lib/API/Extra.js#L436>, I managed to get this working Put it as the last item in your ecosystem file, and it will always have the highest id Make sure that the script path is correct, it was the default on MY system, it might not be on your I'm running 2.9.3, and the current code (3.5.0) is similar, so it SHOULD work ``` { script : '/usr/local/lib/node_modules/pm2/lib/HttpInterface.js', name : 'pm2-http-interface', execMode : 'fork_mode', env : { PM2_WEB_PORT : 9615 } } ```
not sure, but you can try to specify `interpreter`. It should be your PM2 (check it with `whereis`). Try smth like `{ "apps": [{ "name": "web", "script": "", "interpreter": "/usr/local/bin/pm2", "args": "web" }] }` Please note - i didnot checked it at all, it just suggestion
63,201,965
Hi I have made my flask app and I have exposed port 5001 in Docker file. I pushed it to dockerhub repo and ran on different machine by ``` docker container run --name XYZ <username>/<repo_name>:<tag> ``` The log says that app is running on <http://127.0.0.1:5001/> But if I open that localtion in browser its says ``` Unable to connect ``` Dockerfile: ``` FROM ubuntu:18.04 RUN apt-get update && apt-get -y upgrade \ && apt-get -y install python3.8 \ && apt -y install python3-pip \ && pip3 install --upgrade pip WORKDIR /app COPY . /app RUN pip3 --no-cache-dir install -r requirements.txt EXPOSE 5001 ENTRYPOINT ["python3"] CMD ["app.py"] ```
2020/08/01
[ "https://Stackoverflow.com/questions/63201965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5687866/" ]
This sounds like `insert . . . on duplicate key update`. First, though, you need a unique index or constraint: ``` create unique index unq_stocks_ticker on stocks(ticker); ``` Then you can use: ``` insert into stocks (ticker, marketcap) values (?, ?) on duplicate key update marketcap = values(marketcap); ```
An UPDATE query is incapable of creating a new row, so perhaps like: ``` UPDATE stocks SET marketcap = 300000000000 WHERE symbol = '$MMM' ``` Your footnote "unless it doesn't exist" means you probably then need to examine how many rows this altered and if it's 0 then run: ``` INSERT INTO stocks(marketcap, symbol) VALUES(300000000000, '$MMM') ``` It doesn't really matter which way round you do these; if you have a key on symbol you won't get duplicates, you'll get a fail to insert which you could then use to trigger an update. Ideally though you'd look at the likelihood of failure of each and go with the option of putting the least often failing option first. If you will update 10000 symbols 100 times a day each but only insert maybe 100 new symbols a day then put the update first. If you will create 10000 new symbols a day and update them once a year, put the insert first. This ensures the least time is wasted on operations that have no effect/use resources because they raise an error
52,458,754
I want to compare two dictionary keys in python and if the keys are equal, then print their values. For example, ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} ``` and after comparing the keys, print ``` 'fariborz', 'daei' 'jadi', jafar' ```
2018/09/22
[ "https://Stackoverflow.com/questions/52458754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9287224/" ]
You're asking for the intersection of the two dictionaries. Using the builtin type `set` ---------------------------- You can use the builtin type `set` for this, which implements the `intersection()` function. You can turn a list into a set like this: ``` set(my_list) ``` So, in order to find the intersection between the keys of two dictionaries, you can turn the keys into sets and find the intersection. To get a list with the keys of a dictionary: ``` dict_one.keys() ``` So, to find the intersection between the keys of two dicts: ``` set(dict_one.keys()).intersection(set(dict_two.keys())) ``` This will return, in your example, the set `{'12', '14'}`. The code above in a more readable way: ``` keys_one = set(dict_one.keys()) keys_two = set(dict_one.keys()) same_keys = keys_one.intersection(keys_two) # To get a list of the keys: result = list(same_keys) ``` Using anonymous function (lambda function) and list comprehension ----------------------------------------------------------------- Another easy way to solve this problem would be using lambda functions. I'm including this here just in case you'd like to know. Probably not the most efficient way to do! ``` same_keys = lambda first,second: [key1 for key1 in first.keys() if key1 in second.keys()] ``` So, as to get the result: `result = same_keys(dict_one,dict_two)` Any of the above two methods will give you the keys that are common to both dictionaries. Just loop over it and do as you please to print the values: ``` for key in result: print('{},{}'.format(dict_one[key], dict_two[key])) ```
``` for key, val1 in dict_one.items(): val2 = dict_two.get(key) if val2 is not None: print(val1, val2) ```
52,458,754
I want to compare two dictionary keys in python and if the keys are equal, then print their values. For example, ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} ``` and after comparing the keys, print ``` 'fariborz', 'daei' 'jadi', jafar' ```
2018/09/22
[ "https://Stackoverflow.com/questions/52458754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9287224/" ]
You can iterate over the intersection of the keys of the two dicts, and print the corresponding values of the two dicts after mapping them to the `repr` function, which would help quote the strings: ``` for k in dict_one.keys() & dict_two.keys(): print(','.join(map(repr, (dict_one[k], dict_two[k])))) ``` This outputs: ``` 'fariborz','daei' 'jadi','jafar' ```
``` def compare(dict1,dict2): keys1 = dict1.keys() keys2 = dict2.keys() for key in keys1: if key in keys: print(dict1[key],dict2[key]) ```
52,458,754
I want to compare two dictionary keys in python and if the keys are equal, then print their values. For example, ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} ``` and after comparing the keys, print ``` 'fariborz', 'daei' 'jadi', jafar' ```
2018/09/22
[ "https://Stackoverflow.com/questions/52458754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9287224/" ]
You can iterate over the intersection of the keys of the two dicts, and print the corresponding values of the two dicts after mapping them to the `repr` function, which would help quote the strings: ``` for k in dict_one.keys() & dict_two.keys(): print(','.join(map(repr, (dict_one[k], dict_two[k])))) ``` This outputs: ``` 'fariborz','daei' 'jadi','jafar' ```
``` for key, val1 in dict_one.items(): val2 = dict_two.get(key) if val2 is not None: print(val1, val2) ```
52,458,754
I want to compare two dictionary keys in python and if the keys are equal, then print their values. For example, ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} ``` and after comparing the keys, print ``` 'fariborz', 'daei' 'jadi', jafar' ```
2018/09/22
[ "https://Stackoverflow.com/questions/52458754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9287224/" ]
You can use the `&` operator with to find the matching keys ``` for i in d1.keys() & d2.keys(): print("'{}', '{}'".format(d1[i], d2[i])) ``` > > > ``` > ~/python/stack/sept/twenty_2$ python3.7 alice.py > 'fariborz', 'daei' > 'jadi', 'jafar > > ``` > >
Dictionaries are nice in python because they allow us to look up a key's value very easily and also check if a key exists in the dict. So in your example if you want to print the values for whenever the keys are the same between the dicts you can do something like this: ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} # Loop through all keys in dict_one for key in dict_one: # Then check if each key exists in dict_two if key in dict_two: val1 = dict_one[key] val2 = dict_two[key] print('{},{}'.format(val1, val2)) # print out values with comma between them ```
52,458,754
I want to compare two dictionary keys in python and if the keys are equal, then print their values. For example, ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} ``` and after comparing the keys, print ``` 'fariborz', 'daei' 'jadi', jafar' ```
2018/09/22
[ "https://Stackoverflow.com/questions/52458754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9287224/" ]
You can use the `&` operator with to find the matching keys ``` for i in d1.keys() & d2.keys(): print("'{}', '{}'".format(d1[i], d2[i])) ``` > > > ``` > ~/python/stack/sept/twenty_2$ python3.7 alice.py > 'fariborz', 'daei' > 'jadi', 'jafar > > ``` > >
Using intersection .then you can get the same key value from `dict_one` and `dict_two` This is my code: ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} print([(dict_one[vals],dict_two[vals]) for vals in dict_one.keys() & dict_two.keys()]) ``` Output ``` [('fariborz', 'daei'), ('jadi', 'jafar')] ```
52,458,754
I want to compare two dictionary keys in python and if the keys are equal, then print their values. For example, ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} ``` and after comparing the keys, print ``` 'fariborz', 'daei' 'jadi', jafar' ```
2018/09/22
[ "https://Stackoverflow.com/questions/52458754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9287224/" ]
You can use the `&` operator with to find the matching keys ``` for i in d1.keys() & d2.keys(): print("'{}', '{}'".format(d1[i], d2[i])) ``` > > > ``` > ~/python/stack/sept/twenty_2$ python3.7 alice.py > 'fariborz', 'daei' > 'jadi', 'jafar > > ``` > >
Take iteration through one dictionary and check for existence of key in the other: ``` dict_one = {'12':'fariborz','13':'peter','14':'jadi'} dict_two = {'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} for k in dict_one: if k in dict_two: print(dict_one[k], dict_two[k]) # fariborz daei # jadi jafar ```
52,458,754
I want to compare two dictionary keys in python and if the keys are equal, then print their values. For example, ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} ``` and after comparing the keys, print ``` 'fariborz', 'daei' 'jadi', jafar' ```
2018/09/22
[ "https://Stackoverflow.com/questions/52458754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9287224/" ]
You can use the `&` operator with to find the matching keys ``` for i in d1.keys() & d2.keys(): print("'{}', '{}'".format(d1[i], d2[i])) ``` > > > ``` > ~/python/stack/sept/twenty_2$ python3.7 alice.py > 'fariborz', 'daei' > 'jadi', 'jafar > > ``` > >
``` def compare(dict1,dict2): keys1 = dict1.keys() keys2 = dict2.keys() for key in keys1: if key in keys: print(dict1[key],dict2[key]) ```
52,458,754
I want to compare two dictionary keys in python and if the keys are equal, then print their values. For example, ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} ``` and after comparing the keys, print ``` 'fariborz', 'daei' 'jadi', jafar' ```
2018/09/22
[ "https://Stackoverflow.com/questions/52458754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9287224/" ]
You can iterate over the intersection of the keys of the two dicts, and print the corresponding values of the two dicts after mapping them to the `repr` function, which would help quote the strings: ``` for k in dict_one.keys() & dict_two.keys(): print(','.join(map(repr, (dict_one[k], dict_two[k])))) ``` This outputs: ``` 'fariborz','daei' 'jadi','jafar' ```
Using intersection .then you can get the same key value from `dict_one` and `dict_two` This is my code: ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} print([(dict_one[vals],dict_two[vals]) for vals in dict_one.keys() & dict_two.keys()]) ``` Output ``` [('fariborz', 'daei'), ('jadi', 'jafar')] ```
52,458,754
I want to compare two dictionary keys in python and if the keys are equal, then print their values. For example, ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} ``` and after comparing the keys, print ``` 'fariborz', 'daei' 'jadi', jafar' ```
2018/09/22
[ "https://Stackoverflow.com/questions/52458754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9287224/" ]
You're asking for the intersection of the two dictionaries. Using the builtin type `set` ---------------------------- You can use the builtin type `set` for this, which implements the `intersection()` function. You can turn a list into a set like this: ``` set(my_list) ``` So, in order to find the intersection between the keys of two dictionaries, you can turn the keys into sets and find the intersection. To get a list with the keys of a dictionary: ``` dict_one.keys() ``` So, to find the intersection between the keys of two dicts: ``` set(dict_one.keys()).intersection(set(dict_two.keys())) ``` This will return, in your example, the set `{'12', '14'}`. The code above in a more readable way: ``` keys_one = set(dict_one.keys()) keys_two = set(dict_one.keys()) same_keys = keys_one.intersection(keys_two) # To get a list of the keys: result = list(same_keys) ``` Using anonymous function (lambda function) and list comprehension ----------------------------------------------------------------- Another easy way to solve this problem would be using lambda functions. I'm including this here just in case you'd like to know. Probably not the most efficient way to do! ``` same_keys = lambda first,second: [key1 for key1 in first.keys() if key1 in second.keys()] ``` So, as to get the result: `result = same_keys(dict_one,dict_two)` Any of the above two methods will give you the keys that are common to both dictionaries. Just loop over it and do as you please to print the values: ``` for key in result: print('{},{}'.format(dict_one[key], dict_two[key])) ```
Dictionaries are nice in python because they allow us to look up a key's value very easily and also check if a key exists in the dict. So in your example if you want to print the values for whenever the keys are the same between the dicts you can do something like this: ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} # Loop through all keys in dict_one for key in dict_one: # Then check if each key exists in dict_two if key in dict_two: val1 = dict_one[key] val2 = dict_two[key] print('{},{}'.format(val1, val2)) # print out values with comma between them ```
52,458,754
I want to compare two dictionary keys in python and if the keys are equal, then print their values. For example, ``` dict_one={'12':'fariborz','13':'peter','14':'jadi'} dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} ``` and after comparing the keys, print ``` 'fariborz', 'daei' 'jadi', jafar' ```
2018/09/22
[ "https://Stackoverflow.com/questions/52458754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9287224/" ]
You're asking for the intersection of the two dictionaries. Using the builtin type `set` ---------------------------- You can use the builtin type `set` for this, which implements the `intersection()` function. You can turn a list into a set like this: ``` set(my_list) ``` So, in order to find the intersection between the keys of two dictionaries, you can turn the keys into sets and find the intersection. To get a list with the keys of a dictionary: ``` dict_one.keys() ``` So, to find the intersection between the keys of two dicts: ``` set(dict_one.keys()).intersection(set(dict_two.keys())) ``` This will return, in your example, the set `{'12', '14'}`. The code above in a more readable way: ``` keys_one = set(dict_one.keys()) keys_two = set(dict_one.keys()) same_keys = keys_one.intersection(keys_two) # To get a list of the keys: result = list(same_keys) ``` Using anonymous function (lambda function) and list comprehension ----------------------------------------------------------------- Another easy way to solve this problem would be using lambda functions. I'm including this here just in case you'd like to know. Probably not the most efficient way to do! ``` same_keys = lambda first,second: [key1 for key1 in first.keys() if key1 in second.keys()] ``` So, as to get the result: `result = same_keys(dict_one,dict_two)` Any of the above two methods will give you the keys that are common to both dictionaries. Just loop over it and do as you please to print the values: ``` for key in result: print('{},{}'.format(dict_one[key], dict_two[key])) ```
Take iteration through one dictionary and check for existence of key in the other: ``` dict_one = {'12':'fariborz','13':'peter','14':'jadi'} dict_two = {'15':'ronaldo','16':'messi','12':'daei','14':'jafar'} for k in dict_one: if k in dict_two: print(dict_one[k], dict_two[k]) # fariborz daei # jadi jafar ```
68,425,073
I have a list like this: ``` list1 = ['hello', 'halo', 'goodbye', 'bye bye', 'how are you?'] ``` I want for example to replace ‘hello’ and ‘halo’ with ‘welcome’, and ‘goodbye’ and ‘bye bye’ with ‘greetings’ so the list will be like this: ``` list1 or newlist = ['welcome', 'welcome', 'greetings', 'greetings', 'how are you?'] ``` how can I do that the shortest way? I tried [this](https://stackoverflow.com/questions/31035258/how-to-replace-multiple-words-with-one-word-in-python), but it didn’t work unless I convert my list to string first but I want it to be list, any way I converted to string and changed the words and then I tried to convert it back to list but wasn’t converted back properly.
2021/07/17
[ "https://Stackoverflow.com/questions/68425073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16431450/" ]
if the substitutions can easily be grouped then this works: ```py list1 = ['hello', 'halo', 'goodbye', 'bye bye', 'how are you?'] new_list = [] group1 = ('hello', 'halo') group2 = ('goodbye', 'bye bye') for word in list1: if word in group1: new_list.append('welcome') elif word in group2: new_list.append('greetings') else: new_list.append(word) print(new_list) # ['welcome', 'welcome', 'greetings', 'greetings', 'how are you?'] ```
I see this question is marked with the re tag, so I will answer using regular expressions. You can replace text using re.sub. ``` >>> import re >>> list1 = ",".join(['hello', 'halo', 'goodbye', 'bye bye', 'how are you?']) >>> list1 = re.sub(r"hello|halo", r"welcome", list1) >>> list1 = re.sub(r"goodbye|bye bye", r"greetings", list1) >>> print(list1.split(",")) ['welcome', 'welcome', 'greetings', 'greetings', 'how are you?'] >>> ``` Alternatively you can use a list comprehension ``` ["welcome" if i in ["hello","halo"] else "greetings" if i in ["goodbye","bye bye"] else i for i in list1] ```
68,425,073
I have a list like this: ``` list1 = ['hello', 'halo', 'goodbye', 'bye bye', 'how are you?'] ``` I want for example to replace ‘hello’ and ‘halo’ with ‘welcome’, and ‘goodbye’ and ‘bye bye’ with ‘greetings’ so the list will be like this: ``` list1 or newlist = ['welcome', 'welcome', 'greetings', 'greetings', 'how are you?'] ``` how can I do that the shortest way? I tried [this](https://stackoverflow.com/questions/31035258/how-to-replace-multiple-words-with-one-word-in-python), but it didn’t work unless I convert my list to string first but I want it to be list, any way I converted to string and changed the words and then I tried to convert it back to list but wasn’t converted back properly.
2021/07/17
[ "https://Stackoverflow.com/questions/68425073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16431450/" ]
if the substitutions can easily be grouped then this works: ```py list1 = ['hello', 'halo', 'goodbye', 'bye bye', 'how are you?'] new_list = [] group1 = ('hello', 'halo') group2 = ('goodbye', 'bye bye') for word in list1: if word in group1: new_list.append('welcome') elif word in group2: new_list.append('greetings') else: new_list.append(word) print(new_list) # ['welcome', 'welcome', 'greetings', 'greetings', 'how are you?'] ```
List comprehension would be the shortest way... ``` list1 = ['hello', 'halo', 'goodbye', 'bye bye', 'how are you?'] newlist = ['welcome' if i == 'hello' or i == 'halo' else 'greetings' if i == 'goodbye' or i == 'bye bye' else i for i in list1 ] print(newlist) ```
14,976,968
I am trying to run a c++ program from python. My problem is that everytime i run: ``` subprocess.Popen(['sampleprog.exe'], stdin = iterate, stdout = myFile) ``` it only reads the first line in the file. Every time I enclose it with a while loop it ends up crushing because of the infinite loop. Is there any other way to read all the lines inside the `testcases.txt`? My Sample Code below: ``` someFile = open("testcases.txt","r") saveFile = open("store.txt", "r+") try: with someFile as iterate: while iterate is not False: subprocess.Popen(['sampleprog.exe'],stdin = iterate,stdout = saveFile) except EOFError: someFile.close() saveFile.close() sys.exit() ```
2013/02/20
[ "https://Stackoverflow.com/questions/14976968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2090597/" ]
Your line of code ``` 10 open (23,file=outfile,status='old',access='append',err=10) ``` specifies that the `open` statement should transfer control to itself (label 10) in case an error is encountered, so any error could trigger an infinite loop. It also suppresses the output of error messages. If you want to just check for an error status, I would suggest using the `iostat` and/or `iomsg` (Fortran 2003) arguments: ``` open (23, file=outfile, status='old', access='append', iostat=ios, iomsg=str) ``` Here `ios` is an integer that will be zero if no errors occur and nonzero otherwise, and `str` is a character variable that will record the corresponding error message.
The `err=` argument in your `open` statement specifies a statement label to branch to should the `open` fail for some reason. Your code specifies a branch to the line labelled `10` which happens to be the line containing the `open` statement. This is probably not a good idea; a better idea would be to branch to a line which deals gracefully with an error from the `open` statement. The warning from gfortran is spot on. As to the apparent garbage in your output file, without sight of the code you use to write the garbage (or what you think are pearls perhaps) it's very difficult to diagnose and fix that problem.
47,959,991
I have gathered obligatory data from the scopus website. my outputs have been saved in a list named "document". when I use type method for each element of this list, the python returns me this class: ``` "<class'selenium.webdriver.firefox.webelement.FirefoxWebElement'>" ``` In continius in order to solve this issue, I have used text method such this: `document=driver.find_elements_by_tag_name('td')` ``` for i in document: print i.text ``` So, I could see the result in text format. But, when I call each element of the list independently, white space is printed in this code: ``` x=[] for i in document: x.append(i.text) ``` `print (x[2])` will return white space. What should I do?
2017/12/24
[ "https://Stackoverflow.com/questions/47959991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8461493/" ]
As you have used the following line of code : ``` document=driver.find_elements_by_tag_name('td') ``` and see the output on Console as : ``` "<class'selenium.webdriver.firefox.webelement.FirefoxWebElement'>" ``` This is the expected behavior as **`Selenium`** prints the reference of the **`Nodes`** matching your search criteria. As per your `Code Attempt` to print the text leaving out the `white spaces` you can use the following code block : ``` x=[] document = driver.find_elements_by_tag_name('td') for i in document : if (i.get_attribute("innerHTML") != "null") : x.append(i.get_attribute("innerHTML")) print(x[2]) ```
My code was correct. But, the selected elements for displaying were space. By select another element, the result was shown.