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
61,035,989
i am trying to run this simple flask app and I keep getting this error in the terminal when trying to run the flask app `FLASK_APP=app.py flask run` i keep getting this error : `sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) fe_sendauth: no password supplied` here is my app: ``` from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres@localhost:5432/testdb' db = SQLAlchemy(app) class Person(db.Model): __tablename__ = 'persons' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(), nullable=False) db.create_all() @app.route('/') def index(): return 'Hello World!' ``` just to clarify i have psycopg2, flask-SQLAlchemy and all dependencies installed **AND THERE IS NO PASSWORD FOR USER postgres by default** and i haven't changed that and i can log in to database as postgres using psql **without password** without any problems. Full error output: ``` FLASK_APP=app.py flask run * Serving Flask app "app.py" * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off /usr/lib/python3/dist-packages/flask_sqlalchemy/__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning. warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.') Traceback (most recent call last): File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 1122, in _do_get return self._pool.get(wait, self._timeout) File "/usr/lib/python3/dist-packages/sqlalchemy/util/queue.py", line 145, in get raise Empty sqlalchemy.util.queue.Empty During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 2147, in _wrap_pool_connect return fn() File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 387, in connect return _ConnectionFairy._checkout(self) File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 766, in _checkout fairy = _ConnectionRecord.checkout(pool) File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 516, in checkout rec = pool._do_get() File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 1138, in _do_get self._dec_overflow() File "/usr/lib/python3/dist-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File "/usr/lib/python3/dist-packages/sqlalchemy/util/compat.py", line 187, in reraise raise value File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 1135, in _do_get return self._create_connection() File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 333, in _create_connection return _ConnectionRecord(self) File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 461, in __init__ self.__connect(first_connect_check=True) File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 651, in __connect connection = pool._invoke_creator(self) File "/usr/lib/python3/dist-packages/sqlalchemy/engine/strategies.py", line 105, in connect return dialect.connect(*cargs, **cparams) File "/usr/lib/python3/dist-packages/sqlalchemy/engine/default.py", line 393, in connect return self.dbapi.connect(*cargs, **cparams) File "/home/aa/.local/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: fe_sendauth: no password supplied The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/aa/.local/bin/flask", line 11, in <module> sys.exit(main()) File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 967, in main cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None) File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 586, in main return super(FlaskGroup, self).main(*args, **kwargs) File "/home/aa/.local/lib/python3.6/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/home/aa/.local/lib/python3.6/site-packages/click/core.py", line 1259, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/aa/.local/lib/python3.6/site-packages/click/core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/aa/.local/lib/python3.6/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/home/aa/.local/lib/python3.6/site-packages/click/decorators.py", line 73, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "/home/aa/.local/lib/python3.6/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 848, in run_command app = DispatchingApp(info.load_app, use_eager_loading=eager_loading) File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 305, in __init__ self._load_unlocked() File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 330, in _load_unlocked self._app = rv = self.loader() File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 388, in load_app app = locate_app(self, import_name, name) File "/home/aa/.local/lib/python3.6/site-packages/flask/cli.py", line 240, in locate_app __import__(module_name) File "/home/aa/Desktop/Udacity - FullStackND 2020/FullStackND2020/Practice Projects/flask hello world app/app.py", line 18, in <module> db.create_all() File "/usr/lib/python3/dist-packages/flask_sqlalchemy/__init__.py", line 972, in create_all self._execute_for_all_tables(app, bind, 'create_all') File "/usr/lib/python3/dist-packages/flask_sqlalchemy/__init__.py", line 964, in _execute_for_all_tables op(bind=self.get_engine(app, bind), **extra) File "/usr/lib/python3/dist-packages/sqlalchemy/sql/schema.py", line 3934, in create_all tables=tables) File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1928, in _run_visitor with self._optional_conn_ctx_manager(connection) as conn: File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1921, in _optional_conn_ctx_manager with self.contextual_connect() as conn: File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 2112, in contextual_connect self._wrap_pool_connect(self.pool.connect, None), File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 2151, in _wrap_pool_connect e, dialect, self) File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1465, in _handle_dbapi_exception_noconnection exc_info File "/usr/lib/python3/dist-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "/usr/lib/python3/dist-packages/sqlalchemy/util/compat.py", line 186, in reraise raise value.with_traceback(tb) File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 2147, in _wrap_pool_connect return fn() File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 387, in connect return _ConnectionFairy._checkout(self) File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 766, in _checkout fairy = _ConnectionRecord.checkout(pool) File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 516, in checkout rec = pool._do_get() File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 1138, in _do_get self._dec_overflow() File "/usr/lib/python3/dist-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File "/usr/lib/python3/dist-packages/sqlalchemy/util/compat.py", line 187, in reraise raise value File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 1135, in _do_get return self._create_connection() File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 333, in _create_connection return _ConnectionRecord(self) File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 461, in __init__ self.__connect(first_connect_check=True) File "/usr/lib/python3/dist-packages/sqlalchemy/pool.py", line 651, in __connect connection = pool._invoke_creator(self) File "/usr/lib/python3/dist-packages/sqlalchemy/engine/strategies.py", line 105, in connect return dialect.connect(*cargs, **cparams) File "/usr/lib/python3/dist-packages/sqlalchemy/engine/default.py", line 393, in connect return self.dbapi.connect(*cargs, **cparams) File "/home/aa/.local/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) fe_sendauth: no password supplied ```
2020/04/04
[ "https://Stackoverflow.com/questions/61035989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10600856/" ]
Other than just setting a password, you can log in without a password by: 1. Enable trust authentication, eg `echo "local all all trust" | sudo tee -a /etc/postgresql/10/main/pg_hba.conf` 2. Create a role with login access with the same username as your local username, eg if `whoami` returns `myname`, then `sudo -u postgres psql -c "CREATE ROLE myname WITH LOGIN"` 3. Use sqlalchemy's postgresql unix domain connection instead of tcp ([ref](https://docs.sqlalchemy.org/en/13/dialects/postgresql.html?highlight=postgres%20password#unix-domain-connections)), eg `"postgres+psycopg2://myname@/mydb"` Note that this requires installing `pip3 install psycopg2-binary`
so apparently you need a password to connect to database from SQLAlchemy, I was able to work around this by simply creating a password or adding new user with password. let me know if there is a different work around/solution
61,469,948
I am a beginner in the field of Data Science and I am working with Data Preprocessing in python. However, I am working with the Fingers Dataset so I want to move the pictures so every pic fits in its own directory to be able to use **ImageDataGenerator** and **flowfromdirectory** to import the pictures and apply rescaling, flipping... etc the code below shows what I'm trying to do... ``` dataset_path = "/tmp/extracted_fingers/fingers" train_set = os.path.join(dataset_path, "train/") test_set = os.path.join(dataset_path, "test/") for i in range(6): os.mkdir("/tmp/extracted_fingers/fingers/train/" + str(i) + "L") os.mkdir("/tmp/extracted_fingers/fingers/test/" + str(i) + "L") for i in range(6): os.mkdir("/tmp/extracted_fingers/fingers/train/" + str(i) + "R") os.mkdir("/tmp/extracted_fingers/fingers/test/" + str(i) + "R") L_0_tr = glob.glob(train_set + "*0L.png") L_1_tr = glob.glob(train_set + "*1L.png") L_2_tr = glob.glob(train_set + "*2L.png") L_3_tr = glob.glob(train_set + "*3L.png") L_4_tr = glob.glob(train_set + "*4L.png") L_5_tr = glob.glob(train_set + "*5L.png") R_0_tr = glob.glob(train_set + "*0R.png") R_1_tr = glob.glob(train_set + "*1R.png") R_2_tr = glob.glob(train_set + "*2R.png") R_3_tr = glob.glob(train_set + "*3R.png") R_4_tr = glob.glob(train_set + "*4R.png") R_5_tr = glob.glob(train_set + "*5R.png") L_0_ts = glob.glob(test_set + "*0L.png") L_1_ts = glob.glob(test_set + "*1L.png") L_2_ts = glob.glob(test_set + "*2L.png") L_3_ts = glob.glob(test_set + "*3L.png") L_4_ts = glob.glob(test_set + "*4L.png") L_5_ts = glob.glob(test_set + "*5L.png") R_0_ts = glob.glob(test_set + "*0R.png") R_1_ts = glob.glob(test_set + "*1R.png") R_2_ts = glob.glob(test_set + "*2R.png") R_3_ts = glob.glob(test_set + "*3R.png") R_4_ts = glob.glob(test_set + "*4R.png") R_5_ts = glob.glob(test_set + "*5R.png") shutil.move(L_0_tr, "0L") shutil.move(L_1_tr, "1L") shutil.move(L_2_tr, "2L") shutil.move(L_3_tr, "3L") shutil.move(L_4_tr, "4L") shutil.move(L_5_tr, "5L") shutil.move(R_0_tr, "0R") shutil.move(R_1_tr, "1R") shutil.move(R_2_tr, "2R") shutil.move(R_3_tr, "3R") shutil.move(R_4_tr, "4R") shutil.move(R_5_tr, "5R") shutil.move(L_0_ts, "0L") shutil.move(L_1_ts, "1L") shutil.move(L_2_ts, "2L") shutil.move(L_3_ts, "3L") shutil.move(L_4_ts, "4L") shutil.move(L_5_ts, "5L") shutil.move(R_0_ts, "0R") shutil.move(R_1_ts, "1R") shutil.move(R_2_ts, "2R") shutil.move(R_3_ts, "3R") shutil.move(R_4_ts, "4R") shutil.move(R_5_ts, "5R") ``` Now this way can do the job, but I am 100% sure there are better ways with much less typing to do it, so I, as a beginner, am trying to do it... I do not know whether it can be done by loops, Regex, and string formatting or any other way... However, if anyone could help me, I will be appreciated... A little help can be good. Thanks in advance. Much Love **Note:** if you want I can give more information
2020/04/27
[ "https://Stackoverflow.com/questions/61469948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11381138/" ]
Firstly instead of doing a for each and push promises you can map them and do a Promise all. You need no push. Your function can return directly your promise all call. The caller can await it or use then... Something like this (I didn't test it) ```js // serverlist declaration function getList(serverlist) { const operations = serverlist.map(Server => { if (Server.mon_sid.includes('_DB')) { return home.checkOracleDatabase(Server.mon_hostname, Server.mon_port); } else if (Server.mon_sid.includes('_HDB')) { return home.checkHANADatabase(Server.mon_hostname, Server.mon_port); } else { return home.checkPort(Server.mon_port, Server.mon_hostname, 1000); } }); return Promise.all(operations) } const serverlist = [...] const test = await getList(serverlist) // test is an array of fulfilled/unfulfilled results of Promise.all ``` So I would create a function that takes a list of operations(serverList) and returns the promise all like the example above without awaiting for it. The caller would await it or using another promise all of a series of other calls to your function. Potentially you can go deeper like Inception :) ```js // on the caller you can go even deeper await Promise.all([getList([...]) , getList([...]) , getList([...]) ]) ``` Considering what you added you can return something more customized like: ```js if (Server.mon_sid.includes('_DB')) { return home.checkOracleDatabase(Server.mon_hostname, Server.mon_port).then(result => ({result, name: 'Oracle', index:..., date:..., hostname: Server.mon_hostname, port: Server.mon_port})) ``` In the case above your promise would return a json with the output of your operation as result, plus few additional fields you might want to reuse to organize your data.
For more consistency and for resolving this question i/we(other people which can help you) need *all* code this all variables definition (because for now i can't find where is the `promises` variable is defined). Thanks
73,805,667
i am a beginner with python. I need to calculate a binairy number. I used a for loop for this because I need to print those same numbers with the len(). Can someone tell me what i am doing wrong? ``` for binairy in ["101011101"]: binairy = binairy ** 2 print(binairy) print(len(binairy)) ``` > > TypeError: unsupported operand type(s) for \*\* or pow(): 'str' and 'int' > > >
2022/09/21
[ "https://Stackoverflow.com/questions/73805667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14861522/" ]
you used a list but you could use a string directly ``` def binary_to_decimal(binary): decimal = 0 for digit in binary: decimal = decimal*2 + int(digit) return decimal print(binary_to_decimal("1010")) ```
["101011101"] is a list with a single string. "101011101" is a list of characters. Look at this: ```py for let_me_find_out in ["101011101"]: print(let_me_find_out) for let_me_find_out in "101011101": print(let_me_find_out) ``` With this knowledge, you can now start your binary conversion: ```py for binairy in "101011101": binairy = binairy ** 2 print(binairy) ``` That code gives you the error: > > TypeError: unsupported operand type(s) for \*\* or pow(): 'str' and 'int' > > > It means that you have the operator `**` and you put it between a string and a number. However, you can only put it between two numbers. So you need to convert the string into a number using `int()`: ```py for binairy in "101011101": binairy = int(binairy) ** 2 print(binairy) ``` You'll now find that it still gives you 1s and 0s only. That is because you calculated 1^2 instead of 2^1. Swap the order of the operands: ```py for binairy in "101011101": binairy = 2**int(binairy) print(binairy) ``` Now you get 2s and 1s, which is still incorrect. To deal with this, remember basic school where you learned about how numbers work. You don't use the number and take it to the power of something. Let me explain: The number 29 is not calculated by `10^2 + 1^9` (which is 101). It is calculated by `2*10^1 + 9*10^0`. So your formula needs to be rewritten from scratch. As you see, you have 3 components in a single part of the sum: 1. the digit value (2 or 9 in my example, but just 0 or 1 in a binary number) 2. the base (10 in my example, but 2 in your example) 3. the power (starting at 0 and counting upwards) This brings you to ```py power = 0 for binairy in "101011101": digit = int(binairy) base = 2 value = digit * base ** power print(value) power += 1 ``` With above code you get the individual values, but not the total value. So you need to introduce a sum: ```py power = 0 sum = 0 for binairy in "101011101": digit = int(binairy) base = 2 value = digit * base ** power sum += value print(value) power += 1 print(sum) ``` And you'll find that it gives you 373, which is not the correct answer (349 is correct). This is because you started the calculation from the beginning, but you should start at the end. A simple way to fix this is to reverse the text: ```py power = 0 sum = 0 for binairy in reversed("101011101"): digit = int(binairy) base = 2 value = digit * base ** power sum += value print(value) power += 1 print(sum) ``` Bam, you get it. That was easy! Just 1 hour of coding :-) Later in your career, feel free to write `print(int("101011101", 2))` instead. Your colleagues will love you for using built-in functionality instead of writing complicated code.
73,805,667
i am a beginner with python. I need to calculate a binairy number. I used a for loop for this because I need to print those same numbers with the len(). Can someone tell me what i am doing wrong? ``` for binairy in ["101011101"]: binairy = binairy ** 2 print(binairy) print(len(binairy)) ``` > > TypeError: unsupported operand type(s) for \*\* or pow(): 'str' and 'int' > > >
2022/09/21
[ "https://Stackoverflow.com/questions/73805667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14861522/" ]
you used a list but you could use a string directly ``` def binary_to_decimal(binary): decimal = 0 for digit in binary: decimal = decimal*2 + int(digit) return decimal print(binary_to_decimal("1010")) ```
I think I understand what you mean: You are willing to make the weight of every single number and than summing it all like "110" = "0x20+1x21+1x22" = 62dec So I will suggest to write the code like this: ``` weight, result = 0, 0 for binary in "101011101"[::-1]: result += int(binary)*2**weight print(result) ```
73,805,667
i am a beginner with python. I need to calculate a binairy number. I used a for loop for this because I need to print those same numbers with the len(). Can someone tell me what i am doing wrong? ``` for binairy in ["101011101"]: binairy = binairy ** 2 print(binairy) print(len(binairy)) ``` > > TypeError: unsupported operand type(s) for \*\* or pow(): 'str' and 'int' > > >
2022/09/21
[ "https://Stackoverflow.com/questions/73805667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14861522/" ]
["101011101"] is a list with a single string. "101011101" is a list of characters. Look at this: ```py for let_me_find_out in ["101011101"]: print(let_me_find_out) for let_me_find_out in "101011101": print(let_me_find_out) ``` With this knowledge, you can now start your binary conversion: ```py for binairy in "101011101": binairy = binairy ** 2 print(binairy) ``` That code gives you the error: > > TypeError: unsupported operand type(s) for \*\* or pow(): 'str' and 'int' > > > It means that you have the operator `**` and you put it between a string and a number. However, you can only put it between two numbers. So you need to convert the string into a number using `int()`: ```py for binairy in "101011101": binairy = int(binairy) ** 2 print(binairy) ``` You'll now find that it still gives you 1s and 0s only. That is because you calculated 1^2 instead of 2^1. Swap the order of the operands: ```py for binairy in "101011101": binairy = 2**int(binairy) print(binairy) ``` Now you get 2s and 1s, which is still incorrect. To deal with this, remember basic school where you learned about how numbers work. You don't use the number and take it to the power of something. Let me explain: The number 29 is not calculated by `10^2 + 1^9` (which is 101). It is calculated by `2*10^1 + 9*10^0`. So your formula needs to be rewritten from scratch. As you see, you have 3 components in a single part of the sum: 1. the digit value (2 or 9 in my example, but just 0 or 1 in a binary number) 2. the base (10 in my example, but 2 in your example) 3. the power (starting at 0 and counting upwards) This brings you to ```py power = 0 for binairy in "101011101": digit = int(binairy) base = 2 value = digit * base ** power print(value) power += 1 ``` With above code you get the individual values, but not the total value. So you need to introduce a sum: ```py power = 0 sum = 0 for binairy in "101011101": digit = int(binairy) base = 2 value = digit * base ** power sum += value print(value) power += 1 print(sum) ``` And you'll find that it gives you 373, which is not the correct answer (349 is correct). This is because you started the calculation from the beginning, but you should start at the end. A simple way to fix this is to reverse the text: ```py power = 0 sum = 0 for binairy in reversed("101011101"): digit = int(binairy) base = 2 value = digit * base ** power sum += value print(value) power += 1 print(sum) ``` Bam, you get it. That was easy! Just 1 hour of coding :-) Later in your career, feel free to write `print(int("101011101", 2))` instead. Your colleagues will love you for using built-in functionality instead of writing complicated code.
I think I understand what you mean: You are willing to make the weight of every single number and than summing it all like "110" = "0x20+1x21+1x22" = 62dec So I will suggest to write the code like this: ``` weight, result = 0, 0 for binary in "101011101"[::-1]: result += int(binary)*2**weight print(result) ```
51,793,379
In my file, I have a large number of images in **jpg** format and they are named **[fruit type].[index].jpg**. Instead of manually making three new sub folders to copy and paste the images into each sub folder, is there some python code that can parse through the name of the images and choose where to redirect the image to based on the `fruit type` in the name, at the same time create a new sub folder when a new `fruit type` is parsed? --- **Before** * TrainingSet (file) + apple.100.jpg + apple.101.jpg + apple.102.jpg + apple.103.jpg + peach.100.jpg + peach.101.jpg + peach.102.jpg + orange.100.jpg + orange.101.jpg --- **After** * TrainingSet (file) + apple(file) - apple.100.jpg - apple.101.jpg - apple.102.jpg - apple.103.jpg + peach(file) - peach.100.jpg - peach.101.jpg - peach.102.jpg + orange(file) - orange.100.jpg - orange.101.jpg
2018/08/10
[ "https://Stackoverflow.com/questions/51793379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8238011/" ]
Here’s the code to do just that, if you need help merging this into your codebase let me know: ``` import os, os.path, shutil folder_path = "test" images = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))] for image in images: folder_name = image.split('.')[0] new_path = os.path.join(folder_path, folder_name) if not os.path.exists(new_path): os.makedirs(new_path) old_image_path = os.path.join(folder_path, image) new_image_path = os.path.join(new_path, image) shutil.move(old_image_path, new_image_path) ```
If they are all formatted similarly to the three fruit example you gave, you can simply do a string.split(".")[0] on each filename you encounter: ``` import os for image in images: fruit = image.split(".")[0] if not os.path.isdir(fruit): os.mkdir(fruit) os.rename(os.path.join(fruit, image)) ```
51,793,379
In my file, I have a large number of images in **jpg** format and they are named **[fruit type].[index].jpg**. Instead of manually making three new sub folders to copy and paste the images into each sub folder, is there some python code that can parse through the name of the images and choose where to redirect the image to based on the `fruit type` in the name, at the same time create a new sub folder when a new `fruit type` is parsed? --- **Before** * TrainingSet (file) + apple.100.jpg + apple.101.jpg + apple.102.jpg + apple.103.jpg + peach.100.jpg + peach.101.jpg + peach.102.jpg + orange.100.jpg + orange.101.jpg --- **After** * TrainingSet (file) + apple(file) - apple.100.jpg - apple.101.jpg - apple.102.jpg - apple.103.jpg + peach(file) - peach.100.jpg - peach.101.jpg - peach.102.jpg + orange(file) - orange.100.jpg - orange.101.jpg
2018/08/10
[ "https://Stackoverflow.com/questions/51793379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8238011/" ]
Here’s the code to do just that, if you need help merging this into your codebase let me know: ``` import os, os.path, shutil folder_path = "test" images = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))] for image in images: folder_name = image.split('.')[0] new_path = os.path.join(folder_path, folder_name) if not os.path.exists(new_path): os.makedirs(new_path) old_image_path = os.path.join(folder_path, image) new_image_path = os.path.join(new_path, image) shutil.move(old_image_path, new_image_path) ```
As an idea, hope it helps ``` import os from pathlib import Path import shutil folder_path = "images/" nameList=[] for image in os.listdir(folder_paths): folder_name = image.split('.')[0] nameList.append(folder_name) for f in os.listdir(folder_paths): Path(folder_name).mkdir(parents=True, exist_ok=True,mode=0o755) des = folder_name +"/"+str(f) old_path = folder_paths+str(f) for path in nameList: if f.endswith('.jpg'): print(f) if path == folder_name: shutil.move(old_path, str(des)) ```
71,480,638
Atttempted to implement jit decorator to increase the speed of execution of my code. Not getting proper results. It is throughing all sorts of errors.. Key error, type errors, etc.. The actual code without numba is working without any issues. ``` # The Code without numba is: df = pd.DataFrame() df['Serial'] = [865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880] df['Value'] = [586,586.45,585.95,585.85,585.45,585.5,586,585.7,585.7,585.5,585.5,585.45,585.3,584,584,585] df['Ref'] = [586.35,586.1,586.01,586.44,586.04,585.91,585.47,585.99,585.35,585.27,585.32,584.86,585.36,584.18,583.53,585] df['Base'] = [0,-1,1,1,1,1,-1,0,1,1,1,0,1,1,0,-1] df['A'] = 0.0 df['B'] = 0.0 df['Counter'] = 0 df['Counter'][0] = df['Serial'][0] for i in range(0,len(df)-1): # Filling Column 'A' if (df.iloc[1+i,2] > df.iloc[1+i,1]) & (df.iloc[i,5] > df.iloc[1+i,1]) & (df.iloc[1+i,3] >0): df.iloc[1+i,4] = round((df.iloc[1+i,1]*1.02),2) elif (df.iloc[1+i,2] < df.iloc[1+i,1]) & (df.iloc[i,5] < df.iloc[1+i,1]) & (df.iloc[1+i,3] <0): df.iloc[1+i,4] = round((df.iloc[1+i,1]*0.98),2) else: df.iloc[1+i,4] = df.iloc[i,4] # Filling Column 'B' df.iloc[1+i,5] = round(((df.iloc[1+i,1] + df.iloc[1+i,2])/2),2) # Filling Column 'Counter' if (df.iloc[1+i,5] > df.iloc[1+i,1]): df.iloc[1+i,6] = df.iloc[1+i,0] else: df.iloc[1+i,6] = df.iloc[i,6] df ``` The below code is giving me the error. where i tried to implement numba jit decorator to speed up the original python code. ``` #The code with numba jit which is throwing error is: df = pd.DataFrame() df['Serial']=[865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880] df['Value']=[586,586.45,585.95,585.85,585.45,585.5,586,585.7,585.7,585.5,585.5,585.45,585.3,584,584,585] df['Ref']=[586.35,586.1,586.01,586.44,586.04,585.91,585.47,585.99,585.35,585.27,585.32,584.86,585.36,584.18,583.53,585] df['Base'] = [0,-1,1,1,1,1,-1,0,1,1,1,0,1,1,0,-1] from numba import jit @jit(nopython=True) def Calcs(Serial,Value,Ref,Base): n = Base.size A = np.empty(n, dtype='f8') B = np.empty(n, dtype='f8') Counter = np.empty(n, dtype='f8') A[0] = 0.0 B[0] = 0.0 Counter[0] = Serial[0] for i in range(0,n-1): # Filling Column 'A' if (Ref[i+1] > Value[i+1]) & (B[i] > Value[i+1]) & (Base[i+1] > 0): A[i+1] = round((Value[i+1]*1.02),2) elif (Ref[i+1] < Value[i+1]) & (B[i] < Value[i+1]) & (Base[i+1] < 0): A[i+1] = round((Value[i+1]*0.98),2) else: A[i+1] = A[i] # Filling Column 'B' B[i+1] = round(((Value[i+1] + Ref[i+1])/2),2) # Filling Column 'Counter' if (B[i+1] > Value[i+1]): Counter[i+1] = Serial[i+1] else: Counter[i+1] = Counter[i] List = [A,B,Counter] return List Serial = df['Serial'].values.astype(np.float64) Value = df['Value'].values.astype(np.float64) Ref = df['Ref'].values.astype(np.float64) Base = df['Base'].values.astype(np.float64) VCal = Calcs(Serial,Value,Ref,Base) df['A'].values[:] = VCal[0].astype(object) df['B'].values[:] = VCal[1].astype(object) df['Counter'].values[:] = VCal[2].astype(object) df ``` I tried to modify the code as per the guidance provided by @Jérôme Richard for the question [How to Eliminate for loop in Pandas Dataframe in filling each row values of a column based on multiple if,elif statements](https://stackoverflow.com/questions/71458405/how-to-eliminate-for-loop-in-pandas-dataframe-in-filling-each-row-values-of-a-co). But getting the errors and am Unable to correct the code. Looking for some help from the community in correcting & improving the above code or to find an even better code to enhance the speed of execution. The expected outcome of the code is shown in the below pic. [![enter image description here](https://i.stack.imgur.com/3lMZj.jpg)](https://i.stack.imgur.com/3lMZj.jpg)
2022/03/15
[ "https://Stackoverflow.com/questions/71480638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15922454/" ]
You can only use `df['A'].values[:]` if the column `A` exists in the dataframe. Otherwise you need to create a new one, possibly with `df['A'] = ...`. Moreover, the trick with `astype(object)` applies for string but not for numbers. Indeed, string-based dataframe columns do apparently not use Numpy string-based array but Numpy object-based arrays containing CPython strings. For numbers, Pandas properly uses number-based arrays. Converting numbers back to object is inefficient. The same applies for `astype(np.float64)`: it is not needed if the time is already fine. This is the case here. If you are unsure about the input type, you can let them though as they are not very expensive. The Numba function itself is fine (at least with a recent version of Numba). Note that you can specify the signature to [compile the function eagerly](https://numba.readthedocs.io/en/stable/user/jit.html). This feature also help you to catch typing errors sooner and make them a bit more clear. The downside is that it makes the function less generic as only specific types are supported (though you can specify multiple signatures). ```py from numba import njit @njit('List(float64[:])(float64[:], float64[:], float64[:], float64[:])') def Calcs(Serial,Value,Ref,Base): [...] Serial = df['Serial'].values Value = df['Value'].values Ref = df['Ref'].values Base = df['Base'].values VCal = Calcs(Serial, Value, Ref, Base) df['A'] = VCal[0] df['B'] = VCal[1] df['Counter'] = VCal[2] ``` Note that you can use the Numba decorator flag `fastmath=True` to speed up the computation if you are sure that the input array never contains spacial values like NaN or Inf or -0, and you do not rely on FP-math associativity.
This Code is giving list to list convertion typeerror. ``` from numba import njit df = pd.DataFrame() df['Serial'] = [865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880] df['Value'] = [586,586.45,585.95,585.85,585.45,585.5,586,585.7,585.7,585.5,585.5,585.45,585.3,584,584,585] df['Ref'] = [586.35,586.1,586.01,586.44,586.04,585.91,585.47,585.99,585.35,585.27,585.32,584.86,585.36,584.18,583.53,585] df['Base'] = [0,-1,1,1,1,1,-1,0,1,1,1,0,1,1,0,-1] @njit('List(float64[:])(float64[:], float64[:], float64[:], float64[:])',fastmath=True) def Calcs(Serial,Value,Ref,Base): n = Base.size A = np.empty(n) B = np.empty(n) Counter = np.empty(n) A[0] = 0.0 B[0] = 0.0 Counter[0] = Serial[0] for i in range(0,n-1): # Filling Column 'A' if (Ref[i+1] > Value[i+1]) & (B[i] > Value[i+1]) & (Base[i+1] > 0): A[i+1] = round((Value[i+1]*1.02),2) elif (Ref[i+1] < Value[i+1]) & (B[i] < Value[i+1]) & (Base[i+1] < 0): A[i+1] = round((Value[i+1]*0.98),2) else: A[i+1] = A[i] # Filling Column 'B' B[i+1] = round(((Value[i+1] + Ref[i+1])/2),2) # Filling Column 'Counter' if (B[i+1] > Value[i+1]): Counter[i+1] = Serial[i+1] else: Counter[i+1] = Counter[i] List = [A,B,Counter] return List Serial = df['Serial'].values Value = df['Value'].values Ref = df['Ref'].values Base = df['Base'].values VCal = Calcs(Serial, Value, Ref, Base) df['A'] = VCal[0] df['B'] = VCal[1] df['Counter'] = VCal[2] df ``` Getting the below error. ``` TypingError: Failed in nopython mode pipeline (step: nopython frontend) No conversion from list(array(float64, 1d, C))<iv=None> to list(array(float64, 1d, A))<iv=None> for '$408return_value.5', defined at None File "<ipython-input-9-3c9e0fe02b75>", line 33: def Calcs(Serial,Value,Ref,Base): <source elided> List = [A,B,Counter] return List ^ During: typing of assignment at <ipython-input-9-3c9e0fe02b75> (33) File "<ipython-input-9-3c9e0fe02b75>", line 33: def Calcs(Serial,Value,Ref,Base): <source elided> List = [A,B,Counter] return List ^ ```
48,757,747
Let's consider a file called `test1.py` and containing the following code: ``` def init_foo(): global foo foo=10 ``` Let's consider another file called `test2.py` and containing the following: ``` import test1 test1.init_foo() print(foo) ``` Provided that `test1` is on the pythonpath (and gets imported correctly) I will now receive the following error message: `NameError: name 'foo' is not defined` Anyone can explain to me why the variable `foo` is not declared as a `global` in the scope of `test2.py` while it is run? Also if you can provide a workaround for that problem? Thx!
2018/02/13
[ "https://Stackoverflow.com/questions/48757747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4961888/" ]
For this you need to use [`selModel`](https://docs.sencha.com/extjs/5.1.4/api/Ext.grid.Panel.html#cfg-selModel) config for [`grid`](https://docs.sencha.com/extjs/5.1.4/api/Ext.grid.Panel.html) using [`CheckboxModel`](https://docs.sencha.com/extjs/5.1.4/api/Ext.selection.CheckboxModel.html). * A **selModel** Ext.selection.Model instance or config object, or the selection model class's alias string.In latter case its type property determines to which type of selection model this config is applied. * A **CheckboxModel** selection model that renders a column of checkboxes that can be toggled to select or deselect rows. The default mode for this selection model is MULTI. In this **[FIDDLE](https://fiddle.sencha.com/#view/editor&fiddle/2d1r)**, I have create a demo using two grid. In first grid you can select record by `ctrl/shift` key and In second grid you can select directly on row click. I hope this will help/guide you to achieve you requirement. **CODE SNIPPET** ``` Ext.application({ name: 'Fiddle', launch: function () { //define user store Ext.define('User', { extend: 'Ext.data.Store', alias: 'store.users', fields: ['name', 'email', 'phone'], data: [{ name: 'Lisa', email: 'lisa@simpsons.com', phone: '555-111-1224' }, { name: 'Bart', email: 'bart@simpsons.com', phone: '555-222-1234' }, { name: 'Homer', email: 'homer@simpsons.com', phone: '555-222-1244' }, { name: 'Marge', email: 'marge@simpsons.com', phone: '555-222-1254' }, { name: 'AMargeia', email: 'marge@simpsons.com', phone: '555-222-1254' }] }); //Define custom grid Ext.define('MyGrid', { extend: 'Ext.grid.Panel', alias: 'widget.mygrid', store: { type: 'users' }, columns: [{ text: 'Name', flex: 1, dataIndex: 'name' }, { text: 'Email', dataIndex: 'email', flex: 1 }, { text: 'Phone', flex: 1, dataIndex: 'phone' }] }); //create panel with 2 grid Ext.create({ xtype: 'panel', renderTo: Ext.getBody(), items: [{ //select multiple records by using ctrl key and by selecting the checkbox with mouse in extjs grid xtype: 'mygrid', title: 'multi selection example by using ctrl/shif key', /* * selModel * A Ext.selection.Model instance or config object, * or the selection model class's alias string. */ selModel: { /* selType * A selection model that renders a column of checkboxes * that can be toggled to select or deselect rows. * The default mode for this selection model is MULTI. */ selType: 'checkboxmodel' } }, { //select multi record by row click xtype: 'mygrid', margin: '20 0 0 0', title: 'multi selection example on rowclick', /* * selModel * A Ext.selection.Model instance or config object, * or the selection model class's alias string. */ selModel: { /* selType * A selection model that renders a column of checkboxes * that can be toggled to select or deselect rows. * The default mode for this selection model is MULTI. */ selType: 'checkboxmodel', /* mode * "SIMPLE" - Allows simple selection of multiple items one-by-one. * Each click in grid will either select or deselect an item. */ mode: 'SIMPLE' } }] }); } }); ```
I achieved by adding keyup,keydown listeners. Please find the fiddle where i updated the code. <https://fiddle.sencha.com/#view/editor&fiddle/2d98>
56,314,194
I want to get random item from a list, also I don't want some items to be consider while `random.choice()`. Below is my data structure ``` x=[ { 'id': 1, 'version':0.1, 'ready': True } { 'id': 6, 'version':0.2, 'ready': True } { 'id': 4, 'version':0.1, 'ready': False } { 'id': 35, 'version':0.1, 'ready': False } { 'id': 45, 'version':0.1, 'ready': False } { 'id': 63, 'version':0.1, 'ready': True } { 'id': 34, 'version':0.1, 'ready': True } { 'id': 33, 'version':0.1, 'ready': True } ] ``` I can get the random item by using `random.choice(x)`. But is there any way, consider `'ready': True` attribute of item while `random.choice()`. Or any SIMPLE trick to achieve this? NOTE: I want to use python in-built modules to avoid dependencies like `numpy`, etc.
2019/05/26
[ "https://Stackoverflow.com/questions/56314194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2200798/" ]
Have a look at Dotplant2 which uses Yii2 and currency conversion tables in the backend. Specifically these files. 1. components/payment/[PaypalPayment.php](https://github.com/DevGroup-ru/dotplant2/blob/master/application/components/payment/PayPalPayment.php) and 2. their [CurrencyHelper.php](https://github.com/DevGroup-ru/dotplant2/blob/master/application/modules/shop/helpers/CurrencyHelper.php) at modules/shop/helpers. Here are some code snippets. PaypalPayment ``` public function content() { /** @var Order $order */ $order = $this->order; $order->calculate(); $payer = (new Payer())->setPaymentMethod('paypal'); $priceSubTotal = 0; /** @var ItemList $itemList */ $itemList = array_reduce($order->items, function($result, $item) use (&$priceSubTotal) { /** @var OrderItem $item */ /** @var Product $product */ $product = $item->product; $price = CurrencyHelper::convertFromMainCurrency($item->price_per_pcs, $this->currency); $priceSubTotal = $priceSubTotal + ($price * $item->quantity); /** @var ItemList $result */ return $result->addItem( (new Item()) ->setName($product->name) ->setCurrency($this->currency->iso_code) ->setPrice($price) ->setQuantity($item->quantity) ->setUrl(Url::toRoute([ '@product', 'model' => $product, 'category_group_id' => $product->category->category_group_id ], true)) ); }, new ItemList()); $priceTotal = CurrencyHelper::convertFromMainCurrency($order->total_price, $this->currency); $details = (new Details()) ->setShipping($priceTotal - $priceSubTotal) ->setSubtotal($priceSubTotal) ->setTax(0); $amount = (new Amount()) ->setCurrency($this->currency->iso_code) ->setTotal($priceTotal) ->setDetails($details); $transaction = (new Transaction()) ->setAmount($amount) ->setItemList($itemList) ->setDescription($this->transactionDescription) ->setInvoiceNumber($this->transaction->id); $urls = (new RedirectUrls()) ->setReturnUrl($this->createResultUrl(['id' => $this->order->payment_type_id])) ->setCancelUrl($this->createFailUrl()); $payment = (new Payment()) ->setIntent('sale') ->setPayer($payer) ->setTransactions([$transaction]) ->setRedirectUrls($urls); $link = null; try { $link = $payment->create($this->apiContext)->getApprovalLink(); } catch (\Exception $e) { $link = null; } return $this->render('paypal', [ 'order' => $order, 'transaction' => $this->transaction, 'approvalLink' => $link, ]); } ``` CurrencyHelper ``` <?php namespace app\modules\shop\helpers; use app\modules\shop\models\Currency; use app\modules\shop\models\UserPreferences; class CurrencyHelper { /** * @var Currency $userCurrency * @var Currency $mainCurrency */ static protected $userCurrency = null; static protected $mainCurrency = null; /** * @return Currency */ static public function getUserCurrency() { if (null === static::$userCurrency) { static::$userCurrency = static::findCurrencyByIso(UserPreferences::preferences()->userCurrency); } return static::$userCurrency; } /** * @param Currency $userCurrency * @return Currency */ static public function setUserCurrency(Currency $userCurrency) { return static::$userCurrency = $userCurrency; } /** * @return Currency */ static public function getMainCurrency() { return null === static::$mainCurrency ? static::$mainCurrency = Currency::getMainCurrency() : static::$mainCurrency; } /** * @param string $code * @param bool|true $useMainCurrency * @return Currency */ static public function findCurrencyByIso($code) { $currency = Currency::find()->where(['iso_code' => $code])->one(); $currency = null === $currency ? static::getMainCurrency() : $currency; return $currency; } /** * @param float|int $input * @param Currency $from * @param Currency $to * @return float|int */ static public function convertCurrencies($input = 0, Currency $from, Currency $to) { if (0 === $input) { return $input; } if ($from->id !== $to->id) { $main = static::getMainCurrency(); if ($main->id === $from->id && $main->id !== $to->id) { $input = $input / $to->convert_rate * $to->convert_nominal; } elseif ($main->id !== $from->id && $main->id === $to->id) { $input = $input / $from->convert_nominal * $from->convert_rate; } else { $input = $input / $from->convert_nominal * $from->convert_rate; $input = $input / $to->convert_rate * $to->convert_nominal; } } return $to->formatWithoutFormatString($input); } /** * @param float|int $input * @param Currency $from * @return float|int */ static public function convertToUserCurrency($input = 0, Currency $from) { return static::convertCurrencies($input, $from, static::getUserCurrency()); } /** * @param float|int $input * @param Currency $from * @return float|int */ static public function convertToMainCurrency($input = 0, Currency $from) { return static::convertCurrencies($input, $from, static::getMainCurrency()); } /** * @param float|int $input * @param Currency $to * @return float|int */ static public function convertFromMainCurrency($input = 0, Currency $to) { return static::convertCurrencies($input, static::getMainCurrency(), $to); } /** * @param Currency $currency * @param string|null $locale * @return string */ static public function getCurrencySymbol(Currency $currency, $locale = null) { $locale = null === $locale ? \Yii::$app->language : $locale; $result = ''; try { $fake = $locale . '@currency=' . $currency->iso_code; $fmt = new \NumberFormatter($fake, \NumberFormatter::CURRENCY); $result = $fmt->getSymbol(\NumberFormatter::CURRENCY_SYMBOL); } catch (\Exception $e) { $result = preg_replace('%[\d\s,]%i', '', $currency->format(0)); } return $result; } } ```
I got this from PayPal support: > > Unfortunately domestic transaction is not possible to receive in USD and similarly international transaction should be in USD. There is no way to have single currency for both the transactions. Thanks and regards, > > >
4,214,031
I have a PHP website and I would like to execute a very long Python script in background (300 MB memory and 100 seconds). The process communication is done via database: when the Python script finishes its job, it updates a field in database and then the website renders some graphics, based on the results of the Python script. I can execute "manually" the Python script from bash (any current directory) and it works. I would like to integrate it in PHP and I tried the function shell\_exec: `shell_exec("python /full/path/to/my/script")` but it's not working (I don't see any output) Do you have any ideas or suggestions? It worths to mention that the python script is a wrapper over other polyglot tools (Java mixed with C++). Thanks!
2010/11/18
[ "https://Stackoverflow.com/questions/4214031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2203413/" ]
First off [set\_time\_limit(0);](http://php.net/set_time_limit) will make your script run for ever so timeout shouldn't be an issue. Second any \*exec call in PHP does NOT use the PATH by default (might depend on configuration), so your script will exit without giving any info on the problem, and it quite often ends up being that it can't find the program, in this case python. So change it to: ``` shell_exec("/full/path/to/python /full/path/to/my/script"); ``` If your python script is running on it's own without problems, then it's very likely this is the problem. As for the memory, I'm pretty sure PHP won't use the same memory python is using. So if it's using 300MB PHP should stay at default (say 1MB) and just wait for the end of shell\_exec.
I found that the issue when I tried this was the simple fact that I did not compile the source on the server I was running it on. By compiling on your local machine and then uploading to your server, it will be corrupted in some way. shell\_exec() should work by compiling the source you are trying to run on the same server your are running the script.
4,214,031
I have a PHP website and I would like to execute a very long Python script in background (300 MB memory and 100 seconds). The process communication is done via database: when the Python script finishes its job, it updates a field in database and then the website renders some graphics, based on the results of the Python script. I can execute "manually" the Python script from bash (any current directory) and it works. I would like to integrate it in PHP and I tried the function shell\_exec: `shell_exec("python /full/path/to/my/script")` but it's not working (I don't see any output) Do you have any ideas or suggestions? It worths to mention that the python script is a wrapper over other polyglot tools (Java mixed with C++). Thanks!
2010/11/18
[ "https://Stackoverflow.com/questions/4214031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2203413/" ]
shell\_exec returns a string, if you run it alone it won't produce any output, so you can write: ``` $output = shell_exec(...); print $output; ```
Thanks for your answers, but none of them worked :(. I decided to implement in a dirty way, using busy waiting, instead of triggering an event when a record is inserted. I wrote a backup process that runs forever and at each iteration checks if there is something new in database. When it finds a record, it executes the script and everything is fine. The idea is that I launch the backup process from the shell.
4,214,031
I have a PHP website and I would like to execute a very long Python script in background (300 MB memory and 100 seconds). The process communication is done via database: when the Python script finishes its job, it updates a field in database and then the website renders some graphics, based on the results of the Python script. I can execute "manually" the Python script from bash (any current directory) and it works. I would like to integrate it in PHP and I tried the function shell\_exec: `shell_exec("python /full/path/to/my/script")` but it's not working (I don't see any output) Do you have any ideas or suggestions? It worths to mention that the python script is a wrapper over other polyglot tools (Java mixed with C++). Thanks!
2010/11/18
[ "https://Stackoverflow.com/questions/4214031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2203413/" ]
shell\_exec returns a string, if you run it alone it won't produce any output, so you can write: ``` $output = shell_exec(...); print $output; ```
Found this before and helped me solve my background execution problem: ``` function background_exec($command) { if(substr(php_uname(), 0, 7) == 'Windows') { pclose(popen('start "background_exec" ' . $command, 'r')); } else { exec($command . ' > /dev/null &'); } } ``` Source: <http://www.warpturn.com/execute-a-background-process-on-windows-and-linux-with-php/>
4,214,031
I have a PHP website and I would like to execute a very long Python script in background (300 MB memory and 100 seconds). The process communication is done via database: when the Python script finishes its job, it updates a field in database and then the website renders some graphics, based on the results of the Python script. I can execute "manually" the Python script from bash (any current directory) and it works. I would like to integrate it in PHP and I tried the function shell\_exec: `shell_exec("python /full/path/to/my/script")` but it's not working (I don't see any output) Do you have any ideas or suggestions? It worths to mention that the python script is a wrapper over other polyglot tools (Java mixed with C++). Thanks!
2010/11/18
[ "https://Stackoverflow.com/questions/4214031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2203413/" ]
Thanks for your answers, but none of them worked :(. I decided to implement in a dirty way, using busy waiting, instead of triggering an event when a record is inserted. I wrote a backup process that runs forever and at each iteration checks if there is something new in database. When it finds a record, it executes the script and everything is fine. The idea is that I launch the backup process from the shell.
I found that the issue when I tried this was the simple fact that I did not compile the source on the server I was running it on. By compiling on your local machine and then uploading to your server, it will be corrupted in some way. shell\_exec() should work by compiling the source you are trying to run on the same server your are running the script.
4,214,031
I have a PHP website and I would like to execute a very long Python script in background (300 MB memory and 100 seconds). The process communication is done via database: when the Python script finishes its job, it updates a field in database and then the website renders some graphics, based on the results of the Python script. I can execute "manually" the Python script from bash (any current directory) and it works. I would like to integrate it in PHP and I tried the function shell\_exec: `shell_exec("python /full/path/to/my/script")` but it's not working (I don't see any output) Do you have any ideas or suggestions? It worths to mention that the python script is a wrapper over other polyglot tools (Java mixed with C++). Thanks!
2010/11/18
[ "https://Stackoverflow.com/questions/4214031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2203413/" ]
shell\_exec returns a string, if you run it alone it won't produce any output, so you can write: ``` $output = shell_exec(...); print $output; ```
A proplem could be that your script takes longer than the server waiting time definied for a request (can be set in the php.ini or httpd.conf). Another issue could be that the servers account does not have the right to execute or access code or files needed for your script to run.
4,214,031
I have a PHP website and I would like to execute a very long Python script in background (300 MB memory and 100 seconds). The process communication is done via database: when the Python script finishes its job, it updates a field in database and then the website renders some graphics, based on the results of the Python script. I can execute "manually" the Python script from bash (any current directory) and it works. I would like to integrate it in PHP and I tried the function shell\_exec: `shell_exec("python /full/path/to/my/script")` but it's not working (I don't see any output) Do you have any ideas or suggestions? It worths to mention that the python script is a wrapper over other polyglot tools (Java mixed with C++). Thanks!
2010/11/18
[ "https://Stackoverflow.com/questions/4214031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2203413/" ]
Thanks for your answers, but none of them worked :(. I decided to implement in a dirty way, using busy waiting, instead of triggering an event when a record is inserted. I wrote a backup process that runs forever and at each iteration checks if there is something new in database. When it finds a record, it executes the script and everything is fine. The idea is that I launch the backup process from the shell.
A proplem could be that your script takes longer than the server waiting time definied for a request (can be set in the php.ini or httpd.conf). Another issue could be that the servers account does not have the right to execute or access code or files needed for your script to run.
4,214,031
I have a PHP website and I would like to execute a very long Python script in background (300 MB memory and 100 seconds). The process communication is done via database: when the Python script finishes its job, it updates a field in database and then the website renders some graphics, based on the results of the Python script. I can execute "manually" the Python script from bash (any current directory) and it works. I would like to integrate it in PHP and I tried the function shell\_exec: `shell_exec("python /full/path/to/my/script")` but it's not working (I don't see any output) Do you have any ideas or suggestions? It worths to mention that the python script is a wrapper over other polyglot tools (Java mixed with C++). Thanks!
2010/11/18
[ "https://Stackoverflow.com/questions/4214031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2203413/" ]
shell\_exec returns a string, if you run it alone it won't produce any output, so you can write: ``` $output = shell_exec(...); print $output; ```
I found that the issue when I tried this was the simple fact that I did not compile the source on the server I was running it on. By compiling on your local machine and then uploading to your server, it will be corrupted in some way. shell\_exec() should work by compiling the source you are trying to run on the same server your are running the script.
4,214,031
I have a PHP website and I would like to execute a very long Python script in background (300 MB memory and 100 seconds). The process communication is done via database: when the Python script finishes its job, it updates a field in database and then the website renders some graphics, based on the results of the Python script. I can execute "manually" the Python script from bash (any current directory) and it works. I would like to integrate it in PHP and I tried the function shell\_exec: `shell_exec("python /full/path/to/my/script")` but it's not working (I don't see any output) Do you have any ideas or suggestions? It worths to mention that the python script is a wrapper over other polyglot tools (Java mixed with C++). Thanks!
2010/11/18
[ "https://Stackoverflow.com/questions/4214031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2203413/" ]
Thanks for your answers, but none of them worked :(. I decided to implement in a dirty way, using busy waiting, instead of triggering an event when a record is inserted. I wrote a backup process that runs forever and at each iteration checks if there is something new in database. When it finds a record, it executes the script and everything is fine. The idea is that I launch the backup process from the shell.
Found this before and helped me solve my background execution problem: ``` function background_exec($command) { if(substr(php_uname(), 0, 7) == 'Windows') { pclose(popen('start "background_exec" ' . $command, 'r')); } else { exec($command . ' > /dev/null &'); } } ``` Source: <http://www.warpturn.com/execute-a-background-process-on-windows-and-linux-with-php/>
4,214,031
I have a PHP website and I would like to execute a very long Python script in background (300 MB memory and 100 seconds). The process communication is done via database: when the Python script finishes its job, it updates a field in database and then the website renders some graphics, based on the results of the Python script. I can execute "manually" the Python script from bash (any current directory) and it works. I would like to integrate it in PHP and I tried the function shell\_exec: `shell_exec("python /full/path/to/my/script")` but it's not working (I don't see any output) Do you have any ideas or suggestions? It worths to mention that the python script is a wrapper over other polyglot tools (Java mixed with C++). Thanks!
2010/11/18
[ "https://Stackoverflow.com/questions/4214031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2203413/" ]
First off [set\_time\_limit(0);](http://php.net/set_time_limit) will make your script run for ever so timeout shouldn't be an issue. Second any \*exec call in PHP does NOT use the PATH by default (might depend on configuration), so your script will exit without giving any info on the problem, and it quite often ends up being that it can't find the program, in this case python. So change it to: ``` shell_exec("/full/path/to/python /full/path/to/my/script"); ``` If your python script is running on it's own without problems, then it's very likely this is the problem. As for the memory, I'm pretty sure PHP won't use the same memory python is using. So if it's using 300MB PHP should stay at default (say 1MB) and just wait for the end of shell\_exec.
Thanks for your answers, but none of them worked :(. I decided to implement in a dirty way, using busy waiting, instead of triggering an event when a record is inserted. I wrote a backup process that runs forever and at each iteration checks if there is something new in database. When it finds a record, it executes the script and everything is fine. The idea is that I launch the backup process from the shell.
4,214,031
I have a PHP website and I would like to execute a very long Python script in background (300 MB memory and 100 seconds). The process communication is done via database: when the Python script finishes its job, it updates a field in database and then the website renders some graphics, based on the results of the Python script. I can execute "manually" the Python script from bash (any current directory) and it works. I would like to integrate it in PHP and I tried the function shell\_exec: `shell_exec("python /full/path/to/my/script")` but it's not working (I don't see any output) Do you have any ideas or suggestions? It worths to mention that the python script is a wrapper over other polyglot tools (Java mixed with C++). Thanks!
2010/11/18
[ "https://Stackoverflow.com/questions/4214031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2203413/" ]
First off [set\_time\_limit(0);](http://php.net/set_time_limit) will make your script run for ever so timeout shouldn't be an issue. Second any \*exec call in PHP does NOT use the PATH by default (might depend on configuration), so your script will exit without giving any info on the problem, and it quite often ends up being that it can't find the program, in this case python. So change it to: ``` shell_exec("/full/path/to/python /full/path/to/my/script"); ``` If your python script is running on it's own without problems, then it's very likely this is the problem. As for the memory, I'm pretty sure PHP won't use the same memory python is using. So if it's using 300MB PHP should stay at default (say 1MB) and just wait for the end of shell\_exec.
A proplem could be that your script takes longer than the server waiting time definied for a request (can be set in the php.ini or httpd.conf). Another issue could be that the servers account does not have the right to execute or access code or files needed for your script to run.
11,533,939
If I have more than one class in a python script, how do I call a function from the first class in the second class? Here is an Example: ``` Class class1(): def function1(): blah blah blah Class class2(): *How do I call function1 to here from class1* ```
2012/07/18
[ "https://Stackoverflow.com/questions/11533939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1481620/" ]
Functions in classes are also known as methods, and they are invoked on objects. The way to call a method in class1 from class2 is to have an instance of class1: ``` class Class2(object): def __init__(self): self.c1 = Class1() self.c1.function1() ```
The cleanest way is probably through inheritance: ``` class Base(object): def function1(self): # blah blah blah class Class1(Base): def a_method(self): self.function1() # works class Class2(Base): def some_method(self): self.function1() # works c1 = Class1() c1.function1() # works c2 = Class2() c2.function1() # works ```
27,296,373
I'm importing data with XLRD. The overall project involves pulling data from existing Excel files, but there are merged cells. Essentially, an operator is accounting for time on one of 3 shifts. As such, for each date on the grid they're working with, there are 3 columns (one for each shift). I want to change the UI as little as possible. As such, when I pull the list of the dates covered on the sheet, I want it to have the same date 3 times in a row, once for each shift. Here's what I get: ``` [41665.0, '', '', 41666.0, '', '', 41667.0, '', '', 41668.0, '', '', 41669.0, '', '', 41670.0, '', '', 41671.0, '', ''] ``` Here's what I want: ``` [41665.0, 41665.0, 41665.0, 41666.0, 41666.0, 41666.0, 41667.0, 41667.0, 41667.0, 41668.0, 41668.0, 41668.0, 41669.0, 41669.0, 41669.0, 41670.0, 41670.0, 41670.0, 41671.0, 41671.0, 41671.0] ``` I got this list with: ``` dates = temp_sheet.row_values(2)[2:] ``` I don't know if the dates will always show up as floats. I was thinking something along the lines of: ``` dates = [i for i in dates if not i.isspace() else j] ``` It throws an error when it gets to the first value, which is a float. .isnumeric() is a string operator...there has to be a much more elegant way. [I found this answer](https://stackoverflow.com/questions/3441358/python-most-pythonic-way-to-check-if-an-object-is-a-number) but it seems much more involved than what I believe I need.
2014/12/04
[ "https://Stackoverflow.com/questions/27296373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2711535/" ]
I dont think this is a good application for a comprehension, and an explicit loop would be better: ``` lst = [41665.0, '', '', 41666.0, '', '', 41667.0, '', '', 41668.0, '', '', 41669.0, '', '', 41670.0, '', >>> lst = [41665.0, '', '', 41666.0, '', '', 41667.0, '', '', 41668.0, '', '', 41669.0, '', '', 41670.0, '', '', 41671.0, '', ''] >>> temp = lst[0] >>> nlst = [] >>> for i in lst: ... if i: temp = i ... ... nlst.append(temp) ... >>> nlst [41665.0, 41665.0, 41665.0, 41666.0, 41666.0, 41666.0, 41667.0, 41667.0, 41667.0, 41668.0, 41668.0, 41668.0, 41669.0, 41669.0, 41669.0, 41670.0, 41670.0, 41670.0, 41671.0, 41671.0, 41671.0] ```
Another solution, ``` >>> l = [41665.0, '', '', 41666.0, '', '', 41667.0, '', '', 41668.0, '', '', 41669.0, '', '', 41670.0, '', '', 41671.0, '', ''] >>> lst = [ item for item in l if item is not ''] >>> [ v for item in zip(lst,lst,lst) for v in item ] [41665.0, 41665.0, 41665.0, 41666.0, 41666.0, 41666.0, 41667.0, 41667.0, 41667.0, 41668.0, 41668.0, 41668.0, 41669.0, 41669.0, 41669.0, 41670.0, 41670.0, 41670.0, 41671.0, 41671.0, 41671.0] ```
38,971,465
I want to use the stack method to get reverse string in this revers question. "Write a function revstring(mystr) that uses a stack to reverse the characters in a string." This is my code. ``` from pythonds.basic.stack import Stack def revstring(mystr): myStack = Stack() //this is how i have myStack for ch in mystr: //looping through characters in my string myStack.push(ch) //push the characters to form a stack revstr = '' //form an empty reverse string while not myStack.isEmpty(): revstr = revstr + myStack.pop() //adding my characters to the empty reverse string in reverse order return revstr print revstring("martin") ``` **the output seems to print out only the first letter of mystr that is "m"** why this??
2016/08/16
[ "https://Stackoverflow.com/questions/38971465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6712244/" ]
Here's 3 solutions to the same problem, just pick one: **1ST SOLUTION** Fixing your solution, you almost got it, you just need to indent properly your blocks like this: ``` from pythonds.basic.stack import Stack def revstring(mystr): myStack = Stack() # this is how i have myStack for ch in mystr: # looping through characters in my string myStack.push(ch) # push the characters to form a stack revstr = '' # form an empty reverse string while not myStack.isEmpty(): # adding my characters to the empty reverse string in reverse order revstr = revstr + myStack.pop() return revstr print revstring("martin") ``` **2ND SOLUTION** This one is structurally the same than yours but instead of using a custom stack, it's just using the builtin python list ``` def revstring(mystr): myStack = [] # this is how i have myStack for ch in mystr: myStack.append(ch) # push the characters to form a stack revstr = '' # form an empty reverse string while len(myStack): # adding my characters to the empty reverse string in reverse order revstr = revstr + myStack.pop() return revstr print revstring("martin") ``` **3RD SOLUTION** To reverse strings, just use this pythonic way :) ``` print "martin"[::-1] ```
* the `while` should not be in the `for` * the `return` should be outside, not in the `while` **code:** ``` from pythonds.basic.stack import Stack def revstring(mystr): myStack = Stack() # this is how i have myStack for ch in mystr: # looping through characters in my string myStack.push(ch) # push the characters to form a stack revstr = '' # form an empty reverse string while not myStack.isEmpty(): # adding my characters to the empty reverse string in reverse order revstr = revstr + myStack.pop() return revstr print revstring("martin") ```
69,897,646
I'm using seaborn.displot to display a distribution of scores for a group of participants. Is it possible to have the y axis show an actual percentage (example below)? This is required by the audience for the data. Currently it is done in excel but It would be more useful in python. ```py import seaborn as sns data = sns.load_dataset('titanic') p = sns.displot(data=data, x='age', hue='sex', height=4, kind='kde') ``` [![enter image description here](https://i.stack.imgur.com/IYZGt.png)](https://i.stack.imgur.com/IYZGt.png) Desired Format -------------- [![enter image description here](https://i.stack.imgur.com/gk3Cq.png)](https://i.stack.imgur.com/gk3Cq.png)
2021/11/09
[ "https://Stackoverflow.com/questions/69897646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2015461/" ]
As mentioned by @JohanC, the y axis for a KDE is a [density](https://en.wikipedia.org/wiki/Probability_density_function), not a proportion, so it does not make sense to convert it to a percentage. You'd have two options. One would be to plot a KDE curve over a histogram with histogram counts expressed as percentages: ``` sns.displot( data=tips, x="total_bill", hue="sex", kind="hist", stat="percent", kde=True, ) ``` [![enter image description here](https://i.stack.imgur.com/GnJHF.png)](https://i.stack.imgur.com/GnJHF.png) But your "desired plot" actually doesn't look like a density at all, it looks like a histogram plotted with a line instead of bars. You can get that with `element="poly"`: ``` sns.displot( data=tips, x="total_bill", hue="sex", kind="hist", stat="percent", element="poly", fill=False, ) ``` [![enter image description here](https://i.stack.imgur.com/Hw2tH.png)](https://i.stack.imgur.com/Hw2tH.png)
* [`seaborn.displot`](https://seaborn.pydata.org/generated/seaborn.displot.html) is a figure-level plot providing access to several approaches for visualizing the univariate or bivariate distribution of data ([histplot](https://seaborn.pydata.org/generated/seaborn.histplot.html), [kdeplot](https://seaborn.pydata.org/generated/seaborn.kdeplot.html), [ecdfplot](https://seaborn.pydata.org/generated/seaborn.ecdfplot.html)) * See [How to plot percentage with seaborn distplot / histplot / displot](https://stackoverflow.com/a/68850867/7758804) * [seaborn histplot and displot output doesn't match](https://stackoverflow.com/q/68865538/7758804) is relevant for the settings of the `common_bins` and `common_norm`. * **Tested in `python 3.8.12`, `pandas 1.3.4`, `matplotlib 3.4.3`, `seaborn 0.11.2`** + `data` is a pandas dataframe, and `seaborn` is an API for `matplotlib`. `kind='hist'`: [`seaborn.histplot`](https://seaborn.pydata.org/generated/seaborn.histplot.html) ----------------------------------------------------------------------------------------------- * Use `stat='percent'` → available from `seaborn 0.11.2` ```py import seaborn as sns from matplotlib.ticker import PercentFormatter data = sns.load_dataset('titanic') p = sns.displot(data=data, x='age', stat='percent', hue='sex', height=4, kde=True, kind='hist') ``` [![enter image description here](https://i.stack.imgur.com/Tui3d.png)](https://i.stack.imgur.com/Tui3d.png) Don't do the following, as explained ==================================== `kind='kde'`: [`seaborn.kdeplot`](https://seaborn.pydata.org/generated/seaborn.kdeplot.html) -------------------------------------------------------------------------------------------- * As per [mwaskom](https://stackoverflow.com/users/1533576/mwaskom), the creator of `seaborn`: you can wrap a percent formatter around a density value (as shown in the following code), **but it's incorrect because the density is not a proportion** (you may end up with values > 100%). * As per [JohanC](https://stackoverflow.com/users/12046409/johanc), you can't view the y-axis as a percentage, it is a [density](https://en.wikipedia.org/wiki/Probability_density_function). The density can go arbitrarily high or low, depending on the x-axis. **Formatting it as a percentage is a mistake.** * **I will leave this as part of the answer as an explanation, otherwise it will just be posted by someone else.** * Using [`matplotlib.ticker.PercentFormatter`](https://matplotlib.org/stable/api/ticker_api.html#matplotlib.ticker.PercentFormatter) to convert the axis values. ```py import seaborn as sns from matplotlib.ticker import PercentFormatter data = sns.load_dataset('titanic') p = sns.displot(data=data, x='age', hue='sex', height=3, kind='kde') p.axes.flat[0].yaxis.set_major_formatter(PercentFormatter(1)) ``` [![enter image description here](https://i.stack.imgur.com/NUjnt.png)](https://i.stack.imgur.com/NUjnt.png)
73,098,560
Try to use pytorch, when I do import torch ``` --------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-2-eb42ca6e4af3> in <module> ----> 1 import torch C:\Big_Data_app\Anaconda3\lib\site-packages\torch\__init__.py in <module> 124 err = ctypes.WinError(last_error) 125 err.strerror += f' Error loading "{dll}" or one of its dependencies.' --> 126 raise err 127 elif res is not None: 128 is_loaded = True OSError: [WinError 182] <no description> Error loading "C:\Big_Data_app\Anaconda3\lib\site-packages\torch\lib\shm.dll" or one of its dependencies. ``` Not sure what happend. The truth is, I installed pytorch around the end of last year.(I think) I don't remember how, I installed it because I want try to use it. But I guess I never used it after I installed. don't remember running some script with pytorch. And now I start to use it, get this error. Have no clue What I should check first. That means, I don't know what module, framework, driver, app are related with pytorch. So I don't know where to beginning, check is there any other module might cause this Error. If anyone knows how to solve this. Or where to start the problem checking. Please let me know. Thank you. My pytorch version is 1.11.0 OS: window 10
2022/07/24
[ "https://Stackoverflow.com/questions/73098560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14733291/" ]
I solved the problem. Just reinstall your Anaconda. **!!Warning!!: you will lose your lib.** Referring solution: [Problem with Torch 1.11](https://discuss.pytorch.org/t/problem-with-torch-1-11/146885)
The version may not be exactly as same as yours, but maybe [this question](https://stackoverflow.com/questions/63187161/error-while-import-pytorch-module-the-specified-module-could-not-be-found) asked on 2020-09-04 helps.
73,098,560
Try to use pytorch, when I do import torch ``` --------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-2-eb42ca6e4af3> in <module> ----> 1 import torch C:\Big_Data_app\Anaconda3\lib\site-packages\torch\__init__.py in <module> 124 err = ctypes.WinError(last_error) 125 err.strerror += f' Error loading "{dll}" or one of its dependencies.' --> 126 raise err 127 elif res is not None: 128 is_loaded = True OSError: [WinError 182] <no description> Error loading "C:\Big_Data_app\Anaconda3\lib\site-packages\torch\lib\shm.dll" or one of its dependencies. ``` Not sure what happend. The truth is, I installed pytorch around the end of last year.(I think) I don't remember how, I installed it because I want try to use it. But I guess I never used it after I installed. don't remember running some script with pytorch. And now I start to use it, get this error. Have no clue What I should check first. That means, I don't know what module, framework, driver, app are related with pytorch. So I don't know where to beginning, check is there any other module might cause this Error. If anyone knows how to solve this. Or where to start the problem checking. Please let me know. Thank you. My pytorch version is 1.11.0 OS: window 10
2022/07/24
[ "https://Stackoverflow.com/questions/73098560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14733291/" ]
I solved the problem. Just reinstall your Anaconda. **!!Warning!!: you will lose your lib.** Referring solution: [Problem with Torch 1.11](https://discuss.pytorch.org/t/problem-with-torch-1-11/146885)
My problem was solved by creating a new conda environment and installing PyTorch there. Everything worked perfectly on the first try in the new environment. Reinstalling Anaconda will work too, but this solution is less costly.
73,098,560
Try to use pytorch, when I do import torch ``` --------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-2-eb42ca6e4af3> in <module> ----> 1 import torch C:\Big_Data_app\Anaconda3\lib\site-packages\torch\__init__.py in <module> 124 err = ctypes.WinError(last_error) 125 err.strerror += f' Error loading "{dll}" or one of its dependencies.' --> 126 raise err 127 elif res is not None: 128 is_loaded = True OSError: [WinError 182] <no description> Error loading "C:\Big_Data_app\Anaconda3\lib\site-packages\torch\lib\shm.dll" or one of its dependencies. ``` Not sure what happend. The truth is, I installed pytorch around the end of last year.(I think) I don't remember how, I installed it because I want try to use it. But I guess I never used it after I installed. don't remember running some script with pytorch. And now I start to use it, get this error. Have no clue What I should check first. That means, I don't know what module, framework, driver, app are related with pytorch. So I don't know where to beginning, check is there any other module might cause this Error. If anyone knows how to solve this. Or where to start the problem checking. Please let me know. Thank you. My pytorch version is 1.11.0 OS: window 10
2022/07/24
[ "https://Stackoverflow.com/questions/73098560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14733291/" ]
I solved the problem. Just reinstall your Anaconda. **!!Warning!!: you will lose your lib.** Referring solution: [Problem with Torch 1.11](https://discuss.pytorch.org/t/problem-with-torch-1-11/146885)
In my case PyTorch broke after playing around with TensorFlow (installing different CPU and CUDA versions). I've just run Anaconda Prompt (with administrative privileges) and ordered Anaconda to update all possible packages by running following command: ``` conda update --all ``` After that the problem with PyTorch disappeared.
56,303,279
when i run this code: ``` #!/usr/bin/env python import scapy.all as scapy from scapy_http import http def sniff(interface): scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet) def process_sniffed_packet(packet): if packet.haslayer(http.HTTPRequest): print(packet) sniff("eth0") ``` i got : ``` Traceback (most recent call last): File "packet_sniffer.py", line 16, in <module> sniff("eth0") File "packet_sniffer.py", line 8, in sniff scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet) File "/usr/local/lib/python3.7/dist-packages/scapy/sendrecv.py", line 886, in sniff r = prn(p) File "packet_sniffer.py", line 13, in process_sniffed_packet print(packet) File "/usr/local/lib/python3.7/dist-packages/scapy/packet.py", line 438, in __str__ return str(self.build()) File "/usr/local/lib/python3.7/dist-packages/scapy/packet.py", line 556, in build p = self.do_build() File "/usr/local/lib/python3.7/dist-packages/scapy/packet.py", line 541, in do_build pay = self.do_build_payload() File "/usr/local/lib/python3.7/dist-packages/scapy/packet.py", line 528, in do_build_payload return self.payload.do_build() File "/usr/local/lib/python3.7/dist-packages/scapy/packet.py", line 541, in do_build pay = self.do_build_payload() File "/usr/local/lib/python3.7/dist-packages/scapy/packet.py", line 528, in do_build_payload return self.payload.do_build() File "/usr/local/lib/python3.7/dist-packages/scapy/packet.py", line 541, in do_build pay = self.do_build_payload() File "/usr/local/lib/python3.7/dist-packages/scapy/packet.py", line 528, in do_build_payload return self.payload.do_build() File "/usr/local/lib/python3.7/dist-packages/scapy/packet.py", line 541, in do_build pay = self.do_build_payload() File "/usr/local/lib/python3.7/dist-packages/scapy/packet.py", line 528, in do_build_payload return self.payload.do_build() File "/usr/local/lib/python3.7/dist-packages/scapy/packet.py", line 538, in do_build pkt = self.self_build() File "/usr/local/lib/python3.7/dist-packages/scapy_http/http.py", line 179, in self_build return _self_build(self, field_pos_list) File "/usr/local/lib/python3.7/dist-packages/scapy_http/http.py", line 101, in _self_build val = _get_field_value(obj, f.name) File "/usr/local/lib/python3.7/dist-packages/scapy_http/http.py", line 74, in _get_field_value headers = _parse_headers(val) File "/usr/local/lib/python3.7/dist-packages/scapy_http/http.py", line 18, in _parse_headers headers = s.split("\r\n") TypeError: a bytes-like object is required, not 'str' ``` what should i do?
2019/05/25
[ "https://Stackoverflow.com/questions/56303279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11533009/" ]
You can fix this problem by using `python2` instead of `python3`. If you don't want to change your python version then you'd need to make some changes to `scapy-http`'s library codes. From your traceback I can see that file is located at: `/usr/local/lib/python3.7/dist-packages/scapy_http/http.py`. Now open that file with any text editor. Change *line 18* from: ```py headers = s.split("\r\n") ``` to: ```py try: headers = s.split("\r\n") except TypeError as err: headers = s.split(b"\r\n") ``` Then change *line 109* from: ```py p = f.addfield(obj, p, val + separator) ``` to: ```py try: p = f.addfield(obj, p, val + separator) except TypeError as err: p = f.addfield(obj, p, str(val) + str(separator)) ```
You're using `scapy_http` in addition to `scapy`. `scapy_http` hasn't been update in a while, and has poor compatibility with Python 3+ Feel free to have a look at <https://github.com/secdev/scapy/pull/1925> : it's not merged in Scapy yet (should be sometimes soon I guess) but it's an updated & improved port of `scapy_http`, made for the latest `scapy` version
65,977,278
I have a image: It has some time in it. But I need to convert it to this using python: this: [![enter image description here](https://i.stack.imgur.com/j3iIp.png)](https://i.stack.imgur.com/j3iIp.png) to this [![enter image description here](https://i.stack.imgur.com/d61GK.png)](https://i.stack.imgur.com/d61GK.png) In short, I need to paint the text in that image black using python. I think maybe opencv is useful for this, But not sure. And I need to do that for any time that will be in that same type of image(like the image before editing, just different digits). I think we can use canny to detect edges of the digits and the dots and then paint the area between them black. I don't know the perfect way of doing this, but I think it might work. Hoping for a solution. Thanks in advance.
2021/01/31
[ "https://Stackoverflow.com/questions/65977278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13994535/" ]
Try this out. ```py sampleList = [ 'CustomerA', 'Yes', 'No', 'No', 'CustomerB', 'No', 'No', 'No', 'CustomerC', 'Yes', 'Yes', 'No' ] preferredOutput = [ tuple(sampleList[n : n + 4]) for n in range(0, len(sampleList), 4) ] print(preferredOutput) # OUTPUT (IN PRETTY FORM) # # [ # ('CustomerA', 'Yes', 'No', 'No'), # ('CustomerB', 'No', 'No', 'No'), # ('CustomerC', 'Yes', 'Yes', 'No') # ] ```
You can use list comprehension `output=[tuple(sampleList[4*i:4*i+4]) for i in range(3)]`
49,220,569
a=[('<https://www.google.co.in/search?q=kite+zerodha&oq=kite%2Cz&aqs=chrome.1.69i57j0l5.4766j0j7&sourceid=chrome&ie=UTF-8>', 1), ('<https://kite.zerodha.com/>', 1), ('<https://kite.trade/connect/login?api_key=xyz>', 1)] how to get value of api\_key which is xyz from above mentioned `a`. please help me to write code in python.Thank you
2018/03/11
[ "https://Stackoverflow.com/questions/49220569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9337404/" ]
Just looping over all elements and parsing url to get the api\_key, have a look into below code: ``` from urlparse import urlparse, parse_qs a=[('https://www.google.co.in/search?q=kite+zerodha&oq=kite%2Cz&aqs=chrome.1.69i57j0l5.4766j0j7&sourceid=chrome&ie=UTF-8', 1), ('https://kite.zerodha.com/', 1), ('https://kite.trade/connect/login?api_key=xyz', 1)] for value in a: if len(value) > 1: url = value[0] if 'api_key' in parse_qs(urlparse(url).query).keys(): print parse_qs(urlparse(url).query)['api_key'][0] ``` output: ``` xyz ```
This will work too. Hope this helps. > > * Find all items that has the keyword 'api\_key' (in url[0]), > * Split it into columns, delimited by '=' (split by '=') > * The last entry ([-1]) will be the answer (xyz). > > > ``` a=[('https://www.google.co.in/search?q=kite+zerodha&oq=kite%2Cz&aqs=chrome.1.69i57j0l5.4766j0j7&sourceid=chrome&ie=UTF-8', 1), ('https://kite.zerodha.com/', 1), ('https://kite.trade/connect/login?api_key=xyz', 1)] for ky in [url for url in a if 'api_key' in url[0]]: print(ky[0].split('=')[-1]) Sample result: xyz ```
55,905,144
Here is an image showing Python scope activity (version 3.6 and target x64): Python Scope [![](https://i.stack.imgur.com/QqZbP.png)](https://i.stack.imgur.com/QqZbP.png) The main problem is the relation between both invoke python methods, the first one is used to start the class object, and the second one to access a method of that class. Here is an image of the first invoke python properties: Invoke Python init method [![](https://i.stack.imgur.com/ekTvW.png)](https://i.stack.imgur.com/ekTvW.png) And the getNumberPlusOne activity call: Invoke Python getNumberPlusOne method [![](https://i.stack.imgur.com/2ZmUz.png)](https://i.stack.imgur.com/2ZmUz.png) The python code being executed: ```py class ExampleClass: def __init__(self,t,n): self.text = t self.number = n def getNumberPlusOne(self): return (self.number+1) ``` And finally, the error when executing the second Invoke Python Method: > > An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is: > System.InvalidOperationException: Error invoking Python method ----> System.Runtime.Serialization.InvalidDataContractException: Type 'UiPath.Python.PythonObject' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types. > > > Any idea about where is the mistake and how to interact with the output object created in the init method?
2019/04/29
[ "https://Stackoverflow.com/questions/55905144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11425716/" ]
I believe that this activity was designed with simple scripts in mind, not with entire classes. [Here's](https://forum.uipath.com/t/python-script-with-class-and-object/111110/3) an article on their Community Forum where user Sergiu.Wittenberger goes into more details. Let's start with the Load Python Script activity: [![invoke python script](https://i.stack.imgur.com/LnAeb.png)](https://i.stack.imgur.com/LnAeb.png) In my case the local variable "pyScript" is a pointer to the python object, i.e. an instance of `ExampleClass`. Now, there is the Invoke Python Method activity - this one allows us to call a method by name. It seems however that methods on the class are inaccessible to UiPath - you can't just type `pyScript.MethodName()`. [![invoke python method](https://i.stack.imgur.com/hkfu0.png)](https://i.stack.imgur.com/hkfu0.png) So it seems that we can't access class methods (please proof me wrong here!), but there's a workaround as shown by Sergio. In your case, you would add another method outside your class in order to access or manipulate your object: ```py class ExampleClass: def __init__(self,t,n): self.text = t self.number = n def getNumberPlusOne(self): return (self.number+1) foo = ExampleClass("bar", 42) def get_number_plus_one(): return foo.getNumberPlusOne() ``` Note that this also means that the object is instantiated within the very same file: `foo`. At this point this seems to be the only option to interact with an object -- again, I'd hope somebody can prove me wrong. For the sake of completeness, here's the result: [![enter image description here](https://i.stack.imgur.com/EvpVG.png)](https://i.stack.imgur.com/EvpVG.png)
I would like to add to what the above user said that you have to make sure that the imports you use are in the global site-packages, and not in a venv as Studio doesn't have access to that. Moreoever, always add this: ``` import os import sys sys.path.append(os.path.dirname(os.path.realpath(__file__))) ``` to the beginning of your code. Again, a limitation of the implementation. (docs here: <https://docs.uipath.com/activities/docs/load-script>) Doing this you might be able to do more complicated structures I think, but I haven't tested this out.
59,317,919
Training an image classifier using `.fit_generator()` or `.fit()` and passing a dictionary to `class_weight=` as an argument. I never got errors in TF1.x but in 2.1 I get the following output when starting training: ```none WARNING:tensorflow:sample_weight modes were coerced from ... to ['...'] ``` What does it mean to coerce something from `...` to `['...']`? The source for this warning on `tensorflow`'s repo is [here](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1090), comments placed are: > > Attempt to coerce sample\_weight\_modes to the target structure. This implicitly depends on the fact that Model flattens outputs for its internal representation. > > >
2019/12/13
[ "https://Stackoverflow.com/questions/59317919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1838257/" ]
This seems like a bogus message. I get the same warning message after upgrading to TensorFlow 2.1, but I do not use any class weights or sample weights at all. I do use a generator that returns a tuple like this: ``` return inputs, targets ``` And now I just changed it to the following to make the warning go away: ``` return inputs, targets, [None] ``` I don't know if this is relevant, but my model uses 3 inputs, so my `inputs` variable is actually a list of 3 numpy arrays. `targets` is just a single numpy array. In any case, it's just a warning. The training works fine either way. Edit for TensorFlow 2.2: ======================== This bug seems to have been fixed in TensorFlow 2.2, which is great. However the fix above will fail in TF 2.2, because it will try to get the shape of the sample weights, which will obviously fail with `AttributeError: 'NoneType' object has no attribute 'shape'`. So undo the above fix when upgrading to 2.2.
I have taken your Gist and installed Tensorflow 2.0, instead of TFA and it worked without any such Warning. Here is the [Gist](https://colab.sandbox.google.com/gist/rmothukuru/e9d65d1119d90c1ec0d435249f3f5d01/untitled2.ipynb) of the complete code. Code for installing the Tensorflow is shown below: ``` !pip install tensorflow==2.0 ``` Screenshot of the successful execution is shown below: [![enter image description here](https://i.stack.imgur.com/LCNRJ.png)](https://i.stack.imgur.com/LCNRJ.png) **Update:** This bug is fixed in **`Tensorflow Version 2.2.`**
59,317,919
Training an image classifier using `.fit_generator()` or `.fit()` and passing a dictionary to `class_weight=` as an argument. I never got errors in TF1.x but in 2.1 I get the following output when starting training: ```none WARNING:tensorflow:sample_weight modes were coerced from ... to ['...'] ``` What does it mean to coerce something from `...` to `['...']`? The source for this warning on `tensorflow`'s repo is [here](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1090), comments placed are: > > Attempt to coerce sample\_weight\_modes to the target structure. This implicitly depends on the fact that Model flattens outputs for its internal representation. > > >
2019/12/13
[ "https://Stackoverflow.com/questions/59317919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1838257/" ]
I believe this is a bug with tensorflow that will happen when you call `model.compile()` with default parameter `sample_weight_mode=None` and then call `model.fit()` with specified `sample_weight` or `class_weight`. From the tensorflow repos: * `fit()` eventually calls `_process_training_inputs()` * `_process_training_inputs()` [sets](https://github.com/tensorflow/tensorflow/blob/b7a6d319bb7435ad5ea073b09cd60deddc47c14b/tensorflow/python/keras/engine/training_v2.py#L545) `sample_weight_modes = [None]` based on `model.sample_weight_mode = None` and then creates a `DataAdapter` with `sample_weight_modes = [None]` * the `DataAdapter` calls `broadcast_sample_weight_modes()` with `sample_weight_modes = [None]` during [initialization](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L652) * `broadcast_sample_weight_modes()` [seems to expect](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1074) `sample_weight_modes = None` but receives `[None]` * it asserts that `[None]` is a different structure from `sample_weight` / `class_weight`, overwrites it back to `None` by fitting to the structure of `sample_weight` / `class_weight` and outputs a warning Warning aside this has no effect on `fit()` as `sample_weight_modes` in the `DataAdapter` is set back to `None`. Note that tensorflow [documentation](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) states that `sample_weight` must be a numpy-array. If you call `fit()` with `sample_weight.tolist()` instead, you will not get a warning but `sample_weight` is silently overwritten to `None` when `_process_numpy_inputs()` is called in [preprocessing](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1022) and receives an input of length greater than one.
I have taken your Gist and installed Tensorflow 2.0, instead of TFA and it worked without any such Warning. Here is the [Gist](https://colab.sandbox.google.com/gist/rmothukuru/e9d65d1119d90c1ec0d435249f3f5d01/untitled2.ipynb) of the complete code. Code for installing the Tensorflow is shown below: ``` !pip install tensorflow==2.0 ``` Screenshot of the successful execution is shown below: [![enter image description here](https://i.stack.imgur.com/LCNRJ.png)](https://i.stack.imgur.com/LCNRJ.png) **Update:** This bug is fixed in **`Tensorflow Version 2.2.`**
59,317,919
Training an image classifier using `.fit_generator()` or `.fit()` and passing a dictionary to `class_weight=` as an argument. I never got errors in TF1.x but in 2.1 I get the following output when starting training: ```none WARNING:tensorflow:sample_weight modes were coerced from ... to ['...'] ``` What does it mean to coerce something from `...` to `['...']`? The source for this warning on `tensorflow`'s repo is [here](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1090), comments placed are: > > Attempt to coerce sample\_weight\_modes to the target structure. This implicitly depends on the fact that Model flattens outputs for its internal representation. > > >
2019/12/13
[ "https://Stackoverflow.com/questions/59317919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1838257/" ]
I have taken your Gist and installed Tensorflow 2.0, instead of TFA and it worked without any such Warning. Here is the [Gist](https://colab.sandbox.google.com/gist/rmothukuru/e9d65d1119d90c1ec0d435249f3f5d01/untitled2.ipynb) of the complete code. Code for installing the Tensorflow is shown below: ``` !pip install tensorflow==2.0 ``` Screenshot of the successful execution is shown below: [![enter image description here](https://i.stack.imgur.com/LCNRJ.png)](https://i.stack.imgur.com/LCNRJ.png) **Update:** This bug is fixed in **`Tensorflow Version 2.2.`**
instead of providing a dictionary ``` weights = {'0': 42.0, '1': 1.0} ``` i tried a list ``` weights = [42.0, 1.0] ``` and the warning disappeared.
59,317,919
Training an image classifier using `.fit_generator()` or `.fit()` and passing a dictionary to `class_weight=` as an argument. I never got errors in TF1.x but in 2.1 I get the following output when starting training: ```none WARNING:tensorflow:sample_weight modes were coerced from ... to ['...'] ``` What does it mean to coerce something from `...` to `['...']`? The source for this warning on `tensorflow`'s repo is [here](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1090), comments placed are: > > Attempt to coerce sample\_weight\_modes to the target structure. This implicitly depends on the fact that Model flattens outputs for its internal representation. > > >
2019/12/13
[ "https://Stackoverflow.com/questions/59317919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1838257/" ]
This seems like a bogus message. I get the same warning message after upgrading to TensorFlow 2.1, but I do not use any class weights or sample weights at all. I do use a generator that returns a tuple like this: ``` return inputs, targets ``` And now I just changed it to the following to make the warning go away: ``` return inputs, targets, [None] ``` I don't know if this is relevant, but my model uses 3 inputs, so my `inputs` variable is actually a list of 3 numpy arrays. `targets` is just a single numpy array. In any case, it's just a warning. The training works fine either way. Edit for TensorFlow 2.2: ======================== This bug seems to have been fixed in TensorFlow 2.2, which is great. However the fix above will fail in TF 2.2, because it will try to get the shape of the sample weights, which will obviously fail with `AttributeError: 'NoneType' object has no attribute 'shape'`. So undo the above fix when upgrading to 2.2.
I believe this is a bug with tensorflow that will happen when you call `model.compile()` with default parameter `sample_weight_mode=None` and then call `model.fit()` with specified `sample_weight` or `class_weight`. From the tensorflow repos: * `fit()` eventually calls `_process_training_inputs()` * `_process_training_inputs()` [sets](https://github.com/tensorflow/tensorflow/blob/b7a6d319bb7435ad5ea073b09cd60deddc47c14b/tensorflow/python/keras/engine/training_v2.py#L545) `sample_weight_modes = [None]` based on `model.sample_weight_mode = None` and then creates a `DataAdapter` with `sample_weight_modes = [None]` * the `DataAdapter` calls `broadcast_sample_weight_modes()` with `sample_weight_modes = [None]` during [initialization](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L652) * `broadcast_sample_weight_modes()` [seems to expect](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1074) `sample_weight_modes = None` but receives `[None]` * it asserts that `[None]` is a different structure from `sample_weight` / `class_weight`, overwrites it back to `None` by fitting to the structure of `sample_weight` / `class_weight` and outputs a warning Warning aside this has no effect on `fit()` as `sample_weight_modes` in the `DataAdapter` is set back to `None`. Note that tensorflow [documentation](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) states that `sample_weight` must be a numpy-array. If you call `fit()` with `sample_weight.tolist()` instead, you will not get a warning but `sample_weight` is silently overwritten to `None` when `_process_numpy_inputs()` is called in [preprocessing](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1022) and receives an input of length greater than one.
59,317,919
Training an image classifier using `.fit_generator()` or `.fit()` and passing a dictionary to `class_weight=` as an argument. I never got errors in TF1.x but in 2.1 I get the following output when starting training: ```none WARNING:tensorflow:sample_weight modes were coerced from ... to ['...'] ``` What does it mean to coerce something from `...` to `['...']`? The source for this warning on `tensorflow`'s repo is [here](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1090), comments placed are: > > Attempt to coerce sample\_weight\_modes to the target structure. This implicitly depends on the fact that Model flattens outputs for its internal representation. > > >
2019/12/13
[ "https://Stackoverflow.com/questions/59317919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1838257/" ]
This seems like a bogus message. I get the same warning message after upgrading to TensorFlow 2.1, but I do not use any class weights or sample weights at all. I do use a generator that returns a tuple like this: ``` return inputs, targets ``` And now I just changed it to the following to make the warning go away: ``` return inputs, targets, [None] ``` I don't know if this is relevant, but my model uses 3 inputs, so my `inputs` variable is actually a list of 3 numpy arrays. `targets` is just a single numpy array. In any case, it's just a warning. The training works fine either way. Edit for TensorFlow 2.2: ======================== This bug seems to have been fixed in TensorFlow 2.2, which is great. However the fix above will fail in TF 2.2, because it will try to get the shape of the sample weights, which will obviously fail with `AttributeError: 'NoneType' object has no attribute 'shape'`. So undo the above fix when upgrading to 2.2.
instead of providing a dictionary ``` weights = {'0': 42.0, '1': 1.0} ``` i tried a list ``` weights = [42.0, 1.0] ``` and the warning disappeared.
59,317,919
Training an image classifier using `.fit_generator()` or `.fit()` and passing a dictionary to `class_weight=` as an argument. I never got errors in TF1.x but in 2.1 I get the following output when starting training: ```none WARNING:tensorflow:sample_weight modes were coerced from ... to ['...'] ``` What does it mean to coerce something from `...` to `['...']`? The source for this warning on `tensorflow`'s repo is [here](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1090), comments placed are: > > Attempt to coerce sample\_weight\_modes to the target structure. This implicitly depends on the fact that Model flattens outputs for its internal representation. > > >
2019/12/13
[ "https://Stackoverflow.com/questions/59317919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1838257/" ]
I believe this is a bug with tensorflow that will happen when you call `model.compile()` with default parameter `sample_weight_mode=None` and then call `model.fit()` with specified `sample_weight` or `class_weight`. From the tensorflow repos: * `fit()` eventually calls `_process_training_inputs()` * `_process_training_inputs()` [sets](https://github.com/tensorflow/tensorflow/blob/b7a6d319bb7435ad5ea073b09cd60deddc47c14b/tensorflow/python/keras/engine/training_v2.py#L545) `sample_weight_modes = [None]` based on `model.sample_weight_mode = None` and then creates a `DataAdapter` with `sample_weight_modes = [None]` * the `DataAdapter` calls `broadcast_sample_weight_modes()` with `sample_weight_modes = [None]` during [initialization](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L652) * `broadcast_sample_weight_modes()` [seems to expect](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1074) `sample_weight_modes = None` but receives `[None]` * it asserts that `[None]` is a different structure from `sample_weight` / `class_weight`, overwrites it back to `None` by fitting to the structure of `sample_weight` / `class_weight` and outputs a warning Warning aside this has no effect on `fit()` as `sample_weight_modes` in the `DataAdapter` is set back to `None`. Note that tensorflow [documentation](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) states that `sample_weight` must be a numpy-array. If you call `fit()` with `sample_weight.tolist()` instead, you will not get a warning but `sample_weight` is silently overwritten to `None` when `_process_numpy_inputs()` is called in [preprocessing](https://github.com/tensorflow/tensorflow/blob/d1574c209396d38ebe3c20b3ba1cb4c8d82170ae/tensorflow/python/keras/engine/data_adapter.py#L1022) and receives an input of length greater than one.
instead of providing a dictionary ``` weights = {'0': 42.0, '1': 1.0} ``` i tried a list ``` weights = [42.0, 1.0] ``` and the warning disappeared.
21,083,760
I have two files that are tab delimited.I need to compare file 1 column 3 to file 2 column 1 .If there is a match I need to write column 2 of file 2 next to the matching line in file 1.here is a sample of my file: file 1: ``` a rao rocky1 beta b rao buzzy2 beta c Rachel rocky2 alpha ``` file 2: ``` rocky1 highlightpath rimper2 darkenpath rocky2 greenpath ``` output: new file: ``` a rao rocky1 beta highlightpath b rao buzzy2 beta c Rachel rocky2 alpha greenpath ``` the problem is file 1 is huge ! file 2 is also big but not as much. So far I tried awk command , it worked partially. what I mean is number of lines in file 1 and output file which is newfile should be same, which is not what I got ! I get a difference of 20 lines. ``` awk 'FNR==NR{a[$3]=$0;next}{if($1 in a){p=$1;$1="";print a[p],$0}}' file1 file2 > newfile ``` So I thought I could try python to do it, but I am a novice at python. All I know so far is I would like to make a dictionary for file 1 and file 2 and compare. I know how to read a file into dictionary and then I am blank.Any help and suggestion with the code will help. Thanks
2014/01/13
[ "https://Stackoverflow.com/questions/21083760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2464553/" ]
``` import sys # Usage: python SCRIPT.py FILE1 FILE2 > OUTPUT file1, file2 = sys.argv[1:3] # Store info from the smaller file in a dict. d = {} with open(file2) as fh: for line in fh: k, v = line.split() d[k] = v # Process the bigger file line-by-line, printing to standard output. with open(file1) as fh: for line in fh: line = line.rstrip() k = line.split()[2] if k in d: print line, d[k] else: print line ```
``` with open('outfile.txt', 'w') as outfile: with open('file1.txt', 'r') as f1: with open('file2.txt', 'r') as f2: for f1line in f1: for f2line in f2: ## remove new line character at end of each line f1line = f1line.rstrip() f2line = f2line.rstrip() ## extract column fields f1col3 = f1line.split('\t')[2] f2col1 = f2line.split('\t')[0] ## test if fields are equal if (f1col3 == f2col1 ): outfile.write('%s\t%s\n' % (f1line, f2line.split('\t')[1])) else: outfile.write('%s\t\n' % (f1line)) break ``` * This script will compare lines1 of file1&2, then lines2 of file1&2, lines3 ... etc ... * It is good for large files; shouldn't load the memory :)
21,083,760
I have two files that are tab delimited.I need to compare file 1 column 3 to file 2 column 1 .If there is a match I need to write column 2 of file 2 next to the matching line in file 1.here is a sample of my file: file 1: ``` a rao rocky1 beta b rao buzzy2 beta c Rachel rocky2 alpha ``` file 2: ``` rocky1 highlightpath rimper2 darkenpath rocky2 greenpath ``` output: new file: ``` a rao rocky1 beta highlightpath b rao buzzy2 beta c Rachel rocky2 alpha greenpath ``` the problem is file 1 is huge ! file 2 is also big but not as much. So far I tried awk command , it worked partially. what I mean is number of lines in file 1 and output file which is newfile should be same, which is not what I got ! I get a difference of 20 lines. ``` awk 'FNR==NR{a[$3]=$0;next}{if($1 in a){p=$1;$1="";print a[p],$0}}' file1 file2 > newfile ``` So I thought I could try python to do it, but I am a novice at python. All I know so far is I would like to make a dictionary for file 1 and file 2 and compare. I know how to read a file into dictionary and then I am blank.Any help and suggestion with the code will help. Thanks
2014/01/13
[ "https://Stackoverflow.com/questions/21083760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2464553/" ]
``` import sys # Usage: python SCRIPT.py FILE1 FILE2 > OUTPUT file1, file2 = sys.argv[1:3] # Store info from the smaller file in a dict. d = {} with open(file2) as fh: for line in fh: k, v = line.split() d[k] = v # Process the bigger file line-by-line, printing to standard output. with open(file1) as fh: for line in fh: line = line.rstrip() k = line.split()[2] if k in d: print line, d[k] else: print line ```
`file2` is set up to be the associative array and it's the smaller of the two files, so I re-arranged the awk a bit to get: ``` awk 'NR==FNR { if( length($1) > 0) a[$1]=$2; next} { if( $3 in a ) {print $0,a[$3] } else { print $0 } }' file2 file1 > newfile ``` 1. For some reason, my machine wouldn't create `a[]` until I re-ordered the NR==FNR test, so that's a small difference. Also note, I've made the first file handed to awk `file2`. Non-empty lines from `file2` are added to `a[]`. 2. Process every line from `file1` secondly, and append the `file2` column 2 data to the line whenever `$3` in file1 is in `a[]`. Else just print the line as is. Running the above, I get the desired output on two different machines with different versions of awk ( from the generated `newfile` ): ``` a rao rocky1 beta highlightpath b rao buzzy2 beta c Rachel rocky2 alpha greenpath ```
21,083,760
I have two files that are tab delimited.I need to compare file 1 column 3 to file 2 column 1 .If there is a match I need to write column 2 of file 2 next to the matching line in file 1.here is a sample of my file: file 1: ``` a rao rocky1 beta b rao buzzy2 beta c Rachel rocky2 alpha ``` file 2: ``` rocky1 highlightpath rimper2 darkenpath rocky2 greenpath ``` output: new file: ``` a rao rocky1 beta highlightpath b rao buzzy2 beta c Rachel rocky2 alpha greenpath ``` the problem is file 1 is huge ! file 2 is also big but not as much. So far I tried awk command , it worked partially. what I mean is number of lines in file 1 and output file which is newfile should be same, which is not what I got ! I get a difference of 20 lines. ``` awk 'FNR==NR{a[$3]=$0;next}{if($1 in a){p=$1;$1="";print a[p],$0}}' file1 file2 > newfile ``` So I thought I could try python to do it, but I am a novice at python. All I know so far is I would like to make a dictionary for file 1 and file 2 and compare. I know how to read a file into dictionary and then I am blank.Any help and suggestion with the code will help. Thanks
2014/01/13
[ "https://Stackoverflow.com/questions/21083760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2464553/" ]
``` import sys # Usage: python SCRIPT.py FILE1 FILE2 > OUTPUT file1, file2 = sys.argv[1:3] # Store info from the smaller file in a dict. d = {} with open(file2) as fh: for line in fh: k, v = line.split() d[k] = v # Process the bigger file line-by-line, printing to standard output. with open(file1) as fh: for line in fh: line = line.rstrip() k = line.split()[2] if k in d: print line, d[k] else: print line ```
Here is a more short `awk` ``` awk 'NR==FNR {a[$1]=$2;next} {print $0,$3 in a?a[$3]:""}' file2 file1 a rao rocky1 beta highlightpath b rao buzzy2 beta c Rachel rocky2 alpha greenpath ```
21,083,760
I have two files that are tab delimited.I need to compare file 1 column 3 to file 2 column 1 .If there is a match I need to write column 2 of file 2 next to the matching line in file 1.here is a sample of my file: file 1: ``` a rao rocky1 beta b rao buzzy2 beta c Rachel rocky2 alpha ``` file 2: ``` rocky1 highlightpath rimper2 darkenpath rocky2 greenpath ``` output: new file: ``` a rao rocky1 beta highlightpath b rao buzzy2 beta c Rachel rocky2 alpha greenpath ``` the problem is file 1 is huge ! file 2 is also big but not as much. So far I tried awk command , it worked partially. what I mean is number of lines in file 1 and output file which is newfile should be same, which is not what I got ! I get a difference of 20 lines. ``` awk 'FNR==NR{a[$3]=$0;next}{if($1 in a){p=$1;$1="";print a[p],$0}}' file1 file2 > newfile ``` So I thought I could try python to do it, but I am a novice at python. All I know so far is I would like to make a dictionary for file 1 and file 2 and compare. I know how to read a file into dictionary and then I am blank.Any help and suggestion with the code will help. Thanks
2014/01/13
[ "https://Stackoverflow.com/questions/21083760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2464553/" ]
``` import sys # Usage: python SCRIPT.py FILE1 FILE2 > OUTPUT file1, file2 = sys.argv[1:3] # Store info from the smaller file in a dict. d = {} with open(file2) as fh: for line in fh: k, v = line.split() d[k] = v # Process the bigger file line-by-line, printing to standard output. with open(file1) as fh: for line in fh: line = line.rstrip() k = line.split()[2] if k in d: print line, d[k] else: print line ```
Addressing all the suggestions together: I am getting none of these to work ! Maybe because of empty lines in my file 2? Well the lines are not completely empty. for example: rocky1 highlightpath rimper2 darkenpath rocky2 greenpath lacy2 lucy1 pembrooke now when I ran the python codes given above I used a corrected file 2 where I took off the blanks lines (like lacy2) and then used the file. Eventhen I get list index out of range. Is the list that is being created with the lines from file is not right? looks like it. Please comment :)
56,504,180
I have set up a Raspberry Pi connected to an LED strip which is controllable from my phone via a Node server I have running on the RasPi. It triggers a simple python script that sets a colour. I'm looking to expand the functionality such that I have a python script continuously running and I can send colours to it that it will consume the new colour and display both the old and new colour side by side. I.e the python script can receive commands and manage state. I've looked into whether to use a simple loop or a deamon for this but I don't understand how to both run a script continuously and receive the new commands. Is it better to keep state in the Node server and keep sending a lot of simple commands to a basic python script or to write a more involved python script that can receive few simpler commands and continuously update the lights?
2019/06/08
[ "https://Stackoverflow.com/questions/56504180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1635908/" ]
Just delete keys that must be exclude for invalid user: ``` myReportsHeader = () => { const { valid_user } = this.props; const { tableHeaders } = this.props.tableHeaders const { labels: tableLabels } = tableHeaders if (!valid_user) { delete tableLabels['tb4'] } return tableLabels } ``` [Delete operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete)
You can first construct an object with default values. Then add additional property if the condition is true and finally return it e.g: ``` const obj = { tb1: tableLabels.tb1, tb2: tableLabels.tb2, tb3: tableLabels.tb3, tb5: tableLabels.tb5, tb6: tableLabels.tb6, tb7: tableLabels.tb7, tb8: tableLabels.tb8, tb9: tableLabels.tb9, tb10: tableLabels.tb10 }; if (valid_user) { obj.tb4 = tableLabels.tb4, // Add only if valid_user } return obj; ```
56,504,180
I have set up a Raspberry Pi connected to an LED strip which is controllable from my phone via a Node server I have running on the RasPi. It triggers a simple python script that sets a colour. I'm looking to expand the functionality such that I have a python script continuously running and I can send colours to it that it will consume the new colour and display both the old and new colour side by side. I.e the python script can receive commands and manage state. I've looked into whether to use a simple loop or a deamon for this but I don't understand how to both run a script continuously and receive the new commands. Is it better to keep state in the Node server and keep sending a lot of simple commands to a basic python script or to write a more involved python script that can receive few simpler commands and continuously update the lights?
2019/06/08
[ "https://Stackoverflow.com/questions/56504180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1635908/" ]
Just delete keys that must be exclude for invalid user: ``` myReportsHeader = () => { const { valid_user } = this.props; const { tableHeaders } = this.props.tableHeaders const { labels: tableLabels } = tableHeaders if (!valid_user) { delete tableLabels['tb4'] } return tableLabels } ``` [Delete operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete)
What [Maheer Ali commented](https://stackoverflow.com/questions/56504157/add-a-key-to-an-object-at-a-particular-position-in-javascript#comment99596414_56504157) should be an answer: Objects don't guarantee the order of their keys. For that use arrays. So, you will probably have ```js const columns = [tableLabels.tb1, tableLabels.tb3]; if (valid) { columns.splice(1, 0, tableLabels.tb2); } ```
56,504,180
I have set up a Raspberry Pi connected to an LED strip which is controllable from my phone via a Node server I have running on the RasPi. It triggers a simple python script that sets a colour. I'm looking to expand the functionality such that I have a python script continuously running and I can send colours to it that it will consume the new colour and display both the old and new colour side by side. I.e the python script can receive commands and manage state. I've looked into whether to use a simple loop or a deamon for this but I don't understand how to both run a script continuously and receive the new commands. Is it better to keep state in the Node server and keep sending a lot of simple commands to a basic python script or to write a more involved python script that can receive few simpler commands and continuously update the lights?
2019/06/08
[ "https://Stackoverflow.com/questions/56504180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1635908/" ]
Just delete keys that must be exclude for invalid user: ``` myReportsHeader = () => { const { valid_user } = this.props; const { tableHeaders } = this.props.tableHeaders const { labels: tableLabels } = tableHeaders if (!valid_user) { delete tableLabels['tb4'] } return tableLabels } ``` [Delete operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete)
You can use spread syntax to avoid duplicate code. ``` const obj = { ...tableLabels } if (!valid_user) { // Delete tb4 if user is invalid delete obj.tb4; } return obj; ```
56,504,180
I have set up a Raspberry Pi connected to an LED strip which is controllable from my phone via a Node server I have running on the RasPi. It triggers a simple python script that sets a colour. I'm looking to expand the functionality such that I have a python script continuously running and I can send colours to it that it will consume the new colour and display both the old and new colour side by side. I.e the python script can receive commands and manage state. I've looked into whether to use a simple loop or a deamon for this but I don't understand how to both run a script continuously and receive the new commands. Is it better to keep state in the Node server and keep sending a lot of simple commands to a basic python script or to write a more involved python script that can receive few simpler commands and continuously update the lights?
2019/06/08
[ "https://Stackoverflow.com/questions/56504180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1635908/" ]
Just delete keys that must be exclude for invalid user: ``` myReportsHeader = () => { const { valid_user } = this.props; const { tableHeaders } = this.props.tableHeaders const { labels: tableLabels } = tableHeaders if (!valid_user) { delete tableLabels['tb4'] } return tableLabels } ``` [Delete operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete)
I would do like this, a combination of [spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [destructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) ``` myReportsHeader = () => { const { valid_user } = this.props; const { tableHeaders } = this.props.tableHeaders; const { tb4, ...labels } = tableHeaders.labels; return valid_user ? {...labels, tb4 } : {...labels}; } ```
67,899,519
I have a json file with size in 500 MB with structure like ``` {"user": "abc@xyz.com","contact":[{"name":"Jack "John","number":"+1 23456789"},{"name":"Jack Jill","number":"+1 232324789"}]} ``` Issue is when i parse this string with pandas read\_json, I get error `Unexpected character found when decoding object value` Issue is happening because of double quotes `"` in before `John` in first elecment of contact array. Need help in escaping this quote either with sed/awk/python so that i can directly load the file in pandas. **I am fine with ignoring contact with name as Jack as well but i can not ignore the complete row.**
2021/06/09
[ "https://Stackoverflow.com/questions/67899519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9025131/" ]
In general here is no robust way to fix this, nor to ignore any part of the row nor even to ignore the whole row because if a quoted string can contain quotes and can also contain `:`s and `,`s then a messed up string can look exactly like a valid set of fields. Having said that, if we target only the "name" field and assume that the associated string cannot contain `,`s then with GNU awk for the 3rd arg to `match()` we can do: ``` $ cat tst.awk { while ( match($0,/(.*"name":")(([^,"]*"[^,"]*)+)(".*)/,a) ) { gsub(/"/,"",a[2]) $0 = a[1] a[2] a[4] } print } ``` ``` $ awk -f tst.awk file {"user": "abc@xyz.com","contact":[{"name":"Jack O'Malley","number":"+1 23456789"},{"name":"Jack Jill Smith-Jones","number":"+1 232324789"}]} {"user": "abc@xyz.com","contact":[{"name":"X Æ A-12 Musk","number":"+1 23456789"},{"name":"Jack Jill","number":"+1 232324789"}]} ``` I ran the above on this input file: ``` $ cat file {"user": "abc@xyz.com","contact":[{"name":"Jack "O'Malley","number":"+1 23456789"},{"name":"Jack "Jill "Smith-Jones","number":"+1 232324789"}]} {"user": "abc@xyz.com","contact":[{"name":"X Æ A-12 "Musk","number":"+1 23456789"},{"name":"Jack Jill","number":"+1 232324789"}]} ``` and you can do the same using any awk: ``` $ cat tst.awk { while ( match($0,/"name":"([^,"]*"[^,"]*)+"/) ) { tgt = substr($0,RSTART+8,RLENGTH-9) gsub(/"/,"",tgt) $0 = substr($0,1,RSTART+7) tgt substr($0,RSTART+RLENGTH-1) } print } ``` ``` $ awk -f tst.awk file {"user": "abc@xyz.com","contact":[{"name":"Jack O'Malley","number":"+1 23456789"},{"name":"Jack Jill Smith-Jones","number":"+1 232324789"}]} {"user": "abc@xyz.com","contact":[{"name":"X Æ A-12 Musk","number":"+1 23456789"},{"name":"Jack Jill","number":"+1 232324789"}]} ```
You can try removing that extra " using regex `("[\s\w]*)(")([\s\w]*")`. The regex try to match any string with spaces/alphabets followed by a quote and then followed again by spaces/alphabets and removing that additional quote. This will work for the given problem but for more complex patterns, you may have to tweak the regex. Complete code: ``` import re text_json = '{"user": "abc@xyz.com","contact":[{"name":"Jack "John","number":"+1 23456789"},{"name":"Jack Jill","number":"+1 232324789"}]}' text_json = re.sub(r'("[\s\w]*)(")([\s\w]*")', r"\1\3", text_json ) print(text_json) ``` Output: ``` '{"user": "abc@xyz.com","contact":[{"name":"Jack John","number":"+1 23456789"},{"name":"Jack Jill","number":"+1 232324789"}]}' ```
50,848,226
Currently I am trying to run Stardew Valley from python by doing this: ``` import subprocess subprocess.call(['cmd', 'D:\SteamR\steamapps\common\Stardew Valley\Stardew Valley.exe']) ``` However, this fails and only opens a CMD window. I have a basic understanding of how to launch programs from python, but I do not understand how to specifically open a program that is located not only in a different location, but also on a different drive. Any help would be appreciated. Thanks! Edit: This is on windows 10 Stardew Valley version is the beta and is located on the D:/ drive (windows is on C:/ of course)
2018/06/14
[ "https://Stackoverflow.com/questions/50848226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4848801/" ]
Can you try using the steam commandline using the appid of the game: ``` subprocess.call(r"C:\Program Files (x86)\Steam\Steam.exe -applaunch 413150") ``` you can find the app id in the "web document tab" from the desktop shortcut properties (which can be generated by right click and select create desktop shortcut in the steam library). It will be something like this *steam://rungameid/413150*
You don't have to use `cmd`, you can start the `.exe` directly. Additionally you should be aware that `\` is used to escape characters in Python strings, but should not be interpreted specially in Windows paths. Better use raw strings prefixed with `r` for Windows paths, which disable such escapes: ``` import subprocess subprocess.call([r'D:\SteamR\steamapps\common\Stardew Valley\Stardew Valley.exe']) ```
50,848,226
Currently I am trying to run Stardew Valley from python by doing this: ``` import subprocess subprocess.call(['cmd', 'D:\SteamR\steamapps\common\Stardew Valley\Stardew Valley.exe']) ``` However, this fails and only opens a CMD window. I have a basic understanding of how to launch programs from python, but I do not understand how to specifically open a program that is located not only in a different location, but also on a different drive. Any help would be appreciated. Thanks! Edit: This is on windows 10 Stardew Valley version is the beta and is located on the D:/ drive (windows is on C:/ of course)
2018/06/14
[ "https://Stackoverflow.com/questions/50848226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4848801/" ]
You don't have to use `cmd`, you can start the `.exe` directly. Additionally you should be aware that `\` is used to escape characters in Python strings, but should not be interpreted specially in Windows paths. Better use raw strings prefixed with `r` for Windows paths, which disable such escapes: ``` import subprocess subprocess.call([r'D:\SteamR\steamapps\common\Stardew Valley\Stardew Valley.exe']) ```
You can use the following way: ``` import os os.startfile("D:\SteamR\steamapps\common\Stardew Valley\Stardew Valley.exe") ``` What this piece of code does is, **it simply opens the file using its windows assigned default program**. A disadvantage of this way of starting is that it won't return any process object. So in order to manage the process you need to use win32 packages or other.
50,848,226
Currently I am trying to run Stardew Valley from python by doing this: ``` import subprocess subprocess.call(['cmd', 'D:\SteamR\steamapps\common\Stardew Valley\Stardew Valley.exe']) ``` However, this fails and only opens a CMD window. I have a basic understanding of how to launch programs from python, but I do not understand how to specifically open a program that is located not only in a different location, but also on a different drive. Any help would be appreciated. Thanks! Edit: This is on windows 10 Stardew Valley version is the beta and is located on the D:/ drive (windows is on C:/ of course)
2018/06/14
[ "https://Stackoverflow.com/questions/50848226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4848801/" ]
Can you try using the steam commandline using the appid of the game: ``` subprocess.call(r"C:\Program Files (x86)\Steam\Steam.exe -applaunch 413150") ``` you can find the app id in the "web document tab" from the desktop shortcut properties (which can be generated by right click and select create desktop shortcut in the steam library). It will be something like this *steam://rungameid/413150*
You can use the following way: ``` import os os.startfile("D:\SteamR\steamapps\common\Stardew Valley\Stardew Valley.exe") ``` What this piece of code does is, **it simply opens the file using its windows assigned default program**. A disadvantage of this way of starting is that it won't return any process object. So in order to manage the process you need to use win32 packages or other.
11,108,461
I'm having a strange problem while trying to install the Python library `zenlib`, using its `setup.py` file. When I run the `setup.py` file, I get an import error, saying > > ImportError: No module named Cython.Distutils` > > > but I do have such a module, and I can import it on the python command line without any trouble. Why might I be getting this import error? I think that the problem may have to do with the fact that I am using [Enthought Python Distribution](https://www.enthought.com/product/enthought-python-distribution/), which I installed right beforehand, rather than using the Python 2.7 that came with Ubuntu 12.04. More background: Here's exactly what I get when trying to run setup.py: ``` enwe101@enwe101-PCL:~/zenlib/src$ sudo python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from Cython.Distutils import build_ext ImportError: No module named Cython.Distutils ``` But it works from the command line: ``` >>> from Cython.Distutils import build_ext >>> >>> from fake.package import noexist Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named fake.package ``` Note the first import worked and the second throws an error. Compare this to the first few lines of setup.py: ``` #from distutils.core import setup from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import os.path ``` I made sure that the Enthought Python Distribution and not the python that came with Ubuntu is what is run by default by prepending my bash $PATH environment variable by editing `~/.bashrc`, adding this as the last line: ``` export PATH=/usr/local/epd/bin:$PATH ``` and indeed `which python` spits out `/usr/local/epd/bin/python`... not knowing what else to try, I went into my site packages directory, (`/usr/local/epd/lib/python2.7/site-packages`) and give full permissions (r,w,x) to `Cython`, `Distutils`, `build_ext.py`, and the `__init__.py` files. Probably silly to try, and it changed nothing. Can't think of what to try next!? Any ideas?
2012/06/19
[ "https://Stackoverflow.com/questions/11108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467306/" ]
Install Cython: ``` pip install cython ```
In the CLI-python, import sys and look what's inside sys.path Then try to use `export PYTHONPATH=whatyougot`
11,108,461
I'm having a strange problem while trying to install the Python library `zenlib`, using its `setup.py` file. When I run the `setup.py` file, I get an import error, saying > > ImportError: No module named Cython.Distutils` > > > but I do have such a module, and I can import it on the python command line without any trouble. Why might I be getting this import error? I think that the problem may have to do with the fact that I am using [Enthought Python Distribution](https://www.enthought.com/product/enthought-python-distribution/), which I installed right beforehand, rather than using the Python 2.7 that came with Ubuntu 12.04. More background: Here's exactly what I get when trying to run setup.py: ``` enwe101@enwe101-PCL:~/zenlib/src$ sudo python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from Cython.Distutils import build_ext ImportError: No module named Cython.Distutils ``` But it works from the command line: ``` >>> from Cython.Distutils import build_ext >>> >>> from fake.package import noexist Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named fake.package ``` Note the first import worked and the second throws an error. Compare this to the first few lines of setup.py: ``` #from distutils.core import setup from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import os.path ``` I made sure that the Enthought Python Distribution and not the python that came with Ubuntu is what is run by default by prepending my bash $PATH environment variable by editing `~/.bashrc`, adding this as the last line: ``` export PATH=/usr/local/epd/bin:$PATH ``` and indeed `which python` spits out `/usr/local/epd/bin/python`... not knowing what else to try, I went into my site packages directory, (`/usr/local/epd/lib/python2.7/site-packages`) and give full permissions (r,w,x) to `Cython`, `Distutils`, `build_ext.py`, and the `__init__.py` files. Probably silly to try, and it changed nothing. Can't think of what to try next!? Any ideas?
2012/06/19
[ "https://Stackoverflow.com/questions/11108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467306/" ]
I only got one advice for you : Create a virtualenv. This will ensure you have only one version of python and all your packages installed locally (and not on your entire system). Should be one of the solutions.
That is easy. You could try `install cython` package first. It will upgrade your **easy\_install** built in python.
11,108,461
I'm having a strange problem while trying to install the Python library `zenlib`, using its `setup.py` file. When I run the `setup.py` file, I get an import error, saying > > ImportError: No module named Cython.Distutils` > > > but I do have such a module, and I can import it on the python command line without any trouble. Why might I be getting this import error? I think that the problem may have to do with the fact that I am using [Enthought Python Distribution](https://www.enthought.com/product/enthought-python-distribution/), which I installed right beforehand, rather than using the Python 2.7 that came with Ubuntu 12.04. More background: Here's exactly what I get when trying to run setup.py: ``` enwe101@enwe101-PCL:~/zenlib/src$ sudo python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from Cython.Distutils import build_ext ImportError: No module named Cython.Distutils ``` But it works from the command line: ``` >>> from Cython.Distutils import build_ext >>> >>> from fake.package import noexist Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named fake.package ``` Note the first import worked and the second throws an error. Compare this to the first few lines of setup.py: ``` #from distutils.core import setup from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import os.path ``` I made sure that the Enthought Python Distribution and not the python that came with Ubuntu is what is run by default by prepending my bash $PATH environment variable by editing `~/.bashrc`, adding this as the last line: ``` export PATH=/usr/local/epd/bin:$PATH ``` and indeed `which python` spits out `/usr/local/epd/bin/python`... not knowing what else to try, I went into my site packages directory, (`/usr/local/epd/lib/python2.7/site-packages`) and give full permissions (r,w,x) to `Cython`, `Distutils`, `build_ext.py`, and the `__init__.py` files. Probably silly to try, and it changed nothing. Can't think of what to try next!? Any ideas?
2012/06/19
[ "https://Stackoverflow.com/questions/11108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467306/" ]
Your sudo is not getting the right python. This is a known behaviour of sudo in Ubuntu. See this [question](https://stackoverflow.com/questions/257616/sudo-changes-path-why) for more info. You need to make sure that sudo calls the right python, either by using the full path: ``` sudo /usr/local/epd/bin/python setup.py install ``` or by doing the following (in bash): ``` alias sudo='sudo env PATH=$PATH' sudo python setup.py install ```
For python3 use ``` sudo apt-get install cython3 ``` For python2 use ``` sudo apt-get install cython ``` Details can be read at [this](https://superuser.com/questions/388750/install-cython-on-python-3-x)
11,108,461
I'm having a strange problem while trying to install the Python library `zenlib`, using its `setup.py` file. When I run the `setup.py` file, I get an import error, saying > > ImportError: No module named Cython.Distutils` > > > but I do have such a module, and I can import it on the python command line without any trouble. Why might I be getting this import error? I think that the problem may have to do with the fact that I am using [Enthought Python Distribution](https://www.enthought.com/product/enthought-python-distribution/), which I installed right beforehand, rather than using the Python 2.7 that came with Ubuntu 12.04. More background: Here's exactly what I get when trying to run setup.py: ``` enwe101@enwe101-PCL:~/zenlib/src$ sudo python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from Cython.Distutils import build_ext ImportError: No module named Cython.Distutils ``` But it works from the command line: ``` >>> from Cython.Distutils import build_ext >>> >>> from fake.package import noexist Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named fake.package ``` Note the first import worked and the second throws an error. Compare this to the first few lines of setup.py: ``` #from distutils.core import setup from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import os.path ``` I made sure that the Enthought Python Distribution and not the python that came with Ubuntu is what is run by default by prepending my bash $PATH environment variable by editing `~/.bashrc`, adding this as the last line: ``` export PATH=/usr/local/epd/bin:$PATH ``` and indeed `which python` spits out `/usr/local/epd/bin/python`... not knowing what else to try, I went into my site packages directory, (`/usr/local/epd/lib/python2.7/site-packages`) and give full permissions (r,w,x) to `Cython`, `Distutils`, `build_ext.py`, and the `__init__.py` files. Probably silly to try, and it changed nothing. Can't think of what to try next!? Any ideas?
2012/06/19
[ "https://Stackoverflow.com/questions/11108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467306/" ]
I only got one advice for you : Create a virtualenv. This will ensure you have only one version of python and all your packages installed locally (and not on your entire system). Should be one of the solutions.
Ran into this again in modern times. The solution was simple: ``` pip uninstall cython && pip install cython ```
11,108,461
I'm having a strange problem while trying to install the Python library `zenlib`, using its `setup.py` file. When I run the `setup.py` file, I get an import error, saying > > ImportError: No module named Cython.Distutils` > > > but I do have such a module, and I can import it on the python command line without any trouble. Why might I be getting this import error? I think that the problem may have to do with the fact that I am using [Enthought Python Distribution](https://www.enthought.com/product/enthought-python-distribution/), which I installed right beforehand, rather than using the Python 2.7 that came with Ubuntu 12.04. More background: Here's exactly what I get when trying to run setup.py: ``` enwe101@enwe101-PCL:~/zenlib/src$ sudo python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from Cython.Distutils import build_ext ImportError: No module named Cython.Distutils ``` But it works from the command line: ``` >>> from Cython.Distutils import build_ext >>> >>> from fake.package import noexist Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named fake.package ``` Note the first import worked and the second throws an error. Compare this to the first few lines of setup.py: ``` #from distutils.core import setup from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import os.path ``` I made sure that the Enthought Python Distribution and not the python that came with Ubuntu is what is run by default by prepending my bash $PATH environment variable by editing `~/.bashrc`, adding this as the last line: ``` export PATH=/usr/local/epd/bin:$PATH ``` and indeed `which python` spits out `/usr/local/epd/bin/python`... not knowing what else to try, I went into my site packages directory, (`/usr/local/epd/lib/python2.7/site-packages`) and give full permissions (r,w,x) to `Cython`, `Distutils`, `build_ext.py`, and the `__init__.py` files. Probably silly to try, and it changed nothing. Can't think of what to try next!? Any ideas?
2012/06/19
[ "https://Stackoverflow.com/questions/11108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467306/" ]
I only got one advice for you : Create a virtualenv. This will ensure you have only one version of python and all your packages installed locally (and not on your entire system). Should be one of the solutions.
I had dependency from third party library on Cython, didn't manage to build the project on Travis due to the ImportError. In case someone needs it - before installing requirements.txt run this command: > > pip install Cython --install-option="--no-cython-compile" > > > Installing GCC also might help.
11,108,461
I'm having a strange problem while trying to install the Python library `zenlib`, using its `setup.py` file. When I run the `setup.py` file, I get an import error, saying > > ImportError: No module named Cython.Distutils` > > > but I do have such a module, and I can import it on the python command line without any trouble. Why might I be getting this import error? I think that the problem may have to do with the fact that I am using [Enthought Python Distribution](https://www.enthought.com/product/enthought-python-distribution/), which I installed right beforehand, rather than using the Python 2.7 that came with Ubuntu 12.04. More background: Here's exactly what I get when trying to run setup.py: ``` enwe101@enwe101-PCL:~/zenlib/src$ sudo python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from Cython.Distutils import build_ext ImportError: No module named Cython.Distutils ``` But it works from the command line: ``` >>> from Cython.Distutils import build_ext >>> >>> from fake.package import noexist Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named fake.package ``` Note the first import worked and the second throws an error. Compare this to the first few lines of setup.py: ``` #from distutils.core import setup from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import os.path ``` I made sure that the Enthought Python Distribution and not the python that came with Ubuntu is what is run by default by prepending my bash $PATH environment variable by editing `~/.bashrc`, adding this as the last line: ``` export PATH=/usr/local/epd/bin:$PATH ``` and indeed `which python` spits out `/usr/local/epd/bin/python`... not knowing what else to try, I went into my site packages directory, (`/usr/local/epd/lib/python2.7/site-packages`) and give full permissions (r,w,x) to `Cython`, `Distutils`, `build_ext.py`, and the `__init__.py` files. Probably silly to try, and it changed nothing. Can't think of what to try next!? Any ideas?
2012/06/19
[ "https://Stackoverflow.com/questions/11108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467306/" ]
Your sudo is not getting the right python. This is a known behaviour of sudo in Ubuntu. See this [question](https://stackoverflow.com/questions/257616/sudo-changes-path-why) for more info. You need to make sure that sudo calls the right python, either by using the full path: ``` sudo /usr/local/epd/bin/python setup.py install ``` or by doing the following (in bash): ``` alias sudo='sudo env PATH=$PATH' sudo python setup.py install ```
I had dependency from third party library on Cython, didn't manage to build the project on Travis due to the ImportError. In case someone needs it - before installing requirements.txt run this command: > > pip install Cython --install-option="--no-cython-compile" > > > Installing GCC also might help.
11,108,461
I'm having a strange problem while trying to install the Python library `zenlib`, using its `setup.py` file. When I run the `setup.py` file, I get an import error, saying > > ImportError: No module named Cython.Distutils` > > > but I do have such a module, and I can import it on the python command line without any trouble. Why might I be getting this import error? I think that the problem may have to do with the fact that I am using [Enthought Python Distribution](https://www.enthought.com/product/enthought-python-distribution/), which I installed right beforehand, rather than using the Python 2.7 that came with Ubuntu 12.04. More background: Here's exactly what I get when trying to run setup.py: ``` enwe101@enwe101-PCL:~/zenlib/src$ sudo python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from Cython.Distutils import build_ext ImportError: No module named Cython.Distutils ``` But it works from the command line: ``` >>> from Cython.Distutils import build_ext >>> >>> from fake.package import noexist Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named fake.package ``` Note the first import worked and the second throws an error. Compare this to the first few lines of setup.py: ``` #from distutils.core import setup from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import os.path ``` I made sure that the Enthought Python Distribution and not the python that came with Ubuntu is what is run by default by prepending my bash $PATH environment variable by editing `~/.bashrc`, adding this as the last line: ``` export PATH=/usr/local/epd/bin:$PATH ``` and indeed `which python` spits out `/usr/local/epd/bin/python`... not knowing what else to try, I went into my site packages directory, (`/usr/local/epd/lib/python2.7/site-packages`) and give full permissions (r,w,x) to `Cython`, `Distutils`, `build_ext.py`, and the `__init__.py` files. Probably silly to try, and it changed nothing. Can't think of what to try next!? Any ideas?
2012/06/19
[ "https://Stackoverflow.com/questions/11108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467306/" ]
Run > > `which python` > > > Thats the path to the python that your system has defaulted too then go to @tiago's method of: > > `sudo <output of which python> setup.py install` > > >
I had dependency from third party library on Cython, didn't manage to build the project on Travis due to the ImportError. In case someone needs it - before installing requirements.txt run this command: > > pip install Cython --install-option="--no-cython-compile" > > > Installing GCC also might help.
11,108,461
I'm having a strange problem while trying to install the Python library `zenlib`, using its `setup.py` file. When I run the `setup.py` file, I get an import error, saying > > ImportError: No module named Cython.Distutils` > > > but I do have such a module, and I can import it on the python command line without any trouble. Why might I be getting this import error? I think that the problem may have to do with the fact that I am using [Enthought Python Distribution](https://www.enthought.com/product/enthought-python-distribution/), which I installed right beforehand, rather than using the Python 2.7 that came with Ubuntu 12.04. More background: Here's exactly what I get when trying to run setup.py: ``` enwe101@enwe101-PCL:~/zenlib/src$ sudo python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from Cython.Distutils import build_ext ImportError: No module named Cython.Distutils ``` But it works from the command line: ``` >>> from Cython.Distutils import build_ext >>> >>> from fake.package import noexist Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named fake.package ``` Note the first import worked and the second throws an error. Compare this to the first few lines of setup.py: ``` #from distutils.core import setup from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import os.path ``` I made sure that the Enthought Python Distribution and not the python that came with Ubuntu is what is run by default by prepending my bash $PATH environment variable by editing `~/.bashrc`, adding this as the last line: ``` export PATH=/usr/local/epd/bin:$PATH ``` and indeed `which python` spits out `/usr/local/epd/bin/python`... not knowing what else to try, I went into my site packages directory, (`/usr/local/epd/lib/python2.7/site-packages`) and give full permissions (r,w,x) to `Cython`, `Distutils`, `build_ext.py`, and the `__init__.py` files. Probably silly to try, and it changed nothing. Can't think of what to try next!? Any ideas?
2012/06/19
[ "https://Stackoverflow.com/questions/11108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467306/" ]
Your sudo is not getting the right python. This is a known behaviour of sudo in Ubuntu. See this [question](https://stackoverflow.com/questions/257616/sudo-changes-path-why) for more info. You need to make sure that sudo calls the right python, either by using the full path: ``` sudo /usr/local/epd/bin/python setup.py install ``` or by doing the following (in bash): ``` alias sudo='sudo env PATH=$PATH' sudo python setup.py install ```
Read like a thousand of these threads and finally got it for Python 3. (replace pip with pip3 if you have that kind of installation, and run `pip uninstall cython` if you have tried other solutions before running any of these) Mac: ``` brew install cython pip install --upgrade cython ``` Ubuntu ``` sudo apt-get install cython3 python-dev pip install --upgrade cython ``` Windows (must have conda, and MinGW already in path) ``` conda install cython conda install --upgrade cython ```
11,108,461
I'm having a strange problem while trying to install the Python library `zenlib`, using its `setup.py` file. When I run the `setup.py` file, I get an import error, saying > > ImportError: No module named Cython.Distutils` > > > but I do have such a module, and I can import it on the python command line without any trouble. Why might I be getting this import error? I think that the problem may have to do with the fact that I am using [Enthought Python Distribution](https://www.enthought.com/product/enthought-python-distribution/), which I installed right beforehand, rather than using the Python 2.7 that came with Ubuntu 12.04. More background: Here's exactly what I get when trying to run setup.py: ``` enwe101@enwe101-PCL:~/zenlib/src$ sudo python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from Cython.Distutils import build_ext ImportError: No module named Cython.Distutils ``` But it works from the command line: ``` >>> from Cython.Distutils import build_ext >>> >>> from fake.package import noexist Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named fake.package ``` Note the first import worked and the second throws an error. Compare this to the first few lines of setup.py: ``` #from distutils.core import setup from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import os.path ``` I made sure that the Enthought Python Distribution and not the python that came with Ubuntu is what is run by default by prepending my bash $PATH environment variable by editing `~/.bashrc`, adding this as the last line: ``` export PATH=/usr/local/epd/bin:$PATH ``` and indeed `which python` spits out `/usr/local/epd/bin/python`... not knowing what else to try, I went into my site packages directory, (`/usr/local/epd/lib/python2.7/site-packages`) and give full permissions (r,w,x) to `Cython`, `Distutils`, `build_ext.py`, and the `__init__.py` files. Probably silly to try, and it changed nothing. Can't think of what to try next!? Any ideas?
2012/06/19
[ "https://Stackoverflow.com/questions/11108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467306/" ]
Run > > `which python` > > > Thats the path to the python that your system has defaulted too then go to @tiago's method of: > > `sudo <output of which python> setup.py install` > > >
That is easy. You could try `install cython` package first. It will upgrade your **easy\_install** built in python.
11,108,461
I'm having a strange problem while trying to install the Python library `zenlib`, using its `setup.py` file. When I run the `setup.py` file, I get an import error, saying > > ImportError: No module named Cython.Distutils` > > > but I do have such a module, and I can import it on the python command line without any trouble. Why might I be getting this import error? I think that the problem may have to do with the fact that I am using [Enthought Python Distribution](https://www.enthought.com/product/enthought-python-distribution/), which I installed right beforehand, rather than using the Python 2.7 that came with Ubuntu 12.04. More background: Here's exactly what I get when trying to run setup.py: ``` enwe101@enwe101-PCL:~/zenlib/src$ sudo python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from Cython.Distutils import build_ext ImportError: No module named Cython.Distutils ``` But it works from the command line: ``` >>> from Cython.Distutils import build_ext >>> >>> from fake.package import noexist Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named fake.package ``` Note the first import worked and the second throws an error. Compare this to the first few lines of setup.py: ``` #from distutils.core import setup from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import os.path ``` I made sure that the Enthought Python Distribution and not the python that came with Ubuntu is what is run by default by prepending my bash $PATH environment variable by editing `~/.bashrc`, adding this as the last line: ``` export PATH=/usr/local/epd/bin:$PATH ``` and indeed `which python` spits out `/usr/local/epd/bin/python`... not knowing what else to try, I went into my site packages directory, (`/usr/local/epd/lib/python2.7/site-packages`) and give full permissions (r,w,x) to `Cython`, `Distutils`, `build_ext.py`, and the `__init__.py` files. Probably silly to try, and it changed nothing. Can't think of what to try next!? Any ideas?
2012/06/19
[ "https://Stackoverflow.com/questions/11108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467306/" ]
Read like a thousand of these threads and finally got it for Python 3. (replace pip with pip3 if you have that kind of installation, and run `pip uninstall cython` if you have tried other solutions before running any of these) Mac: ``` brew install cython pip install --upgrade cython ``` Ubuntu ``` sudo apt-get install cython3 python-dev pip install --upgrade cython ``` Windows (must have conda, and MinGW already in path) ``` conda install cython conda install --upgrade cython ```
Just install Cython from <http://cython.org/#download> and install it using this command ``` sudo python setup.py install ``` Then run the command ``` sudo python -c 'import Cython.Distutils' ``` and it will be installed and the error message will disappear.
38,557,849
A peak finding program in a 1-D python list which returns a peak with its index if for an index 'x' in the list 'arr' if (arr[x] > arr[x+1] and arr[x] > arr[x-1]). Special case Case 1 : In case of the first element. Only compare it to the second element. If arr[x] > arr[x+1], peak found. Case 2 : Last element. Compare with the previous element. If arr[x] > arr[x-1], peak found. Below is the code. For some reason it is not working in the case the peak is at index = 0. Its perfectly working for the peak in the middle and peak at the end. Any help is greatly appreciated. ``` import sys def find_peak(lst): for x in lst: if x == 0 and lst[x] > lst[x+1]: print "Peak found at index", x print "Peak :", lst[x] return elif x == len(lst)-1 and lst[x] > lst[x-1]: print "Peak found at index", x print "Peak :", lst[x] return elif x > 0 and x < len(lst)-1: if lst[x] > lst[x+1] and lst[x] > lst[x-1]: print "Peak found at index", x print "Peak :", lst[x] return else : print "No peak found" def main(): lst = [] for x in sys.argv[1:]: lst.append(int(x)) find_peak(lst) if __name__ == '__main__': main() Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 1 2 3 4 Peak found at index 3 Peak : 4 Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 1 2 3 4 3 Peak found at index 3 Peak : 4 Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 4 3 2 1 No peak found ```
2016/07/24
[ "https://Stackoverflow.com/questions/38557849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4254959/" ]
for example, let us create a middleware function that will handle CORS using: *[github.com/buaazp/fasthttprouter](https://github.com/buaazp/fasthttprouter)* and *[github.com/valyala/fasthttp](https://github.com/valyala/fasthttp)* ``` var ( corsAllowHeaders = "authorization" corsAllowMethods = "HEAD,GET,POST,PUT,DELETE,OPTIONS" corsAllowOrigin = "*" corsAllowCredentials = "true" ) func CORS(next fasthttp.RequestHandler) fasthttp.RequestHandler { return func(ctx *fasthttp.RequestCtx) { ctx.Response.Header.Set("Access-Control-Allow-Credentials", corsAllowCredentials) ctx.Response.Header.Set("Access-Control-Allow-Headers", corsAllowHeaders) ctx.Response.Header.Set("Access-Control-Allow-Methods", corsAllowMethods) ctx.Response.Header.Set("Access-Control-Allow-Origin", corsAllowOrigin) next(ctx) } } ``` Now we chain this middleware function on our Index handler and register it on the router. ``` func Index(ctx *fasthttp.RequestCtx) { fmt.Fprint(ctx, "some-api") } func main() { router := fasthttprouter.New() router.GET("/", Index) if err := fasthttp.ListenAndServe(":8181", CORS(router.Handler)); err != nil { log.Fatalf("Error in ListenAndServe: %s", err) } } ```
Example of auth middleware for fasthttp & fasthttprouter (new versions) ``` type Middleware func(h fasthttp.RequestHandler) fasthttp.RequestHandler type AuthFunc func(ctx *fasthttp.RequestCtx) bool func NewAuthMiddleware(authFunc AuthFunc) Middleware { return func(h fasthttp.RequestHandler) fasthttp.RequestHandler { return func(ctx *fasthttp.RequestCtx) { result, err: = authFunc(ctx) if result { h(ctx) } else { ctx.Response.SetStatusCode(fasthttp.StatusUnauthorized) } } } } func AuthCheck(ctx *fasthttp.RequestCtx)(bool, error) { return false; // for example ;) } // router authMiddleware: = middleware.NewAuthMiddleware(security.AuthCheck) ... router.GET("/protected", authMiddleware(handlers.ProtectedHandler)) ```
12,902,178
> > **Possible Duplicate:** > > [Compare two different files line by line and write the difference in third file - Python](https://stackoverflow.com/questions/7757626/compare-two-different-files-line-by-line-and-write-the-difference-in-third-file) > > > The logic in my head works something like this... for line in import\_file check to see if it contains any of the items in Existing-user-string-list if it contains any one of the items from that list then delete that line for the file. ``` filenew = open('new-user', 'r') filexist = open('existing-user', 'r') fileresult = open('result-file', 'r+') xlines = filexist.readlines() newlines = filenew.readlines() for item in newlines: if item contains an item from xlines break else fileresult.write(item) filenew.close() filexist.close() fileresult.close() ``` I know this code is all jacked up but perhaps you can point me in the right direction. Thanks! Edit ---- **Here is an example of what is in my existing user file....** ``` allyson.knanishu amy.curtiss amy.hunter amy.schelker andrea.vallejo angel.bender angie.loebach ``` **Here is an example of what is in my new user file....** ``` aimee.neece,aimee,neece,aimee.neece@faculty.asdf.org,aimee neece,aimee neece,"CN=aimee neece,OU=Imported,dc=Faculty,dc=asdf,dc=org" alexis.andrews,alexis,andrews,alexis.andrews@faculty.asdf.org,alexis andrews,alexis andrews,"CN=alexis andrews,OU=Imported,dc=Faculty,dc=asdf,dc=org" alice.lee,alice,lee,alice.lee@faculty.asdf.org,alice lee,alice lee,"CN=alice lee,OU=Imported,dc=Faculty,dc=asdf,dc=org" allyson.knanishu,allyson,knanishu,allyson.knanishu@faculty.asdf.org,allyson knanishu,allyson knanishu,"CN=allyson knanishu,OU=Imported,dc=Faculty,dc=asdf,dc=org" ``` New code from @mikebabcock ... thanks. ``` outfile = file("result-file.txt", "w") lines_to_check_for = [ parser(line) for line in file("existing-user.txt", "r") ] for line in file("new-user.txt", "r"): if not parser(line) in lines_to_check_for: outfile.write(line) ``` Added an import statement for the parser... I am receiving the following error... ``` C:\temp\ad-import\test-files>python new-script.py Traceback (most recent call last): File "new-script.py", line 7, in <module> lines_to_check_for = [ parser(line) for line in file("existing-user.txt", "r ") ] TypeError: 'module' object is not callable ``` Thanks!
2012/10/15
[ "https://Stackoverflow.com/questions/12902178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1747993/" ]
assuming I understand what you want to do .... use set intersection :) ``` for line in newlines: if set(line.split()) & set(xlines): #set intersection print "overlap between xlines and current line" break else: fileresult.write(item) ```
I presume this is what you want to do: ``` outfile = file("outfile.txt", "w") lines_to_check_for = [ line for line in file("list.txt", "r") ] for line in file("testing.txt", "r"): if not line in lines_to_check_for: outfile.write(line) ``` This will read all the lines in `list.txt` into an array, and then check each line of `testing.txt` against that array. All the lines that aren't in that array will be written out to `outfile.txt`. Here's an updated example based on your new question: ``` newusers = file("newusers.txt", "w") existing_users = [ line for line in file("users.txt", "r") ] for line in file("testing.txt", "r"): # grab each comma-separated user, take the portion left of the @, if any new_users = [ entry.split["@"](0) for entry in line.split(",") ] for user in new_users: if not user in existing_users: newusers.write(user) ```
12,902,178
> > **Possible Duplicate:** > > [Compare two different files line by line and write the difference in third file - Python](https://stackoverflow.com/questions/7757626/compare-two-different-files-line-by-line-and-write-the-difference-in-third-file) > > > The logic in my head works something like this... for line in import\_file check to see if it contains any of the items in Existing-user-string-list if it contains any one of the items from that list then delete that line for the file. ``` filenew = open('new-user', 'r') filexist = open('existing-user', 'r') fileresult = open('result-file', 'r+') xlines = filexist.readlines() newlines = filenew.readlines() for item in newlines: if item contains an item from xlines break else fileresult.write(item) filenew.close() filexist.close() fileresult.close() ``` I know this code is all jacked up but perhaps you can point me in the right direction. Thanks! Edit ---- **Here is an example of what is in my existing user file....** ``` allyson.knanishu amy.curtiss amy.hunter amy.schelker andrea.vallejo angel.bender angie.loebach ``` **Here is an example of what is in my new user file....** ``` aimee.neece,aimee,neece,aimee.neece@faculty.asdf.org,aimee neece,aimee neece,"CN=aimee neece,OU=Imported,dc=Faculty,dc=asdf,dc=org" alexis.andrews,alexis,andrews,alexis.andrews@faculty.asdf.org,alexis andrews,alexis andrews,"CN=alexis andrews,OU=Imported,dc=Faculty,dc=asdf,dc=org" alice.lee,alice,lee,alice.lee@faculty.asdf.org,alice lee,alice lee,"CN=alice lee,OU=Imported,dc=Faculty,dc=asdf,dc=org" allyson.knanishu,allyson,knanishu,allyson.knanishu@faculty.asdf.org,allyson knanishu,allyson knanishu,"CN=allyson knanishu,OU=Imported,dc=Faculty,dc=asdf,dc=org" ``` New code from @mikebabcock ... thanks. ``` outfile = file("result-file.txt", "w") lines_to_check_for = [ parser(line) for line in file("existing-user.txt", "r") ] for line in file("new-user.txt", "r"): if not parser(line) in lines_to_check_for: outfile.write(line) ``` Added an import statement for the parser... I am receiving the following error... ``` C:\temp\ad-import\test-files>python new-script.py Traceback (most recent call last): File "new-script.py", line 7, in <module> lines_to_check_for = [ parser(line) for line in file("existing-user.txt", "r ") ] TypeError: 'module' object is not callable ``` Thanks!
2012/10/15
[ "https://Stackoverflow.com/questions/12902178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1747993/" ]
assuming I understand what you want to do .... use set intersection :) ``` for line in newlines: if set(line.split()) & set(xlines): #set intersection print "overlap between xlines and current line" break else: fileresult.write(item) ```
If the input files format is that you have one item per line (so that the check for existing element in readlines lists is ok), you are looking for list membership test: ``` if item in xlines: break ``` To point some some more python stuff: make a set from the list you test for membership (because the tests will be logarithmic time instead of linear as in the case of list): ``` xlines = set(filexists.readlines()) ``` Also, you can use the with statement to avoid closing the files and provide clearer code (like the first example [here](http://preshing.com/20110920/the-python-with-statement-by-example)).
11,452,887
Based on this example of a line from a file ``` 1:alpha:beta ``` I'm trying to get python to read the file in and then line by line print whats after the 2nd `':'` ``` import fileinput #input file x = fileinput.input('ids.txt') strip_char = ":" for line in x: strip_char.join(line.split(strip_char)[2:]) ``` This produces no results, however from a console session on a single line it works fine ``` Python 2.7.3rc2 (default, Apr 22 2012, 22:35:38) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. data = '1:alpha:beta' strip_char = ":" strip_char.join(data.split(strip_char)[2:]) 'beta' ``` What am i doing wrong please? Thanks
2012/07/12
[ "https://Stackoverflow.com/questions/11452887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
For the data format given this will work: ``` with open('data.txt') as inf: for line in inf: line = line.strip() line = line.split(':') print ':'.join(line[2:]) ``` For `'1:alpha:beta'` the output would be `'beta'` For `'1:alpha:beta:gamma'` the output would be `'beta:gamma'` (Thanks for @JAB pointing this out)
Values returned by functions aren't automatically sent to stdout in non-interactive mode, you have to explicitly print them. So, for Python 2, use `print line.split(strip_char, 2)[2]`. If you ever use Python 3, it'll be `print(line.split(strip_char, 2)[2])`. (Props to Jon Clements, I forgot you could limit how many times a string will be split.)
11,452,887
Based on this example of a line from a file ``` 1:alpha:beta ``` I'm trying to get python to read the file in and then line by line print whats after the 2nd `':'` ``` import fileinput #input file x = fileinput.input('ids.txt') strip_char = ":" for line in x: strip_char.join(line.split(strip_char)[2:]) ``` This produces no results, however from a console session on a single line it works fine ``` Python 2.7.3rc2 (default, Apr 22 2012, 22:35:38) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. data = '1:alpha:beta' strip_char = ":" strip_char.join(data.split(strip_char)[2:]) 'beta' ``` What am i doing wrong please? Thanks
2012/07/12
[ "https://Stackoverflow.com/questions/11452887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Values returned by functions aren't automatically sent to stdout in non-interactive mode, you have to explicitly print them. So, for Python 2, use `print line.split(strip_char, 2)[2]`. If you ever use Python 3, it'll be `print(line.split(strip_char, 2)[2])`. (Props to Jon Clements, I forgot you could limit how many times a string will be split.)
You get just 'beta' because join gives you a string: ``` data = '1:alpha:beta' strip_char = ":" strip_char.join(data.split(strip_char)[2:]) 'beta' ``` Try this: ``` lines=[] with open('filePath', 'r') as f: for line in f.readlines(): lines.append(line.strip()) for line in lines: print line.split(':')[1:] ```
11,452,887
Based on this example of a line from a file ``` 1:alpha:beta ``` I'm trying to get python to read the file in and then line by line print whats after the 2nd `':'` ``` import fileinput #input file x = fileinput.input('ids.txt') strip_char = ":" for line in x: strip_char.join(line.split(strip_char)[2:]) ``` This produces no results, however from a console session on a single line it works fine ``` Python 2.7.3rc2 (default, Apr 22 2012, 22:35:38) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. data = '1:alpha:beta' strip_char = ":" strip_char.join(data.split(strip_char)[2:]) 'beta' ``` What am i doing wrong please? Thanks
2012/07/12
[ "https://Stackoverflow.com/questions/11452887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
For the data format given this will work: ``` with open('data.txt') as inf: for line in inf: line = line.strip() line = line.split(':') print ':'.join(line[2:]) ``` For `'1:alpha:beta'` the output would be `'beta'` For `'1:alpha:beta:gamma'` the output would be `'beta:gamma'` (Thanks for @JAB pointing this out)
If it's everything after the 2nd ':' as a string (which can include ':') then use the maxsplit option, eg: ``` line.split(':', 2)[2] ``` eg: ``` >>> d = '1:alpha:beta:charlie:delta' >>> d.split(':', 2) ['1', 'alpha', 'beta:charlie:delta'] ``` **This saves joining afterwards**
11,452,887
Based on this example of a line from a file ``` 1:alpha:beta ``` I'm trying to get python to read the file in and then line by line print whats after the 2nd `':'` ``` import fileinput #input file x = fileinput.input('ids.txt') strip_char = ":" for line in x: strip_char.join(line.split(strip_char)[2:]) ``` This produces no results, however from a console session on a single line it works fine ``` Python 2.7.3rc2 (default, Apr 22 2012, 22:35:38) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. data = '1:alpha:beta' strip_char = ":" strip_char.join(data.split(strip_char)[2:]) 'beta' ``` What am i doing wrong please? Thanks
2012/07/12
[ "https://Stackoverflow.com/questions/11452887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
For the data format given this will work: ``` with open('data.txt') as inf: for line in inf: line = line.strip() line = line.split(':') print ':'.join(line[2:]) ``` For `'1:alpha:beta'` the output would be `'beta'` For `'1:alpha:beta:gamma'` the output would be `'beta:gamma'` (Thanks for @JAB pointing this out)
You get just 'beta' because join gives you a string: ``` data = '1:alpha:beta' strip_char = ":" strip_char.join(data.split(strip_char)[2:]) 'beta' ``` Try this: ``` lines=[] with open('filePath', 'r') as f: for line in f.readlines(): lines.append(line.strip()) for line in lines: print line.split(':')[1:] ```
11,452,887
Based on this example of a line from a file ``` 1:alpha:beta ``` I'm trying to get python to read the file in and then line by line print whats after the 2nd `':'` ``` import fileinput #input file x = fileinput.input('ids.txt') strip_char = ":" for line in x: strip_char.join(line.split(strip_char)[2:]) ``` This produces no results, however from a console session on a single line it works fine ``` Python 2.7.3rc2 (default, Apr 22 2012, 22:35:38) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. data = '1:alpha:beta' strip_char = ":" strip_char.join(data.split(strip_char)[2:]) 'beta' ``` What am i doing wrong please? Thanks
2012/07/12
[ "https://Stackoverflow.com/questions/11452887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If it's everything after the 2nd ':' as a string (which can include ':') then use the maxsplit option, eg: ``` line.split(':', 2)[2] ``` eg: ``` >>> d = '1:alpha:beta:charlie:delta' >>> d.split(':', 2) ['1', 'alpha', 'beta:charlie:delta'] ``` **This saves joining afterwards**
You get just 'beta' because join gives you a string: ``` data = '1:alpha:beta' strip_char = ":" strip_char.join(data.split(strip_char)[2:]) 'beta' ``` Try this: ``` lines=[] with open('filePath', 'r') as f: for line in f.readlines(): lines.append(line.strip()) for line in lines: print line.split(':')[1:] ```
48,753,297
I am trying to evaluate istio and trying to deploy the bookinfo example app provided with the istio installation. While doing that, I am facing the following issue. ``` Environment: Non production 1. Server Node - red hat enterprise linux 7 64 bit VM [3.10.0-693.11.6.el7.x86_64] Server in customer secure vpn with no access to enterprise/public DNS. 2. docker client and server: 1.12.6 3. kubernetes client - 1.9.1, server - 1.8.4 4. kubernetes install method: kubeadm. 5. kubernetes deployment mode: single node with master and slave. 6. Istio install method: - istio version: 0.5.0 - no SSL, no automatic side car injection, no Helm. - Instructions followed: https://istio.io/docs/setup/kubernetes/quick-start.html - Cloned the istio github project - https://github.com/istio/istio. - Used the istio.yaml and bookinfo.yaml files for the installation and example implementation. ``` Issue: The installation of istio client and control plane components went through fine. The control plane also starts up fine. However, when I launch the bookinfo app, the app's proxy init containers crash with a cryptic "iptables: Chain already exists" log message. ``` ISTIO CONTROL PLANE -------------------- $ kubectl get deployments,pods,svc,ep -n istio-system NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE deploy/istio-ca 1 1 1 1 2d deploy/istio-ingress 1 1 1 1 2d deploy/istio-mixer 1 1 1 1 2d deploy/istio-pilot 1 1 1 1 2d NAME READY STATUS RESTARTS AGE po/istio-ca-5796758d78-md7fl 1/1 Running 0 2d po/istio-ingress-f7ff9dcfd-fl85s 1/1 Running 0 2d po/istio-mixer-69f48ddb6c-d4ww2 3/3 Running 0 2d po/istio-pilot-69cc4dd5cb-fglsg 2/2 Running 0 2d NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE svc/istio-ingress LoadBalancer 10.103.67.68 <pending> 80:31445/TCP,443:30412/TCP 2d svc/istio-mixer ClusterIP 10.101.47.150 <none> 9091/TCP,15004/TCP,9093/TCP,9094/TCP,9102/TCP,9125/UDP,42422/TCP 2d svc/istio-pilot ClusterIP 10.110.58.219 <none> 15003/TCP,8080/TCP,9093/TCP,443/TCP 2d NAME ENDPOINTS AGE ep/istio-ingress 10.244.0.22:443,10.244.0.22:80 2d ep/istio-mixer 10.244.0.20:9125,10.244.0.20:9094,10.244.0.20:15004 + 4 more... 2d ep/istio-pilot 10.244.0.21:443,10.244.0.21:15003,10.244.0.21:8080 + 1 more... 2d BOOKINFO APP ------------- $ kubectl get deployments,pods,svc,ep NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE deploy/details-v1 1 1 1 1 2d deploy/productpage-v1 1 1 1 1 2d deploy/ratings-v1 1 1 1 1 2d deploy/reviews-v1 1 1 1 1 2d deploy/reviews-v2 1 1 1 1 2d deploy/reviews-v3 1 1 1 1 2d NAME READY STATUS RESTARTS AGE po/details-v1-df5d6ff55-92jrx 0/2 Init:CrashLoopBackOff 738 2d po/productpage-v1-85f65888f5-xdkt6 0/2 Init:CrashLoopBackOff 738 2d po/ratings-v1-668b7f9ddc-9nhcw 0/2 Init:CrashLoopBackOff 738 2d po/reviews-v1-5845b57d57-2cjvn 0/2 Init:CrashLoopBackOff 738 2d po/reviews-v2-678b446795-hkkvv 0/2 Init:CrashLoopBackOff 738 2d po/reviews-v3-8b796f-64lm8 0/2 Init:CrashLoopBackOff 738 2d NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE svc/details ClusterIP 10.104.237.100 <none> 9080/TCP 2d svc/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 70d svc/productpage ClusterIP 10.100.136.14 <none> 9080/TCP 2d svc/ratings ClusterIP 10.105.166.190 <none> 9080/TCP 2d svc/reviews ClusterIP 10.110.221.19 <none> 9080/TCP 2d NAME ENDPOINTS AGE ep/details 10.244.0.24:9080 2d ep/kubernetes NNN.NN.NN.NNN:6443 70d ep/productpage 10.244.0.45:9080 2d ep/ratings 10.244.0.25:9080 2d ep/reviews 10.244.0.26:9080,10.244.0.28:9080,10.244.0.29:9080 2d PROXY INIT CRASHED CONTAINERS ------------------------------ $ docker ps -a | grep -i istio | grep -i exit 9109bafcf9e7 docker.io/istio/proxy_init@sha256:0962ff2159796a66b9d243cac82cfccb6730cd5149c91a0f64baa08f065b22f8 "/usr/local /bin/prepa" 11 seconds ago Exited (1) 10 seconds ago k8s_istio-init_details-v1-df5d6ff55-92jrx_default_b54d921c-0dcd-11e8-8de9-0050568 e45b4_740 0ed3b188d7ba docker.io/istio/proxy_init@sha256:0962ff2159796a66b9d243cac82cfccb6730cd5149c91a0f64baa08f065b22f8 "/usr/local /bin/prepa" 27 seconds ago Exited (1) 26 seconds ago k8s_istio-init_reviews-v2-678b446795-hkkvv_default_b557b5a5-0dcd-11e8-8de9-005056 8e45b4_740 893fcec0b01e docker.io/istio/proxy_init@sha256:0962ff2159796a66b9d243cac82cfccb6730cd5149c91a0f64baa08f065b22f8 "/usr/local /bin/prepa" About a minute ago Exited (1) About a minute ago k8s_istio-init_reviews-v1-5845b57d57-2cjvn_default_b555bb75-0dcd-11e8-8de9-005056 8e45b4_740 a2a036273402 docker.io/istio/proxy_init@sha256:0962ff2159796a66b9d243cac82cfccb6730cd5149c91a0f64baa08f065b22f8 "/usr/local /bin/prepa" About a minute ago Exited (1) About a minute ago k8s_istio-init_productpage-v1-85f65888f5-xdkt6_default_b579277b-0dcd-11e8-8de9-00 50568e45b4_740 520beb6779e0 docker.io/istio/proxy_init@sha256:0962ff2159796a66b9d243cac82cfccb6730cd5149c91a0f64baa08f065b22f8 "/usr/local /bin/prepa" About a minute ago Exited (1) About a minute ago k8s_istio-init_reviews-v3-8b796f-64lm8_default_b559d9ef-0dcd-11e8-8de9-0050568e45 b4_740 91a0f41f5fde docker.io/istio/proxy_init@sha256:0962ff2159796a66b9d243cac82cfccb6730cd5149c91a0f64baa08f065b22f8 "/usr/local /bin/prepa" 3 minutes ago Exited (1) 3 minutes ago k8s_istio-init_ratings-v1-668b7f9ddc-9nhcw_default_b55128a5-0dcd-11e8-8de9-005056 8e45b4_740 PROXY PROCESSES FOR EACH ISTIO COMPONENT ----------------------------------------- $ docker ps | grep -vi exit | grep proxy 4d9b37839e44 docker.io/istio/proxy@sha256:3a9fc8a72faec478a7eca222bbb2ceec688514c95cf06ac12ab6235958c6883c "/usr/local/bin/pilot" 2 days ago Up 2 days k8s_istio-proxy_reviews-v2-678b446795-hkkvv_default_b557b5a5-0dcd-11e8-8de9-0050568e45b4_0 1c72e3a990cb docker.io/istio/proxy@sha256:3a9fc8a72faec478a7eca222bbb2ceec688514c95cf06ac12ab6235958c6883c "/usr/local/bin/pilot" 2 days ago Up 2 days k8s_istio-proxy_productpage-v1-85f65888f5-xdkt6_default_b579277b-0dcd-11e8-8de9-0050568e45b4_0 f6ffcaf4b24b docker.io/istio/proxy@sha256:3a9fc8a72faec478a7eca222bbb2ceec688514c95cf06ac12ab6235958c6883c "/usr/local/bin/pilot" 2 days ago Up 2 days k8s_istio-proxy_reviews-v1-5845b57d57-2cjvn_default_b555bb75-0dcd-11e8-8de9-0050568e45b4_0 b66b7ab90a2d docker.io/istio/proxy@sha256:3a9fc8a72faec478a7eca222bbb2ceec688514c95cf06ac12ab6235958c6883c "/usr/local/bin/pilot" 2 days ago Up 2 days k8s_istio-proxy_ratings-v1-668b7f9ddc-9nhcw_default_b55128a5-0dcd-11e8-8de9-0050568e45b4_0 08bf2370b5be docker.io/istio/proxy@sha256:3a9fc8a72faec478a7eca222bbb2ceec688514c95cf06ac12ab6235958c6883c "/usr/local/bin/pilot" 2 days ago Up 2 days k8s_istio-proxy_reviews-v3-8b796f-64lm8_default_b559d9ef-0dcd-11e8-8de9-0050568e45b4_0 0c10d8d594bc docker.io/istio/proxy@sha256:3a9fc8a72faec478a7eca222bbb2ceec688514c95cf06ac12ab6235958c6883c "/usr/local/bin/pilot" 2 days ago Up 2 days k8s_istio-proxy_details-v1-df5d6ff55-92jrx_default_b54d921c-0dcd-11e8-8de9-0050568e45b4_0 6134fa756f35 docker.io/istio/proxy@sha256:3a9fc8a72faec478a7eca222bbb2ceec688514c95cf06ac12ab6235958c6883c "/usr/local/bin/pilot" 2 days ago Up 2 days k8s_istio-proxy_istio-pilot-69cc4dd5cb-fglsg_istio-system_5ecf54b6-0dcd-11e8-8de9-0050568e45b4_0 9a18ea74b6bf docker.io/istio/proxy@sha256:3a9fc8a72faec478a7eca222bbb2ceec688514c95cf06ac12ab6235958c6883c "/usr/local/bin/pilot" 2 days ago Up 2 days k8s_istio-proxy_istio-mixer-69f48ddb6c-d4ww2_istio-system_5e8801ab-0dcd-11e8-8de9-0050568e45b4_0 5db18d722bb1 docker.io/istio/proxy@sha256:3a9fc8a72faec478a7eca222bbb2ceec688514c95cf06ac12ab6235958c6883c "/usr/local/bin/pilot" 2 days ago Up 2 days k8s_istio-ingress_istio-ingress-f7ff9dcfd-fl85s_istio-system_5ed6333d-0dcd-11e8-8de9-0050568e45b4_0 $ docker ps | egrep -iv "proxy|pause|kube-|etcd|defaultbackend|ingress" CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES Docker Containers for the apps (These seem to have started up without issues) ------------------------------ 61951f88b83c docker.io/istio/examples-bookinfo-reviews-v2@sha256:e390023aa6180827373293747f1bff8846ffdf19fdcd46ad91549d3277dfd4ea "/bin/sh -c '/opt/ibm" 2 days ago Up 2 days k8s_reviews_reviews-v2-678b446795-hkkvv_default_b557b5a5-0dcd-11e8-8de9-0050568e45b4_0 18d2137257c0 docker.io/istio/examples-bookinfo-productpage-v1@sha256:ce983ff8f7563e582a8ff1adaf4c08c66a44db331208e4cfe264ae9ada0c5a48 "/bin/sh -c 'python p" 2 days ago Up 2 days k8s_productpage_productpage-v1-85f65888f5-xdkt6_default_b579277b-0dcd-11e8-8de9-0050568e45b4_0 5ba97591e5c7 docker.io/istio/examples-bookinfo-reviews-v1@sha256:aac2cfc27fad662f7a4473ea549d8980eb00cd72e590749fe4186caf5abc6706 "/bin/sh -c '/opt/ibm" 2 days ago Up 2 days k8s_reviews_reviews-v1-5845b57d57-2cjvn_default_b555bb75-0dcd-11e8-8de9-0050568e45b4_0 ed11b00eff22 docker.io/istio/examples-bookinfo-reviews-v3@sha256:6829a5dfa14d10fa359708cf6c11ec9022a3d047a089e73dea3f3bfa41f7ed66 "/bin/sh -c '/opt/ibm" 2 days ago Up 2 days k8s_reviews_reviews-v3-8b796f-64lm8_default_b559d9ef-0dcd-11e8-8de9-0050568e45b4_0 be88278186c2 docker.io/istio/examples-bookinfo-ratings-v1@sha256:b14905701620fc7217c12330771cd426677bc5314661acd1b2c2aeedc5378206 "/bin/sh -c 'node rat" 2 days ago Up 2 days k8s_ratings_ratings-v1-668b7f9ddc-9nhcw_default_b55128a5-0dcd-11e8-8de9-0050568e45b4_0 e1c749eedf3c docker.io/istio/examples-bookinfo-details-v1@sha256:02c863b54d676489c7e006948e254439c63f299290d664e5c0eaf2209ee7865e "/bin/sh -c 'ruby det" 2 days ago Up 2 days k8s_details_details-v1-df5d6ff55-92jrx_default_b54d921c-0dcd-11e8-8de9-0050568e45b4_0 Docker Containers for Control Plane components ----------------------------------------------- (CA: no ssl setup done) 5847934ca3c6 docker.io/istio/istio-ca@sha256:b3aaa5e5df2c16b13ea641d9f6b21f1fa3fb01b2f36a6df5928f17815aa63307 "/usr/local/bin/istio" 2 days ago Up 2 days k8s_istio-ca_istio-ca-5796758d78-md7fl_istio-system_5ed9a9e4-0dcd-11e8-8de9-0050568e45b4_0 (PILOT: [1] W0209 19:13:58.364556 1 client_config.go:529] Neither --kubeconfig nor --master was specified. Using the inClusterConfig. This might not work.) [2] warn AvailabilityZone couldn't find the given cluster node [3] warn AvailabilityZone unexpected service-node: invalid node type (valid types: ingress, sidecar, router in the service node "mixer~~.~.svc.cluster.local" [4] warn AvailabilityZone couldn't find the given cluster node pattern 2, 3, 4 repeats) f7a7816bd147 docker.io/istio/pilot@sha256:96c2174f30d084e0ed950ea4b9332853f6cd0ace904e731e7086822af726fa2b "/usr/local/bin/pilot" 2 days ago Up 2 days k8s_discovery_istio-pilot-69cc4dd5cb-fglsg_istio-system_5ecf54b6-0dcd-11e8-8de9-0050568e45b4_0 (MIXER: W0209 19:13:57.948480 1 client_config.go:529] Neither --kubeconfig nor --master was specified. Using the inClusterConfig. This might not work.) f4c85eb7f652 docker.io/istio/mixer@sha256:a2d5f14fd55198239817b6c1dac85651ac3e124c241feab795d72d2ffa004bda "/usr/local/bin/mixs " 2 days ago Up 2 days k8s_mixer_istio-mixer-69f48ddb6c-d4ww2_istio-system_5e8801ab-0dcd-11e8-8de9-0050568e45b4_0 (STATD EXPORTER: No issues/errors) 9fa2865b7e9b docker.io/prom/statsd-exporter@sha256:d08dd0db8eaaf716089d6914ed0236a794d140f4a0fe1fd165cda3e673d1ed4c "/bin/statsd_exporter" 2 days ago Up 2 days k8s_statsd-to-prometheus_istio-mixer-69f48ddb6c-d4ww2_istio-system_5e8801ab-0dcd-11e8-8de9-0050568e45b4_0 ```
2018/02/12
[ "https://Stackoverflow.com/questions/48753297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3675410/" ]
For your example string, you could remove the `^` like: [`(?<=FN=).+?(?=&.+?$)`](https://regex101.com/r/33BiQU/1) `^` means assert the position at start of the string. For this example, you could also write this as: [`(?<=FN=)[^&]+`](https://regex101.com/r/uIORIF/1) **Explanation** * `(?<=` Positive lookbehind that asserts what is before + `FN=` Match FN# * `)` Close lookbehind * `[^&]+` Negated character set that matches not an ampersand one or more times
Instead of a regex, you could use the "proper" way of parsing the URI and the query string: ``` Imports System.Web Module Module1 Sub Main() Dim u = New Uri("https://portal-gamma.myColgate.com/sites/ENG/Pages/r.aspx?RT=Modify Support&Element=Business Direct&SE=Chain Supply&FN=Freight Forwarder Standard Operating Procedure - United Kingdom.pdf&DocID=400") Dim parts = HttpUtility.ParseQueryString(u.Query) Console.WriteLine(parts("FN")) Console.ReadLine() End Sub End Module ``` Outputs: > > Freight Forwarder Standard Operating Procedure - United Kingdom.pdf > > > You will need to add a reference in the project to System.Web if there isn't one already.
63,461,566
Currently using selenium in python and was trying to for loop after locating element by "img" tags in whole webpage. I am trying to save all the urls and img names to my 2 arrays. ``` imgurl = [] imgname = [] allimgtags = browser.find_element_by_tag_name("img") for a in len(allimgtags): imgurl.append(wholeimgtags.get_attribute("src")) imgname.append(wholeimgtags.get_attribute("alt")) ``` but i am getting this error in the terminal. How do i save the sub urls and names to my 2 arrays? ``` Traceback (most recent call last): File "scrpy_selenium.py", line 31, in <module> for a in len(wholeimgtags): TypeError: object of type 'WebElement' has no len() ```
2020/08/18
[ "https://Stackoverflow.com/questions/63461566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14082479/" ]
You can refer the below sample code: ``` class SampleAdapter(private var list: List<String>, private val viewmodel: SampleViewModel, private val lifecycleOwner: LifecycleOwner) : RecyclerView.Adapter<SampleAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding: ItemRowBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_row, parent, false) val holder= ViewHolder(binding, lifecycleOwner) binding.lifecycleOwner=holder holder.lifecycleCreate() return holder } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind() } override fun getItemCount(): Int { return list.size } override fun onViewAttachedToWindow(holder: ViewHolder) { super.onViewAttachedToWindow(holder) holder.attachToWindow() } inner class ViewHolder(private val binding: ItemRowBinding, private var lifecycleOwner: LifecycleOwner) : RecyclerView.ViewHolder(binding.root),LifecycleOwner { private val lifecycleRegistry = LifecycleRegistry(this) private var paused: Boolean = false init { lifecycleRegistry.currentState = Lifecycle.State.INITIALIZED } fun lifecycleCreate() { lifecycleRegistry.currentState = Lifecycle.State.CREATED } override fun getLifecycle(): Lifecycle { return lifecycleRegistry } fun bind() { lifecycleOwner = this@SampleAdapter.lifecycleOwner binding.viewmodel = viewmodel binding.executePendingBindings() } fun attachToWindow() { if (paused) { lifecycleRegistry.currentState = Lifecycle.State.RESUMED paused = false } else { lifecycleRegistry.currentState = Lifecycle.State.STARTED } } } fun setList(list: List<String>) { this.list = list notifyDataSetChanged() } } ``` Reason why we need to pass a lifecycle owner is because: ViewHolder is not a lifecycle owner and that is why it can not observe LiveData. The entire idea is to make Viewholder a lifecycle owner by implementing LifecycleOwner and after that start its lifecycle.
If i understand correctly from [this page](https://medium.com/@stephen.brewer/an-adventure-with-recyclerview-databinding-livedata-and-room-beaae4fc8116) it is not best to pass the `lifeCycleOwner` to a `RecyclerView.Adapter` binding item, since: > > When a ViewHolder has been > detached, meaning it is not currently visible on the screen, > parentLifecycleOwner is still in the resumed state, so the > ViewDataBindings are still active and observing the data. This means > that when a LiveData instance is updated, it triggers the View to be > updated, but the View is not currently being displayed! Not ideal. > > > Stephen Brewer seems to suggest some solutions but i did not test them
63,461,566
Currently using selenium in python and was trying to for loop after locating element by "img" tags in whole webpage. I am trying to save all the urls and img names to my 2 arrays. ``` imgurl = [] imgname = [] allimgtags = browser.find_element_by_tag_name("img") for a in len(allimgtags): imgurl.append(wholeimgtags.get_attribute("src")) imgname.append(wholeimgtags.get_attribute("alt")) ``` but i am getting this error in the terminal. How do i save the sub urls and names to my 2 arrays? ``` Traceback (most recent call last): File "scrpy_selenium.py", line 31, in <module> for a in len(wholeimgtags): TypeError: object of type 'WebElement' has no len() ```
2020/08/18
[ "https://Stackoverflow.com/questions/63461566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14082479/" ]
You can refer the below sample code: ``` class SampleAdapter(private var list: List<String>, private val viewmodel: SampleViewModel, private val lifecycleOwner: LifecycleOwner) : RecyclerView.Adapter<SampleAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding: ItemRowBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_row, parent, false) val holder= ViewHolder(binding, lifecycleOwner) binding.lifecycleOwner=holder holder.lifecycleCreate() return holder } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind() } override fun getItemCount(): Int { return list.size } override fun onViewAttachedToWindow(holder: ViewHolder) { super.onViewAttachedToWindow(holder) holder.attachToWindow() } inner class ViewHolder(private val binding: ItemRowBinding, private var lifecycleOwner: LifecycleOwner) : RecyclerView.ViewHolder(binding.root),LifecycleOwner { private val lifecycleRegistry = LifecycleRegistry(this) private var paused: Boolean = false init { lifecycleRegistry.currentState = Lifecycle.State.INITIALIZED } fun lifecycleCreate() { lifecycleRegistry.currentState = Lifecycle.State.CREATED } override fun getLifecycle(): Lifecycle { return lifecycleRegistry } fun bind() { lifecycleOwner = this@SampleAdapter.lifecycleOwner binding.viewmodel = viewmodel binding.executePendingBindings() } fun attachToWindow() { if (paused) { lifecycleRegistry.currentState = Lifecycle.State.RESUMED paused = false } else { lifecycleRegistry.currentState = Lifecycle.State.STARTED } } } fun setList(list: List<String>) { this.list = list notifyDataSetChanged() } } ``` Reason why we need to pass a lifecycle owner is because: ViewHolder is not a lifecycle owner and that is why it can not observe LiveData. The entire idea is to make Viewholder a lifecycle owner by implementing LifecycleOwner and after that start its lifecycle.
Instead of passing LifeCycleOwner to RecyclerView. Try to use `observeForever(Observer)` in case of observing data from the RecyclerView. And remove observer after the work has been done using `removeObserver(Observer)`. Refer Documentation: <https://developer.android.com/reference/androidx/lifecycle/LiveData#observeForever(androidx.lifecycle.Observer%3C?%20super%20T%3E)>
63,461,566
Currently using selenium in python and was trying to for loop after locating element by "img" tags in whole webpage. I am trying to save all the urls and img names to my 2 arrays. ``` imgurl = [] imgname = [] allimgtags = browser.find_element_by_tag_name("img") for a in len(allimgtags): imgurl.append(wholeimgtags.get_attribute("src")) imgname.append(wholeimgtags.get_attribute("alt")) ``` but i am getting this error in the terminal. How do i save the sub urls and names to my 2 arrays? ``` Traceback (most recent call last): File "scrpy_selenium.py", line 31, in <module> for a in len(wholeimgtags): TypeError: object of type 'WebElement' has no len() ```
2020/08/18
[ "https://Stackoverflow.com/questions/63461566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14082479/" ]
You can refer the below sample code: ``` class SampleAdapter(private var list: List<String>, private val viewmodel: SampleViewModel, private val lifecycleOwner: LifecycleOwner) : RecyclerView.Adapter<SampleAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding: ItemRowBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_row, parent, false) val holder= ViewHolder(binding, lifecycleOwner) binding.lifecycleOwner=holder holder.lifecycleCreate() return holder } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind() } override fun getItemCount(): Int { return list.size } override fun onViewAttachedToWindow(holder: ViewHolder) { super.onViewAttachedToWindow(holder) holder.attachToWindow() } inner class ViewHolder(private val binding: ItemRowBinding, private var lifecycleOwner: LifecycleOwner) : RecyclerView.ViewHolder(binding.root),LifecycleOwner { private val lifecycleRegistry = LifecycleRegistry(this) private var paused: Boolean = false init { lifecycleRegistry.currentState = Lifecycle.State.INITIALIZED } fun lifecycleCreate() { lifecycleRegistry.currentState = Lifecycle.State.CREATED } override fun getLifecycle(): Lifecycle { return lifecycleRegistry } fun bind() { lifecycleOwner = this@SampleAdapter.lifecycleOwner binding.viewmodel = viewmodel binding.executePendingBindings() } fun attachToWindow() { if (paused) { lifecycleRegistry.currentState = Lifecycle.State.RESUMED paused = false } else { lifecycleRegistry.currentState = Lifecycle.State.STARTED } } } fun setList(list: List<String>) { this.list = list notifyDataSetChanged() } } ``` Reason why we need to pass a lifecycle owner is because: ViewHolder is not a lifecycle owner and that is why it can not observe LiveData. The entire idea is to make Viewholder a lifecycle owner by implementing LifecycleOwner and after that start its lifecycle.
You can pass lifecycleOwner to binding in onCreateViewHolder method. ``` override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { ... binding.lifecycleOwner = parent.findViewTreeLifecycleOwner() return ViewHolder(binding) } ```
63,461,566
Currently using selenium in python and was trying to for loop after locating element by "img" tags in whole webpage. I am trying to save all the urls and img names to my 2 arrays. ``` imgurl = [] imgname = [] allimgtags = browser.find_element_by_tag_name("img") for a in len(allimgtags): imgurl.append(wholeimgtags.get_attribute("src")) imgname.append(wholeimgtags.get_attribute("alt")) ``` but i am getting this error in the terminal. How do i save the sub urls and names to my 2 arrays? ``` Traceback (most recent call last): File "scrpy_selenium.py", line 31, in <module> for a in len(wholeimgtags): TypeError: object of type 'WebElement' has no len() ```
2020/08/18
[ "https://Stackoverflow.com/questions/63461566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14082479/" ]
You can refer the below sample code: ``` class SampleAdapter(private var list: List<String>, private val viewmodel: SampleViewModel, private val lifecycleOwner: LifecycleOwner) : RecyclerView.Adapter<SampleAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding: ItemRowBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_row, parent, false) val holder= ViewHolder(binding, lifecycleOwner) binding.lifecycleOwner=holder holder.lifecycleCreate() return holder } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind() } override fun getItemCount(): Int { return list.size } override fun onViewAttachedToWindow(holder: ViewHolder) { super.onViewAttachedToWindow(holder) holder.attachToWindow() } inner class ViewHolder(private val binding: ItemRowBinding, private var lifecycleOwner: LifecycleOwner) : RecyclerView.ViewHolder(binding.root),LifecycleOwner { private val lifecycleRegistry = LifecycleRegistry(this) private var paused: Boolean = false init { lifecycleRegistry.currentState = Lifecycle.State.INITIALIZED } fun lifecycleCreate() { lifecycleRegistry.currentState = Lifecycle.State.CREATED } override fun getLifecycle(): Lifecycle { return lifecycleRegistry } fun bind() { lifecycleOwner = this@SampleAdapter.lifecycleOwner binding.viewmodel = viewmodel binding.executePendingBindings() } fun attachToWindow() { if (paused) { lifecycleRegistry.currentState = Lifecycle.State.RESUMED paused = false } else { lifecycleRegistry.currentState = Lifecycle.State.STARTED } } } fun setList(list: List<String>) { this.list = list notifyDataSetChanged() } } ``` Reason why we need to pass a lifecycle owner is because: ViewHolder is not a lifecycle owner and that is why it can not observe LiveData. The entire idea is to make Viewholder a lifecycle owner by implementing LifecycleOwner and after that start its lifecycle.
As you can get lifecycle owner from Binding in the following; ``` inner class ViewHolder(binding: List....): RecyclerView.ViewHolder(binding.root) { private val lifecycleOwner by lazy{ binding.root.context as? LifecycleOwner } } ```
63,461,566
Currently using selenium in python and was trying to for loop after locating element by "img" tags in whole webpage. I am trying to save all the urls and img names to my 2 arrays. ``` imgurl = [] imgname = [] allimgtags = browser.find_element_by_tag_name("img") for a in len(allimgtags): imgurl.append(wholeimgtags.get_attribute("src")) imgname.append(wholeimgtags.get_attribute("alt")) ``` but i am getting this error in the terminal. How do i save the sub urls and names to my 2 arrays? ``` Traceback (most recent call last): File "scrpy_selenium.py", line 31, in <module> for a in len(wholeimgtags): TypeError: object of type 'WebElement' has no len() ```
2020/08/18
[ "https://Stackoverflow.com/questions/63461566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14082479/" ]
If i understand correctly from [this page](https://medium.com/@stephen.brewer/an-adventure-with-recyclerview-databinding-livedata-and-room-beaae4fc8116) it is not best to pass the `lifeCycleOwner` to a `RecyclerView.Adapter` binding item, since: > > When a ViewHolder has been > detached, meaning it is not currently visible on the screen, > parentLifecycleOwner is still in the resumed state, so the > ViewDataBindings are still active and observing the data. This means > that when a LiveData instance is updated, it triggers the View to be > updated, but the View is not currently being displayed! Not ideal. > > > Stephen Brewer seems to suggest some solutions but i did not test them
Instead of passing LifeCycleOwner to RecyclerView. Try to use `observeForever(Observer)` in case of observing data from the RecyclerView. And remove observer after the work has been done using `removeObserver(Observer)`. Refer Documentation: <https://developer.android.com/reference/androidx/lifecycle/LiveData#observeForever(androidx.lifecycle.Observer%3C?%20super%20T%3E)>
63,461,566
Currently using selenium in python and was trying to for loop after locating element by "img" tags in whole webpage. I am trying to save all the urls and img names to my 2 arrays. ``` imgurl = [] imgname = [] allimgtags = browser.find_element_by_tag_name("img") for a in len(allimgtags): imgurl.append(wholeimgtags.get_attribute("src")) imgname.append(wholeimgtags.get_attribute("alt")) ``` but i am getting this error in the terminal. How do i save the sub urls and names to my 2 arrays? ``` Traceback (most recent call last): File "scrpy_selenium.py", line 31, in <module> for a in len(wholeimgtags): TypeError: object of type 'WebElement' has no len() ```
2020/08/18
[ "https://Stackoverflow.com/questions/63461566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14082479/" ]
If i understand correctly from [this page](https://medium.com/@stephen.brewer/an-adventure-with-recyclerview-databinding-livedata-and-room-beaae4fc8116) it is not best to pass the `lifeCycleOwner` to a `RecyclerView.Adapter` binding item, since: > > When a ViewHolder has been > detached, meaning it is not currently visible on the screen, > parentLifecycleOwner is still in the resumed state, so the > ViewDataBindings are still active and observing the data. This means > that when a LiveData instance is updated, it triggers the View to be > updated, but the View is not currently being displayed! Not ideal. > > > Stephen Brewer seems to suggest some solutions but i did not test them
You can pass lifecycleOwner to binding in onCreateViewHolder method. ``` override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { ... binding.lifecycleOwner = parent.findViewTreeLifecycleOwner() return ViewHolder(binding) } ```
63,461,566
Currently using selenium in python and was trying to for loop after locating element by "img" tags in whole webpage. I am trying to save all the urls and img names to my 2 arrays. ``` imgurl = [] imgname = [] allimgtags = browser.find_element_by_tag_name("img") for a in len(allimgtags): imgurl.append(wholeimgtags.get_attribute("src")) imgname.append(wholeimgtags.get_attribute("alt")) ``` but i am getting this error in the terminal. How do i save the sub urls and names to my 2 arrays? ``` Traceback (most recent call last): File "scrpy_selenium.py", line 31, in <module> for a in len(wholeimgtags): TypeError: object of type 'WebElement' has no len() ```
2020/08/18
[ "https://Stackoverflow.com/questions/63461566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14082479/" ]
If i understand correctly from [this page](https://medium.com/@stephen.brewer/an-adventure-with-recyclerview-databinding-livedata-and-room-beaae4fc8116) it is not best to pass the `lifeCycleOwner` to a `RecyclerView.Adapter` binding item, since: > > When a ViewHolder has been > detached, meaning it is not currently visible on the screen, > parentLifecycleOwner is still in the resumed state, so the > ViewDataBindings are still active and observing the data. This means > that when a LiveData instance is updated, it triggers the View to be > updated, but the View is not currently being displayed! Not ideal. > > > Stephen Brewer seems to suggest some solutions but i did not test them
As you can get lifecycle owner from Binding in the following; ``` inner class ViewHolder(binding: List....): RecyclerView.ViewHolder(binding.root) { private val lifecycleOwner by lazy{ binding.root.context as? LifecycleOwner } } ```
63,461,566
Currently using selenium in python and was trying to for loop after locating element by "img" tags in whole webpage. I am trying to save all the urls and img names to my 2 arrays. ``` imgurl = [] imgname = [] allimgtags = browser.find_element_by_tag_name("img") for a in len(allimgtags): imgurl.append(wholeimgtags.get_attribute("src")) imgname.append(wholeimgtags.get_attribute("alt")) ``` but i am getting this error in the terminal. How do i save the sub urls and names to my 2 arrays? ``` Traceback (most recent call last): File "scrpy_selenium.py", line 31, in <module> for a in len(wholeimgtags): TypeError: object of type 'WebElement' has no len() ```
2020/08/18
[ "https://Stackoverflow.com/questions/63461566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14082479/" ]
Instead of passing LifeCycleOwner to RecyclerView. Try to use `observeForever(Observer)` in case of observing data from the RecyclerView. And remove observer after the work has been done using `removeObserver(Observer)`. Refer Documentation: <https://developer.android.com/reference/androidx/lifecycle/LiveData#observeForever(androidx.lifecycle.Observer%3C?%20super%20T%3E)>
You can pass lifecycleOwner to binding in onCreateViewHolder method. ``` override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { ... binding.lifecycleOwner = parent.findViewTreeLifecycleOwner() return ViewHolder(binding) } ```
63,461,566
Currently using selenium in python and was trying to for loop after locating element by "img" tags in whole webpage. I am trying to save all the urls and img names to my 2 arrays. ``` imgurl = [] imgname = [] allimgtags = browser.find_element_by_tag_name("img") for a in len(allimgtags): imgurl.append(wholeimgtags.get_attribute("src")) imgname.append(wholeimgtags.get_attribute("alt")) ``` but i am getting this error in the terminal. How do i save the sub urls and names to my 2 arrays? ``` Traceback (most recent call last): File "scrpy_selenium.py", line 31, in <module> for a in len(wholeimgtags): TypeError: object of type 'WebElement' has no len() ```
2020/08/18
[ "https://Stackoverflow.com/questions/63461566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14082479/" ]
Instead of passing LifeCycleOwner to RecyclerView. Try to use `observeForever(Observer)` in case of observing data from the RecyclerView. And remove observer after the work has been done using `removeObserver(Observer)`. Refer Documentation: <https://developer.android.com/reference/androidx/lifecycle/LiveData#observeForever(androidx.lifecycle.Observer%3C?%20super%20T%3E)>
As you can get lifecycle owner from Binding in the following; ``` inner class ViewHolder(binding: List....): RecyclerView.ViewHolder(binding.root) { private val lifecycleOwner by lazy{ binding.root.context as? LifecycleOwner } } ```
32,177,869
I have several pods, for example a python web app and a redis(shared by other apps), so I need to place redis in a separate pod. But they are all use the same subnet from docker(172.17.0.0/16) or even the same ip address. how can app pods talk with redis pod? Maybe what I want ask is what's the best way to setup multi-host conainer networking. --- 7 weeks later, I get more familiar with kubernetes. I know kubernetes has network assuming that pods can access each other. so if you app service pod need to access a shared service(redis) pod, you need expose the the shared service as a kubernetes service, then you can get the shared service endpoint from app pods' environment variables or hostname.
2015/08/24
[ "https://Stackoverflow.com/questions/32177869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853876/" ]
How did you set up Kubernetes? I'm not aware of any installation scripts that put pod IPs into a 172 subnet. But in general, assuming Kubernetes has been set up properly (ideally using one of the provided scripts), using a [service object](https://github.com/kubernetes/kubernetes/blob/release-1.0/docs/user-guide/services.md) to load balance across your 1 or more redis pods would be the standard approach.
I realize maybe the question was a bit vague: if what you want is for your app to talk to the redis service, then set a service for redis (with a name of 'redis' for example) and then the redis service will be accessible simply by calling it by its hostname 'redis' check the guestbook example that sets up a Redis master + replica slaves and get connected to the php app(s) that way <https://github.com/kubernetes/kubernetes/tree/master/examples/guestbook>
32,177,869
I have several pods, for example a python web app and a redis(shared by other apps), so I need to place redis in a separate pod. But they are all use the same subnet from docker(172.17.0.0/16) or even the same ip address. how can app pods talk with redis pod? Maybe what I want ask is what's the best way to setup multi-host conainer networking. --- 7 weeks later, I get more familiar with kubernetes. I know kubernetes has network assuming that pods can access each other. so if you app service pod need to access a shared service(redis) pod, you need expose the the shared service as a kubernetes service, then you can get the shared service endpoint from app pods' environment variables or hostname.
2015/08/24
[ "https://Stackoverflow.com/questions/32177869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853876/" ]
How did you set up Kubernetes? I'm not aware of any installation scripts that put pod IPs into a 172 subnet. But in general, assuming Kubernetes has been set up properly (ideally using one of the provided scripts), using a [service object](https://github.com/kubernetes/kubernetes/blob/release-1.0/docs/user-guide/services.md) to load balance across your 1 or more redis pods would be the standard approach.
Kubernetes provides a basic service discovery mechanism by providing DNS names to the kubernetes services (which are associated with pods). When a pod wants to talk to another pod, it should use the DNS name (e.g. svc1.namespace1.svc.cluster.local)
32,177,869
I have several pods, for example a python web app and a redis(shared by other apps), so I need to place redis in a separate pod. But they are all use the same subnet from docker(172.17.0.0/16) or even the same ip address. how can app pods talk with redis pod? Maybe what I want ask is what's the best way to setup multi-host conainer networking. --- 7 weeks later, I get more familiar with kubernetes. I know kubernetes has network assuming that pods can access each other. so if you app service pod need to access a shared service(redis) pod, you need expose the the shared service as a kubernetes service, then you can get the shared service endpoint from app pods' environment variables or hostname.
2015/08/24
[ "https://Stackoverflow.com/questions/32177869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853876/" ]
When you create a service, the service will proxy the connection to the different pods. A service therefore maintains the list of IPs of the pods' containers. You can then look those up in the API they will be at ``` http(s)://${KUBERNETES_SERVICE_HOST}/api/v1/namespaces/${NAMESPACE}/endpoints/${SERVICE_NAME} ``` NAMESPACE is the name of the namespace. By default it is default, so if you didn't set a namespace in the pod replace with 'default' SERVICE\_NAME is your service name KUBERNETES\_SERVICE\_HOST is an environment variable available in your container. You will get a JSON object with containers and "ip" tags. You can then pipe the answer to a ``` grep '\"ip\"' | awk '{print $2}' | awk -F\" '{print $2}' ``` do isolate the IPs You might also need credentials to reach the https (test it with curl) in Google Cloud, credentials can be found by looking up ``` gcloud cluster-info <your-cluster-name> ``` Note: even if you don't use the service to talk to your pods, it serves the purpose of gathering the IPs for your pods. However note that these may change if the pod get rescheduled somewhere else when a node fails, the Service takes care of maintaining the up-to-date list, but your app needs to pull at intervals or set a watch on the endpoints to keep it's list up to date.
I realize maybe the question was a bit vague: if what you want is for your app to talk to the redis service, then set a service for redis (with a name of 'redis' for example) and then the redis service will be accessible simply by calling it by its hostname 'redis' check the guestbook example that sets up a Redis master + replica slaves and get connected to the php app(s) that way <https://github.com/kubernetes/kubernetes/tree/master/examples/guestbook>
32,177,869
I have several pods, for example a python web app and a redis(shared by other apps), so I need to place redis in a separate pod. But they are all use the same subnet from docker(172.17.0.0/16) or even the same ip address. how can app pods talk with redis pod? Maybe what I want ask is what's the best way to setup multi-host conainer networking. --- 7 weeks later, I get more familiar with kubernetes. I know kubernetes has network assuming that pods can access each other. so if you app service pod need to access a shared service(redis) pod, you need expose the the shared service as a kubernetes service, then you can get the shared service endpoint from app pods' environment variables or hostname.
2015/08/24
[ "https://Stackoverflow.com/questions/32177869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853876/" ]
When you create a service, the service will proxy the connection to the different pods. A service therefore maintains the list of IPs of the pods' containers. You can then look those up in the API they will be at ``` http(s)://${KUBERNETES_SERVICE_HOST}/api/v1/namespaces/${NAMESPACE}/endpoints/${SERVICE_NAME} ``` NAMESPACE is the name of the namespace. By default it is default, so if you didn't set a namespace in the pod replace with 'default' SERVICE\_NAME is your service name KUBERNETES\_SERVICE\_HOST is an environment variable available in your container. You will get a JSON object with containers and "ip" tags. You can then pipe the answer to a ``` grep '\"ip\"' | awk '{print $2}' | awk -F\" '{print $2}' ``` do isolate the IPs You might also need credentials to reach the https (test it with curl) in Google Cloud, credentials can be found by looking up ``` gcloud cluster-info <your-cluster-name> ``` Note: even if you don't use the service to talk to your pods, it serves the purpose of gathering the IPs for your pods. However note that these may change if the pod get rescheduled somewhere else when a node fails, the Service takes care of maintaining the up-to-date list, but your app needs to pull at intervals or set a watch on the endpoints to keep it's list up to date.
Kubernetes provides a basic service discovery mechanism by providing DNS names to the kubernetes services (which are associated with pods). When a pod wants to talk to another pod, it should use the DNS name (e.g. svc1.namespace1.svc.cluster.local)
32,177,869
I have several pods, for example a python web app and a redis(shared by other apps), so I need to place redis in a separate pod. But they are all use the same subnet from docker(172.17.0.0/16) or even the same ip address. how can app pods talk with redis pod? Maybe what I want ask is what's the best way to setup multi-host conainer networking. --- 7 weeks later, I get more familiar with kubernetes. I know kubernetes has network assuming that pods can access each other. so if you app service pod need to access a shared service(redis) pod, you need expose the the shared service as a kubernetes service, then you can get the shared service endpoint from app pods' environment variables or hostname.
2015/08/24
[ "https://Stackoverflow.com/questions/32177869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853876/" ]
I realize maybe the question was a bit vague: if what you want is for your app to talk to the redis service, then set a service for redis (with a name of 'redis' for example) and then the redis service will be accessible simply by calling it by its hostname 'redis' check the guestbook example that sets up a Redis master + replica slaves and get connected to the php app(s) that way <https://github.com/kubernetes/kubernetes/tree/master/examples/guestbook>
Kubernetes provides a basic service discovery mechanism by providing DNS names to the kubernetes services (which are associated with pods). When a pod wants to talk to another pod, it should use the DNS name (e.g. svc1.namespace1.svc.cluster.local)
69,602,778
I have installed the library in Base conda environment (the only one I have): ``` (base) C:\Users\44444>conda install graphviz Collecting package metadata (current_repodata.json): done Solving environment: done # All requested packages already installed. ``` Set the path in System -> Environment Variables : to both locations : where conda and where python ``` PATHs: C:\Users\44444\anaconda3\Scripts\ C:\Users\44444\anaconda3\ ``` and when I try to import the library I get the error: ``` ModuleNotFoundError: No module named 'graphviz' ``` Am I missing something please? How to import the library.
2021/10/17
[ "https://Stackoverflow.com/questions/69602778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16339433/" ]
You have only installed the `graphiz` software, not the python interface to it. For that you will need [this package](https://anaconda.org/conda-forge/python-graphviz) which you can install with ``` conda install -c conda-forge python-graphviz ```
Don't add conda's folders to the system PATH manually. What you need to do to work with Anaconda is activating the environment via ``` conda activate ``` This will add all the following folders temporarily to the PATH: ``` C:\Users\44444\anaconda3 C:\Users\44444\anaconda3\Library\mingw-w64\bin C:\Users\44444\anaconda3\Library\usr\bin C:\Users\44444\anaconda3\Library\bin C:\Users\44444\anaconda3\Scripts C:\Users\44444\anaconda3\bin ```
52,089,002
I was trying to install a plugin for tmux called powerline. I was installing some thing on brew like PyPy and python. Now when I try to open a vim file I get: ``` dyld: Library not loaded: /usr/local/opt/python/Frameworks/Python.framework/Versions/3.6/Python Referenced from: /usr/local/bin/vim Reason: image not found Abort trap: 6 ``` and when I try to open tmux i get: ``` exited ```
2018/08/30
[ "https://Stackoverflow.com/questions/52089002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9470570/" ]
`=AVERAGE.WEIGHTED(FILTER(A:A,ISNUMBER(A:A)),FILTER(B:B,ISNUMBER(A:A)))` `=SUM(FILTER(A:A*B:B / sum(FILTER(B:B,ISNUMBER(A:A))),ISNUMBER(A:A)))` `=SUM(FILTER(A:A*B:B / (sum(B:B) - SUMIF(A:A,"><", B:B)),ISNUMBER(A:A)))` case both columns contain strings, add 1 more condition for each formula: `=AVERAGE.WEIGHTED(FILTER(A:A,ISNUMBER(A:A),ISNUMBER(B:B)),FILTER(B:B,ISNUMBER(A:A), ISNUMBER(B:B)))`
So let us suppose our numbers (we hope) sit in A2:A4 and the weights are in B2:B4. In C2, place ``` =if(and(ISNUMBER(A2),isnumber(B2)),A2,"") ``` and drag that down to C4 to keep only actual numbers for which we have weights. Similarly in D2 (and drag to D4), use ``` =if(and(ISNUMBER(A2),isnumber(B2)),B2,"") ``` and in E2 (and drag to E4) we need ``` =if(and(ISNUMBER(C2),isnumber(D2)),C2*D2,"") ``` then our weighted average will be: ``` =iferror(sum(E2:E4)/sum(D2:D4)) ``` you can hide the working columns or place them in the middle of nowhere if you wish.
18,560,993
This may be a well-known question stored in some FAQ but i can't google the solution. I'm trying to write a scalar function of scalar argument but allowing for ndarray argument. The function should check its argument for domain correctness because domain violation may cause an exception. This example demonstrates what I tried to do: ``` import numpy as np def f(x): x = np.asarray(x) y = np.zeros_like(x) y[x>0.0] = 1.0/x return y print f(1.0) ``` On assigning `y[x>0.0]=...` python says `0-d arrays can't be indexed`. What's the right way to solve this execution?
2013/09/01
[ "https://Stackoverflow.com/questions/18560993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1038377/" ]
This will work fine in NumPy >= 1.9 (not released as of writing this). On previous versions you can work around by an extra `np.asarray` call: ``` x[np.asarray(x > 0)] = 0 ```
Could you call `f([1.0])` instead? Otherwise you can do: ``` x = np.asarray(x) if x.ndim == 0: x = x[..., None] ```
32,395,635
I'm very new to odoo and python and was wondering if I could get some help getting my module to load. I've been following the odoo 8 documentation very closely and can't get anything to appear in the local modules part. (Yes, I have clicked refresh/update module list). I have also made sure that I put the correct path in my odoo-server.conf file and ensured their are no clashes. Below is the code: ``` Models.py Created on 4 Sep 2015 @author: ''' # -*- coding: utf-8 -*- from openerp import models, fields, api # class test(model.Model): # _name = 'test.test' # name = fields.Char() __init__.py from . import controllers from . import models __openerp__.py file { 'name': "models", 'version': '1.0', 'depends': ['base'], 'author': "Elliot", 'category': 'Category', 'description': """ My first working module. """, 'installable': True, 'auto_install': False, 'data': [ 'templates.xml', ], 'xml': [ 'xml.xml' ], } controllers.py from openerp import http # class test_mod(http.Controller): # @http.route('/test_mod/model/', auth='public') # def index(self, **kw): # return "Hello, world" # @http.route('/test_mod/model/objects/', auth='public') # def list(self, **kw): # return http.request.render('test_mod.listing', { # 'root': '/Test_mod/Test_mod', # 'objects': http.request.env['test_mod.model'].search([]), # }) # @http.route('/test_mod/model/objects/<model("test_mod.model"):obj>/', auth= 'public') # def object(self, obj, **kw): # return http.request.render('test_mod.object', { # 'object': obj # }) and templates.xml <openerp> <data> <!-- <template id="listing"> --> <!-- <ul> --> <!-- <li t-foreach="objects" t-as="object"> --> <!-- <a t-attf-href="{{ root }}/objects/{{ object.id }}"> --> <!-- <t t-esc="object.display_name"/> --> <!-- </a> --> <!-- </li> --> <!-- </ul> --> <!-- </template> --> <!-- <template id="object"> --> <!-- <h1><t t-esc="object.display_name"/></h1> --> <!-- <dl> --> <!-- <t t-foreach="object._fields" t-as="field"> --> <!-- <dt><t t-esc="field"/></dt> --> <!-- <dd><t t-esc="object[field]"/></dd> --> <!-- </t> --> <!-- </dl> --> <!-- </template> --> </data> </openerp> ```
2015/09/04
[ "https://Stackoverflow.com/questions/32395635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5300262/" ]
I think you might have missed to include the addon directory which includes the custom module. It can be accomplished via two methods. 1. You can add to, the addons\_path directive in openerp-server.conf, (separate paths with a comma) ``` eg: addons_path = /opt/openerp/server/openerp/addons,custom_path_here ``` 2. You can use ``` --addons='addon_path', ``` if starting your server from the command line.
You need to restart your service (odoo-service).
58,506,732
**Objective**: to extract the first email from an email thread **Description**: Based on manual inspection of the emails, I realized that the next email in the email thread always starts with a set of From, Sent, To and Subject **Test Input**: ``` Hello World from: the other side of the first email from: this sent: at to: that subject: what second email from: this sent: at to: that subject: what third email from: this date: at to: that subject: what fourth email ``` **Expected output**: ``` Hello World from: the other side of the first email ``` **Failed Attempts**: Following breaks when there's a `from:` in the first email `(.*)((from:[\s\S]+?)(sent:[\s\S]+?)(to:[\s\S]+?)(subject:[\s\S]+))` Following fails when there are repeated groups of From, Sent, To and Subject `([\s\S]+)((from:(?:(?!from:)[\s\S])+?sent:(?:(?!sent:)[\s\S])+?to:(?:(?!to:)[\s\S])+?subject:(?:(?!subject:)[\s\S])+))` The second attempt [works with PCRE(PHP)](https://regex101.com/r/dw05sx/5) when an ungreedy option (flag) is selected. However, this option is not available in python and I couldn't figure out a way to make it work. [Regex101 demo](https://regex101.com/r/dw05sx/4)
2019/10/22
[ "https://Stackoverflow.com/questions/58506732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4457330/" ]
To only get the first match, you could use a capturing group and match exactly what should follow. ``` ^(.*)\r?\n\s*\r?\nfrom:.*\r?\nsent:.*\r?\nto:.*\r?\nsubject: ``` * `^` Start of string * `(.*)` Match any char except a newline 0+ times * `\r?\n\s*` Match a newline followed by 0+ times a whitespace char using `\s*` * `\r?\nfrom:.*` Match the next line starting with `from:` * `\r?\nsent:.*` Match the next line starting with `sent:` * `\r?\nto:.*` Match the next line starting with `to:` * `\r?\nsubject:.*` Match the next line starting with `subject:` Note that in the demo link the global flag `g` at the right top is not enabled. [Regex demo](https://regex101.com/r/v09eBp/1) | [Python demo](https://ideone.com/iEdbqO) If the first line can span multiple lines and if it acceptable to note cross any of the lines that start with `from:`, `sent:`, `to:` or `subject:` you could also use a negative lookahead. ``` ^(.*(?:\r?\n(?!(?:from|sent|to|subject):).*)*)\r?\n\s*\r?\nfrom:.*\r?\nsent:.*\r?\nto:.*\r?\nsubject: ``` [Regex demo](https://regex101.com/r/p33Sde/1) If there are spaces between `from`, `sent`, `to` and `subject` 0+ (`*`) whitespace characters can be matched ``` ^(.*(?:\r?\n(?!(?:from|sent|to|subject):).*)*)\r?\s*\r?\sfrom:.*\r?\s*sent:.*\r?\s*to:.*\r?\s*subject: ``` [Regex demo](https://regex101.com/r/p33Sde/2)
Maybe I am misunderstanding, but why don't you just do this: ``` re.compile(r"^.*from:\s(\w+@\w+\.\w+)") ``` This will find the first string in "email-form" (group 1) after the first "from: " at beginning of the string.
58,506,732
**Objective**: to extract the first email from an email thread **Description**: Based on manual inspection of the emails, I realized that the next email in the email thread always starts with a set of From, Sent, To and Subject **Test Input**: ``` Hello World from: the other side of the first email from: this sent: at to: that subject: what second email from: this sent: at to: that subject: what third email from: this date: at to: that subject: what fourth email ``` **Expected output**: ``` Hello World from: the other side of the first email ``` **Failed Attempts**: Following breaks when there's a `from:` in the first email `(.*)((from:[\s\S]+?)(sent:[\s\S]+?)(to:[\s\S]+?)(subject:[\s\S]+))` Following fails when there are repeated groups of From, Sent, To and Subject `([\s\S]+)((from:(?:(?!from:)[\s\S])+?sent:(?:(?!sent:)[\s\S])+?to:(?:(?!to:)[\s\S])+?subject:(?:(?!subject:)[\s\S])+))` The second attempt [works with PCRE(PHP)](https://regex101.com/r/dw05sx/5) when an ungreedy option (flag) is selected. However, this option is not available in python and I couldn't figure out a way to make it work. [Regex101 demo](https://regex101.com/r/dw05sx/4)
2019/10/22
[ "https://Stackoverflow.com/questions/58506732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4457330/" ]
To only get the first match, you could use a capturing group and match exactly what should follow. ``` ^(.*)\r?\n\s*\r?\nfrom:.*\r?\nsent:.*\r?\nto:.*\r?\nsubject: ``` * `^` Start of string * `(.*)` Match any char except a newline 0+ times * `\r?\n\s*` Match a newline followed by 0+ times a whitespace char using `\s*` * `\r?\nfrom:.*` Match the next line starting with `from:` * `\r?\nsent:.*` Match the next line starting with `sent:` * `\r?\nto:.*` Match the next line starting with `to:` * `\r?\nsubject:.*` Match the next line starting with `subject:` Note that in the demo link the global flag `g` at the right top is not enabled. [Regex demo](https://regex101.com/r/v09eBp/1) | [Python demo](https://ideone.com/iEdbqO) If the first line can span multiple lines and if it acceptable to note cross any of the lines that start with `from:`, `sent:`, `to:` or `subject:` you could also use a negative lookahead. ``` ^(.*(?:\r?\n(?!(?:from|sent|to|subject):).*)*)\r?\n\s*\r?\nfrom:.*\r?\nsent:.*\r?\nto:.*\r?\nsubject: ``` [Regex demo](https://regex101.com/r/p33Sde/1) If there are spaces between `from`, `sent`, `to` and `subject` 0+ (`*`) whitespace characters can be matched ``` ^(.*(?:\r?\n(?!(?:from|sent|to|subject):).*)*)\r?\s*\r?\sfrom:.*\r?\s*sent:.*\r?\s*to:.*\r?\s*subject: ``` [Regex demo](https://regex101.com/r/p33Sde/2)
``` import re text = """Hello World from: the other side of the first email from: this sent: at to: that subject: what second email from: this sent: at to: that subject: what third email from: this date: at to: that subject: what fourth email""" m = re.match(r'.*?(?=^from:[^\n]*\nsent:[^\n]*\nto:[^\n]*\nsubject:[^\n]*$)', text, re.MULTILINE | re.DOTALL) print(m.group(0)) ``` Prints: ``` Hello World from: the other side of the first email ```
58,506,732
**Objective**: to extract the first email from an email thread **Description**: Based on manual inspection of the emails, I realized that the next email in the email thread always starts with a set of From, Sent, To and Subject **Test Input**: ``` Hello World from: the other side of the first email from: this sent: at to: that subject: what second email from: this sent: at to: that subject: what third email from: this date: at to: that subject: what fourth email ``` **Expected output**: ``` Hello World from: the other side of the first email ``` **Failed Attempts**: Following breaks when there's a `from:` in the first email `(.*)((from:[\s\S]+?)(sent:[\s\S]+?)(to:[\s\S]+?)(subject:[\s\S]+))` Following fails when there are repeated groups of From, Sent, To and Subject `([\s\S]+)((from:(?:(?!from:)[\s\S])+?sent:(?:(?!sent:)[\s\S])+?to:(?:(?!to:)[\s\S])+?subject:(?:(?!subject:)[\s\S])+))` The second attempt [works with PCRE(PHP)](https://regex101.com/r/dw05sx/5) when an ungreedy option (flag) is selected. However, this option is not available in python and I couldn't figure out a way to make it work. [Regex101 demo](https://regex101.com/r/dw05sx/4)
2019/10/22
[ "https://Stackoverflow.com/questions/58506732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4457330/" ]
To only get the first match, you could use a capturing group and match exactly what should follow. ``` ^(.*)\r?\n\s*\r?\nfrom:.*\r?\nsent:.*\r?\nto:.*\r?\nsubject: ``` * `^` Start of string * `(.*)` Match any char except a newline 0+ times * `\r?\n\s*` Match a newline followed by 0+ times a whitespace char using `\s*` * `\r?\nfrom:.*` Match the next line starting with `from:` * `\r?\nsent:.*` Match the next line starting with `sent:` * `\r?\nto:.*` Match the next line starting with `to:` * `\r?\nsubject:.*` Match the next line starting with `subject:` Note that in the demo link the global flag `g` at the right top is not enabled. [Regex demo](https://regex101.com/r/v09eBp/1) | [Python demo](https://ideone.com/iEdbqO) If the first line can span multiple lines and if it acceptable to note cross any of the lines that start with `from:`, `sent:`, `to:` or `subject:` you could also use a negative lookahead. ``` ^(.*(?:\r?\n(?!(?:from|sent|to|subject):).*)*)\r?\n\s*\r?\nfrom:.*\r?\nsent:.*\r?\nto:.*\r?\nsubject: ``` [Regex demo](https://regex101.com/r/p33Sde/1) If there are spaces between `from`, `sent`, `to` and `subject` 0+ (`*`) whitespace characters can be matched ``` ^(.*(?:\r?\n(?!(?:from|sent|to|subject):).*)*)\r?\s*\r?\sfrom:.*\r?\s*sent:.*\r?\s*to:.*\r?\s*subject: ``` [Regex demo](https://regex101.com/r/p33Sde/2)
Normally, each email message has a `Message-id:` header that uniquely identifies that message. Messages grouped in a thread make a tree of messages, al based on the header `In-response-to:` header, that links children (responses) with parents. Your assumption can be used to link messages that lack the `Message-id:` header or the ones that lack `In-Response-to:` header, but that's infrequent, difficult to correlate and error prone. RFC-822 compliant messages can be authored by a different person than the one they are sent on behalf (fields `From:`, `Sender:`, `Resent-from:`, `Resent-Sender:`, etc.) A thorough reading of [RFC-2822](https://www.rfc-editor.org/rfc/rfc2822) is suggested, in order to know how to manage or archive internet mail messages. The `Message-id:` and `In-Response-To:` headers are in the RFC-822 definition of an internet message format, and have been conserved in the later updates to those RFCs. It is the right way to proceed to group messages and answers. It has been included also in the update done in RFC-2822, so the use of those headers should sound mandatory to link messages in conversation threads. It is used also in NNTP (news) messages, and almmost any mail reader uses them.
34,998,210
How do I pip install pattern packages in python 3.5? While in CMD: ``` pip install pattern syntaxerror: missing parentheses in call to 'print' ``` Shows error: ``` messageCommand "python setup.py egg_info" failed with error code 1 in temp\pip-build-3uegov4d\pattern ``` `seaborn` and `tweepy` were all successful. How can I solve this problem?
2016/01/25
[ "https://Stackoverflow.com/questions/34998210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5818150/" ]
The short answer at the moment is - you can't. They haven't quite finished the port to python3 yet. There is alleged compatibility in the development branch but the recommended manual setup didn't work for me (in virtualenv) - it fails in a different way. <https://github.com/clips/pattern/tree/development> The porting issue thread is here, spanning 2013 to yesterday: <https://github.com/clips/pattern/issues/62> The official A contributing port repo is here, but it's not finished yet (the readme says there is no Python3 support). <https://github.com/pattern3/pattern> So you could try `pip install pattern3` which does install it - but it has a different package name, so you would have to modify any references to it. For me this is "impossible" as it's required by other 3rd party packages like GenSim. UPDATE I did get it working in the end in Python3 with Gensim, by manually installing it from the development branch as suggested and fixing up a few problems both during install and execution. (I removed the mysql-client dependency as the installer isn't working on Mac. I manually downloaded the certs for the NTLK wordnet corpus, to fix an SSL error in the setup. I also fixed a couple of scripts which were erroring, e.g. an empty 'try' clause in tree.py). It has a huge set of dependencies! After reading more on the port activity, it seems they're almost finished and should release in a few months (perhaps early 2018). Furthermore the pattern3 repository is more of a "friend" than the official Python3 fork. They have already pulled the changes from this contributor into the main repo and they are preparing to get it released. Therefore it should become available on `pip` in the main `pattern` package (not the pattern3 one which I presume will be removed), and there should be no package name-change problems.
Additionally, I was facing : ``` "BadZipFile: File is not a zip file" error while importing from pattern. ``` This is because `sentiwordnet` which is out of date in nltk. So comment it in : ``` C:\Anaconda3\Lib\site-packages\Pattern-2.6-py3.5.egg\pattern\text\en\wordnet\_init.py ``` Make sure the necessary corpora are downloaded to the local drive for token in ("wordnet", "wordnet\_ic"): , "sentiwordnet" try: ``` nltk.data.find("corpora/" + token) ```
34,998,210
How do I pip install pattern packages in python 3.5? While in CMD: ``` pip install pattern syntaxerror: missing parentheses in call to 'print' ``` Shows error: ``` messageCommand "python setup.py egg_info" failed with error code 1 in temp\pip-build-3uegov4d\pattern ``` `seaborn` and `tweepy` were all successful. How can I solve this problem?
2016/01/25
[ "https://Stackoverflow.com/questions/34998210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5818150/" ]
As of writing, Python 3.6 support is still not merged with master. However, it is available in the python3 branch. To install via pip: ``` pip install https://github.com/clips/pattern/archive/python3.zip ``` Note that ThReSholD's answer for Python 3 (pattern3) is for a: [deprecated pattern3 repository which contains a completely different code base that is not maintained anymore](https://github.com/clips/pattern/issues/62#issuecomment-370766376)
Additionally, I was facing : ``` "BadZipFile: File is not a zip file" error while importing from pattern. ``` This is because `sentiwordnet` which is out of date in nltk. So comment it in : ``` C:\Anaconda3\Lib\site-packages\Pattern-2.6-py3.5.egg\pattern\text\en\wordnet\_init.py ``` Make sure the necessary corpora are downloaded to the local drive for token in ("wordnet", "wordnet\_ic"): , "sentiwordnet" try: ``` nltk.data.find("corpora/" + token) ```
34,998,210
How do I pip install pattern packages in python 3.5? While in CMD: ``` pip install pattern syntaxerror: missing parentheses in call to 'print' ``` Shows error: ``` messageCommand "python setup.py egg_info" failed with error code 1 in temp\pip-build-3uegov4d\pattern ``` `seaborn` and `tweepy` were all successful. How can I solve this problem?
2016/01/25
[ "https://Stackoverflow.com/questions/34998210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5818150/" ]
**pip install pattern3** - Python 3.x **pip install pattern** - Python 2.7.x
In the upgrade from python 2.x to 3.x, the print statement was made into a function call rather than a keyword. What used to be the line `print "Hello world!"` is now the line `print("Hello world!")`. So now all code written for 2.x that prints to the console does not work in version 3.x, as the compiler hits a runtime error on the print statement. There are really only two fixes to this problem: Use version 2.x instead, or find a library built for version 3.x.
34,998,210
How do I pip install pattern packages in python 3.5? While in CMD: ``` pip install pattern syntaxerror: missing parentheses in call to 'print' ``` Shows error: ``` messageCommand "python setup.py egg_info" failed with error code 1 in temp\pip-build-3uegov4d\pattern ``` `seaborn` and `tweepy` were all successful. How can I solve this problem?
2016/01/25
[ "https://Stackoverflow.com/questions/34998210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5818150/" ]
**pip install pattern3** - Python 3.x **pip install pattern** - Python 2.7.x
Additionally, I was facing : ``` "BadZipFile: File is not a zip file" error while importing from pattern. ``` This is because `sentiwordnet` which is out of date in nltk. So comment it in : ``` C:\Anaconda3\Lib\site-packages\Pattern-2.6-py3.5.egg\pattern\text\en\wordnet\_init.py ``` Make sure the necessary corpora are downloaded to the local drive for token in ("wordnet", "wordnet\_ic"): , "sentiwordnet" try: ``` nltk.data.find("corpora/" + token) ```
34,998,210
How do I pip install pattern packages in python 3.5? While in CMD: ``` pip install pattern syntaxerror: missing parentheses in call to 'print' ``` Shows error: ``` messageCommand "python setup.py egg_info" failed with error code 1 in temp\pip-build-3uegov4d\pattern ``` `seaborn` and `tweepy` were all successful. How can I solve this problem?
2016/01/25
[ "https://Stackoverflow.com/questions/34998210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5818150/" ]
The short answer at the moment is - you can't. They haven't quite finished the port to python3 yet. There is alleged compatibility in the development branch but the recommended manual setup didn't work for me (in virtualenv) - it fails in a different way. <https://github.com/clips/pattern/tree/development> The porting issue thread is here, spanning 2013 to yesterday: <https://github.com/clips/pattern/issues/62> The official A contributing port repo is here, but it's not finished yet (the readme says there is no Python3 support). <https://github.com/pattern3/pattern> So you could try `pip install pattern3` which does install it - but it has a different package name, so you would have to modify any references to it. For me this is "impossible" as it's required by other 3rd party packages like GenSim. UPDATE I did get it working in the end in Python3 with Gensim, by manually installing it from the development branch as suggested and fixing up a few problems both during install and execution. (I removed the mysql-client dependency as the installer isn't working on Mac. I manually downloaded the certs for the NTLK wordnet corpus, to fix an SSL error in the setup. I also fixed a couple of scripts which were erroring, e.g. an empty 'try' clause in tree.py). It has a huge set of dependencies! After reading more on the port activity, it seems they're almost finished and should release in a few months (perhaps early 2018). Furthermore the pattern3 repository is more of a "friend" than the official Python3 fork. They have already pulled the changes from this contributor into the main repo and they are preparing to get it released. Therefore it should become available on `pip` in the main `pattern` package (not the pattern3 one which I presume will be removed), and there should be no package name-change problems.
In the upgrade from python 2.x to 3.x, the print statement was made into a function call rather than a keyword. What used to be the line `print "Hello world!"` is now the line `print("Hello world!")`. So now all code written for 2.x that prints to the console does not work in version 3.x, as the compiler hits a runtime error on the print statement. There are really only two fixes to this problem: Use version 2.x instead, or find a library built for version 3.x.
34,998,210
How do I pip install pattern packages in python 3.5? While in CMD: ``` pip install pattern syntaxerror: missing parentheses in call to 'print' ``` Shows error: ``` messageCommand "python setup.py egg_info" failed with error code 1 in temp\pip-build-3uegov4d\pattern ``` `seaborn` and `tweepy` were all successful. How can I solve this problem?
2016/01/25
[ "https://Stackoverflow.com/questions/34998210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5818150/" ]
**pip install pattern3** - Python 3.x **pip install pattern** - Python 2.7.x
The short answer at the moment is - you can't. They haven't quite finished the port to python3 yet. There is alleged compatibility in the development branch but the recommended manual setup didn't work for me (in virtualenv) - it fails in a different way. <https://github.com/clips/pattern/tree/development> The porting issue thread is here, spanning 2013 to yesterday: <https://github.com/clips/pattern/issues/62> The official A contributing port repo is here, but it's not finished yet (the readme says there is no Python3 support). <https://github.com/pattern3/pattern> So you could try `pip install pattern3` which does install it - but it has a different package name, so you would have to modify any references to it. For me this is "impossible" as it's required by other 3rd party packages like GenSim. UPDATE I did get it working in the end in Python3 with Gensim, by manually installing it from the development branch as suggested and fixing up a few problems both during install and execution. (I removed the mysql-client dependency as the installer isn't working on Mac. I manually downloaded the certs for the NTLK wordnet corpus, to fix an SSL error in the setup. I also fixed a couple of scripts which were erroring, e.g. an empty 'try' clause in tree.py). It has a huge set of dependencies! After reading more on the port activity, it seems they're almost finished and should release in a few months (perhaps early 2018). Furthermore the pattern3 repository is more of a "friend" than the official Python3 fork. They have already pulled the changes from this contributor into the main repo and they are preparing to get it released. Therefore it should become available on `pip` in the main `pattern` package (not the pattern3 one which I presume will be removed), and there should be no package name-change problems.
34,998,210
How do I pip install pattern packages in python 3.5? While in CMD: ``` pip install pattern syntaxerror: missing parentheses in call to 'print' ``` Shows error: ``` messageCommand "python setup.py egg_info" failed with error code 1 in temp\pip-build-3uegov4d\pattern ``` `seaborn` and `tweepy` were all successful. How can I solve this problem?
2016/01/25
[ "https://Stackoverflow.com/questions/34998210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5818150/" ]
**pip install pattern3** - Python 3.x **pip install pattern** - Python 2.7.x
Using Windows Subsystem for Linux, I made pattern to work using conda from (miniconda) in Python 3.6: ----------- ```sh conda create -n test -c conda-forge python=3.7 pattern conda activate test ``` works without issues Python 3.7: ----------- ```sh conda create -n test -c conda-forge python=3.7 pattern conda activate test ``` I discovered that there is a bug with StopInteration due to PEP-479, and [replacing](https://github.com/clips/pattern/pull/251/files) `raise StopIteration` with `return` in `pattern\text\__init__.py` fixes it. To find the location if the file, I executed ``` cd $(python -c "from distutils.sysconfig import get_python_lib;print(get_python_lib())") nano pattern/text/__init__.py ``` [Line 605](https://github.com/clips/pattern/pull/251/files), just above `class Lexicon(lazydict): ...` replace `raise StopIteration` with `return`. And all is working fine. [![enter image description here](https://i.stack.imgur.com/p4r8L.png)](https://i.stack.imgur.com/p4r8L.png)
34,998,210
How do I pip install pattern packages in python 3.5? While in CMD: ``` pip install pattern syntaxerror: missing parentheses in call to 'print' ``` Shows error: ``` messageCommand "python setup.py egg_info" failed with error code 1 in temp\pip-build-3uegov4d\pattern ``` `seaborn` and `tweepy` were all successful. How can I solve this problem?
2016/01/25
[ "https://Stackoverflow.com/questions/34998210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5818150/" ]
The short answer at the moment is - you can't. They haven't quite finished the port to python3 yet. There is alleged compatibility in the development branch but the recommended manual setup didn't work for me (in virtualenv) - it fails in a different way. <https://github.com/clips/pattern/tree/development> The porting issue thread is here, spanning 2013 to yesterday: <https://github.com/clips/pattern/issues/62> The official A contributing port repo is here, but it's not finished yet (the readme says there is no Python3 support). <https://github.com/pattern3/pattern> So you could try `pip install pattern3` which does install it - but it has a different package name, so you would have to modify any references to it. For me this is "impossible" as it's required by other 3rd party packages like GenSim. UPDATE I did get it working in the end in Python3 with Gensim, by manually installing it from the development branch as suggested and fixing up a few problems both during install and execution. (I removed the mysql-client dependency as the installer isn't working on Mac. I manually downloaded the certs for the NTLK wordnet corpus, to fix an SSL error in the setup. I also fixed a couple of scripts which were erroring, e.g. an empty 'try' clause in tree.py). It has a huge set of dependencies! After reading more on the port activity, it seems they're almost finished and should release in a few months (perhaps early 2018). Furthermore the pattern3 repository is more of a "friend" than the official Python3 fork. They have already pulled the changes from this contributor into the main repo and they are preparing to get it released. Therefore it should become available on `pip` in the main `pattern` package (not the pattern3 one which I presume will be removed), and there should be no package name-change problems.
Using Windows Subsystem for Linux, I made pattern to work using conda from (miniconda) in Python 3.6: ----------- ```sh conda create -n test -c conda-forge python=3.7 pattern conda activate test ``` works without issues Python 3.7: ----------- ```sh conda create -n test -c conda-forge python=3.7 pattern conda activate test ``` I discovered that there is a bug with StopInteration due to PEP-479, and [replacing](https://github.com/clips/pattern/pull/251/files) `raise StopIteration` with `return` in `pattern\text\__init__.py` fixes it. To find the location if the file, I executed ``` cd $(python -c "from distutils.sysconfig import get_python_lib;print(get_python_lib())") nano pattern/text/__init__.py ``` [Line 605](https://github.com/clips/pattern/pull/251/files), just above `class Lexicon(lazydict): ...` replace `raise StopIteration` with `return`. And all is working fine. [![enter image description here](https://i.stack.imgur.com/p4r8L.png)](https://i.stack.imgur.com/p4r8L.png)
34,998,210
How do I pip install pattern packages in python 3.5? While in CMD: ``` pip install pattern syntaxerror: missing parentheses in call to 'print' ``` Shows error: ``` messageCommand "python setup.py egg_info" failed with error code 1 in temp\pip-build-3uegov4d\pattern ``` `seaborn` and `tweepy` were all successful. How can I solve this problem?
2016/01/25
[ "https://Stackoverflow.com/questions/34998210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5818150/" ]
The short answer at the moment is - you can't. They haven't quite finished the port to python3 yet. There is alleged compatibility in the development branch but the recommended manual setup didn't work for me (in virtualenv) - it fails in a different way. <https://github.com/clips/pattern/tree/development> The porting issue thread is here, spanning 2013 to yesterday: <https://github.com/clips/pattern/issues/62> The official A contributing port repo is here, but it's not finished yet (the readme says there is no Python3 support). <https://github.com/pattern3/pattern> So you could try `pip install pattern3` which does install it - but it has a different package name, so you would have to modify any references to it. For me this is "impossible" as it's required by other 3rd party packages like GenSim. UPDATE I did get it working in the end in Python3 with Gensim, by manually installing it from the development branch as suggested and fixing up a few problems both during install and execution. (I removed the mysql-client dependency as the installer isn't working on Mac. I manually downloaded the certs for the NTLK wordnet corpus, to fix an SSL error in the setup. I also fixed a couple of scripts which were erroring, e.g. an empty 'try' clause in tree.py). It has a huge set of dependencies! After reading more on the port activity, it seems they're almost finished and should release in a few months (perhaps early 2018). Furthermore the pattern3 repository is more of a "friend" than the official Python3 fork. They have already pulled the changes from this contributor into the main repo and they are preparing to get it released. Therefore it should become available on `pip` in the main `pattern` package (not the pattern3 one which I presume will be removed), and there should be no package name-change problems.
For Mac OS: ``` brew install mysql export PATH=$PATH:/usr/local/mysql/bin pip3 install mysql-connector pip3 install https://github.com/clips/pattern/archive/python3.zip ```
34,998,210
How do I pip install pattern packages in python 3.5? While in CMD: ``` pip install pattern syntaxerror: missing parentheses in call to 'print' ``` Shows error: ``` messageCommand "python setup.py egg_info" failed with error code 1 in temp\pip-build-3uegov4d\pattern ``` `seaborn` and `tweepy` were all successful. How can I solve this problem?
2016/01/25
[ "https://Stackoverflow.com/questions/34998210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5818150/" ]
For Mac OS: ``` brew install mysql export PATH=$PATH:/usr/local/mysql/bin pip3 install mysql-connector pip3 install https://github.com/clips/pattern/archive/python3.zip ```
Additionally, I was facing : ``` "BadZipFile: File is not a zip file" error while importing from pattern. ``` This is because `sentiwordnet` which is out of date in nltk. So comment it in : ``` C:\Anaconda3\Lib\site-packages\Pattern-2.6-py3.5.egg\pattern\text\en\wordnet\_init.py ``` Make sure the necessary corpora are downloaded to the local drive for token in ("wordnet", "wordnet\_ic"): , "sentiwordnet" try: ``` nltk.data.find("corpora/" + token) ```
8,891,099
I seem to have stumbled across a quirk in Django custom model fields. I have the following custom modelfield: ``` class PriceField(models.DecimalField): __metaclass__ = models.SubfieldBase def to_python(self, value): try: return Price(super(PriceField, self).to_python(value)) except (TypeError, AttributeError): return None def get_db_prep_value(self, value): return super(PriceField, self).get_db_prep_value(value.d if value else value) def value_to_string(self, instance): return 'blah' ``` Which should always return the custom Price class in python. This works as expected: ``` >>> PricePoint.objects.all()[0].price Price('1.00') ``` However when retrieving prices in the form of a values\_list I get decimals back: ``` >>> PricePoint.objects.all().values_list('price') [(Decimal('1'),)] ``` Then if I change the DB type to foat and try again I get a float: ``` >>> PricePoint.objects.all().values_list('price') [(1.0,)] >>> type(PricePoint.objects.all().values_list('price')[0][0]) <type 'float'> ``` This makes me think that values\_list does not rely on to\_python at all and instead just returns the type as defined in the database. Is that correct? Is there any way to return a custom type through values\_list?
2012/01/17
[ "https://Stackoverflow.com/questions/8891099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/836049/" ]
Answered my own question: This apparently is a Django bug. values\_list does not deserialize the database data. It's being tracked here: <https://code.djangoproject.com/ticket/9619> and is pending a design decision.
Just to note that this was resolved in Django 1.8 with the addition of the `from_db_value` method on custom fields. See <https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/#converting-values-to-python-objects>