qid
int64
1
74.6M
question
stringlengths
45
24.2k
date
stringlengths
10
10
metadata
stringlengths
101
178
response_j
stringlengths
32
23.2k
response_k
stringlengths
21
13.2k
55,409,656
I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset I have some error in my code I don't know who I can fix it. code: [enter image description here][1] [enter image description here][2]
2019/03/29
['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']
Combining the methods from Pankaj Sharma and Jean Monet, I wrote the following snippet that acts as asyncio.run (with slightly different syntax), but also works within a Jupyter notebook. ``` class RunThread(threading.Thread): def __init__(self, func, args, kwargs): self.func = func self.args = args self.kwargs = kwargs self.result = None super().__init__() def run(self): self.result = asyncio.run(self.func(*self.args, **self.kwargs)) def run_async(func, *args, **kwargs): try: loop = asyncio.get_running_loop() except RuntimeError: loop = None if loop and loop.is_running(): thread = RunThread(func, args, kwargs) thread.start() thread.join() return thread.result else: return asyncio.run(func(*args, **kwargs)) ``` Usage: ``` async def test(name): await asyncio.sleep(5) return f"hello {name}" run_async(test, "user") # blocks for 5 seconds and returns "hello user" ```
I found the [`unsync`](https://github.com/alex-sherman/unsync) package useful for writing code that behaves the same way in a Python script and the Jupyter REPL. ```py import asyncio from unsync import unsync @unsync async def demo_async_fn(): await asyncio.sleep(0.1) return "done!" print(demo_async_fn().result()) ```
55,409,656
I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset I have some error in my code I don't know who I can fix it. code: [enter image description here][1] [enter image description here][2]
2019/03/29
['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']
Just use this: <https://github.com/erdewit/nest_asyncio> ``` import nest_asyncio nest_asyncio.apply() ```
Combining the methods from Pankaj Sharma and Jean Monet, I wrote the following snippet that acts as asyncio.run (with slightly different syntax), but also works within a Jupyter notebook. ``` class RunThread(threading.Thread): def __init__(self, func, args, kwargs): self.func = func self.args = args self.kwargs = kwargs self.result = None super().__init__() def run(self): self.result = asyncio.run(self.func(*self.args, **self.kwargs)) def run_async(func, *args, **kwargs): try: loop = asyncio.get_running_loop() except RuntimeError: loop = None if loop and loop.is_running(): thread = RunThread(func, args, kwargs) thread.start() thread.join() return thread.result else: return asyncio.run(func(*args, **kwargs)) ``` Usage: ``` async def test(name): await asyncio.sleep(5) return f"hello {name}" run_async(test, "user") # blocks for 5 seconds and returns "hello user" ```
55,409,656
I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset I have some error in my code I don't know who I can fix it. code: [enter image description here][1] [enter image description here][2]
2019/03/29
['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']
The [`asyncio.run()`](https://docs.python.org/3.7/library/asyncio-task.html#asyncio.run) documentation says: > > This function [cannot](https://github.com/python/cpython/blob/3.8/Lib/asyncio/runners.py#L32-L34) be called when another asyncio event loop is running in the same thread. > > > In your case, jupyter ([IPython ≥ 7.0](https://blog.jupyter.org/ipython-7-0-async-repl-a35ce050f7f7)) is already running an event loop: > > You can now use async/await at the top level in the IPython terminal and in the notebook, it should — in most of the cases — “just work”. Update IPython to version 7+, IPykernel to version 5+, and you’re off to the races. > > > Therefore you don't need to start the event loop yourself and can instead call `await main(url)` directly, even if your code lies outside any asynchronous function. **Jupyter / IPython** ```py async def main(): print(1) await main() ``` **Python (≥ 3.7) or older versions of IPython** ```py import asyncio async def main(): print(1) asyncio.run(main()) ``` In your code that would give: ```py url = ['url1', 'url2'] result = await main(url) for text in result: pass # text contains your html (text) response ``` **Caution** There is a [slight difference](https://ipython.readthedocs.io/en/stable/interactive/autoawait.html#difference-between-terminal-ipython-and-ipykernel) on how Jupyter uses the loop compared to IPython.
Combining the methods from Pankaj Sharma and Jean Monet, I wrote the following snippet that acts as asyncio.run (with slightly different syntax), but also works within a Jupyter notebook. ``` class RunThread(threading.Thread): def __init__(self, func, args, kwargs): self.func = func self.args = args self.kwargs = kwargs self.result = None super().__init__() def run(self): self.result = asyncio.run(self.func(*self.args, **self.kwargs)) def run_async(func, *args, **kwargs): try: loop = asyncio.get_running_loop() except RuntimeError: loop = None if loop and loop.is_running(): thread = RunThread(func, args, kwargs) thread.start() thread.join() return thread.result else: return asyncio.run(func(*args, **kwargs)) ``` Usage: ``` async def test(name): await asyncio.sleep(5) return f"hello {name}" run_async(test, "user") # blocks for 5 seconds and returns "hello user" ```
55,409,656
I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset I have some error in my code I don't know who I can fix it. code: [enter image description here][1] [enter image description here][2]
2019/03/29
['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']
The [`asyncio.run()`](https://docs.python.org/3.7/library/asyncio-task.html#asyncio.run) documentation says: > > This function [cannot](https://github.com/python/cpython/blob/3.8/Lib/asyncio/runners.py#L32-L34) be called when another asyncio event loop is running in the same thread. > > > In your case, jupyter ([IPython ≥ 7.0](https://blog.jupyter.org/ipython-7-0-async-repl-a35ce050f7f7)) is already running an event loop: > > You can now use async/await at the top level in the IPython terminal and in the notebook, it should — in most of the cases — “just work”. Update IPython to version 7+, IPykernel to version 5+, and you’re off to the races. > > > Therefore you don't need to start the event loop yourself and can instead call `await main(url)` directly, even if your code lies outside any asynchronous function. **Jupyter / IPython** ```py async def main(): print(1) await main() ``` **Python (≥ 3.7) or older versions of IPython** ```py import asyncio async def main(): print(1) asyncio.run(main()) ``` In your code that would give: ```py url = ['url1', 'url2'] result = await main(url) for text in result: pass # text contains your html (text) response ``` **Caution** There is a [slight difference](https://ipython.readthedocs.io/en/stable/interactive/autoawait.html#difference-between-terminal-ipython-and-ipykernel) on how Jupyter uses the loop compared to IPython.
Just use this: <https://github.com/erdewit/nest_asyncio> ``` import nest_asyncio nest_asyncio.apply() ```
55,409,656
I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset I have some error in my code I don't know who I can fix it. code: [enter image description here][1] [enter image description here][2]
2019/03/29
['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']
Combining the methods from Pankaj Sharma and Jean Monet, I wrote the following snippet that acts as asyncio.run (with slightly different syntax), but also works within a Jupyter notebook. ``` class RunThread(threading.Thread): def __init__(self, func, args, kwargs): self.func = func self.args = args self.kwargs = kwargs self.result = None super().__init__() def run(self): self.result = asyncio.run(self.func(*self.args, **self.kwargs)) def run_async(func, *args, **kwargs): try: loop = asyncio.get_running_loop() except RuntimeError: loop = None if loop and loop.is_running(): thread = RunThread(func, args, kwargs) thread.start() thread.join() return thread.result else: return asyncio.run(func(*args, **kwargs)) ``` Usage: ``` async def test(name): await asyncio.sleep(5) return f"hello {name}" run_async(test, "user") # blocks for 5 seconds and returns "hello user" ```
As cglacet mentioned that documentation says > > This function cannot be called when another asyncio event loop is > running in the same thread. > > > You can use another thread i.e - ``` class ResolveThread(threading.Thread): def __init__(self,result1,fun,url): self.result1= result1 self.fun = fun self.url = url threading.Thread.__init__(self) def run(self): result1[0] = asyncio.run(self.fun(self.url)) result1 = [None] sp = ResolveThread(result1) sp.start() sp.join() # connect main thread result = result1[0] ```
55,409,656
I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset I have some error in my code I don't know who I can fix it. code: [enter image description here][1] [enter image description here][2]
2019/03/29
['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']
The [`asyncio.run()`](https://docs.python.org/3.7/library/asyncio-task.html#asyncio.run) documentation says: > > This function [cannot](https://github.com/python/cpython/blob/3.8/Lib/asyncio/runners.py#L32-L34) be called when another asyncio event loop is running in the same thread. > > > In your case, jupyter ([IPython ≥ 7.0](https://blog.jupyter.org/ipython-7-0-async-repl-a35ce050f7f7)) is already running an event loop: > > You can now use async/await at the top level in the IPython terminal and in the notebook, it should — in most of the cases — “just work”. Update IPython to version 7+, IPykernel to version 5+, and you’re off to the races. > > > Therefore you don't need to start the event loop yourself and can instead call `await main(url)` directly, even if your code lies outside any asynchronous function. **Jupyter / IPython** ```py async def main(): print(1) await main() ``` **Python (≥ 3.7) or older versions of IPython** ```py import asyncio async def main(): print(1) asyncio.run(main()) ``` In your code that would give: ```py url = ['url1', 'url2'] result = await main(url) for text in result: pass # text contains your html (text) response ``` **Caution** There is a [slight difference](https://ipython.readthedocs.io/en/stable/interactive/autoawait.html#difference-between-terminal-ipython-and-ipykernel) on how Jupyter uses the loop compared to IPython.
As cglacet mentioned that documentation says > > This function cannot be called when another asyncio event loop is > running in the same thread. > > > You can use another thread i.e - ``` class ResolveThread(threading.Thread): def __init__(self,result1,fun,url): self.result1= result1 self.fun = fun self.url = url threading.Thread.__init__(self) def run(self): result1[0] = asyncio.run(self.fun(self.url)) result1 = [None] sp = ResolveThread(result1) sp.start() sp.join() # connect main thread result = result1[0] ```
55,409,656
I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset I have some error in my code I don't know who I can fix it. code: [enter image description here][1] [enter image description here][2]
2019/03/29
['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']
To add to `cglacet`'s answer - if one wants to detect whether a loop is running and adjust automatically (ie run `main()` on the existing loop, otherwise `asyncio.run()`), here is a snippet that may prove useful: ```py # async def main(): # ... try: loop = asyncio.get_running_loop() except RuntimeError: # 'RuntimeError: There is no current event loop...' loop = None if loop and loop.is_running(): print('Async event loop already running. Adding coroutine to the event loop.') tsk = loop.create_task(main()) # ^-- https://docs.python.org/3/library/asyncio-task.html#task-object # Optionally, a callback function can be executed when the coroutine completes tsk.add_done_callback( lambda t: print(f'Task done with result={t.result()} << return val of main()')) else: print('Starting new event loop') result = asyncio.run(main()) ```
Combining the methods from Pankaj Sharma and Jean Monet, I wrote the following snippet that acts as asyncio.run (with slightly different syntax), but also works within a Jupyter notebook. ``` class RunThread(threading.Thread): def __init__(self, func, args, kwargs): self.func = func self.args = args self.kwargs = kwargs self.result = None super().__init__() def run(self): self.result = asyncio.run(self.func(*self.args, **self.kwargs)) def run_async(func, *args, **kwargs): try: loop = asyncio.get_running_loop() except RuntimeError: loop = None if loop and loop.is_running(): thread = RunThread(func, args, kwargs) thread.start() thread.join() return thread.result else: return asyncio.run(func(*args, **kwargs)) ``` Usage: ``` async def test(name): await asyncio.sleep(5) return f"hello {name}" run_async(test, "user") # blocks for 5 seconds and returns "hello user" ```
11,422,517
I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. ``` product color size ------- ------- ------- id id id unique_id id_product (FK from product) id_product (FK from version) stock unique_id id_version (FK from version) title stock unique_id stock ``` The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: ``` select title, stock from product where unique_id = 10 UNION select p.title, c.stock from color c join product p on c.id_product = p.id where c.unique_id = 10 UNION select p.title, s.stock from size s join product p on s.id_product = p.id where s.unique_id = 10; ``` Is there a better way to do this? Thanks for any suggestion! **EDIT 1** Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: 1) As `unique_id` has indexes in all tables, i will get a good performance 2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join ``` SELECT p.title, ps.stock FROM ( select id as id_product, stock from product where unique_id = 10 UNION select id_product, stock from color where unique_id = 10 UNION select id_product, stock from size where unique_id = 10 ) AS ps JOIN product p ON ps.id_product = p.id; ```
2012/07/10
['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']
### PL/pgSQL function To solve the problem at hand, a plpgsql function like the following should be faster: ``` CREATE OR REPLACE FUNCTION func(int) RETURNS TABLE (title text, stock int) LANGUAGE plpgsql AS $BODY$ BEGIN RETURN QUERY SELECT p.title, p.stock FROM product p WHERE p.unique_id = $1; -- Put the most likely table first. IF NOT FOUND THEN RETURN QUERY SELECT p.title, c.stock FROM color c JOIN product p ON c.id_product = p.id WHERE c.unique_id = $1; END; IF NOT FOUND THEN RETURN QUERY SELECT p.title, s.stock FROM size s JOIN product p ON s.id_product = p.id WHERE s.unique_id = $1; END IF; END; $BODY$; ``` Updated function with table-qualified column names to avoid naming conflicts with `OUT` parameters. `RETURNS TABLE` requires PostgreSQL 8.4, `RETURN QUERY` requires version 8.2. You can substitute both for older versions. It goes without saying that you need to **index** the columns `unique_id` of every involved table. `id` should be indexed automatically, being the primary key. --- ### Redesign Ideally, you can tell which table from the ID alone. You could keep using one common sequence, but add `100000000` for the first table, `200000000` for the second and `300000000` for the third - or whatever suits your needs. This way, the least significant part of the number is easily distinguishable. A plain integer spans numbers from -2147483648 to +2147483647, move to [`bigint`](http://www.postgresql.org/docs/current/interactive/datatype-numeric.html#DATATYPE-INT) if that's not enough for you. I would stick to `integer` IDs, though, if possible. They are smaller and faster than `bigint` or `text`. --- ### CTEs (experimental!) If you cannot create a function for some reason, this pure SQL solution might do a similar trick: ``` WITH x(uid) AS (SELECT 10) -- provide unique_id here , a AS ( SELECT title, stock FROM x, product WHERE unique_id = x.uid ) , b AS ( SELECT p.title, c.stock FROM x, color c JOIN product p ON c.id_product = p.id WHERE NOT EXISTS (SELECT 1 FROM a) AND c.unique_id = x.uid ) , c AS ( SELECT p.title, s.stock FROM x, size s JOIN product p ON s.id_product = p.id WHERE NOT EXISTS (SELECT 1 FROM b) AND s.unique_id = x.uid ) SELECT * FROM a UNION ALL SELECT * FROM b UNION ALL SELECT * FROM c; ``` I am *not sure* whether it avoids additional scans like I hope. Would have to be tested. This query requires at least PostgreSQL 8.4. --- ### Upgrade! As I just learned, the OP runs on PostgreSQL 8.1. **Upgrading alone** would speed up the operation a lot. --- ### Query for PostgreSQL 8.1 As you are limited in your options, and a plpgsql function is not possible, this function should perform better than the one you have. Test with [`EXPLAIN ANALYZE`](http://www.postgresql.org/docs/8.1/interactive/sql-explain.html) - available in v8.1. ``` SELECT title, stock FROM product WHERE unique_id = 10 UNION ALL SELECT p.title, ps.stock FROM product p JOIN ( SELECT id_product, stock FROM color WHERE unique_id = 10 UNION ALL SELECT id_product, stock FROM size WHERE unique_id = 10 ) ps ON ps.id_product = p.id; ```
There's an easier way to generate unique IDs using three separate auto\_increment columns. Just prepend a letter to the ID to uniquify it: Colors: ``` C0000001 C0000002 C0000003 ``` Sizes: ``` S0000001 S0000002 S0000003 ... ``` Products: ``` P0000001 P0000002 P0000003 ... ``` A few advantages: * You don't need to serialize creation of ids across tables to ensure uniqueness. This will give better performance. * You don't actually need to store the letter in the table. All IDs in the same table start with the same letter, so you only need to store the number. This means that you can use an ordinary `auto_increment` column to generate your IDs. * If you have an ID you only need to check the first character to see which table it can be found in. You don't even need to make a query to the database if you just want to know whether it's a product ID or a size ID. A disadvantage: * It's no longer a number. But you can get around that by using 1,2,3 instead of C,S,P.
11,422,517
I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. ``` product color size ------- ------- ------- id id id unique_id id_product (FK from product) id_product (FK from version) stock unique_id id_version (FK from version) title stock unique_id stock ``` The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: ``` select title, stock from product where unique_id = 10 UNION select p.title, c.stock from color c join product p on c.id_product = p.id where c.unique_id = 10 UNION select p.title, s.stock from size s join product p on s.id_product = p.id where s.unique_id = 10; ``` Is there a better way to do this? Thanks for any suggestion! **EDIT 1** Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: 1) As `unique_id` has indexes in all tables, i will get a good performance 2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join ``` SELECT p.title, ps.stock FROM ( select id as id_product, stock from product where unique_id = 10 UNION select id_product, stock from color where unique_id = 10 UNION select id_product, stock from size where unique_id = 10 ) AS ps JOIN product p ON ps.id_product = p.id; ```
2012/07/10
['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']
I think it's time for a redesign. You have things that you're using as bar codes for items that are basically all the same in one respect (they are SerialNumberItems), but have been split into multiple tables because they are different in other respects. I have several ideas for you: Change the Defaults ------------------- Just make each product required to have one color "no color" and one size "no size". Then you can query any table you want to find the info you need. SuperType/SubType ----------------- Without too much modification you could use the supertype/subtype database design pattern. In it, there is a parent table where all the distinct detail-level identifiers live, and the shared columns of the subtype tables go in the supertype table (the ways that all the items are the same). There is one subtype table for each different way that the items are distinct. If mutual exclusivity of the subtype is required (you can have a Color or a Size but not both), then the parent table is given a TypeID column and the subtype tables have an FK to both the ParentID and the TypeID. Looking at your design, in fact you would not use mutual exclusivity. If you use the pattern of a supertype table, you do have the issue of having to insert in two parts, first to the supertype, then the subtype. Deleting also requires deleting in reverse order. But you get a great benefit of being able to get basic information such as Title and Stock out of the supertype table with a single query. You could even create schema-bound views for each subtype, with instead-of triggers that convert inserts, updates, and deletes into operations on the base table + child table. A Bigger Redesign ----------------- You could completely change how Colors and Sizes are related to products. First, your patterns of "has-a" are these: * Product (has nothing) * Product->Color * Product->Size * Product->Color->Size There is a problem here. Clearly Product is the main item that has other things (colors and sizes) but colors don't have sizes! That is an arbitrary assignment. You may as well have said that Sizes have Colors--it doesn't make a difference. This reveals that your table design may not be best, as you're trying to model orthogonal data in a parent-child type of relationship. Really, products have a ColorAndSize. Furthermore, when a product comes in colors and sizes, what does the `uniqueid` in the Color table mean? Can such a product be ordered without a size, having only a color? This design is assigning a unique ID to something that (it seems to me) should never be allowed to be ordered--but you can't find this information out from the Color table, you have to compare the Color and Size tables first. It is a problem. I would design this as: Table `Product`. Table `Size` listing all distinct sizes possible for any product ever. Table `Color` listing all distinct colors possible for any product ever. And table `OrderableProduct` that has columns `ProductId`, `ColorID`, `SizeID`, and `UniqueID` (your bar code value). Additionally, each product must have one color and one size or it doesn't exist. Basically, Color and Size are like X and Y coordinates into a grid; you are filling in the boxes that are allowable combinations. Which one is the row and which the column is irrelevant. Certainly, one is not a child of the other. If there are any reasonable rules, in general, about what colors or sizes can be applied to various sub-groups of products, there might be utility in a ProductType table and a ProductTypeOrderables table that, when creating a new product, could populate the OrderableProduct table with the standard set—it could still be customized but might be easier to modify than to create anew. Or, it could define the range of colors and sizes that are allowable. You might need separate ProductTypeAllowedColor and ProductTypeAllowedSize tables. For example, if you are selling T-shirts, you'd want to allow XXXS, XXS, XS, S, M, L, XL, XXL, XXXL, and XXXXL, even if most products never use all those sizes. But for soft drinks, the sizes might be 6-pack 8oz, 24-pack 8oz, 2 liter, and so on, even if each soft drink is not offered in that size (and soft drinks don't have colors). In this new scheme, you only have one table to query to find the correct orderable product. With proper indexes, it should be blazing fast. Your Question ------------- You asked: > > in PostgreSQL, so do you think if i use indexes on unique\_id i will get a satisfactory performance? > > > Any column or set of columns that you use to repeatedly look up data must have an index! Any other pattern will result in a full table scan each time, which will be awful performance. I am sure that these indexes will make your queries lightning fast as it will take only one leaf-level read per table.
There's an easier way to generate unique IDs using three separate auto\_increment columns. Just prepend a letter to the ID to uniquify it: Colors: ``` C0000001 C0000002 C0000003 ``` Sizes: ``` S0000001 S0000002 S0000003 ... ``` Products: ``` P0000001 P0000002 P0000003 ... ``` A few advantages: * You don't need to serialize creation of ids across tables to ensure uniqueness. This will give better performance. * You don't actually need to store the letter in the table. All IDs in the same table start with the same letter, so you only need to store the number. This means that you can use an ordinary `auto_increment` column to generate your IDs. * If you have an ID you only need to check the first character to see which table it can be found in. You don't even need to make a query to the database if you just want to know whether it's a product ID or a size ID. A disadvantage: * It's no longer a number. But you can get around that by using 1,2,3 instead of C,S,P.
11,422,517
I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. ``` product color size ------- ------- ------- id id id unique_id id_product (FK from product) id_product (FK from version) stock unique_id id_version (FK from version) title stock unique_id stock ``` The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: ``` select title, stock from product where unique_id = 10 UNION select p.title, c.stock from color c join product p on c.id_product = p.id where c.unique_id = 10 UNION select p.title, s.stock from size s join product p on s.id_product = p.id where s.unique_id = 10; ``` Is there a better way to do this? Thanks for any suggestion! **EDIT 1** Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: 1) As `unique_id` has indexes in all tables, i will get a good performance 2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join ``` SELECT p.title, ps.stock FROM ( select id as id_product, stock from product where unique_id = 10 UNION select id_product, stock from color where unique_id = 10 UNION select id_product, stock from size where unique_id = 10 ) AS ps JOIN product p ON ps.id_product = p.id; ```
2012/07/10
['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']
### PL/pgSQL function To solve the problem at hand, a plpgsql function like the following should be faster: ``` CREATE OR REPLACE FUNCTION func(int) RETURNS TABLE (title text, stock int) LANGUAGE plpgsql AS $BODY$ BEGIN RETURN QUERY SELECT p.title, p.stock FROM product p WHERE p.unique_id = $1; -- Put the most likely table first. IF NOT FOUND THEN RETURN QUERY SELECT p.title, c.stock FROM color c JOIN product p ON c.id_product = p.id WHERE c.unique_id = $1; END; IF NOT FOUND THEN RETURN QUERY SELECT p.title, s.stock FROM size s JOIN product p ON s.id_product = p.id WHERE s.unique_id = $1; END IF; END; $BODY$; ``` Updated function with table-qualified column names to avoid naming conflicts with `OUT` parameters. `RETURNS TABLE` requires PostgreSQL 8.4, `RETURN QUERY` requires version 8.2. You can substitute both for older versions. It goes without saying that you need to **index** the columns `unique_id` of every involved table. `id` should be indexed automatically, being the primary key. --- ### Redesign Ideally, you can tell which table from the ID alone. You could keep using one common sequence, but add `100000000` for the first table, `200000000` for the second and `300000000` for the third - or whatever suits your needs. This way, the least significant part of the number is easily distinguishable. A plain integer spans numbers from -2147483648 to +2147483647, move to [`bigint`](http://www.postgresql.org/docs/current/interactive/datatype-numeric.html#DATATYPE-INT) if that's not enough for you. I would stick to `integer` IDs, though, if possible. They are smaller and faster than `bigint` or `text`. --- ### CTEs (experimental!) If you cannot create a function for some reason, this pure SQL solution might do a similar trick: ``` WITH x(uid) AS (SELECT 10) -- provide unique_id here , a AS ( SELECT title, stock FROM x, product WHERE unique_id = x.uid ) , b AS ( SELECT p.title, c.stock FROM x, color c JOIN product p ON c.id_product = p.id WHERE NOT EXISTS (SELECT 1 FROM a) AND c.unique_id = x.uid ) , c AS ( SELECT p.title, s.stock FROM x, size s JOIN product p ON s.id_product = p.id WHERE NOT EXISTS (SELECT 1 FROM b) AND s.unique_id = x.uid ) SELECT * FROM a UNION ALL SELECT * FROM b UNION ALL SELECT * FROM c; ``` I am *not sure* whether it avoids additional scans like I hope. Would have to be tested. This query requires at least PostgreSQL 8.4. --- ### Upgrade! As I just learned, the OP runs on PostgreSQL 8.1. **Upgrading alone** would speed up the operation a lot. --- ### Query for PostgreSQL 8.1 As you are limited in your options, and a plpgsql function is not possible, this function should perform better than the one you have. Test with [`EXPLAIN ANALYZE`](http://www.postgresql.org/docs/8.1/interactive/sql-explain.html) - available in v8.1. ``` SELECT title, stock FROM product WHERE unique_id = 10 UNION ALL SELECT p.title, ps.stock FROM product p JOIN ( SELECT id_product, stock FROM color WHERE unique_id = 10 UNION ALL SELECT id_product, stock FROM size WHERE unique_id = 10 ) ps ON ps.id_product = p.id; ```
Your query will be pretty much efficient, as long as you have an index on `unique_id`, on every table and indices on the joining columns. You could turn those `UNION` into `UNION ALL` but the won't be any differnce on performance, for this query.
11,422,517
I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. ``` product color size ------- ------- ------- id id id unique_id id_product (FK from product) id_product (FK from version) stock unique_id id_version (FK from version) title stock unique_id stock ``` The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: ``` select title, stock from product where unique_id = 10 UNION select p.title, c.stock from color c join product p on c.id_product = p.id where c.unique_id = 10 UNION select p.title, s.stock from size s join product p on s.id_product = p.id where s.unique_id = 10; ``` Is there a better way to do this? Thanks for any suggestion! **EDIT 1** Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: 1) As `unique_id` has indexes in all tables, i will get a good performance 2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join ``` SELECT p.title, ps.stock FROM ( select id as id_product, stock from product where unique_id = 10 UNION select id_product, stock from color where unique_id = 10 UNION select id_product, stock from size where unique_id = 10 ) AS ps JOIN product p ON ps.id_product = p.id; ```
2012/07/10
['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']
### PL/pgSQL function To solve the problem at hand, a plpgsql function like the following should be faster: ``` CREATE OR REPLACE FUNCTION func(int) RETURNS TABLE (title text, stock int) LANGUAGE plpgsql AS $BODY$ BEGIN RETURN QUERY SELECT p.title, p.stock FROM product p WHERE p.unique_id = $1; -- Put the most likely table first. IF NOT FOUND THEN RETURN QUERY SELECT p.title, c.stock FROM color c JOIN product p ON c.id_product = p.id WHERE c.unique_id = $1; END; IF NOT FOUND THEN RETURN QUERY SELECT p.title, s.stock FROM size s JOIN product p ON s.id_product = p.id WHERE s.unique_id = $1; END IF; END; $BODY$; ``` Updated function with table-qualified column names to avoid naming conflicts with `OUT` parameters. `RETURNS TABLE` requires PostgreSQL 8.4, `RETURN QUERY` requires version 8.2. You can substitute both for older versions. It goes without saying that you need to **index** the columns `unique_id` of every involved table. `id` should be indexed automatically, being the primary key. --- ### Redesign Ideally, you can tell which table from the ID alone. You could keep using one common sequence, but add `100000000` for the first table, `200000000` for the second and `300000000` for the third - or whatever suits your needs. This way, the least significant part of the number is easily distinguishable. A plain integer spans numbers from -2147483648 to +2147483647, move to [`bigint`](http://www.postgresql.org/docs/current/interactive/datatype-numeric.html#DATATYPE-INT) if that's not enough for you. I would stick to `integer` IDs, though, if possible. They are smaller and faster than `bigint` or `text`. --- ### CTEs (experimental!) If you cannot create a function for some reason, this pure SQL solution might do a similar trick: ``` WITH x(uid) AS (SELECT 10) -- provide unique_id here , a AS ( SELECT title, stock FROM x, product WHERE unique_id = x.uid ) , b AS ( SELECT p.title, c.stock FROM x, color c JOIN product p ON c.id_product = p.id WHERE NOT EXISTS (SELECT 1 FROM a) AND c.unique_id = x.uid ) , c AS ( SELECT p.title, s.stock FROM x, size s JOIN product p ON s.id_product = p.id WHERE NOT EXISTS (SELECT 1 FROM b) AND s.unique_id = x.uid ) SELECT * FROM a UNION ALL SELECT * FROM b UNION ALL SELECT * FROM c; ``` I am *not sure* whether it avoids additional scans like I hope. Would have to be tested. This query requires at least PostgreSQL 8.4. --- ### Upgrade! As I just learned, the OP runs on PostgreSQL 8.1. **Upgrading alone** would speed up the operation a lot. --- ### Query for PostgreSQL 8.1 As you are limited in your options, and a plpgsql function is not possible, this function should perform better than the one you have. Test with [`EXPLAIN ANALYZE`](http://www.postgresql.org/docs/8.1/interactive/sql-explain.html) - available in v8.1. ``` SELECT title, stock FROM product WHERE unique_id = 10 UNION ALL SELECT p.title, ps.stock FROM product p JOIN ( SELECT id_product, stock FROM color WHERE unique_id = 10 UNION ALL SELECT id_product, stock FROM size WHERE unique_id = 10 ) ps ON ps.id_product = p.id; ```
I think it's time for a redesign. You have things that you're using as bar codes for items that are basically all the same in one respect (they are SerialNumberItems), but have been split into multiple tables because they are different in other respects. I have several ideas for you: Change the Defaults ------------------- Just make each product required to have one color "no color" and one size "no size". Then you can query any table you want to find the info you need. SuperType/SubType ----------------- Without too much modification you could use the supertype/subtype database design pattern. In it, there is a parent table where all the distinct detail-level identifiers live, and the shared columns of the subtype tables go in the supertype table (the ways that all the items are the same). There is one subtype table for each different way that the items are distinct. If mutual exclusivity of the subtype is required (you can have a Color or a Size but not both), then the parent table is given a TypeID column and the subtype tables have an FK to both the ParentID and the TypeID. Looking at your design, in fact you would not use mutual exclusivity. If you use the pattern of a supertype table, you do have the issue of having to insert in two parts, first to the supertype, then the subtype. Deleting also requires deleting in reverse order. But you get a great benefit of being able to get basic information such as Title and Stock out of the supertype table with a single query. You could even create schema-bound views for each subtype, with instead-of triggers that convert inserts, updates, and deletes into operations on the base table + child table. A Bigger Redesign ----------------- You could completely change how Colors and Sizes are related to products. First, your patterns of "has-a" are these: * Product (has nothing) * Product->Color * Product->Size * Product->Color->Size There is a problem here. Clearly Product is the main item that has other things (colors and sizes) but colors don't have sizes! That is an arbitrary assignment. You may as well have said that Sizes have Colors--it doesn't make a difference. This reveals that your table design may not be best, as you're trying to model orthogonal data in a parent-child type of relationship. Really, products have a ColorAndSize. Furthermore, when a product comes in colors and sizes, what does the `uniqueid` in the Color table mean? Can such a product be ordered without a size, having only a color? This design is assigning a unique ID to something that (it seems to me) should never be allowed to be ordered--but you can't find this information out from the Color table, you have to compare the Color and Size tables first. It is a problem. I would design this as: Table `Product`. Table `Size` listing all distinct sizes possible for any product ever. Table `Color` listing all distinct colors possible for any product ever. And table `OrderableProduct` that has columns `ProductId`, `ColorID`, `SizeID`, and `UniqueID` (your bar code value). Additionally, each product must have one color and one size or it doesn't exist. Basically, Color and Size are like X and Y coordinates into a grid; you are filling in the boxes that are allowable combinations. Which one is the row and which the column is irrelevant. Certainly, one is not a child of the other. If there are any reasonable rules, in general, about what colors or sizes can be applied to various sub-groups of products, there might be utility in a ProductType table and a ProductTypeOrderables table that, when creating a new product, could populate the OrderableProduct table with the standard set—it could still be customized but might be easier to modify than to create anew. Or, it could define the range of colors and sizes that are allowable. You might need separate ProductTypeAllowedColor and ProductTypeAllowedSize tables. For example, if you are selling T-shirts, you'd want to allow XXXS, XXS, XS, S, M, L, XL, XXL, XXXL, and XXXXL, even if most products never use all those sizes. But for soft drinks, the sizes might be 6-pack 8oz, 24-pack 8oz, 2 liter, and so on, even if each soft drink is not offered in that size (and soft drinks don't have colors). In this new scheme, you only have one table to query to find the correct orderable product. With proper indexes, it should be blazing fast. Your Question ------------- You asked: > > in PostgreSQL, so do you think if i use indexes on unique\_id i will get a satisfactory performance? > > > Any column or set of columns that you use to repeatedly look up data must have an index! Any other pattern will result in a full table scan each time, which will be awful performance. I am sure that these indexes will make your queries lightning fast as it will take only one leaf-level read per table.
11,422,517
I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. ``` product color size ------- ------- ------- id id id unique_id id_product (FK from product) id_product (FK from version) stock unique_id id_version (FK from version) title stock unique_id stock ``` The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: ``` select title, stock from product where unique_id = 10 UNION select p.title, c.stock from color c join product p on c.id_product = p.id where c.unique_id = 10 UNION select p.title, s.stock from size s join product p on s.id_product = p.id where s.unique_id = 10; ``` Is there a better way to do this? Thanks for any suggestion! **EDIT 1** Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: 1) As `unique_id` has indexes in all tables, i will get a good performance 2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join ``` SELECT p.title, ps.stock FROM ( select id as id_product, stock from product where unique_id = 10 UNION select id_product, stock from color where unique_id = 10 UNION select id_product, stock from size where unique_id = 10 ) AS ps JOIN product p ON ps.id_product = p.id; ```
2012/07/10
['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']
### PL/pgSQL function To solve the problem at hand, a plpgsql function like the following should be faster: ``` CREATE OR REPLACE FUNCTION func(int) RETURNS TABLE (title text, stock int) LANGUAGE plpgsql AS $BODY$ BEGIN RETURN QUERY SELECT p.title, p.stock FROM product p WHERE p.unique_id = $1; -- Put the most likely table first. IF NOT FOUND THEN RETURN QUERY SELECT p.title, c.stock FROM color c JOIN product p ON c.id_product = p.id WHERE c.unique_id = $1; END; IF NOT FOUND THEN RETURN QUERY SELECT p.title, s.stock FROM size s JOIN product p ON s.id_product = p.id WHERE s.unique_id = $1; END IF; END; $BODY$; ``` Updated function with table-qualified column names to avoid naming conflicts with `OUT` parameters. `RETURNS TABLE` requires PostgreSQL 8.4, `RETURN QUERY` requires version 8.2. You can substitute both for older versions. It goes without saying that you need to **index** the columns `unique_id` of every involved table. `id` should be indexed automatically, being the primary key. --- ### Redesign Ideally, you can tell which table from the ID alone. You could keep using one common sequence, but add `100000000` for the first table, `200000000` for the second and `300000000` for the third - or whatever suits your needs. This way, the least significant part of the number is easily distinguishable. A plain integer spans numbers from -2147483648 to +2147483647, move to [`bigint`](http://www.postgresql.org/docs/current/interactive/datatype-numeric.html#DATATYPE-INT) if that's not enough for you. I would stick to `integer` IDs, though, if possible. They are smaller and faster than `bigint` or `text`. --- ### CTEs (experimental!) If you cannot create a function for some reason, this pure SQL solution might do a similar trick: ``` WITH x(uid) AS (SELECT 10) -- provide unique_id here , a AS ( SELECT title, stock FROM x, product WHERE unique_id = x.uid ) , b AS ( SELECT p.title, c.stock FROM x, color c JOIN product p ON c.id_product = p.id WHERE NOT EXISTS (SELECT 1 FROM a) AND c.unique_id = x.uid ) , c AS ( SELECT p.title, s.stock FROM x, size s JOIN product p ON s.id_product = p.id WHERE NOT EXISTS (SELECT 1 FROM b) AND s.unique_id = x.uid ) SELECT * FROM a UNION ALL SELECT * FROM b UNION ALL SELECT * FROM c; ``` I am *not sure* whether it avoids additional scans like I hope. Would have to be tested. This query requires at least PostgreSQL 8.4. --- ### Upgrade! As I just learned, the OP runs on PostgreSQL 8.1. **Upgrading alone** would speed up the operation a lot. --- ### Query for PostgreSQL 8.1 As you are limited in your options, and a plpgsql function is not possible, this function should perform better than the one you have. Test with [`EXPLAIN ANALYZE`](http://www.postgresql.org/docs/8.1/interactive/sql-explain.html) - available in v8.1. ``` SELECT title, stock FROM product WHERE unique_id = 10 UNION ALL SELECT p.title, ps.stock FROM product p JOIN ( SELECT id_product, stock FROM color WHERE unique_id = 10 UNION ALL SELECT id_product, stock FROM size WHERE unique_id = 10 ) ps ON ps.id_product = p.id; ```
This is a bit different. I don't understand the intended behaviour if stocks exists in more than one of the {product,color,zsize} tables. (UNION will remove duplicates, but for the row-as-a-whole, eg the {product\_id,stock} tuples. That makes no sense to me. I just take the first. (Note the funky self-join!!) ``` SELECT p.title , COALESCE (p2.stock, c.stock, s.stock) AS stock FROM product p LEFT JOIN product p2 on p2.id = p.id AND p2.unique_id = 10 LEFT JOIN color c on c.id_product = p.id AND c.unique_id = 10 LEFT JOIN zsize s on s.id_product = p.id AND s.unique_id = 10 WHERE COALESCE (p2.stock, c.stock, s.stock) IS NOT NULL ; ```
11,422,517
I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. ``` product color size ------- ------- ------- id id id unique_id id_product (FK from product) id_product (FK from version) stock unique_id id_version (FK from version) title stock unique_id stock ``` The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: ``` select title, stock from product where unique_id = 10 UNION select p.title, c.stock from color c join product p on c.id_product = p.id where c.unique_id = 10 UNION select p.title, s.stock from size s join product p on s.id_product = p.id where s.unique_id = 10; ``` Is there a better way to do this? Thanks for any suggestion! **EDIT 1** Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: 1) As `unique_id` has indexes in all tables, i will get a good performance 2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join ``` SELECT p.title, ps.stock FROM ( select id as id_product, stock from product where unique_id = 10 UNION select id_product, stock from color where unique_id = 10 UNION select id_product, stock from size where unique_id = 10 ) AS ps JOIN product p ON ps.id_product = p.id; ```
2012/07/10
['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']
I think it's time for a redesign. You have things that you're using as bar codes for items that are basically all the same in one respect (they are SerialNumberItems), but have been split into multiple tables because they are different in other respects. I have several ideas for you: Change the Defaults ------------------- Just make each product required to have one color "no color" and one size "no size". Then you can query any table you want to find the info you need. SuperType/SubType ----------------- Without too much modification you could use the supertype/subtype database design pattern. In it, there is a parent table where all the distinct detail-level identifiers live, and the shared columns of the subtype tables go in the supertype table (the ways that all the items are the same). There is one subtype table for each different way that the items are distinct. If mutual exclusivity of the subtype is required (you can have a Color or a Size but not both), then the parent table is given a TypeID column and the subtype tables have an FK to both the ParentID and the TypeID. Looking at your design, in fact you would not use mutual exclusivity. If you use the pattern of a supertype table, you do have the issue of having to insert in two parts, first to the supertype, then the subtype. Deleting also requires deleting in reverse order. But you get a great benefit of being able to get basic information such as Title and Stock out of the supertype table with a single query. You could even create schema-bound views for each subtype, with instead-of triggers that convert inserts, updates, and deletes into operations on the base table + child table. A Bigger Redesign ----------------- You could completely change how Colors and Sizes are related to products. First, your patterns of "has-a" are these: * Product (has nothing) * Product->Color * Product->Size * Product->Color->Size There is a problem here. Clearly Product is the main item that has other things (colors and sizes) but colors don't have sizes! That is an arbitrary assignment. You may as well have said that Sizes have Colors--it doesn't make a difference. This reveals that your table design may not be best, as you're trying to model orthogonal data in a parent-child type of relationship. Really, products have a ColorAndSize. Furthermore, when a product comes in colors and sizes, what does the `uniqueid` in the Color table mean? Can such a product be ordered without a size, having only a color? This design is assigning a unique ID to something that (it seems to me) should never be allowed to be ordered--but you can't find this information out from the Color table, you have to compare the Color and Size tables first. It is a problem. I would design this as: Table `Product`. Table `Size` listing all distinct sizes possible for any product ever. Table `Color` listing all distinct colors possible for any product ever. And table `OrderableProduct` that has columns `ProductId`, `ColorID`, `SizeID`, and `UniqueID` (your bar code value). Additionally, each product must have one color and one size or it doesn't exist. Basically, Color and Size are like X and Y coordinates into a grid; you are filling in the boxes that are allowable combinations. Which one is the row and which the column is irrelevant. Certainly, one is not a child of the other. If there are any reasonable rules, in general, about what colors or sizes can be applied to various sub-groups of products, there might be utility in a ProductType table and a ProductTypeOrderables table that, when creating a new product, could populate the OrderableProduct table with the standard set—it could still be customized but might be easier to modify than to create anew. Or, it could define the range of colors and sizes that are allowable. You might need separate ProductTypeAllowedColor and ProductTypeAllowedSize tables. For example, if you are selling T-shirts, you'd want to allow XXXS, XXS, XS, S, M, L, XL, XXL, XXXL, and XXXXL, even if most products never use all those sizes. But for soft drinks, the sizes might be 6-pack 8oz, 24-pack 8oz, 2 liter, and so on, even if each soft drink is not offered in that size (and soft drinks don't have colors). In this new scheme, you only have one table to query to find the correct orderable product. With proper indexes, it should be blazing fast. Your Question ------------- You asked: > > in PostgreSQL, so do you think if i use indexes on unique\_id i will get a satisfactory performance? > > > Any column or set of columns that you use to repeatedly look up data must have an index! Any other pattern will result in a full table scan each time, which will be awful performance. I am sure that these indexes will make your queries lightning fast as it will take only one leaf-level read per table.
Your query will be pretty much efficient, as long as you have an index on `unique_id`, on every table and indices on the joining columns. You could turn those `UNION` into `UNION ALL` but the won't be any differnce on performance, for this query.
11,422,517
I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. ``` product color size ------- ------- ------- id id id unique_id id_product (FK from product) id_product (FK from version) stock unique_id id_version (FK from version) title stock unique_id stock ``` The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: ``` select title, stock from product where unique_id = 10 UNION select p.title, c.stock from color c join product p on c.id_product = p.id where c.unique_id = 10 UNION select p.title, s.stock from size s join product p on s.id_product = p.id where s.unique_id = 10; ``` Is there a better way to do this? Thanks for any suggestion! **EDIT 1** Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: 1) As `unique_id` has indexes in all tables, i will get a good performance 2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join ``` SELECT p.title, ps.stock FROM ( select id as id_product, stock from product where unique_id = 10 UNION select id_product, stock from color where unique_id = 10 UNION select id_product, stock from size where unique_id = 10 ) AS ps JOIN product p ON ps.id_product = p.id; ```
2012/07/10
['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']
I think it's time for a redesign. You have things that you're using as bar codes for items that are basically all the same in one respect (they are SerialNumberItems), but have been split into multiple tables because they are different in other respects. I have several ideas for you: Change the Defaults ------------------- Just make each product required to have one color "no color" and one size "no size". Then you can query any table you want to find the info you need. SuperType/SubType ----------------- Without too much modification you could use the supertype/subtype database design pattern. In it, there is a parent table where all the distinct detail-level identifiers live, and the shared columns of the subtype tables go in the supertype table (the ways that all the items are the same). There is one subtype table for each different way that the items are distinct. If mutual exclusivity of the subtype is required (you can have a Color or a Size but not both), then the parent table is given a TypeID column and the subtype tables have an FK to both the ParentID and the TypeID. Looking at your design, in fact you would not use mutual exclusivity. If you use the pattern of a supertype table, you do have the issue of having to insert in two parts, first to the supertype, then the subtype. Deleting also requires deleting in reverse order. But you get a great benefit of being able to get basic information such as Title and Stock out of the supertype table with a single query. You could even create schema-bound views for each subtype, with instead-of triggers that convert inserts, updates, and deletes into operations on the base table + child table. A Bigger Redesign ----------------- You could completely change how Colors and Sizes are related to products. First, your patterns of "has-a" are these: * Product (has nothing) * Product->Color * Product->Size * Product->Color->Size There is a problem here. Clearly Product is the main item that has other things (colors and sizes) but colors don't have sizes! That is an arbitrary assignment. You may as well have said that Sizes have Colors--it doesn't make a difference. This reveals that your table design may not be best, as you're trying to model orthogonal data in a parent-child type of relationship. Really, products have a ColorAndSize. Furthermore, when a product comes in colors and sizes, what does the `uniqueid` in the Color table mean? Can such a product be ordered without a size, having only a color? This design is assigning a unique ID to something that (it seems to me) should never be allowed to be ordered--but you can't find this information out from the Color table, you have to compare the Color and Size tables first. It is a problem. I would design this as: Table `Product`. Table `Size` listing all distinct sizes possible for any product ever. Table `Color` listing all distinct colors possible for any product ever. And table `OrderableProduct` that has columns `ProductId`, `ColorID`, `SizeID`, and `UniqueID` (your bar code value). Additionally, each product must have one color and one size or it doesn't exist. Basically, Color and Size are like X and Y coordinates into a grid; you are filling in the boxes that are allowable combinations. Which one is the row and which the column is irrelevant. Certainly, one is not a child of the other. If there are any reasonable rules, in general, about what colors or sizes can be applied to various sub-groups of products, there might be utility in a ProductType table and a ProductTypeOrderables table that, when creating a new product, could populate the OrderableProduct table with the standard set—it could still be customized but might be easier to modify than to create anew. Or, it could define the range of colors and sizes that are allowable. You might need separate ProductTypeAllowedColor and ProductTypeAllowedSize tables. For example, if you are selling T-shirts, you'd want to allow XXXS, XXS, XS, S, M, L, XL, XXL, XXXL, and XXXXL, even if most products never use all those sizes. But for soft drinks, the sizes might be 6-pack 8oz, 24-pack 8oz, 2 liter, and so on, even if each soft drink is not offered in that size (and soft drinks don't have colors). In this new scheme, you only have one table to query to find the correct orderable product. With proper indexes, it should be blazing fast. Your Question ------------- You asked: > > in PostgreSQL, so do you think if i use indexes on unique\_id i will get a satisfactory performance? > > > Any column or set of columns that you use to repeatedly look up data must have an index! Any other pattern will result in a full table scan each time, which will be awful performance. I am sure that these indexes will make your queries lightning fast as it will take only one leaf-level read per table.
This is a bit different. I don't understand the intended behaviour if stocks exists in more than one of the {product,color,zsize} tables. (UNION will remove duplicates, but for the row-as-a-whole, eg the {product\_id,stock} tuples. That makes no sense to me. I just take the first. (Note the funky self-join!!) ``` SELECT p.title , COALESCE (p2.stock, c.stock, s.stock) AS stock FROM product p LEFT JOIN product p2 on p2.id = p.id AND p2.unique_id = 10 LEFT JOIN color c on c.id_product = p.id AND c.unique_id = 10 LEFT JOIN zsize s on s.id_product = p.id AND s.unique_id = 10 WHERE COALESCE (p2.stock, c.stock, s.stock) IS NOT NULL ; ```
597,528
From Wikipedia I have the compliment of the CDF parameterized for fat-tails distributions. $$ \Pr[X>x] \sim x^{- \alpha}\text{ as }x \to \infty,\qquad \alpha > 0.\, $$ Here $\alpha$ is the fatness parameter. According to Taleb. $\alpha \leq 2.5$ is forecastable, but $\alpha > 2.5$ is not. I would like to fit $\alpha$ given my data so I can mark it as forecastable or not. I thought I would start by trying to fit my data to a linear model. ``` set.seed(42) df_tails <- tibble(y = 1- seq(0.01,1, 0.01), norm = sort(rnorm(n = 100, 0,1)), cauchy = sort(rcauchy(n = 100, 0,1))) lm(log(y) ~ norm - 1, data = df_tails) lm(log(y) ~ cauchy - 1, data = df_tails) ``` The problem is that I end up with many `NAs` so I think I am coding something wrong. ### Try 2 ``` library(tidyverse) set.seed(42) df_tails_raw <- tibble(y = log(1- seq(0.01,1, 0.01)), norm = log(sort(rnorm(n = 100, 0,1))), cauchy = log(sort(rcauchy(n = 100, 0,1)))) df_tails <- na.omit(df_tails_raw) df_tails |> ggplot() + geom_point(aes(x = norm, y=y), color = 'tomato', size = 2, stroke = 2, shape = 1) + geom_point(aes(x = cauchy, y = y), color = 'grey50', size = 2, stroke = 2, shape = 1) + theme_classic() + labs('Red is normal and Grey is Cauchy') lm(y ~ norm, data = df_tails) lm(y ~ cauchy - 1, data = df_tails) ``` [![enter image description here](https://i.stack.imgur.com/1WjzT.png)](https://i.stack.imgur.com/1WjzT.png) My error is > > Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : > NA/NaN/Inf in 'y' > > >
2022/11/30
['https://stats.stackexchange.com/questions/597528', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/142914/']
There are several issues with this question. ### The error message The simplest, is the issue about the error message which is the explicit question in the text. > > Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : > NA/NaN/Inf in 'y' > > > The error says that the dependent variable in the linear model is not right and contains NA/NaN/Inf. The reason is because your $y$ variable contains a zero and when you take the logarithm of this then you get an NA value. Then, when you pass this to the `lm` function you get the error. (Because you pass log(y) nested inside the lm function this is not so clear, but the 'y' of the lm function is your 'log(y)' value and not your 'y' value) Sidenote: to fit a powerlaw with linearisation you should use $\log(y) = a + b \cdot \log(x)$. In your code you use $\log(y) = bx$ and you miss the intercept as well as taking the logarithm of $x$. ### The fitting of the power law Distributions that have power law behaviour are often only having this behaviour for a limited range. In your fitting method you should only fit the part of the distribution that follows the power law. In the log-log plot below you see that you don't have a straight line over the entire range, in addition, the points in the tail are the ones with a large scatter and error. If you plot the points along with the known underlying distribution you see that the error is not just the scatter but also the error is correlated and the entire curve can have an error. [![example of behaviour on log log scale](https://i.stack.imgur.com/HIXsD.png)](https://i.stack.imgur.com/HIXsD.png) On the plot I also have added a log-normal distribution. It shows that curves that are not really straight can appear to be straight. Just fitting a straight line does not tell that you also actually have a straight line. The article mentioned by Sycorax on the comments, [Power-law distributions in empirical data](https://arxiv.org/abs/0706.1062), discusses this issue on more detail.
#### You might want to use the `tailplot` function in the `utilities` package The standard way of examining tail behaviour of data is through a tail-plot or a Hill plot (or variations of these). The tailplot shows the tails of a dataset against the empirical tail probability, each exhibited on a logarithmic scale. The plot can be generated in `R` by using the [`tailplot` function](https://search.r-project.org/CRAN/refmans/utilities/html/tailplot.html) in the [`utilities` package](https://CRAN.R-project.org/package=utilities). This function allows you to plot the data in one or both tails using a chosen proportion of the dataset (by default the plot will show 5% of the data in each tail) and it will compare this with a specified power-rate of decay (by default it is compared with cubic decay, which determines finiteness of the variance. In the code below I give an example of a tailplot for a set of $n=1000$ datapoints generated from a standard normal distribution. The plot shows that the tails of the distributin decays substantially faster than cubic decay, which is sufficient to give finite variance. You can compare your data with an alternate rate-of-decay if you prefer. ``` #Set some mock data set.seed(1) DATA <- rnorm(1000) #Show the tail plots library(utilities) tailplot(DATA) ``` [![enter image description here](https://i.stack.imgur.com/4yIFi.jpg)](https://i.stack.imgur.com/4yIFi.jpg) Note that the `tailplot` function also allows you to include a Hill-plot and/or De Sousa-Michailidis plot used for estimating the rate-of-decay of the tails. To include these plots, just set `hill.plot = TRUE` and/or `dsm.plot = TRUE`.
5,174,788
I have a Perl controller class in which I do: ``` sub func1 { my $f1 = Model::myModel->new(); my $param = "test"; $f1->func2($param); } ``` Model class: ``` sub new { my ($class, %arg) = @_; my $self = bless {}, $class; return $self; } sub func2 { my ($self, $param) = shift(@_); warn $param; } ``` `$param` is blank. What is the mistake I am doing?
2011/03/02
['https://Stackoverflow.com/questions/5174788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67476/']
`shift` only shifts the first value off of `@_`. `perldoc -f shift` will tell you more about how shift works. You want: ``` my( $self, $param ) = @_; ``` You had it right in `new()`. Not sure what happened ;) Actually, FYI, your `new()` will give the warning: ``` Odd number of elements in hash assignment ``` If you call it like `$package->new( 'a' );` You might want to trap that, something like: ``` use Carp qw( croak confess ); sub new { my $class = shift; confess "$class requires an even number of args" if( @_ & 1 ); my %args = @_; # ... } ``` Or using whatever exception catching mechanism you use.
Try: ``` sub func2 { my ( $self, $param ) = @_; warn $param; } ``` or ``` sub func2 { my $self = shift @_; my $param = shift @_; warn $param; } ```
184,845
This is my current partition table: ![screen0](https://i.stack.imgur.com/GeuKx.png) In which `/dev/sda8` is the partition on Which I am currently running my primary OS - [Trisquel](https://trisquel.info) GNU/Linux (you can see it's mount point as `/`). The `/dev/sda1` is the primary partition containing Windows XP. I want to resize `/dev/sda1` (Size:50GB ; Used 27.97GB) i.e. want to reduce it to 30GB (Split into 30GB + 20GB). So, I've first Unmounted `/dev/sda1`. Now When I use **Resize/Move** option (from right-click menu) The following window appears: ![screen1](https://i.stack.imgur.com/POAWi.png) The **problem** is that it doesn't allow to reduce partition! Why?(Because it is primary partition?) And Finally **How can I resize (reduce/split) `/dev/sda1`?** Note:- Gparted is running from Trisquel (GNU/Linux).
2015/02/14
['https://unix.stackexchange.com/questions/184845', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/66803/']
My guess is that Windows XP places a master file table at the end of the partition, preventing you from resizing it. You should be able to move the master file table from within XP. Also maybe you need to defrag the Windows partition? And finally, are you sure you unmounted sda1? Run `df` in a terminal and make sure you don't see /dev/sda1 anywhere in the output, then close and reopen GParted
Try running a chkdsk and/or scandisk in Windows [to rule out bad sectors & other inconcistencies] then attempt to resize.
184,845
This is my current partition table: ![screen0](https://i.stack.imgur.com/GeuKx.png) In which `/dev/sda8` is the partition on Which I am currently running my primary OS - [Trisquel](https://trisquel.info) GNU/Linux (you can see it's mount point as `/`). The `/dev/sda1` is the primary partition containing Windows XP. I want to resize `/dev/sda1` (Size:50GB ; Used 27.97GB) i.e. want to reduce it to 30GB (Split into 30GB + 20GB). So, I've first Unmounted `/dev/sda1`. Now When I use **Resize/Move** option (from right-click menu) The following window appears: ![screen1](https://i.stack.imgur.com/POAWi.png) The **problem** is that it doesn't allow to reduce partition! Why?(Because it is primary partition?) And Finally **How can I resize (reduce/split) `/dev/sda1`?** Note:- Gparted is running from Trisquel (GNU/Linux).
2015/02/14
['https://unix.stackexchange.com/questions/184845', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/66803/']
Before you can resize any ntfs based partition, you need to ensure all the files are pushed up to the start of the partition. This is acomplisehd by running the defragmentation process on the partition within windowsXP. It may also be useful to delete any temporal files or any other stuff you don't want from the windows partition. In addition, deleting the windows swap file may also be helpfull, as it is normally not moved by the defragmentation tool. You can safely delete the pagefile from linux before resizing the partition, or you may turn off the swap file within windows.
My guess is that Windows XP places a master file table at the end of the partition, preventing you from resizing it. You should be able to move the master file table from within XP. Also maybe you need to defrag the Windows partition? And finally, are you sure you unmounted sda1? Run `df` in a terminal and make sure you don't see /dev/sda1 anywhere in the output, then close and reopen GParted
184,845
This is my current partition table: ![screen0](https://i.stack.imgur.com/GeuKx.png) In which `/dev/sda8` is the partition on Which I am currently running my primary OS - [Trisquel](https://trisquel.info) GNU/Linux (you can see it's mount point as `/`). The `/dev/sda1` is the primary partition containing Windows XP. I want to resize `/dev/sda1` (Size:50GB ; Used 27.97GB) i.e. want to reduce it to 30GB (Split into 30GB + 20GB). So, I've first Unmounted `/dev/sda1`. Now When I use **Resize/Move** option (from right-click menu) The following window appears: ![screen1](https://i.stack.imgur.com/POAWi.png) The **problem** is that it doesn't allow to reduce partition! Why?(Because it is primary partition?) And Finally **How can I resize (reduce/split) `/dev/sda1`?** Note:- Gparted is running from Trisquel (GNU/Linux).
2015/02/14
['https://unix.stackexchange.com/questions/184845', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/66803/']
Before you can resize any ntfs based partition, you need to ensure all the files are pushed up to the start of the partition. This is acomplisehd by running the defragmentation process on the partition within windowsXP. It may also be useful to delete any temporal files or any other stuff you don't want from the windows partition. In addition, deleting the windows swap file may also be helpfull, as it is normally not moved by the defragmentation tool. You can safely delete the pagefile from linux before resizing the partition, or you may turn off the swap file within windows.
Try running a chkdsk and/or scandisk in Windows [to rule out bad sectors & other inconcistencies] then attempt to resize.
69,677,554
I am extreme beginner and I have this dumb problem. So I wrote a css file and html file. HTML : ``` <!DOCTYPE html> <html> <body> <img src="https://i.pinimg.com/originals/67/b2/a9/67b2a9ba5e85822f237caae92111e938.gif" width="300" id="para1"> <p>Paragraph</p> </body> </html> ``` I did this for my css file ``` p { color: red; } ``` When I save and refresh my website, the html shows up. The css doesnt show up like the paragraph doesnt change red. I also want to change the position of the image. Please help! I also want to know about indenting please. Also should for website developing, should I learn css and html at the same time, or like html for 1 year, and then css for one year, because im learning javascript like in a 2 years, next year.
2021/10/22
['https://Stackoverflow.com/questions/69677554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17187107/']
You must tell your HMTL page where to find your CSS. To do that you have to add `link` tag into your `head` tag using: ``` <head> <link href="/path/to/your/style.css" rel="stylesheet"> </head> ``` `<link>`: The External Resource Link element > > The HTML element specifies relationships between the current > document and an external resource. This element is most commonly used > to link to stylesheets, but is also used to establish site icons (both > "favicon" style icons and icons for the home screen and apps on mobile > devices) among other things. > > > Take a look at <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link> In your case if your css file named `style.css` and `your index.html` file are on the same folder, your html should look like that: ``` <!DOCTYPE html> <html> <head> <link href="style.css" rel="stylesheet"> </head> <body> <img src="https://i.pinimg.com/originals/67/b2/a9/67b2a9ba5e85822f237caae92111e938.gif" width="300" id="para1"> <p>Paragraph</p> </body> </html> ``` > > The HTML element contains machine-readable information > (metadata) about the document, like its title, scripts, and style > sheets. > > > <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head> If you want to use [inline css](https://www.w3schools.com/css/css_howto.asp) you have to put your `<style>` tag between your `<head>` tag to make it processed by HTML. ```html <!DOCTYPE html> <html> <head> <style> p { color: red; } </style> </head> <body> <img src="https://i.pinimg.com/originals/67/b2/a9/67b2a9ba5e85822f237caae92111e938.gif" width="300" id="para1"> <p>Paragraph</p> </body> </html> ```
> > Also should for website developing, should I learn css and html at the > same time, or like html for 1 year, and then css for one year, because > im learning javascript like in a 2 years, next year. > > > Well, HTML, CSS & JS are the fabric of the front end so my advice is why not all three at the same time? They each compliment each other and after 3 years studying you will have understood more about them than focusing your time and energy learning each as separate entities. Think of HTML as your initial sketch (your structure), CSS as painting your sketch (your make-up and beautifier), and JS as making your painting come to life (your functional and interactive parts). Simply put, it's more fun with working with all 3
4,307,118
I've a JSONArray and I need to get the hashmap with the values, because I need to populate a stream, like twitter done. What you suggest to do?
2010/11/29
['https://Stackoverflow.com/questions/4307118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/496371/']
``` HashMap<String, String> pairs = new HashMap<String, String>(); for (int i = 0; i < myArray.length(); i++) { JSONObject j = myArray.optJSONObject(i); Iterator it = j.keys(); while (it.hasNext()) { String n = it.next(); pairs.put(n, j.getString(n)); } } ``` Something like that.
You can use `Iterator` for getting `JsonArrays`. or use this way eg. json ``` { ........ ........ "FARE":[ //JSON Array { "REG_ID":3, "PACKAGE_ID":1, "MODEL_ID":9, "MIN_HOUR":0 ....... ....... ....... } ] } ``` > > > ``` > HashMap<String, String> mMap= new HashMap<>(); > for (int i = 0; i < myArray.length(); i++) { > > JSONObject j = myArray.optJSONObject(i); > mMap.put("KEY1", j.getString("REG_ID")); > mMap.put("KEY2", j.getString("PACKAGE_ID")); > ............ > ............ > } > > ``` > > **note**: For better coding use `Iterator`
25,467,734
I have a JXTreeTable with an add button. The button works as expected: it adds a new node to the end, with values that (for the purpose of testing) are hard-coded into my program. The line: ``` modelSupport.fireChildAdded(new TreePath(root), noOfChildren-1, dataNode); ``` tells the JXTreeTable to recognise the update made to the TreeTableModel, and to refresh accordingly. I then execute: ``` treeTable.changeSelection(treeTable.getRowCount()-1, 0, false, false); ``` to automatically select this new node. This works as expected, BUT I also expected it to automatically scroll to bring this new node into sight, which it does not. Instead, it scrolls to show only the penultimate node, leaving the new node hidden just slightly beyond view. I've also tried using tricks to programmatically scroll to the final record. However, this code: ``` JScrollBar vertical = scrollPane.getVerticalScrollBar(); vertical.setValue(vertical.getMaximum()); ``` revealed the same problem. Bizarrely, if I attach either of the above two blocks of code to a "Scroll to Bottom" button, and press this button manually after adding the new node, it all works fine! Please can anyone isolate the cause of this bug, or offer a fix/workaround?
2014/08/24
['https://Stackoverflow.com/questions/25467734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313909/']
Give it a Name ``` <Page.Resources> <Flyout x:Name="myFlyout" x:Key="WinningPopup"> // ...... </Flyout> </Page.Resources> ``` Then you can just Hide() ``` myFlyout.Hide(); ``` [FlyoutBase.Hide method](http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.primitives.flyoutbase.hide.aspx)
``` public void btnRestart_Click(object sender, RoutedEventArgs) { ((((sender as Button).Parent as StackPanel).Parent as StackPanel).Parent as Flyout).Hide(); } ``` Very ugly but should work.
25,467,734
I have a JXTreeTable with an add button. The button works as expected: it adds a new node to the end, with values that (for the purpose of testing) are hard-coded into my program. The line: ``` modelSupport.fireChildAdded(new TreePath(root), noOfChildren-1, dataNode); ``` tells the JXTreeTable to recognise the update made to the TreeTableModel, and to refresh accordingly. I then execute: ``` treeTable.changeSelection(treeTable.getRowCount()-1, 0, false, false); ``` to automatically select this new node. This works as expected, BUT I also expected it to automatically scroll to bring this new node into sight, which it does not. Instead, it scrolls to show only the penultimate node, leaving the new node hidden just slightly beyond view. I've also tried using tricks to programmatically scroll to the final record. However, this code: ``` JScrollBar vertical = scrollPane.getVerticalScrollBar(); vertical.setValue(vertical.getMaximum()); ``` revealed the same problem. Bizarrely, if I attach either of the above two blocks of code to a "Scroll to Bottom" button, and press this button manually after adding the new node, it all works fine! Please can anyone isolate the cause of this bug, or offer a fix/workaround?
2014/08/24
['https://Stackoverflow.com/questions/25467734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313909/']
Give it a Name ``` <Page.Resources> <Flyout x:Name="myFlyout" x:Key="WinningPopup"> // ...... </Flyout> </Page.Resources> ``` Then you can just Hide() ``` myFlyout.Hide(); ``` [FlyoutBase.Hide method](http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.primitives.flyoutbase.hide.aspx)
You need to get it first. Then you can call `Hide`. ``` FlyoutBase.GetAttachedFlyout((FrameworkElement)LayoutRoot).Hide(); ```
25,467,734
I have a JXTreeTable with an add button. The button works as expected: it adds a new node to the end, with values that (for the purpose of testing) are hard-coded into my program. The line: ``` modelSupport.fireChildAdded(new TreePath(root), noOfChildren-1, dataNode); ``` tells the JXTreeTable to recognise the update made to the TreeTableModel, and to refresh accordingly. I then execute: ``` treeTable.changeSelection(treeTable.getRowCount()-1, 0, false, false); ``` to automatically select this new node. This works as expected, BUT I also expected it to automatically scroll to bring this new node into sight, which it does not. Instead, it scrolls to show only the penultimate node, leaving the new node hidden just slightly beyond view. I've also tried using tricks to programmatically scroll to the final record. However, this code: ``` JScrollBar vertical = scrollPane.getVerticalScrollBar(); vertical.setValue(vertical.getMaximum()); ``` revealed the same problem. Bizarrely, if I attach either of the above two blocks of code to a "Scroll to Bottom" button, and press this button manually after adding the new node, it all works fine! Please can anyone isolate the cause of this bug, or offer a fix/workaround?
2014/08/24
['https://Stackoverflow.com/questions/25467734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313909/']
``` public void btnRestart_Click(object sender, RoutedEventArgs) { ((((sender as Button).Parent as StackPanel).Parent as StackPanel).Parent as Flyout).Hide(); } ``` Very ugly but should work.
You need to get it first. Then you can call `Hide`. ``` FlyoutBase.GetAttachedFlyout((FrameworkElement)LayoutRoot).Hide(); ```
45,658
I move an elbow from my IK bone and the other arm moves too. Why is that? how can i solve it? Help =([![enter image description here](https://i.stack.imgur.com/ZMiDL.png)](https://i.stack.imgur.com/ZMiDL.png)
2016/01/26
['https://blender.stackexchange.com/questions/45658', 'https://blender.stackexchange.com', 'https://blender.stackexchange.com/users/21236/']
Your bone is called Bone.011 so it's not getting mirrored properly. You need to make sure the bones have names like hand.l, hand.r (for the other side) and so on. For the automatic weighting, you can just redo it by reparenting the mesh to the armature with automatic weights. Another thing that can break the automatic weights are incorrect normals, so you can go into edit mode, select all vertices and Recalculate Normals to make sure they are good.
When you link your armature to your mesh using automatic weight, sometimes the weight is applied wrongly to the mesh. It could be that you did not apply your mesh's scale. 1. In object mode, Hit `Alt``A` 2. Select "Scale" from the Drop down menu. You could also go to the vertex group control panel and manually remove those vertices that aren't suppose to be affected by the bone.
49,192,427
How could **this.\_arr** array be updated inside a socket.io callback? ``` class SocketClass{ constructor(server) { this._arr = []; this._io = require('socket.io').listen(server); this._initListeners(); } _initListeners() { this._io.on('connection', (socket, arr) => { socket.on('event1', (data) => { this._arr.push(data); }); }); } } ``` The problem is that **this.\_arr** is ***undefined*** inside a callback. I suppose it's because **this** is referencing to callback function itself...
2018/03/09
['https://Stackoverflow.com/questions/49192427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1811410/']
I'd use a data attribute for this. Store a template for the image src and a path value for each button, then update the image src values accordingly for each button click... ```js var buttons = document.querySelectorAll("button"); var images = document.querySelectorAll("img"); [].forEach.call(buttons, function(button) { button.addEventListener("click", function() { var path = this.getAttribute("data-path"); [].forEach.call(images, function(img) { var src = img.getAttribute("data-src-template").replace("{path}", path); img.src = src; console.log(img.src); }); }); }); // intialize the image... document.querySelector("#one").click(); ``` ```html <button id="one" type="button" data-path="dist/one">This should change the path to "dist/one/"</button><br/> <button id="two" type="button" data-path="dist/two">This should change the path to "dist/two/"</button><br/> <button id="three" type="button" data-path="dist/three">This should change the path to "dist/three/"</button><br/> <img data-src-template="{path}/rocket.png" alt="" /> <img data-src-template="{path}/rocket.png" alt="" /> <img data-src-template="{path}/rocket.png" alt="" /> ``` This gives you what you need as well as being flexible if the path format ever changes, since everything you need is defined in the html and the script never needs to change. For example, if you decided to move the images into another subfolder you could just change the image tag and it would still work... ``` <img data-src-template="newSubFolder/{path}/rocket.png" alt="" /> ```
I believe you can do that by creating script. If you assign ID to each of the `<img>` tags you can then do something like: ``` document.getElementById('exampleID').innerHTML="<src="new_path">"; ``` Eventually put each `<img>` tag in DIV ``` <div id=someid> <img src="dist/one/rocket.png" alt="" /> </div> ``` Script: ``` document.getElementById('someid').innerHTML="<img src="new_path"/>"; ``` I did not test it but the answer should be really close to this. I hope this was helpfull.
612,405
Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function such that $$E(u+v)=E(u)E(v).$$ Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. My partial answer: The function $x\mapsto e^{ax}$ satisfies the properties immediately. For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then $$E'(x+y)=E(y)E'(x)$$. I don't know how to continue the answer. Could you give me some hint? Thanks.
2013/12/19
['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']
$\newcommand{\+}{^{\dagger}}% \newcommand{\angles}[1]{\left\langle #1 \right\rangle}% \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}% \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}% \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}% \newcommand{\dd}{{\rm d}}% \newcommand{\ds}[1]{\displaystyle{#1}}% \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}% \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}% \newcommand{\fermi}{\,{\rm f}}% \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}% \newcommand{\half}{{1 \over 2}}% \newcommand{\ic}{{\rm i}}% \newcommand{\iff}{\Longleftrightarrow} \newcommand{\imp}{\Longrightarrow}% \newcommand{\isdiv}{\,\left.\right\vert\,}% \newcommand{\ket}[1]{\left\vert #1\right\rangle}% \newcommand{\ol}[1]{\overline{#1}}% \newcommand{\pars}[1]{\left( #1 \right)}% \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\pp}{{\cal P}}% \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}% \newcommand{\sech}{\,{\rm sech}}% \newcommand{\sgn}{\,{\rm sgn}}% \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} \newcommand{\ul}[1]{\underline{#1}}% \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$ The probability density for the step $n$ is given by $\ds{{\rm p}\pars{\vec{r}\_{n}} \equiv {\delta\pars{r\_{n} - 1} \over 2\pi}}$. The probability density $\pp\_{N}\pars{\vec{r}}$ of arriving at $\vec{r}$ after $N$ steps is given by: > > \begin{align} > \pp\_{N}\pars{\vec{r}} > &\equiv > \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots > \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} > \delta\pars{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}} > \\[3mm]&= > \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots > \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} > \int\exp\pars{\ic\vec{k}\cdot\bracks{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}}} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > \\[3mm]&= > \int\expo{\ic\vec{k}\cdot\vec{r}} > \bracks{\int\dd^{2}\vec{R}\,{\rm p}\pars{\vec{R}}\expo{-\ic\vec{k}\cdot\vec{R}}}^{N} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > = > \int\expo{\ic\vec{k}\cdot\vec{r}} > \bracks{\int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi}}^{N} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > \end{align} > However $$ \int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} = \int\_{-\pi}^{\pi}\expo{\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} = {1 \over \pi}\int\_{0}^{\pi}\expo{\ic k\cos\pars{\theta}}\,\dd\theta = {\rm J}\_{0}\pars{k} $$ where ${\rm J}\_{\nu}\pars{k}$ is the $\nu$-$\it\mbox{order Bessel Function of the First Kind}$. > > \begin{align} > \pp\_{N}\pars{\vec{r}} > &= > \int\expo{\ic\vec{k}\cdot\vec{r}}{\rm J}\_{0}^{N}\pars{k} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > = > {1 \over 2\pi}\int\_{0}^{\infty}\dd k\,k\,{\rm J}\_{0}^{N}\pars{k}\int\_{0}^{2\pi} > \expo{\ic kr\cos\pars{\theta}}\,{\dd\theta \over 2\pi} > \end{align} > $$ > \color{#ff0000}{\pp\_{N}\pars{\vec{r}} > = > {1 \over 2\pi}\int\_{0}^{\infty}{\rm J}\_{0}\pars{kr}{\rm J}\_{0}^{N}\pars{k}k > \,\dd k} > $$ > The probability ${\rm P}\_{N{\Huge\circ}}$ that it returns to the unit circle after $N$ steps is given by: \begin{align} \color{#0000ff}{\large{\rm P}\_{N{\Huge\circ}}} &= \int\_{r\ <\ 1}\pp\_{N}\pars{\vec{r}}\,\dd^{2}\vec{r} = \int\_{0}^{\infty}\overbrace{\bracks{\int\_{0}^{1}{\rm J}\_{0}\pars{kr}r\,\dd r}} ^{{\rm J}\_{1}\pars{k}/k} {\rm J}\_{0}^{N}\pars{k}k\,\dd k \\[3mm]&= \color{#0000ff}{\large\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}^{N}\pars{k}\,\dd k} \end{align} We compute a few values with Wolfram Alpha: $$ \begin{array}{rclrcl} {\rm P}\_{0{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} \,\dd k & = & 1\,,\quad {\rm P}\_{1{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}\pars{k}\,\dd k & = & \half \\ {\rm P}\_{2{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{2}\pars{k} \,\dd k & = & {1 \over 3}\,,\quad {\rm P}\_{3{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}^{3}\pars{k}\,\dd k & = & {1 \over 4} \\ {\rm P}\_{4{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{4}\pars{k} \,\dd k & = & {1 \over 5}\,,\quad {\rm P}\_{5{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}^{5}\pars{k}\,\dd k & = & {1 \over 6} \end{array} $$ It $\tt\large seems$ the exact result is $\ds{% {\rm P}\_{N{\Huge\circ}} = \int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{N}\pars{k} \,\dd k = {1 \over N + 1}}$ Mathematica can solve this integral and it yields the $\ul{\mbox{exact result}}$ $\color{#0000ff}{\Large{1 \over N + 1}}$ when $\color{#ff0000}{\large\Re N > -1}$.
You can create a probility dristribution for the location after one step (the unit circle with a certain constant prbability). After two steps, I think that should be doable too. You can also carculate for each point the probability of entering de unit disk in the next step. Then, by combining the probability distribution ($P\_1(x,y)$) and the probability of ending in the disk $P\_2(x,y)$, you get $$ \int P\_1(x,y)P\_2(x,y) \,dx\,dy $$
612,405
Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function such that $$E(u+v)=E(u)E(v).$$ Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. My partial answer: The function $x\mapsto e^{ax}$ satisfies the properties immediately. For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then $$E'(x+y)=E(y)E'(x)$$. I don't know how to continue the answer. Could you give me some hint? Thanks.
2013/12/19
['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']
$\newcommand{\+}{^{\dagger}}% \newcommand{\angles}[1]{\left\langle #1 \right\rangle}% \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}% \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}% \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}% \newcommand{\dd}{{\rm d}}% \newcommand{\ds}[1]{\displaystyle{#1}}% \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}% \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}% \newcommand{\fermi}{\,{\rm f}}% \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}% \newcommand{\half}{{1 \over 2}}% \newcommand{\ic}{{\rm i}}% \newcommand{\iff}{\Longleftrightarrow} \newcommand{\imp}{\Longrightarrow}% \newcommand{\isdiv}{\,\left.\right\vert\,}% \newcommand{\ket}[1]{\left\vert #1\right\rangle}% \newcommand{\ol}[1]{\overline{#1}}% \newcommand{\pars}[1]{\left( #1 \right)}% \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\pp}{{\cal P}}% \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}% \newcommand{\sech}{\,{\rm sech}}% \newcommand{\sgn}{\,{\rm sgn}}% \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} \newcommand{\ul}[1]{\underline{#1}}% \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$ The probability density for the step $n$ is given by $\ds{{\rm p}\pars{\vec{r}\_{n}} \equiv {\delta\pars{r\_{n} - 1} \over 2\pi}}$. The probability density $\pp\_{N}\pars{\vec{r}}$ of arriving at $\vec{r}$ after $N$ steps is given by: > > \begin{align} > \pp\_{N}\pars{\vec{r}} > &\equiv > \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots > \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} > \delta\pars{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}} > \\[3mm]&= > \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots > \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} > \int\exp\pars{\ic\vec{k}\cdot\bracks{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}}} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > \\[3mm]&= > \int\expo{\ic\vec{k}\cdot\vec{r}} > \bracks{\int\dd^{2}\vec{R}\,{\rm p}\pars{\vec{R}}\expo{-\ic\vec{k}\cdot\vec{R}}}^{N} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > = > \int\expo{\ic\vec{k}\cdot\vec{r}} > \bracks{\int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi}}^{N} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > \end{align} > However $$ \int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} = \int\_{-\pi}^{\pi}\expo{\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} = {1 \over \pi}\int\_{0}^{\pi}\expo{\ic k\cos\pars{\theta}}\,\dd\theta = {\rm J}\_{0}\pars{k} $$ where ${\rm J}\_{\nu}\pars{k}$ is the $\nu$-$\it\mbox{order Bessel Function of the First Kind}$. > > \begin{align} > \pp\_{N}\pars{\vec{r}} > &= > \int\expo{\ic\vec{k}\cdot\vec{r}}{\rm J}\_{0}^{N}\pars{k} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > = > {1 \over 2\pi}\int\_{0}^{\infty}\dd k\,k\,{\rm J}\_{0}^{N}\pars{k}\int\_{0}^{2\pi} > \expo{\ic kr\cos\pars{\theta}}\,{\dd\theta \over 2\pi} > \end{align} > $$ > \color{#ff0000}{\pp\_{N}\pars{\vec{r}} > = > {1 \over 2\pi}\int\_{0}^{\infty}{\rm J}\_{0}\pars{kr}{\rm J}\_{0}^{N}\pars{k}k > \,\dd k} > $$ > The probability ${\rm P}\_{N{\Huge\circ}}$ that it returns to the unit circle after $N$ steps is given by: \begin{align} \color{#0000ff}{\large{\rm P}\_{N{\Huge\circ}}} &= \int\_{r\ <\ 1}\pp\_{N}\pars{\vec{r}}\,\dd^{2}\vec{r} = \int\_{0}^{\infty}\overbrace{\bracks{\int\_{0}^{1}{\rm J}\_{0}\pars{kr}r\,\dd r}} ^{{\rm J}\_{1}\pars{k}/k} {\rm J}\_{0}^{N}\pars{k}k\,\dd k \\[3mm]&= \color{#0000ff}{\large\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}^{N}\pars{k}\,\dd k} \end{align} We compute a few values with Wolfram Alpha: $$ \begin{array}{rclrcl} {\rm P}\_{0{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} \,\dd k & = & 1\,,\quad {\rm P}\_{1{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}\pars{k}\,\dd k & = & \half \\ {\rm P}\_{2{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{2}\pars{k} \,\dd k & = & {1 \over 3}\,,\quad {\rm P}\_{3{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}^{3}\pars{k}\,\dd k & = & {1 \over 4} \\ {\rm P}\_{4{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{4}\pars{k} \,\dd k & = & {1 \over 5}\,,\quad {\rm P}\_{5{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}^{5}\pars{k}\,\dd k & = & {1 \over 6} \end{array} $$ It $\tt\large seems$ the exact result is $\ds{% {\rm P}\_{N{\Huge\circ}} = \int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{N}\pars{k} \,\dd k = {1 \over N + 1}}$ Mathematica can solve this integral and it yields the $\ul{\mbox{exact result}}$ $\color{#0000ff}{\Large{1 \over N + 1}}$ when $\color{#ff0000}{\large\Re N > -1}$.
This is not a complete answer, but is kind of long for a comment. For $t=2$, draw a picture. It's pretty easy to see the answer is $1/3$. For the $t=3$ case, let the angles be $\theta\_1$, $\theta\_2$, and $\theta\_3$. By symmetry, you can assume without loss of generality that $\theta\_1 = 0$. So you need to find the probability that $\|\langle 1, 0 \rangle + \langle \cos\theta\_2, \sin\theta\_2 \rangle +\langle \cos\theta\_3,\sin\theta\_3\rangle \|<1$. A little computation shows that this is equals $P(1+\cos\theta\_2+\cos\theta\_3+\cos(\theta\_2-\theta\_3)<0)$, where $\theta\_2$ and $\theta\_3$ are chosen independently from the uniform distribution on $[0,2\pi]$. That's as far as I got. This is the probability that the particle is in the unit disc *at time* $t=3$ (not $t$ equals 2 or 3).
612,405
Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function such that $$E(u+v)=E(u)E(v).$$ Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. My partial answer: The function $x\mapsto e^{ax}$ satisfies the properties immediately. For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then $$E'(x+y)=E(y)E'(x)$$. I don't know how to continue the answer. Could you give me some hint? Thanks.
2013/12/19
['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']
$\newcommand{\+}{^{\dagger}}% \newcommand{\angles}[1]{\left\langle #1 \right\rangle}% \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}% \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}% \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}% \newcommand{\dd}{{\rm d}}% \newcommand{\ds}[1]{\displaystyle{#1}}% \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}% \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}% \newcommand{\fermi}{\,{\rm f}}% \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}% \newcommand{\half}{{1 \over 2}}% \newcommand{\ic}{{\rm i}}% \newcommand{\iff}{\Longleftrightarrow} \newcommand{\imp}{\Longrightarrow}% \newcommand{\isdiv}{\,\left.\right\vert\,}% \newcommand{\ket}[1]{\left\vert #1\right\rangle}% \newcommand{\ol}[1]{\overline{#1}}% \newcommand{\pars}[1]{\left( #1 \right)}% \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\pp}{{\cal P}}% \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}% \newcommand{\sech}{\,{\rm sech}}% \newcommand{\sgn}{\,{\rm sgn}}% \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} \newcommand{\ul}[1]{\underline{#1}}% \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$ The probability density for the step $n$ is given by $\ds{{\rm p}\pars{\vec{r}\_{n}} \equiv {\delta\pars{r\_{n} - 1} \over 2\pi}}$. The probability density $\pp\_{N}\pars{\vec{r}}$ of arriving at $\vec{r}$ after $N$ steps is given by: > > \begin{align} > \pp\_{N}\pars{\vec{r}} > &\equiv > \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots > \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} > \delta\pars{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}} > \\[3mm]&= > \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots > \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} > \int\exp\pars{\ic\vec{k}\cdot\bracks{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}}} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > \\[3mm]&= > \int\expo{\ic\vec{k}\cdot\vec{r}} > \bracks{\int\dd^{2}\vec{R}\,{\rm p}\pars{\vec{R}}\expo{-\ic\vec{k}\cdot\vec{R}}}^{N} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > = > \int\expo{\ic\vec{k}\cdot\vec{r}} > \bracks{\int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi}}^{N} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > \end{align} > However $$ \int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} = \int\_{-\pi}^{\pi}\expo{\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} = {1 \over \pi}\int\_{0}^{\pi}\expo{\ic k\cos\pars{\theta}}\,\dd\theta = {\rm J}\_{0}\pars{k} $$ where ${\rm J}\_{\nu}\pars{k}$ is the $\nu$-$\it\mbox{order Bessel Function of the First Kind}$. > > \begin{align} > \pp\_{N}\pars{\vec{r}} > &= > \int\expo{\ic\vec{k}\cdot\vec{r}}{\rm J}\_{0}^{N}\pars{k} > \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} > = > {1 \over 2\pi}\int\_{0}^{\infty}\dd k\,k\,{\rm J}\_{0}^{N}\pars{k}\int\_{0}^{2\pi} > \expo{\ic kr\cos\pars{\theta}}\,{\dd\theta \over 2\pi} > \end{align} > $$ > \color{#ff0000}{\pp\_{N}\pars{\vec{r}} > = > {1 \over 2\pi}\int\_{0}^{\infty}{\rm J}\_{0}\pars{kr}{\rm J}\_{0}^{N}\pars{k}k > \,\dd k} > $$ > The probability ${\rm P}\_{N{\Huge\circ}}$ that it returns to the unit circle after $N$ steps is given by: \begin{align} \color{#0000ff}{\large{\rm P}\_{N{\Huge\circ}}} &= \int\_{r\ <\ 1}\pp\_{N}\pars{\vec{r}}\,\dd^{2}\vec{r} = \int\_{0}^{\infty}\overbrace{\bracks{\int\_{0}^{1}{\rm J}\_{0}\pars{kr}r\,\dd r}} ^{{\rm J}\_{1}\pars{k}/k} {\rm J}\_{0}^{N}\pars{k}k\,\dd k \\[3mm]&= \color{#0000ff}{\large\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}^{N}\pars{k}\,\dd k} \end{align} We compute a few values with Wolfram Alpha: $$ \begin{array}{rclrcl} {\rm P}\_{0{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} \,\dd k & = & 1\,,\quad {\rm P}\_{1{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}\pars{k}\,\dd k & = & \half \\ {\rm P}\_{2{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{2}\pars{k} \,\dd k & = & {1 \over 3}\,,\quad {\rm P}\_{3{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}^{3}\pars{k}\,\dd k & = & {1 \over 4} \\ {\rm P}\_{4{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{4}\pars{k} \,\dd k & = & {1 \over 5}\,,\quad {\rm P}\_{5{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} {\rm J}\_{0}^{5}\pars{k}\,\dd k & = & {1 \over 6} \end{array} $$ It $\tt\large seems$ the exact result is $\ds{% {\rm P}\_{N{\Huge\circ}} = \int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{N}\pars{k} \,\dd k = {1 \over N + 1}}$ Mathematica can solve this integral and it yields the $\ul{\mbox{exact result}}$ $\color{#0000ff}{\Large{1 \over N + 1}}$ when $\color{#ff0000}{\large\Re N > -1}$.
This addresses the t=3 case: Assume you start at origin ($P\_0$), and without loss of generality, assume first move is to $P\_1=(1, 0)$. Your second move will be to $P\_2=(1 + cos(\theta), sin(\theta))$, where theta is uniform [0, $\pi$] (can ignore the [$\pi,2\pi$] range due to symmetry). Density function of $\theta$ is just $f(\theta)=\frac{1}{\pi}$ Draw unit-circles around $P\_0$ and $P\_2$, and let X be the second intersection point of these two circles (aside from $P\_1$). Now draw the quadrilateral $\overline{P\_0P\_1P\_2X}$. Turns out this is actually a rhombus, with each side of length 1. From geometry of parallel-lines, one can see that the angle $\angle P\_1P\_2X$ equals theta. Also, this angle $\theta$ subtends the arc of the $P\_2$ circle that is inside the $P\_0$ circle. Therefore, for any given $\theta$, the probability that a chosen point on the $P\_2$ circle will be inside the $P\_0$ circle is simply $\frac{\theta}{2\pi}$. Putting this all together, the probability that we return to the unit-circle after 3 moves is: $\int^\pi\_0(1/\pi) \* (\theta/2\pi) d\theta = 1/4$
612,405
Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function such that $$E(u+v)=E(u)E(v).$$ Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. My partial answer: The function $x\mapsto e^{ax}$ satisfies the properties immediately. For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then $$E'(x+y)=E(y)E'(x)$$. I don't know how to continue the answer. Could you give me some hint? Thanks.
2013/12/19
['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']
This is a classic problem, first solved by the Dutch mathematician J.C. Kluyver in 1905. He derives the result given in the [answer](https://math.stackexchange.com/a/612395/87355) of Felix Marin, that the probability to return to the unit disc after $n$ steps is $1/(n+1)$: ![](https://ilorentz.org/beenakker/MO/Kluyver1.png) ![](https://ilorentz.org/beenakker/MO/Kluyver2.png) For a purely geometric derivation, see [arXiv:1007.4870](https://arxiv.org/abs/1007.4870). (There the result is attributed to Rayleigh, but it appears Rayleigh only considered the large-$n$ limit.) See also this [MO posting.](https://mathoverflow.net/a/347336/11260)
You can create a probility dristribution for the location after one step (the unit circle with a certain constant prbability). After two steps, I think that should be doable too. You can also carculate for each point the probability of entering de unit disk in the next step. Then, by combining the probability distribution ($P\_1(x,y)$) and the probability of ending in the disk $P\_2(x,y)$, you get $$ \int P\_1(x,y)P\_2(x,y) \,dx\,dy $$
612,405
Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function such that $$E(u+v)=E(u)E(v).$$ Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. My partial answer: The function $x\mapsto e^{ax}$ satisfies the properties immediately. For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then $$E'(x+y)=E(y)E'(x)$$. I don't know how to continue the answer. Could you give me some hint? Thanks.
2013/12/19
['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']
This is a classic problem, first solved by the Dutch mathematician J.C. Kluyver in 1905. He derives the result given in the [answer](https://math.stackexchange.com/a/612395/87355) of Felix Marin, that the probability to return to the unit disc after $n$ steps is $1/(n+1)$: ![](https://ilorentz.org/beenakker/MO/Kluyver1.png) ![](https://ilorentz.org/beenakker/MO/Kluyver2.png) For a purely geometric derivation, see [arXiv:1007.4870](https://arxiv.org/abs/1007.4870). (There the result is attributed to Rayleigh, but it appears Rayleigh only considered the large-$n$ limit.) See also this [MO posting.](https://mathoverflow.net/a/347336/11260)
This is not a complete answer, but is kind of long for a comment. For $t=2$, draw a picture. It's pretty easy to see the answer is $1/3$. For the $t=3$ case, let the angles be $\theta\_1$, $\theta\_2$, and $\theta\_3$. By symmetry, you can assume without loss of generality that $\theta\_1 = 0$. So you need to find the probability that $\|\langle 1, 0 \rangle + \langle \cos\theta\_2, \sin\theta\_2 \rangle +\langle \cos\theta\_3,\sin\theta\_3\rangle \|<1$. A little computation shows that this is equals $P(1+\cos\theta\_2+\cos\theta\_3+\cos(\theta\_2-\theta\_3)<0)$, where $\theta\_2$ and $\theta\_3$ are chosen independently from the uniform distribution on $[0,2\pi]$. That's as far as I got. This is the probability that the particle is in the unit disc *at time* $t=3$ (not $t$ equals 2 or 3).
612,405
Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function such that $$E(u+v)=E(u)E(v).$$ Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. My partial answer: The function $x\mapsto e^{ax}$ satisfies the properties immediately. For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then $$E'(x+y)=E(y)E'(x)$$. I don't know how to continue the answer. Could you give me some hint? Thanks.
2013/12/19
['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']
This is a classic problem, first solved by the Dutch mathematician J.C. Kluyver in 1905. He derives the result given in the [answer](https://math.stackexchange.com/a/612395/87355) of Felix Marin, that the probability to return to the unit disc after $n$ steps is $1/(n+1)$: ![](https://ilorentz.org/beenakker/MO/Kluyver1.png) ![](https://ilorentz.org/beenakker/MO/Kluyver2.png) For a purely geometric derivation, see [arXiv:1007.4870](https://arxiv.org/abs/1007.4870). (There the result is attributed to Rayleigh, but it appears Rayleigh only considered the large-$n$ limit.) See also this [MO posting.](https://mathoverflow.net/a/347336/11260)
This addresses the t=3 case: Assume you start at origin ($P\_0$), and without loss of generality, assume first move is to $P\_1=(1, 0)$. Your second move will be to $P\_2=(1 + cos(\theta), sin(\theta))$, where theta is uniform [0, $\pi$] (can ignore the [$\pi,2\pi$] range due to symmetry). Density function of $\theta$ is just $f(\theta)=\frac{1}{\pi}$ Draw unit-circles around $P\_0$ and $P\_2$, and let X be the second intersection point of these two circles (aside from $P\_1$). Now draw the quadrilateral $\overline{P\_0P\_1P\_2X}$. Turns out this is actually a rhombus, with each side of length 1. From geometry of parallel-lines, one can see that the angle $\angle P\_1P\_2X$ equals theta. Also, this angle $\theta$ subtends the arc of the $P\_2$ circle that is inside the $P\_0$ circle. Therefore, for any given $\theta$, the probability that a chosen point on the $P\_2$ circle will be inside the $P\_0$ circle is simply $\frac{\theta}{2\pi}$. Putting this all together, the probability that we return to the unit-circle after 3 moves is: $\int^\pi\_0(1/\pi) \* (\theta/2\pi) d\theta = 1/4$
41,073,364
how can I ignore all the duplicating records and get only those which do not have a tie in mysql for example; from the following data set; ``` 1|item1| data1 2|item1| data2 3|item2| data3 4|item3| data4 ``` I want to get this get this kind of results; ``` 3|item2| data3 4|item3| data4 ```
2016/12/10
['https://Stackoverflow.com/questions/41073364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6870393/']
before call third function you need to call first two functions that will assign values to $this->a & $this->b try below code : ``` protected $a; protected $b; function fast() { $a=10; $this->a = $a; } function slow() { $b=20; $this->b = $b; } function avg() { $c=$this->a+$this->b; echo $c; } } $relay = new race(); $relay->fast(); $relay->slow(); $relay->avg(); ```
Firstly, you are using object properties incorrectly. You need to first specify the scope of the property; in this case, I used protected scopes so you can extend the class as and when you need to use the properties directly. Also, note if you're trying to add an **unset** variable, it will not work, you can either add this instance to your `__construct()` or set them to equal to 0 in the property instance. ``` class Speed { protected $_a = 0; protected $_b = 0; public function fast() { $this->_a = 20; return $this; } public function slow() { $this->_b = 10; return $this; } public function avg() { return $this->_a + $this->_b; } } ``` This can then be used like this: ``` $s = new Speed(); $s->fast()->slow(); // todo: add logic echo $s->avg(); ``` --- **Update:** Just side note, try **not** to output directly to a view in a method closure. Use templates, return the values from your methods and output them to a template.
3,090,509
--- I have been trying to simplify the following summation with the intention of breaking it into less complex summations, but I keep getting stuck no matter what I try: $$\sum\_{i=0}^{k-1} 3^{i} \cdot \frac{\sqrt{\frac{n}{3^i}}}{\log\_{2}\frac{n}{3^i}}$$ Among the things I tried was raising to the power of $1/2$\* the upper part of the fraction to cancel out the $3^i$, but after that I'm left with $\sqrt{n\,3^i}$ anyways without any clear steps to simplify further. Also tried putting the lower part of the fraction as a difference of logarithms, but got stuck in the same way. I even tried to use the change of base identity to put the lower part of the fraction in terms of $\log\_3(2)$ and see if I could have canceled something but no luck. Just simplifying the sum would be good enough since I can try to take it from there by substituting $k\; (k = \log\_3(n)$ in case that is useful).
2019/01/28
['https://math.stackexchange.com/questions/3090509', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/635189/']
The issue expression can be presented in the form of $$S={\large\sum\limits\_{i=0}^{k-1}}3^i\dfrac{\sqrt{\dfrac n{3^i}}}{\log\_2\dfrac{n}{3^i}} = \sqrt n \log\_32{\large\sum\limits\_{i=0}^{k-1}}\dfrac{(\sqrt3)^i}{\log\_3{n}-i},$$ so $$S=\sqrt n \log\_32\left(3^{k/2}\Phi(\sqrt3,1,k-\log\_3n)-\Phi(\sqrt3,1,-\log\_3n)\right)$$ (see also [Wolfram Alpha](https://www.wolframalpha.com/input/?i=sum_(i%3D0,k-1)%20a%5Ei%2F(b-i))), where > > $$\Phi(z,s,a) = {\large\sum\limits\_{m=0}^\infty\,\dfrac > {z^m}{(m+a)^s}}$$ > is [Lerch transcendent](http://mathworld.wolfram.com/LerchTranscendent.html). > > > Assuming $k=\lceil\log\_3n -1\rceil,$ can be built the plots [for the issue sums](https://www.wolframalpha.com/input/?i=plot%20table%20sum_(j%3D0,%20ceil(log_3(n)%20-2))%20(sqrt(n)%20%20log_3(2)%203.0%5E(j%2F2)%20%2F(log_3(n)-j)),%20%7Bn,3,99%7D) [![The issue sums](https://i.stack.imgur.com/oUqlQ.png)](https://i.stack.imgur.com/oUqlQ.png) and [via Lerch transcendent](https://www.wolframalpha.com/input/?i=plot%20%7Bsqrt(n)%20%20log_3(2)%20(3%5E(ceil(log_3%20n%20-1)%2F2)%20HurwitzLerchPhi(sqrt3,%201,%20ceil(log_3%20n%20-1)%20-%20log_3(n))%20-%20HurwitzLerchPhi(sqrt3,%201,%20%20-%20log_3%20(n)))%7D,%20n%3D3,%2099) [![Lerch transcendent sums](https://i.stack.imgur.com/3jXyV.png)](https://i.stack.imgur.com/3jXyV.png) Easy to see that summation via Lerch transcendent is correct.
If I plug $$ \sum\_{i=0}^{\log\_3(n)-1}3^i \frac{\sqrt{\frac{n}{3^i}}}{\log\_2(\frac{n}{3^i})} $$ into Wolfram Mathematica, then I get no simplification, so an nice simplification probably does not exist. The best we can probably do is, with thanks to @NoChance, $$ \sum\_{i=0}^{\log\_3(n)-1}3^i \frac{\sqrt{\frac{n}{3^i}}}{\log\_2(\frac{n}{3^i})} = \sum\_{i=0}^{\log\_3(n)-1}3^i \frac{\sqrt{\frac{n}{3^i}}}{\log\_2(n)-\log\_2(3^i))} \\ =\sum\_{i=0}^{\log\_3(n)-1} 3^i\frac{\sqrt{\frac{n}{3^i}}}{\log\_2(n)-i\log\_2(3))} \\ =\sum\_{i=0}^{\log\_3(n)-1} \sqrt{n}\frac{3^i\sqrt{\frac{1}{3^i}}}{\log\_2(n)-i\log\_2(3))} \\ = \sqrt{n}\sum\_{i=0}^{\log\_3(n)-1}\frac{\sqrt{3^i}}{\log\_2(n)-i\log\_2(3))} \\ $$ If I plug this into Wolfram Mathematica, then we see that we get something $$ \sqrt{n}\sum\_{i=0}^{\log\_3(n)-1}\frac{\sqrt{3^i}}{\log\_2(n)-i\log\_2(3))} = -\frac{n\bigg(\log(3-\sqrt{3})-\log(3)\bigg)}{\log\_2(3)}-\frac{\sqrt{n}HyperGeometric2F1\bigg(1,\log\_3(3n),2+\log\_3(n),\frac{1}{\sqrt{3}}\bigg)}{\sqrt{3}\log\_2{3n}} $$ If we look at Wikipedia, <https://en.wikipedia.org/wiki/Hypergeometric_function>, for some more info on the Hypergeometric2F1 we see that there are no further simplifications listed.
50,219,323
My project is very similar to the famous ATM problem. I have to create a hotel check in/check out system. I have to get the user input for the last name and confirm it. However when I try to return the string, it tells me it cant convert string to int. ``` import java.util.Scanner; public class Keyboard { private Scanner input; String lastName; public Keyboard() { input = new Scanner( System.in); } public int getInput() { lastName = input.nextLine(); return lastName; } } ```
2018/05/07
['https://Stackoverflow.com/questions/50219323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9732237/']
The problem is that your server time is different from Google server time. And when you validate received token from google it might be that token will be valid in 1 or n seconds. That's why you get an error `JWT not yet valid` To fix it you can synchronize time of your server with google server time. Google doc how to do this is <https://developers.google.com/time/>
You can configure the system time as per google or if your computer is part of a domain and you don't want to change the domain controller config, then you can pass a clock object in the Validateasync method like this: ``` var googleUser = await GoogleJsonWebSignature.ValidateAsync(token, new GoogleJsonWebSignature.ValidationSettings() { Clock = new clock(), Audience = new[] { "your client id" } }); ``` For this, you need to make a class implementing the IClock interface as below: ``` public class clock : IClock { public DateTime Now => DateTime.Now.AddMinutes(5); public DateTime UtcNow => DateTime.UtcNow.AddMinutes(5); } ``` In this, you can set the time accordingly like if my system time is 5 min. ahead of google time, I'll add 5 min., then your token will be successfully validated. And to check the google time, you can make use of JwtSecurityTokenHandler class like: ``` var handler = new JwtSecurityTokenHandler(); var tokenS = handler.ReadToken(token) as JwtSecurityToken; ``` in tokenS, you will have a property as issued at which will provide the UTC time, if you want local time then you can use `toLocal()` method on that property and compare that time to your system's time.
23,341,774
I am trying to create a form that updates user information stored in an Oracle database, the updates are not going through correctly and I can't see a problem as I have the form printing out the SQL being submitted to oracle and it all checks out. Here is the php that forms the connection: ``` <?php $sql="select * from Members where MemberID = ".$_GET["memberid"]; $conn = oci_connect("user","pass", "conn"); $stmt = oci_parse($conn, $sql); oci_execute($stmt); $row=oci_fetch_row($stmt); oci_free_statement($stmt); oci_close($conn); ?> ``` Here is the form with an example or two of the forms inputs: ``` <div class="topwrapper"><img src="logo.png" alt="Peak Park Sailing Club"></div> <form name="form1" method="post" action="editmemhandler.php"> <input name="MemberID" type=hidden id="MemberID" value=<?php print $row[0];?>> <table class="infotable"> <tr> <td><strong>Member ID</strong></td> <td><input name="memberid" type="text" id="memberid" value=<?php print $row[0];?>></td> </tr> <tr> <td><strong>First Name</strong></td> <td><input name="firstname" type="text" id="firstname" value=<?php print $row[1];?>></td> </tr> ``` And here is the handler php: ``` <?php IF ($_POST[groupid]=="") $groupid=0; ELSE $groupid=$_POST[groupid]; $memberid=$_POST["memberid"]; $firstname=$_POST["firstname"]; $lastname=$_POST["lastname"]; $dob=$_POST["dob"]; $membertype=$_POST["membertype"]; $houseno=$_POST["houseno"]; $street=$_POST["street"]; $town=$_POST["town"]; $county=$_POST["county"]; $postcode=$_POST["postcode"]; $lastjoined=$_POST["lastjoined"]; $sql = "UPDATE Members SET firstname='$firstname', lastname='$lastname', dob='$dob', membertype='$membertype', groupid=$groupid, houseno='$houseno', street='$street', town='$town', county='$county', postcode='$postcode' where memberid=$memberid;"; $conn = oci_connect("user","pass", "conn"); $stmt = oci_parse($conn, $sql); oci_execute($stmt); print "Record updated ok </br>"; print $sql; oci_free_statement($stmt); oci_close($conn); ?> ``` I am very new to php and using it with Oracle so it is likely to be something obvious... Thanks in advance! Bob P
2014/04/28
['https://Stackoverflow.com/questions/23341774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3548774/']
Try this: ``` $conn = oci_connect("user","pass", "conn"); $sql = "UPDATE Members SET firstname=:firstname, lastname=:lastname, dob=:dob, membertype=:membertype, groupid=:groupid, houseno=:houseno, street=:street, town=:town, county=:county, postcode=:postcode where memberid=:memberid;"; $stmt = oci_parse($conn, $update); oci_bind_by_name($stmt, ':firstname', $firstname); oci_bind_by_name($stmt, ':lastname', $lastname); oci_bind_by_name($stmt, ':dob', $dob); oci_bind_by_name($stmt, ':membertype', $membertype); oci_bind_by_name($stmt, ':groupid', $groupid); oci_bind_by_name($stmt, ':houseno', $houseno); oci_bind_by_name($stmt, ':street', $street); oci_bind_by_name($stmt, ':county', $county); oci_bind_by_name($stmt, ':postcode', $postcode); oci_bind_by_name($stmt, ':memberid', $memberid); $result = oci_execute($stmt, OCI_DEFAULT); if (!$result) { echo oci_error(); } oci_commit($conn); ``` This way of working will reduce your sql injection a little aswell.. I wrote this just out of my head.. Havn't had the chance of testing this, because I don't have the oracle DB for it. But try it.
You haven't enclosed $memberid variable in qoutes in query .... `where memberid='$memberid';"`
39,871,505
``` public static void main(String[] args) throws Exception { Connection connection = getMySqlConnection(); CallableStatement proc = connection.prepareCall("{ call LCD_GetDispInfoAllTimeTable() }"); proc.registerOutParameter(1, Types.INTEGER); proc.execute(); int returnValue = proc.getInt(1); System.out.println(returnValue + ""); // conn.close(); } public static Connection getMySqlConnection() throws Exception { String driver = "com.mysql.jdbc.Driver"; String url = ""; String username = ""; String password = ""; Class.forName(driver); Connection conn = DriverManager.getConnection(url, username, password); return conn; } } ``` When I run this code I see a Exception in thread "main" java.sql.SQLException: Parameter index of 1 is out of range (1, 0) , why ? This procedure return : ``` Niemstów 07 pętla 10 05:33:00 3673114 11558169 754378 1 NŻ Niemstów 05 16 05:35:00 3669905 11556510 754379 3 NŻ Niemstów 03 16 05:37:00 3666969 11555665 754380 3 ``` My procedure ; ``` CREATE DEFINER=`root`@`%` PROCEDURE `LCD_GetDispInfoAllTimeTable`() BEGIN SELECT bs.name as bsName, tt.busstoptype as bsType, tt.time as ttTime, bs.longitude as lon, bs.latitude as lat, tt.timetable_id as ttID, Bus_Stop_Status_GET( tt.timetable_id, bst.timetable_id, bst.busstate_id ) as bus_stop_status -- 0 zrobiony, 1 - aktualny, 2- pomiędzy, 3 następne FROM (SELECT * FROM mpk_currentbusstate ORDER BY changestime desc LIMIT 1 )bst join mpk_timetable t ON( bst.timetable_id = t.timetable_id ) join mpk_timetable tt ON ( t.linelogin_id = tt.linelogin_id AND t.line_id = tt.line_id AND t.brigade = tt.brigade AND t.rate = tt.rate and t.schedudle_id = tt.schedudle_id) LEFT JOIN mpk_busstop bs ON (bs.busstop_id = tt.busstop_id) LEFT JOIN mpk_busstate bt ON( bst.busstate_id = bt.busstate_id ); END ```
2016/10/05
['https://Stackoverflow.com/questions/39871505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
You need to specify the parameter in your call String: `CallableStatement proc = connection.prepareCall("{ call LCD_GetDispInfoAllTimeTable(?) }");` Notice that `?`, it says that there is a parameter to be set. Now it knows that there is a parameter to be set, just like methods in Java or some other language. If you wanted to use multiple parameters you can write multiple `?`, like: `...LCD_GetDispInfoAllTimeTable(?, ?, ?)`.
as far as your procedecure declaration is concerned, its code is: ``` CREATE DEFINER=`root`@`%` PROCEDURE `LCD_GetDispInfoAllTimeTable`() BEGIN SELECT bs.name as bsName, tt.busstoptype as bsType, tt.time as ttTime, bs.longitude as lon, bs.latitude as lat, tt.timetable_id as ttID, Bus_Stop ``` where the procedure definition does NOT contain any parameter definition, so setParameter or registerOutParameter, cannot be applied for this procedure
8,412,710
I want to make a custom include tag (like `{% smart_include something %}` ), which realize what kind a thing we want to include and then call regular `{% include %}` tag. That's should be something like this: ``` @register.simple_tag def smart_include(something): if something == "post": template_name = "post.html" return regular_include_tag(template_name) ``` Is there a way to use `{% include %}` tag in python code, and how exactly? **UPD.** turn's out, the best way to solve this problem is just use `render_to_string` shortcut
2011/12/07
['https://Stackoverflow.com/questions/8412710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/277262/']
I assume there is a reason why you are not doing: ``` {% if foo %} {% include 'hello.html' %} {% endif %} ``` If `something` is a fixed number, you can use [inclusion tags](https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags-inclusion-tags). In your template instead of `{% smart_tag something %}`, you have `{% something %}`, then your tag library looks like this: ``` @register.inclusion_tag('post.html') def something(): return {} # return an empty dict ``` Finally, you can replicate the functionality of the include tag. This snippet should point you in the right direction: ``` filepath = '/full/path/to/your/template/%s' % something try: fp = open(filepath, 'r') output = fp.read() fp.close() except IOError: output = '' try: t = Template(output, name=filepath) return t.render(context) except TemplateSyntaxError, e: return '' # Fail silently. return output ```
If you look into the **django.template.loader\_tags** you fill find a function **do\_include** which is basically the function that is called when we use {% include %}. So you should be able to import it call the function itself in python. I have not tried this but I think it should work
8,412,710
I want to make a custom include tag (like `{% smart_include something %}` ), which realize what kind a thing we want to include and then call regular `{% include %}` tag. That's should be something like this: ``` @register.simple_tag def smart_include(something): if something == "post": template_name = "post.html" return regular_include_tag(template_name) ``` Is there a way to use `{% include %}` tag in python code, and how exactly? **UPD.** turn's out, the best way to solve this problem is just use `render_to_string` shortcut
2011/12/07
['https://Stackoverflow.com/questions/8412710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/277262/']
I assume there is a reason why you are not doing: ``` {% if foo %} {% include 'hello.html' %} {% endif %} ``` If `something` is a fixed number, you can use [inclusion tags](https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags-inclusion-tags). In your template instead of `{% smart_tag something %}`, you have `{% something %}`, then your tag library looks like this: ``` @register.inclusion_tag('post.html') def something(): return {} # return an empty dict ``` Finally, you can replicate the functionality of the include tag. This snippet should point you in the right direction: ``` filepath = '/full/path/to/your/template/%s' % something try: fp = open(filepath, 'r') output = fp.read() fp.close() except IOError: output = '' try: t = Template(output, name=filepath) return t.render(context) except TemplateSyntaxError, e: return '' # Fail silently. return output ```
`render_to_string` will render the given template\_name to an html string ```py from django.template.loader import render_to_string template_name = 'post.html' optional_context = {} html = render_to_string(template_name, optional_context) ```
73,394
This guy put money into my bank account and wanted me to send some of it to another person in Nigeria. 500.00 to be exact. But since he wired money into my account I was unable to touch the money. He told me it was a donation to UNICEF. Since I was unable to take the money out he threatened to get the police involved and said he was going to. I got a bunch of missed calls from an unknown number and a really unprofessional email from a guy who supposedly worked for UNICEF saying I had 4 hours until I am suppose to be visited by police and that there was nowhere I could run to. The money is still in my account I have not touched it. He has my bank account info, and I just want to know where I stand legally.
2016/12/06
['https://money.stackexchange.com/questions/73394', 'https://money.stackexchange.com', 'https://money.stackexchange.com/users/51081/']
> > He has my bank account info, and I just want to know where I stand legally. > > > Legally you can't keep the money. It would either go back to the originator or to Government unclaimed department. > > I got a bunch of missed calls from an unknown number and a really unprofessional email from a guy who supposedly worked for UNICEF saying I had 4 hours until I am suppose to be visited by police and that there was nowhere I could run to. > > > These are common tactics employed to ensure you take some action and transfer the real money somewhere. Do not succumb to such tactics. > > The money is still in my account I have not touched it. > > > Advise your Bank immediately that there is this deposit into your account that is not your's. Let the bank take appropriate action. Do not authorize Bank to debit your account. The max you can do is authorize the bank to reverse this transaction. The best is stick to statement that said transaction is not yours and Bank is free to do what is right. There is a small difference and very important. If you authorize bank to debit, you have initiated a payment. So if the original payment were revered by originator bank, you are left short of money. However if your instructions are very clear, that this specific transaction can be reversed, you cannot be additionally debited if this transaction is reversed. > > He has my bank account info, > > > Depending on how easy / difficult, my suggestion would be monitor this account closely, best is if you can close it out and open a new one.
To add to @Dheer's answer, this is almost certainly a scam. The money deposited into your account is not from a person that made an honest mistake with account numbers. It's coming from someone that has access to "send" money that isn't their own. I don't know exactly what they're doing to "send" the money but at some point in the near future your bank will claw that money back from you on the grounds that it was illegitimately transferred to you in the first place. If you send someone money on the premise that you're returning this money then that will be a separate transaction which won't be undone when the deposit in question is undone. Another possibility is that this person has gained access to an account from which they can send domestic wires but not international wires. Their hope is to send money to someone domestically (you) and that this person will then send the money on to Nigeria. If you comply with them; you, in a worst case scenario, could be seen as a money laundering accomplice in addition to having the deposit taken back from you. It's not very likely you wouldn't be seen as another victim of a scam but people have been thrown in jail for less. You should not respond to this person at all. Don't answer the phone when they call and ignore their emails. Don't delete the emails, it's possible that someone at the bank or LE want them. Call your bank immediately and tell them what's up.
176,688
I am converting RPG files in NTF\_Lambert\_II\_etendu to wgs\_84 using: ``` ogr2ogr -t_srs EPSG:4326 ilot_2008_027_wgs84_2.shp ilot_2008_027.shp ``` but the result is off by about 30 meters. Surprisingly, the same conversion using Qgis works fine. Could anybody tell me how to correct that or how to investigate the exact transformation qgis is doing? The proj file of the intial file is : ``` PROJCS["NTF_Lambert_II_etendu",GEOGCS["GCS_NTF",DATUM["D_NTF",SPHEROID["Clarke_1880_IGN",6378249.2,293.46602]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["False_Easting",600000.0],PARAMETER["False_Northing",2200000.0],PARAMETER["Central_Meridian",2.3372291667],PARAMETER["Standard_Parallel_1",45.8989188889],PARAMETER["Standard_Parallel_2",47.6960144444],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",46.8],UNIT["Meter",1.0]] ```
2016/01/13
['https://gis.stackexchange.com/questions/176688', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/49290/']
NTF Lambert II has a `towgs84` datum shift, but that is not included in the .prj file. The .prj file uses a different naming for the projection, so the EPSG code finder might fail. I assume QGIS assigns the correct EPSG code (maybe in the .qpj file), and makes a standard transformation from one EPSG code to another using full towgs84 parameters. You should get the same result with ogr2ogr using EPSG codes 27572, 7411, 7412 or 7421 as `-s_srs`.
As mentioned by @AndreJ specifying the EPSG code makes it work. Specifically the following work: ``` ogr2ogr -t_srs EPSG:4326 -s_srs EPSG:7421 ilot_2008_027_wgs84_2.shp ilot_2008_027.shp ``` Alternatively, I was trying to use the qgis python API to do it all in python using qgis but could not get it to work.
3,909
Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. Would I be able to use a fishing kayak like a regular touring/recreation kayak? Thanks
2013/04/01
['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']
I have used a touring kayak for fishing, and it works out ok. You can rig up a rod holder in your cockpit, but paddling is a bit awkward, though this is probably also a problem with any kayak used for fishing. It might be somewhat difficult to use a fishing kayak on overnight trips given that most fishing kayaks are sit on top (SOT) and have no internal storage.
I would recommend checking out something like Hobie's Mirage pedal driven kayaks. With their spiffy pedal drive, you can trivially outrun(outpedal?) just about anyone while hardly breaking a sweat. Additionally, because you power yourself with your feet, your hands are free for fishing. The mirage drive is also quiet as a corpse. No splashing sounds from your paddles, whatsoever. A guy I know has one of their fishing-specific models, and loves it. However, if you ever want to go on an overnight camping adventure via your kayaks, the storage capacity of the Hobies is pretty bad, and while in general portaging kayaks is no fun, portaging a Hobie kayak would be especially miserable. Otherwise, you could try getting a tandem traditional kayak. Perhaps you can sweet-talk your wife into paddling while you fish?
3,909
Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. Would I be able to use a fishing kayak like a regular touring/recreation kayak? Thanks
2013/04/01
['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']
Yes, there is definitely a performance difference between different types of kayaks. In fact, there are performance differences among the same types of kayaks. For example, a 14-foot kayak will always track more straightly than a 10-foot kayak. A wide recreational kayak will always have more primary stability than a narrower touring kayak. Even if you both get the same type of kayak I suspect you'll find they work differently for each of you. No doubt you both do not weigh the same -- if you're heavier, a given kayak will sit lower in the water than for her. That may result in increased stability, or it could mean that you capsize easily. Alternatively, consider height and armspan: if she's short she may find it difficult to paddle in a wide rec kayak where the paddle is constantly bumping the edge of the boat. In short: you should each look for a kayak that suits you. That means you will see performance differences between the two kayaks, but if the boats really do suit each of you, that won't be a problem because you've found something that fits well. As to a fishing kayak specifically, if you get a longer kayak than her you'll likely be able to keep up with her on a day trip (though at the expense of maneuverability). Of course, keeping up with a partner is about more than the just the kayak. The paddle will also make a difference (especially its weight as it relates to your fatigue), and paddling technique can be a big difference between feeling good at the end of an outing and feeling whipped.
I have used a touring kayak for fishing, and it works out ok. You can rig up a rod holder in your cockpit, but paddling is a bit awkward, though this is probably also a problem with any kayak used for fishing. It might be somewhat difficult to use a fishing kayak on overnight trips given that most fishing kayaks are sit on top (SOT) and have no internal storage.
3,909
Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. Would I be able to use a fishing kayak like a regular touring/recreation kayak? Thanks
2013/04/01
['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']
I have used a touring kayak for fishing, and it works out ok. You can rig up a rod holder in your cockpit, but paddling is a bit awkward, though this is probably also a problem with any kayak used for fishing. It might be somewhat difficult to use a fishing kayak on overnight trips given that most fishing kayaks are sit on top (SOT) and have no internal storage.
I have been considering just the same. I have come up with two kayacks that I like. The first is a fishing kayak by kudo. It tracks well and speed is good. I have a strong upper body so it makes it easier for me but its all in the core. Try different techniques as you will get tired just doing one. The other kayak is a 14 foot looksha by Necky. I have been eyeing that one for 3 years now. It is a sit in oh the kudo is a sit on top which I stood up in and tried paddle boarding on it. Great stability. The looksha tracks and maneuvers great. Not stable enough for fishing, what are you going to do when you land the mother of all fishes? How you bring that into the boat? Consider what you do more spending time with the wife or fishing in a kayak?
3,909
Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. Would I be able to use a fishing kayak like a regular touring/recreation kayak? Thanks
2013/04/01
['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']
Yes, there is definitely a performance difference between different types of kayaks. In fact, there are performance differences among the same types of kayaks. For example, a 14-foot kayak will always track more straightly than a 10-foot kayak. A wide recreational kayak will always have more primary stability than a narrower touring kayak. Even if you both get the same type of kayak I suspect you'll find they work differently for each of you. No doubt you both do not weigh the same -- if you're heavier, a given kayak will sit lower in the water than for her. That may result in increased stability, or it could mean that you capsize easily. Alternatively, consider height and armspan: if she's short she may find it difficult to paddle in a wide rec kayak where the paddle is constantly bumping the edge of the boat. In short: you should each look for a kayak that suits you. That means you will see performance differences between the two kayaks, but if the boats really do suit each of you, that won't be a problem because you've found something that fits well. As to a fishing kayak specifically, if you get a longer kayak than her you'll likely be able to keep up with her on a day trip (though at the expense of maneuverability). Of course, keeping up with a partner is about more than the just the kayak. The paddle will also make a difference (especially its weight as it relates to your fatigue), and paddling technique can be a big difference between feeling good at the end of an outing and feeling whipped.
I would recommend checking out something like Hobie's Mirage pedal driven kayaks. With their spiffy pedal drive, you can trivially outrun(outpedal?) just about anyone while hardly breaking a sweat. Additionally, because you power yourself with your feet, your hands are free for fishing. The mirage drive is also quiet as a corpse. No splashing sounds from your paddles, whatsoever. A guy I know has one of their fishing-specific models, and loves it. However, if you ever want to go on an overnight camping adventure via your kayaks, the storage capacity of the Hobies is pretty bad, and while in general portaging kayaks is no fun, portaging a Hobie kayak would be especially miserable. Otherwise, you could try getting a tandem traditional kayak. Perhaps you can sweet-talk your wife into paddling while you fish?
3,909
Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. Would I be able to use a fishing kayak like a regular touring/recreation kayak? Thanks
2013/04/01
['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']
There are a few differences between the SOT kayaks and a touring kayak that you'll want to consider. **Length** SOT kayaks tend to be shorter and wider than touring boats. This can make SOT's a little more stable but a longer boat will track better (go straight). The more rough the water you want to travel in the longer boat you want. **Storage** Touring boats will have much more storage in them as that's what they're meant to do. It's usually covered storage in the bow and stern of the boat. Sometimes SOT's have storage but most of the time it's sitting on top of the boat with you. Having gear on top of the boat makes it more accessible but easier to lose in the waves. **Ease of Use** SOT's are easy to use. Just sit on them and go. Touring boats take a little practice getting into and out of. A nylon or neoprene skirt to go around the cockpit and around your waist is a good thing to have in rough water or just to prevent drips from the paddle falling onto your lap. Using a skirt makes them a little more complicated to get into an out of though. **Cost** Touring boats tend to be longer and have more features so they'll probably cost you more. All the SOT's I've seen are made out of roto-molded plastic which is the least expensive to make. You can get touring boats out of roto-molded plastic, thermoformed plastic or fiberglass. Roto-molded is cheaper, heavier but very durable. Thermoformed is lighter and faster but more expensive. Fibreglass is the most expensive, the fastest but the most fragile. **Weather conditions** Rougher conditions in the water will warrant a longer boat and probably one of the touring variety. The longer boats will be more stable and you'll be much more dry being inside the touring boat with a skirt covering the cockpit. Hope that helps.
I would recommend checking out something like Hobie's Mirage pedal driven kayaks. With their spiffy pedal drive, you can trivially outrun(outpedal?) just about anyone while hardly breaking a sweat. Additionally, because you power yourself with your feet, your hands are free for fishing. The mirage drive is also quiet as a corpse. No splashing sounds from your paddles, whatsoever. A guy I know has one of their fishing-specific models, and loves it. However, if you ever want to go on an overnight camping adventure via your kayaks, the storage capacity of the Hobies is pretty bad, and while in general portaging kayaks is no fun, portaging a Hobie kayak would be especially miserable. Otherwise, you could try getting a tandem traditional kayak. Perhaps you can sweet-talk your wife into paddling while you fish?
3,909
Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. Would I be able to use a fishing kayak like a regular touring/recreation kayak? Thanks
2013/04/01
['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']
Yes, there is definitely a performance difference between different types of kayaks. In fact, there are performance differences among the same types of kayaks. For example, a 14-foot kayak will always track more straightly than a 10-foot kayak. A wide recreational kayak will always have more primary stability than a narrower touring kayak. Even if you both get the same type of kayak I suspect you'll find they work differently for each of you. No doubt you both do not weigh the same -- if you're heavier, a given kayak will sit lower in the water than for her. That may result in increased stability, or it could mean that you capsize easily. Alternatively, consider height and armspan: if she's short she may find it difficult to paddle in a wide rec kayak where the paddle is constantly bumping the edge of the boat. In short: you should each look for a kayak that suits you. That means you will see performance differences between the two kayaks, but if the boats really do suit each of you, that won't be a problem because you've found something that fits well. As to a fishing kayak specifically, if you get a longer kayak than her you'll likely be able to keep up with her on a day trip (though at the expense of maneuverability). Of course, keeping up with a partner is about more than the just the kayak. The paddle will also make a difference (especially its weight as it relates to your fatigue), and paddling technique can be a big difference between feeling good at the end of an outing and feeling whipped.
There are a few differences between the SOT kayaks and a touring kayak that you'll want to consider. **Length** SOT kayaks tend to be shorter and wider than touring boats. This can make SOT's a little more stable but a longer boat will track better (go straight). The more rough the water you want to travel in the longer boat you want. **Storage** Touring boats will have much more storage in them as that's what they're meant to do. It's usually covered storage in the bow and stern of the boat. Sometimes SOT's have storage but most of the time it's sitting on top of the boat with you. Having gear on top of the boat makes it more accessible but easier to lose in the waves. **Ease of Use** SOT's are easy to use. Just sit on them and go. Touring boats take a little practice getting into and out of. A nylon or neoprene skirt to go around the cockpit and around your waist is a good thing to have in rough water or just to prevent drips from the paddle falling onto your lap. Using a skirt makes them a little more complicated to get into an out of though. **Cost** Touring boats tend to be longer and have more features so they'll probably cost you more. All the SOT's I've seen are made out of roto-molded plastic which is the least expensive to make. You can get touring boats out of roto-molded plastic, thermoformed plastic or fiberglass. Roto-molded is cheaper, heavier but very durable. Thermoformed is lighter and faster but more expensive. Fibreglass is the most expensive, the fastest but the most fragile. **Weather conditions** Rougher conditions in the water will warrant a longer boat and probably one of the touring variety. The longer boats will be more stable and you'll be much more dry being inside the touring boat with a skirt covering the cockpit. Hope that helps.
3,909
Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. Would I be able to use a fishing kayak like a regular touring/recreation kayak? Thanks
2013/04/01
['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']
Yes, there is definitely a performance difference between different types of kayaks. In fact, there are performance differences among the same types of kayaks. For example, a 14-foot kayak will always track more straightly than a 10-foot kayak. A wide recreational kayak will always have more primary stability than a narrower touring kayak. Even if you both get the same type of kayak I suspect you'll find they work differently for each of you. No doubt you both do not weigh the same -- if you're heavier, a given kayak will sit lower in the water than for her. That may result in increased stability, or it could mean that you capsize easily. Alternatively, consider height and armspan: if she's short she may find it difficult to paddle in a wide rec kayak where the paddle is constantly bumping the edge of the boat. In short: you should each look for a kayak that suits you. That means you will see performance differences between the two kayaks, but if the boats really do suit each of you, that won't be a problem because you've found something that fits well. As to a fishing kayak specifically, if you get a longer kayak than her you'll likely be able to keep up with her on a day trip (though at the expense of maneuverability). Of course, keeping up with a partner is about more than the just the kayak. The paddle will also make a difference (especially its weight as it relates to your fatigue), and paddling technique can be a big difference between feeling good at the end of an outing and feeling whipped.
I have been considering just the same. I have come up with two kayacks that I like. The first is a fishing kayak by kudo. It tracks well and speed is good. I have a strong upper body so it makes it easier for me but its all in the core. Try different techniques as you will get tired just doing one. The other kayak is a 14 foot looksha by Necky. I have been eyeing that one for 3 years now. It is a sit in oh the kudo is a sit on top which I stood up in and tried paddle boarding on it. Great stability. The looksha tracks and maneuvers great. Not stable enough for fishing, what are you going to do when you land the mother of all fishes? How you bring that into the boat? Consider what you do more spending time with the wife or fishing in a kayak?
3,909
Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. Would I be able to use a fishing kayak like a regular touring/recreation kayak? Thanks
2013/04/01
['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']
There are a few differences between the SOT kayaks and a touring kayak that you'll want to consider. **Length** SOT kayaks tend to be shorter and wider than touring boats. This can make SOT's a little more stable but a longer boat will track better (go straight). The more rough the water you want to travel in the longer boat you want. **Storage** Touring boats will have much more storage in them as that's what they're meant to do. It's usually covered storage in the bow and stern of the boat. Sometimes SOT's have storage but most of the time it's sitting on top of the boat with you. Having gear on top of the boat makes it more accessible but easier to lose in the waves. **Ease of Use** SOT's are easy to use. Just sit on them and go. Touring boats take a little practice getting into and out of. A nylon or neoprene skirt to go around the cockpit and around your waist is a good thing to have in rough water or just to prevent drips from the paddle falling onto your lap. Using a skirt makes them a little more complicated to get into an out of though. **Cost** Touring boats tend to be longer and have more features so they'll probably cost you more. All the SOT's I've seen are made out of roto-molded plastic which is the least expensive to make. You can get touring boats out of roto-molded plastic, thermoformed plastic or fiberglass. Roto-molded is cheaper, heavier but very durable. Thermoformed is lighter and faster but more expensive. Fibreglass is the most expensive, the fastest but the most fragile. **Weather conditions** Rougher conditions in the water will warrant a longer boat and probably one of the touring variety. The longer boats will be more stable and you'll be much more dry being inside the touring boat with a skirt covering the cockpit. Hope that helps.
I have been considering just the same. I have come up with two kayacks that I like. The first is a fishing kayak by kudo. It tracks well and speed is good. I have a strong upper body so it makes it easier for me but its all in the core. Try different techniques as you will get tired just doing one. The other kayak is a 14 foot looksha by Necky. I have been eyeing that one for 3 years now. It is a sit in oh the kudo is a sit on top which I stood up in and tried paddle boarding on it. Great stability. The looksha tracks and maneuvers great. Not stable enough for fishing, what are you going to do when you land the mother of all fishes? How you bring that into the boat? Consider what you do more spending time with the wife or fishing in a kayak?
652,362
Consider the differential equation $$x^2y''+3(x-x^2)y'-3y=0$$ $(a)$ Find the recurrence equation and first three nonzero terms of the series solution in powers of $$ corresponding to the larger root of the indicial equation. $(b)$ What would be the form of a second linearly independent solution of this differential equation? I found the indicial equation to be $r(r-1)+3r-3 = 0$, so the two roots are $r\_1=-3$ and $r\_2=1$. And the recurrence relation is $a\_n = \dfrac{3(n-1+r)a\_{n-1}}{(n+r)(n+r-1)+3(n+r)-3}$ set $r=1$, then $a\_n = \dfrac{3na\_{n-1}}{(n+3)(n+1)-3}$. And I can figure out first linearly independent solution. But for $r=-3$,then $a\_n = \dfrac{3(n-4)a\_{n-1}}{(n-3)(n-1)-3}$, if let $a\_0$ be an arbitrary constant, then $a\_1 =\dfrac{3(-3)a\_0}{(-2)(0)}$, which doesn't work. Then how do I figure out the second linearly independent solution?
2014/01/26
['https://math.stackexchange.com/questions/652362', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59036/']
Here is the procedure. Denote the two roots by $r\_1$ and $r\_2$, with $r\_1 \gt r\_2$. The Method of Frobenius will always generate a solution corresponding to $r\_1$, but **may** generate a solution for the smaller second root $r\_2$ of the indicial equation. If the method fails for $r\_2$, then an approach is to keep the recursion solution in terms of $r$ and use it to find the coefficients $a\_n$ (for $n \ge 1$), in terms of both $r$ and $a\_0$, where $a\_0 \ne 0$. For ease, $a\_0$ is typically chose to be one. Using this more general form and the coefficients, the two independent solutions can be written as: $$y\_1(r, x) = x^r \sum\_{n=0}^\infty ~ a\_n(r)x^n = \sum\_{n=0}^\infty ~ a\_n(r)x^{n+r} \\y\_2(r,x) = \dfrac{\partial}{\partial r}[(r - r\_2)y\_1(r, x)]~\Bigr|\_{r=r\_2}$$ You should be able to use this approach and show: $$y(x) = y\_1(x) + y\_2(x) = \dfrac{c\_1(3x(3x^2 + 3x+ 2) + 2)}{x^3} + \dfrac{c\_2e^{3x}}{x^3}$$
Let me rewrite your ODE as follows: $$L[y] = p\_0 y'' + p\_1 y' + p\_2 y = 0,$$ where $p\_i(x)$ are the coefficients of the equation. If you know one of the two linear indepent solutions of the homogenous part (indeed the whole ode is homogenouse), say $y\_1$, you can obtain $y\_2$ ($y = A y\_1+B y\_2$) by using the method of *variation of parameters*. Let me show you. Set $y = A(x)y\_1$ and substitute back into the original ode: $$p\_0 (A''y\_1 + 2A'y\_1' + A y\_1'') + p\_1 (A'y\_1 + A y\_1') + p\_2 A y\_1 = 0,$$ arrange terms in order to get a ODE-1 for $A(x)$: $$ A'' + \left(\frac{2y'\_1}{y\_1} + \frac{p\_1 y\_1}{p\_0} \right) A' + \frac{1}{p\_0} L[y\_1] A= 0,$$ since $L[y\_1]=0$, $A$ can be obtained by solving this equation in terms of an integrating factor as follows: $$\frac{d}{dx} (u A') = u \cdot 0 = 0,$$ where $u = e^{\int \left(\frac{2y'\_1}{y\_1} + \frac{p\_1 y\_1}{p\_0} \right) \, dx}$. It yields: $$uA' = a\_2 \Rightarrow A = a\_1 + a\_2 \int \frac{dx}{u},$$ and hence the solution, $y = a\_1 y\_1 + a\_2 y\_1 \int \frac{dx}{u}$, being $a\_i$ constants of integration. I hope this is useful to you. Cheers!
652,362
Consider the differential equation $$x^2y''+3(x-x^2)y'-3y=0$$ $(a)$ Find the recurrence equation and first three nonzero terms of the series solution in powers of $$ corresponding to the larger root of the indicial equation. $(b)$ What would be the form of a second linearly independent solution of this differential equation? I found the indicial equation to be $r(r-1)+3r-3 = 0$, so the two roots are $r\_1=-3$ and $r\_2=1$. And the recurrence relation is $a\_n = \dfrac{3(n-1+r)a\_{n-1}}{(n+r)(n+r-1)+3(n+r)-3}$ set $r=1$, then $a\_n = \dfrac{3na\_{n-1}}{(n+3)(n+1)-3}$. And I can figure out first linearly independent solution. But for $r=-3$,then $a\_n = \dfrac{3(n-4)a\_{n-1}}{(n-3)(n-1)-3}$, if let $a\_0$ be an arbitrary constant, then $a\_1 =\dfrac{3(-3)a\_0}{(-2)(0)}$, which doesn't work. Then how do I figure out the second linearly independent solution?
2014/01/26
['https://math.stackexchange.com/questions/652362', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59036/']
Here is the procedure. Denote the two roots by $r\_1$ and $r\_2$, with $r\_1 \gt r\_2$. The Method of Frobenius will always generate a solution corresponding to $r\_1$, but **may** generate a solution for the smaller second root $r\_2$ of the indicial equation. If the method fails for $r\_2$, then an approach is to keep the recursion solution in terms of $r$ and use it to find the coefficients $a\_n$ (for $n \ge 1$), in terms of both $r$ and $a\_0$, where $a\_0 \ne 0$. For ease, $a\_0$ is typically chose to be one. Using this more general form and the coefficients, the two independent solutions can be written as: $$y\_1(r, x) = x^r \sum\_{n=0}^\infty ~ a\_n(r)x^n = \sum\_{n=0}^\infty ~ a\_n(r)x^{n+r} \\y\_2(r,x) = \dfrac{\partial}{\partial r}[(r - r\_2)y\_1(r, x)]~\Bigr|\_{r=r\_2}$$ You should be able to use this approach and show: $$y(x) = y\_1(x) + y\_2(x) = \dfrac{c\_1(3x(3x^2 + 3x+ 2) + 2)}{x^3} + \dfrac{c\_2e^{3x}}{x^3}$$
Let $y=\sum\limits\_{n=0}^\infty a\_nx^{n+r}$ , Then $y'=\sum\limits\_{n=0}^\infty(n+r)a\_nx^{n+r-1}$ $y''=\sum\limits\_{n=0}^\infty(n+r)(n+r-1)a\_nx^{n+r-2}$ $\therefore x^2\sum\limits\_{n=0}^\infty(n+r)(n+r-1)a\_nx^{n+r-2}+3(x-x^2)\sum\limits\_{n=0}^\infty(n+r)a\_nx^{n+r-1}-3\sum\limits\_{n=0}^\infty a\_nx^{n+r}=0$ $\sum\limits\_{n=0}^\infty(n+r)(n+r-1)a\_nx^{n+r}+\sum\limits\_{n=0}^\infty3(n+r)a\_nx^{n+r}-\sum\limits\_{n=0}^\infty3(n+r)a\_nx^{n+r+1}-\sum\limits\_{n=0}^\infty 3a\_nx^{n+r}=0$ $\sum\limits\_{n=0}^\infty(n+r+3)(n+r-1)a\_nx^{n+r}-\sum\limits\_{n=1}^\infty3(n+r-1)a\_{n-1}x^{n+r}=0$ $(r+3)(r-1)a\_0x^r+\sum\limits\_{n=1}^\infty((n+r+3)(n+r-1)a\_n-3(n+r-1)a\_{n-1})x^{n+r}=0$ The indicial equation is $(r+3)(r-1)=0$ , the two roots are $r\_1=-3$ and $r\_2=1$ . The recurrence relation is $(n+r+3)(n+r-1)a\_n-3(n+r-1)a\_{n-1}=0$ , i.e. $(n+r+3)(n+r-1)a\_n=3(n+r-1)a\_{n-1}$ Each root from the indical equations may not always only find one group of the linearly independent solutions, sometimes we can find more than one group of the linearly independent solutions at the same time. When we choose $r=-3$ , the recurrence relation becomes $n(n-4)a\_n=3(n-4)a\_{n-1}$ , which has a value of $n$ at $n=4$ so that it is independent to the recurrence relation. Besides $a\_0$ can chooes arbitrary, $a\_4$ can also chooes arbitrary. This makes the effect that we can find two groups of the linearly independent solutions that basing on $n=0$ to $n=3$ and $n=4$ to $n=+\infty$ respectively.
14,653,177
I would like to create an array containing static methods (or containing references to static methods). I have tried to create an array of classes which implement an interface with the method. With this method, I would get the object and then call the method on it. This does not work for static methods. Is there a way of doing it in Java? EDIT: Here is the method I have used so far: ``` interface TableElement{ public Integer lookup(int value); } TableElement[] table = new TableElement[] { new TableElement() { public Integer lookup(int value) { return 0; } }, new TableElement() { public Integer lookup(int value) { return value * 3; } }, new TableElement() { public Integer lookup(int value) { return value * value + 3; } }, }; public Integer find(int i, int value) { return table[i].lookup(value); } ``` I would like the find method to be static.
2013/02/01
['https://Stackoverflow.com/questions/14653177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1571830/']
Of course, you can have an array of `Method` and then you can call it using invoke, check these examples: [How do I invoke a private static method using reflection (Java)?](https://stackoverflow.com/questions/4770425/how-do-i-invoke-a-private-static-method-using-reflection-java)
If you can meet the following conditions: 1. You know all of the keys at code generation time. 2. You know all of the values (methods) at code generation time. You can use code like this: ``` public class Table { public static int hash(String key) { /* you can use any type of key and whatever hash function is * appropriate; this just meant as a simple example. */ return key.length(); } public static Integer find(String s, int value) { int h = hash(s); switch (h) { case 4: // "zero" if (s.equals("zero")) return methodZero(value); case 6: // "triple" if (s.equals("triple")) return methodTriple(value); case 11: // "squarePlus3" if (s.equals("squarePlus3")) return methodSquarePlus3(value); default: throw new UnsupportedOperationException(s); } } private static Integer methodZero(int value) { return 0; }; private static Integer methodTriple(int value) { return value * 3; }; private static Integer methodSquarePlus3(int value) { return value * value + 3; }; /** * Just a demo. */ public static void main(String arguments[]) { System.out.println("Zero(5): " + find("zero", 5)); System.out.println("Triple(5): " + find("triple", 5)); System.out.println("SquarePlus3(5): " + find("squarePlus3", 5)); System.out.println("boom!"); find("missingcode", 5); } } ``` If you need to relax either of the requirements I don't believe you can do everything statically. If you want to be able to add new keys, you'll have to create a normal hash table at adding time to store them. (You can check it in the `default` code.) If you want to be able to replace values, you'll have to use a level of indirection there, probably using `Method` objects or implementations of `Callable` (You can call these from within the body of the `methodZero` methods).
29,714,078
I am creating an application that takes input from user and save it permanently in form of table. ``` Console.Write("\n\tEnter roll no\n\t"); v= Convert.ToInt32(Console.ReadLine()); a[i].setroll(v); Console.Write("\n\tEnter name\n\t"); k = Console.ReadLine(); a[i].setname(k); Console.Write("\n\tEnter father name\n\t"); k = Console.ReadLine(); a[i].setfname(k); Console.Write("\n\tEnter CNIC NO\n\t "); k = Console.ReadLine(); a[i].setcnic(k); Console.Write("\n\tEnter permanent address\n\t"); k = Console.ReadLine(); a[i].setpaddress(k); Console.Write("\n\tEnter present address\n\t"); k = Console.ReadLine(); ``` I want to save all this info entered by user to be used later. How can I do this?
2015/04/18
['https://Stackoverflow.com/questions/29714078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4663076/']
Refer to [System.IO.File](https://msdn.microsoft.com/en-us/library/System.IO.File(v=vs.110).aspx) And this may be a quick help: ``` using System; public class Test { public static void Main() { String Str = ""; for(int i =0;i<10;i++) { Str += i.ToString(); } Console.WriteLine(Str); System.IO.File.WriteAllText(@"C:\SaveInfo.Txt",Str); } } ```
First you have to create an string array with your data then you can write it to the txt file ``` string[] lines = { "First line", "Second line", "Third line" }; ``` WriteAllLines creates a file, writes a collection of strings to the file,and then closes the file. ``` System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt",lines); ``` [How to: Write to a Text File (C# Programming Guide)](https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx)
552,323
In PHP, will these always return the same values? ``` //example 1 $array = array(); if ($array) { echo 'the array has items'; } // example 2 $array = array(); if (count($array)) { echo 'the array has items'; } ``` Thank you!
2009/02/16
['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']
From <http://www.php.net/manual/en/language.types.boolean.php>, it says that an empty array is considered FALSE. --- (Quoted): When converting to boolean, the following values are considered FALSE: * the boolean FALSE itself * the integer 0 (zero) * the float 0.0 (zero) * the empty string, and the string "0" * **an array with zero elements** * an object with zero member variables (PHP 4 only) * the special type NULL (including unset variables) * SimpleXML objects created from empty tags --- Since * a count() of > 0 IS NOT FALSE * a filled array IS NOT FALSE then both cases illustrated in the question will always work as expected.
Indeed they will. Converting an array to a bool will give you true if it is non-empty, and the count of an array is true with more than one element. See also: <http://ca2.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting>
552,323
In PHP, will these always return the same values? ``` //example 1 $array = array(); if ($array) { echo 'the array has items'; } // example 2 $array = array(); if (count($array)) { echo 'the array has items'; } ``` Thank you!
2009/02/16
['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']
From <http://www.php.net/manual/en/language.types.boolean.php>, it says that an empty array is considered FALSE. --- (Quoted): When converting to boolean, the following values are considered FALSE: * the boolean FALSE itself * the integer 0 (zero) * the float 0.0 (zero) * the empty string, and the string "0" * **an array with zero elements** * an object with zero member variables (PHP 4 only) * the special type NULL (including unset variables) * SimpleXML objects created from empty tags --- Since * a count() of > 0 IS NOT FALSE * a filled array IS NOT FALSE then both cases illustrated in the question will always work as expected.
Note that the second example (using `count()`) is significantly slower, by at least 50% on my system (over 10000 iterations). `count()` actually counts the elements of an array. I'm not positive, but I imagine casting an array to a boolean works much like `empty()`, and stops as soon as it finds at least one element.
552,323
In PHP, will these always return the same values? ``` //example 1 $array = array(); if ($array) { echo 'the array has items'; } // example 2 $array = array(); if (count($array)) { echo 'the array has items'; } ``` Thank you!
2009/02/16
['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']
From <http://www.php.net/manual/en/language.types.boolean.php>, it says that an empty array is considered FALSE. --- (Quoted): When converting to boolean, the following values are considered FALSE: * the boolean FALSE itself * the integer 0 (zero) * the float 0.0 (zero) * the empty string, and the string "0" * **an array with zero elements** * an object with zero member variables (PHP 4 only) * the special type NULL (including unset variables) * SimpleXML objects created from empty tags --- Since * a count() of > 0 IS NOT FALSE * a filled array IS NOT FALSE then both cases illustrated in the question will always work as expected.
Those will always return the same value, but I find ``` $array = array(); if (empty($array)) { echo 'the array is empty'; } ``` to be a lot more readable.
552,323
In PHP, will these always return the same values? ``` //example 1 $array = array(); if ($array) { echo 'the array has items'; } // example 2 $array = array(); if (count($array)) { echo 'the array has items'; } ``` Thank you!
2009/02/16
['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']
Note that the second example (using `count()`) is significantly slower, by at least 50% on my system (over 10000 iterations). `count()` actually counts the elements of an array. I'm not positive, but I imagine casting an array to a boolean works much like `empty()`, and stops as soon as it finds at least one element.
Indeed they will. Converting an array to a bool will give you true if it is non-empty, and the count of an array is true with more than one element. See also: <http://ca2.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting>
552,323
In PHP, will these always return the same values? ``` //example 1 $array = array(); if ($array) { echo 'the array has items'; } // example 2 $array = array(); if (count($array)) { echo 'the array has items'; } ``` Thank you!
2009/02/16
['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']
Those will always return the same value, but I find ``` $array = array(); if (empty($array)) { echo 'the array is empty'; } ``` to be a lot more readable.
Indeed they will. Converting an array to a bool will give you true if it is non-empty, and the count of an array is true with more than one element. See also: <http://ca2.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting>
552,323
In PHP, will these always return the same values? ``` //example 1 $array = array(); if ($array) { echo 'the array has items'; } // example 2 $array = array(); if (count($array)) { echo 'the array has items'; } ``` Thank you!
2009/02/16
['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']
Those will always return the same value, but I find ``` $array = array(); if (empty($array)) { echo 'the array is empty'; } ``` to be a lot more readable.
Note that the second example (using `count()`) is significantly slower, by at least 50% on my system (over 10000 iterations). `count()` actually counts the elements of an array. I'm not positive, but I imagine casting an array to a boolean works much like `empty()`, and stops as soon as it finds at least one element.
46,975,929
I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? [This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).
2017/10/27
['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']
For Python 3: ``` def jaccard_similarity(list1, list2): s1 = set(list1) s2 = set(list2) return float(len(s1.intersection(s2)) / len(s1.union(s2))) list1 = ['dog', 'cat', 'cat', 'rat'] list2 = ['dog', 'cat', 'mouse'] jaccard_similarity(list1, list2) >>> 0.5 ``` For Python2 use `return len(s1.intersection(s2)) / float(len(s1.union(s2)))`
If you'd like to include repeated elements, you can use `Counter`, which I would imagine is relatively quick since it's just an extended `dict` under the hood: ``` from collections import Counter def jaccard_repeats(a, b): """Jaccard similarity measure between input iterables, allowing repeated elements""" _a = Counter(a) _b = Counter(b) c = (_a - _b) + (_b - _a) n = sum(c.values()) return n/(len(a) + len(b) - n) list1 = ['dog', 'cat', 'rat', 'cat'] list2 = ['dog', 'cat', 'rat'] list3 = ['dog', 'cat', 'mouse'] jaccard_repeats(list1, list3) >>> 0.75 jaccard_repeats(list1, list2) >>> 0.16666666666666666 jaccard_repeats(list2, list3) >>> 0.5 ```
46,975,929
I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? [This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).
2017/10/27
['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']
@aventinus I don't have enough reputation to add a comment to your answer, but just to make things clearer, your solution measures the `jaccard_similarity` but the function is misnamed as `jaccard_distance`, which is actually `1 - jaccard_similarity`
You can use the [Distance](https://github.com/doukremt/distance) library ``` #pip install Distance import distance distance.jaccard("decide", "resize") # Returns 0.7142857142857143 ```
46,975,929
I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? [This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).
2017/10/27
['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']
You can use the [Distance](https://github.com/doukremt/distance) library ``` #pip install Distance import distance distance.jaccard("decide", "resize") # Returns 0.7142857142857143 ```
To avoid repetition of elements in the union (denominator), and a little bit faster I propose: ``` def Jaccar_score(lista1, lista2): inter = len(list(set(lista_1) & set(lista_2))) union = len(list(set(lista_1) | set(lista_2))) return inter/union ```
46,975,929
I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? [This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).
2017/10/27
['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']
For Python 3: ``` def jaccard_similarity(list1, list2): s1 = set(list1) s2 = set(list2) return float(len(s1.intersection(s2)) / len(s1.union(s2))) list1 = ['dog', 'cat', 'cat', 'rat'] list2 = ['dog', 'cat', 'mouse'] jaccard_similarity(list1, list2) >>> 0.5 ``` For Python2 use `return len(s1.intersection(s2)) / float(len(s1.union(s2)))`
Assuming your usernames don't repeat, you can use the same idea: ``` def jaccard(a, b): c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c)) list1 = ['dog', 'cat', 'rat'] list2 = ['dog', 'cat', 'mouse'] # The intersection is ['dog', 'cat'] # union is ['dog', 'cat', 'rat', 'mouse] words1 = set(list1) words2 = set(list2) jaccard(words1, words2) >>> 0.5 ```
46,975,929
I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? [This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).
2017/10/27
['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']
@Aventinus (I also cannot comment): Note that Jaccard *similarity* is an operation on sets, so in the denominator part it should also use sets (instead of lists). So for example `jaccard_similarity('aa', 'ab')` should result in `0.5`. ``` def jaccard_similarity(list1, list2): intersection = len(set(list1).intersection(list2)) union = len(set(list1)) + len(set(list2)) - intersection return intersection / union ``` Note that in the intersection, there is no need to cast to list first. Also, the cast to float is not needed in Python 3.
Creator of the [Simphile NLP text similarity](https://github.com/brianrisk/simphile) package here. Simphile contains several text similarity methods, Jaccard being one of them. In the terminal install the package: ``` pip install simphile ``` Then your code could be something like: ``` from simphile import jaccard_list_similarity list_a = ['cat', 'cat', 'dog'] list_b = ['dog', 'dog', 'cat'] print(f"Jaccard Similarity: {jaccard_list_similarity(list_a, list_b)}") ``` The output being: ``` Jaccard Similarity: 0.5 ``` Note that this solution accounts for repeated elements -- critical for text similarity; without it, the above example would show 100% similarity due to the fact that both lists as sets would reduce to {'dog', 'cat'}.
46,975,929
I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? [This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).
2017/10/27
['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']
I ended up writing my own solution after all: ``` def jaccard_similarity(list1, list2): intersection = len(list(set(list1).intersection(list2))) union = (len(set(list1)) + len(set(list2))) - intersection return float(intersection) / union ```
If you'd like to include repeated elements, you can use `Counter`, which I would imagine is relatively quick since it's just an extended `dict` under the hood: ``` from collections import Counter def jaccard_repeats(a, b): """Jaccard similarity measure between input iterables, allowing repeated elements""" _a = Counter(a) _b = Counter(b) c = (_a - _b) + (_b - _a) n = sum(c.values()) return n/(len(a) + len(b) - n) list1 = ['dog', 'cat', 'rat', 'cat'] list2 = ['dog', 'cat', 'rat'] list3 = ['dog', 'cat', 'mouse'] jaccard_repeats(list1, list3) >>> 0.75 jaccard_repeats(list1, list2) >>> 0.16666666666666666 jaccard_repeats(list2, list3) >>> 0.5 ```
46,975,929
I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? [This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).
2017/10/27
['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']
Assuming your usernames don't repeat, you can use the same idea: ``` def jaccard(a, b): c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c)) list1 = ['dog', 'cat', 'rat'] list2 = ['dog', 'cat', 'mouse'] # The intersection is ['dog', 'cat'] # union is ['dog', 'cat', 'rat', 'mouse] words1 = set(list1) words2 = set(list2) jaccard(words1, words2) >>> 0.5 ```
You can use the [Distance](https://github.com/doukremt/distance) library ``` #pip install Distance import distance distance.jaccard("decide", "resize") # Returns 0.7142857142857143 ```
46,975,929
I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? [This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).
2017/10/27
['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']
I ended up writing my own solution after all: ``` def jaccard_similarity(list1, list2): intersection = len(list(set(list1).intersection(list2))) union = (len(set(list1)) + len(set(list2))) - intersection return float(intersection) / union ```
For Python 3: ``` def jaccard_similarity(list1, list2): s1 = set(list1) s2 = set(list2) return float(len(s1.intersection(s2)) / len(s1.union(s2))) list1 = ['dog', 'cat', 'cat', 'rat'] list2 = ['dog', 'cat', 'mouse'] jaccard_similarity(list1, list2) >>> 0.5 ``` For Python2 use `return len(s1.intersection(s2)) / float(len(s1.union(s2)))`
46,975,929
I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? [This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).
2017/10/27
['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']
Assuming your usernames don't repeat, you can use the same idea: ``` def jaccard(a, b): c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c)) list1 = ['dog', 'cat', 'rat'] list2 = ['dog', 'cat', 'mouse'] # The intersection is ['dog', 'cat'] # union is ['dog', 'cat', 'rat', 'mouse] words1 = set(list1) words2 = set(list2) jaccard(words1, words2) >>> 0.5 ```
If you'd like to include repeated elements, you can use `Counter`, which I would imagine is relatively quick since it's just an extended `dict` under the hood: ``` from collections import Counter def jaccard_repeats(a, b): """Jaccard similarity measure between input iterables, allowing repeated elements""" _a = Counter(a) _b = Counter(b) c = (_a - _b) + (_b - _a) n = sum(c.values()) return n/(len(a) + len(b) - n) list1 = ['dog', 'cat', 'rat', 'cat'] list2 = ['dog', 'cat', 'rat'] list3 = ['dog', 'cat', 'mouse'] jaccard_repeats(list1, list3) >>> 0.75 jaccard_repeats(list1, list2) >>> 0.16666666666666666 jaccard_repeats(list2, list3) >>> 0.5 ```
46,975,929
I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? [This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).
2017/10/27
['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']
For Python 3: ``` def jaccard_similarity(list1, list2): s1 = set(list1) s2 = set(list2) return float(len(s1.intersection(s2)) / len(s1.union(s2))) list1 = ['dog', 'cat', 'cat', 'rat'] list2 = ['dog', 'cat', 'mouse'] jaccard_similarity(list1, list2) >>> 0.5 ``` For Python2 use `return len(s1.intersection(s2)) / float(len(s1.union(s2)))`
@aventinus I don't have enough reputation to add a comment to your answer, but just to make things clearer, your solution measures the `jaccard_similarity` but the function is misnamed as `jaccard_distance`, which is actually `1 - jaccard_similarity`
4,252,818
I have in trouble to trigger a click event when enter key is pressed. When I use below codes, the live('click') event is triggered 3 times (which means the alert message is shown 3 thmes) when I press an enter key. Thanks in advance!! - KS from Korea ``` $('.searchWord').live('keypress', function(e) { if(e.keyCode == 13) { $('.bBtnSearchBoard').trigger('click'); } }); $('.bBtnSearchBoard').live('click', function() { alert('a'); }); ```
2010/11/23
['https://Stackoverflow.com/questions/4252818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516975/']
It looks like you either have multiple `.searchWord` elements nested within each other, or, you have multiple `.bBtnSearchBoard` elements.
try keydown ``` $('.searchWord').live('keydown', function(e) { if(e.keyCode == 13) { $('.bBtnSearchBoard').trigger('click'); } }); ```
4,252,818
I have in trouble to trigger a click event when enter key is pressed. When I use below codes, the live('click') event is triggered 3 times (which means the alert message is shown 3 thmes) when I press an enter key. Thanks in advance!! - KS from Korea ``` $('.searchWord').live('keypress', function(e) { if(e.keyCode == 13) { $('.bBtnSearchBoard').trigger('click'); } }); $('.bBtnSearchBoard').live('click', function() { alert('a'); }); ```
2010/11/23
['https://Stackoverflow.com/questions/4252818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516975/']
It looks like you either have multiple `.searchWord` elements nested within each other, or, you have multiple `.bBtnSearchBoard` elements.
It looks fine on [this test](http://jsfiddle.net/DjASs/). Maybe your problem is that `.bBtnSearchBoard` returns more than one element.
4,252,818
I have in trouble to trigger a click event when enter key is pressed. When I use below codes, the live('click') event is triggered 3 times (which means the alert message is shown 3 thmes) when I press an enter key. Thanks in advance!! - KS from Korea ``` $('.searchWord').live('keypress', function(e) { if(e.keyCode == 13) { $('.bBtnSearchBoard').trigger('click'); } }); $('.bBtnSearchBoard').live('click', function() { alert('a'); }); ```
2010/11/23
['https://Stackoverflow.com/questions/4252818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516975/']
It looks like you either have multiple `.searchWord` elements nested within each other, or, you have multiple `.bBtnSearchBoard` elements.
``` $('.searchWord').live('keypress', function(e) { if(e.keyCode == 13) { $('.bBtnSearchBoard').click(); } }); $('.bBtnSearchBoard').live('click', function() { //do your stuff here $(this).die("click"); //The first time this method executes unbinds the click handler from matched elements return false; //to prevent bubbling up of this event higher up the DOM }); ```
41,694,421
I'm calling my Java Servlet with an AJAX call, but I'm not able to read the input parameter from the request. I've tried two ways but with no luck: ``` var id; $("#scan").click(function() { id = 1; $.ajax({ type: "POST", data: id, url: "http://10.1.42.249:8080/test-notifier-web/RestLayer" }); }); ``` And: ``` id = 1; $.post('http://10.1.42.249:8080/test-notifier-web/RestLayer', { reqValue: id }, function(responseText) { // $('#welcometext').text(responseText); alert("OK!!!"); }); ``` My servlet code is a simple log print of the request parameter, but the return value is always null: ``` String reqID = ""; log.info("Servlet called"); reqID = request.getParameter("reqValue"); log.info("reqID = " + reqID); ``` How can I get this working? The only way I've found to get the code working is manually add the parameter to servlet url, like `http://10.1.42.249:8080/test-notifier-web/RestLayer?reqValue=1`
2017/01/17
['https://Stackoverflow.com/questions/41694421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3991150/']
i have check you code.this is my working code. ``` <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script type="text/javascript"> var id; function fun() { alert("aaaa"); id = 1; $.ajax({ type : "POST", data : { reqValue : id }, url : "/WebProject/callAjax" }); } </script> </head> <body> <button id="scan" onclick="fun()">Sacn</button> </body> </html> ``` //Servlet ``` @WebServlet(urlPatterns = {"/callAjax",}) public class Test extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println(request.getParameter("reqValue")); } } ```
``` var id; $("#scan").click(function() { id = 1; $.ajax({ type: "POST", data: { reqValue : id}, url: "http://10.1.42.249:8080/test-notifier-web/RestLayer" }); }); ``` There are different methods you need to override in servlet. Those are doPost(), doGet(), service() and etc. I suspect you are using doGet() method that's why when you add parameter to the URL your java code is working and in other two cases as you are using `type : "POST"` java code is unable to read the data from Request Body( in post method the data will be added to Request Body). I suggest you to use `doPost()` or `service()` methods instead doGet().
37,357,896
I am using sublime to automatically word-wrap python code-lines that go beyond 79 Characters as the Pep-8 defines. Initially i was doing return to not go beyond the limit. The only downside with that is that anyone else not having the word-wrap active wouldn't have the limitation. So should i strive forward of actually word-wrapping or is the visual word-wrap ok? [![enter image description here](https://i.stack.imgur.com/Wz4ko.png)](https://i.stack.imgur.com/Wz4ko.png)
2016/05/21
['https://Stackoverflow.com/questions/37357896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1767754/']
PEP8 wants you to perform an actual word wrap. The point of PEP8’s stylistic rules is that the file looks the same in every editor, so you cannot rely on editor visualizations to satisfy PEP8. This also makes you choose the point where to break deliberately. For example, Sublime will do a pretty basic job in wrapping that line; but you could do it in a more readable way, e.g.: ``` x = os.path.split(os.path.split(os.path.split( os.path.split(os.path.split(path)[0])[0] )[0])[0]) ``` Of course that’s not necessarily pretty (I blame that mostly on this example code though), but it makes clear what belongs to what. That being said, a good strategy is to simply avoid having to wrap lines. For example, you are using `os.path.split` over and over; so you could change your import: ``` from os.path import split x = split(split(split(split(split(path)[0])[0])[0])[0]) ``` And of course, if you find yourself doing something over and over, maybe there’s a better way to do this, for example using Python 3.4’s `pathlib`: ``` import pathlib p = pathlib.Path(path).parents[2] print(p.parent.absolute(), p.name) ```
In-file word wrapping would let your code conform to Pep-8 most consistently, even if other programmers are looking at your code using different coding environments. That seems to me to be the best solution to keeping to the standard, particularly if you are expecting that others will, at some point, be looking at your code. If you are working with a set group of people on a project, or even in a company, it may be possible to coordinate with the other programmers to find what solution you are all most satisfied with. For personal projects that you really aren't expecting anyone else to ever look at, I'm sure it's fine to use the visual word wrapping, but enforcing it yourself would certainly help to build on a good habit.
31,768,349
I tried an SSE (Server-Sent-Events) using java on tomcat 8.0. Here are few things I noticed. I click a button that automatically makes a request to the servlet. Servlet's GET method gets executed which returns an event stream. Once the full stream is received, the page again automatically makes another request which receives the same data again!!! I don't have an infinite loop there!!! 1. What is actually happening on the server? In normal scenarios, tomcat creates a thread to handle every request. What is happening now? 2. What is the correct way to ensure that the event stream is sent only once to the same connection/browser session? 3. What is the correct way to ensure that the event stream is closed and no resource overhead incurs on the server? 4. How to differentiate between GET and POST requests. Why did it choose GET? 5. Is it too early to use SSE on Tomcat? Any performance issues? Here is the code for the curious, ``` @WebServlet("/TestServlet") public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //content type must be set to text/event-stream response.setContentType("text/event-stream"); //cache must be set to no-cache response.setHeader("Cache-Control", "no-cache"); //encoding is set to UTF-8 response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); for(int i=0; i<10; i++) { System.out.println(i); writer.write("data: "+ i +"\n\n"); writer.flush(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } writer.close(); } } ``` Javascript on the page (I don't have anything else on the page), ``` <button onclick="start()">Start</button> <script type="text/javascript"> function start() { var eventSource = new EventSource("TestServlet"); eventSource.onmessage = function(event) { console.log("data: "+event.data) document.getElementById('foo').innerHTML = event.data; }; } </script> ``` Tried this using CURL. And the response came just once. I'm using chrome, so this must be a issue with chorme?? **EDIT:** What I have learned and learning is now documented in my blog - [Server Sent Events](http://www.cs-repository.info/2016/08/server-sent-events.html)
2015/08/02
['https://Stackoverflow.com/questions/31768349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548634/']
Change this line ``` writer.write("data: "+ i +"\n\n"); ``` to ``` writer.write("data: "+ i +"\r\n"); ``` BTW, your code will have a serious performance issue because it will hold a thread until all events are sent.Please use Asynchronous processing API instead. e.g. ``` protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AsyncContext actx = req.startAsync(); actx.setTimeout(30*1000); //save actx and use it when we need sent data to the client. } ``` Then we can use AsyncContext later ``` //write some data to client when a certain event happens actx.getResponse().getWriter().write("data: " + mydata + "\r\n"); actx.getResponse().getWriter().flush(); ``` if all events sent we can close it ``` actx.complete(); ``` **UPDATE 1:** We need close the event source at browser if we do not want browser reconnect the server again when server completes the response. ``` eventSource.close(); ``` Another method maybe helps, viz. we set a quite large retry time but I have not tried it, e.g. ``` protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AsyncContext actx = req.startAsync(); actx.getResponse().getWriter().write("retry: 36000000000\r\n"); // 10000 hours! actx.getResponse().getWriter().flush(); //save actx and use it when we need sent data to the client. } ``` **UPDATE 2:** I think Websocket maybe is better for your case. **UPDATE 3: (answer the questions)** > > 1. What is actually happening on the server? In normal scenarios, tomcat creates a thread to handle every request. What is happening now? > > > If use NIO connector which is default in Tomcat 8.0.X, within the whole processing cycle HTTP I/O about a request won't hold a thread. If use BIO a thread will be hold until the whole processing cycle completes. All threads are from a thread pool, tomcat won't create a thread for each request. > > 2. What is the correct way to ensure that the event stream is sent only once to the same connection/browser session? > > > Do `eventSource.close()` at browser side is the best choice. > > 3. What is the correct way to ensure that the event stream is closed and no resource overhead incurs on the server? > > > Do not forget to invoke AsyncContext.complete() at server side. > > 4. How to differentiate between GET and POST requests. Why did it choose GET? > > > The EventSource API in a browser only supports GET requests but at the server side there 's no such restriction. SSE is mainly used to receive events data from server. If a event happens the browser can receive it in time and no need to create a new request to poll it. If you need full-duplex communication try WebSocket instread of SSE. > > 5. Is it too early to use SSE on Tomcat? Any performance issues? > > > There should be no performance issues if we use NIO connector & Asynchronous processing API. I don't know whether Tomcat NIO connector is mature or not but something will never be known unless we try it.
I highly recommend first to read [Stream Updates with Server-Sent Events](http://www.html5rocks.com/en/tutorials/eventsource/basics/) to get a good general understanding of the technology. Then follow [Server-Sent Events with Async Servlet By Example](https://weblogs.java.net/blog/swchan2/archive/2014/05/21/server-sent-events-async-servlet-example) to see how SSE can be used specifically with the Servlet technology.
31,768,349
I tried an SSE (Server-Sent-Events) using java on tomcat 8.0. Here are few things I noticed. I click a button that automatically makes a request to the servlet. Servlet's GET method gets executed which returns an event stream. Once the full stream is received, the page again automatically makes another request which receives the same data again!!! I don't have an infinite loop there!!! 1. What is actually happening on the server? In normal scenarios, tomcat creates a thread to handle every request. What is happening now? 2. What is the correct way to ensure that the event stream is sent only once to the same connection/browser session? 3. What is the correct way to ensure that the event stream is closed and no resource overhead incurs on the server? 4. How to differentiate between GET and POST requests. Why did it choose GET? 5. Is it too early to use SSE on Tomcat? Any performance issues? Here is the code for the curious, ``` @WebServlet("/TestServlet") public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //content type must be set to text/event-stream response.setContentType("text/event-stream"); //cache must be set to no-cache response.setHeader("Cache-Control", "no-cache"); //encoding is set to UTF-8 response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); for(int i=0; i<10; i++) { System.out.println(i); writer.write("data: "+ i +"\n\n"); writer.flush(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } writer.close(); } } ``` Javascript on the page (I don't have anything else on the page), ``` <button onclick="start()">Start</button> <script type="text/javascript"> function start() { var eventSource = new EventSource("TestServlet"); eventSource.onmessage = function(event) { console.log("data: "+event.data) document.getElementById('foo').innerHTML = event.data; }; } </script> ``` Tried this using CURL. And the response came just once. I'm using chrome, so this must be a issue with chorme?? **EDIT:** What I have learned and learning is now documented in my blog - [Server Sent Events](http://www.cs-repository.info/2016/08/server-sent-events.html)
2015/08/02
['https://Stackoverflow.com/questions/31768349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548634/']
Change this line ``` writer.write("data: "+ i +"\n\n"); ``` to ``` writer.write("data: "+ i +"\r\n"); ``` BTW, your code will have a serious performance issue because it will hold a thread until all events are sent.Please use Asynchronous processing API instead. e.g. ``` protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AsyncContext actx = req.startAsync(); actx.setTimeout(30*1000); //save actx and use it when we need sent data to the client. } ``` Then we can use AsyncContext later ``` //write some data to client when a certain event happens actx.getResponse().getWriter().write("data: " + mydata + "\r\n"); actx.getResponse().getWriter().flush(); ``` if all events sent we can close it ``` actx.complete(); ``` **UPDATE 1:** We need close the event source at browser if we do not want browser reconnect the server again when server completes the response. ``` eventSource.close(); ``` Another method maybe helps, viz. we set a quite large retry time but I have not tried it, e.g. ``` protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AsyncContext actx = req.startAsync(); actx.getResponse().getWriter().write("retry: 36000000000\r\n"); // 10000 hours! actx.getResponse().getWriter().flush(); //save actx and use it when we need sent data to the client. } ``` **UPDATE 2:** I think Websocket maybe is better for your case. **UPDATE 3: (answer the questions)** > > 1. What is actually happening on the server? In normal scenarios, tomcat creates a thread to handle every request. What is happening now? > > > If use NIO connector which is default in Tomcat 8.0.X, within the whole processing cycle HTTP I/O about a request won't hold a thread. If use BIO a thread will be hold until the whole processing cycle completes. All threads are from a thread pool, tomcat won't create a thread for each request. > > 2. What is the correct way to ensure that the event stream is sent only once to the same connection/browser session? > > > Do `eventSource.close()` at browser side is the best choice. > > 3. What is the correct way to ensure that the event stream is closed and no resource overhead incurs on the server? > > > Do not forget to invoke AsyncContext.complete() at server side. > > 4. How to differentiate between GET and POST requests. Why did it choose GET? > > > The EventSource API in a browser only supports GET requests but at the server side there 's no such restriction. SSE is mainly used to receive events data from server. If a event happens the browser can receive it in time and no need to create a new request to poll it. If you need full-duplex communication try WebSocket instread of SSE. > > 5. Is it too early to use SSE on Tomcat? Any performance issues? > > > There should be no performance issues if we use NIO connector & Asynchronous processing API. I don't know whether Tomcat NIO connector is mature or not but something will never be known unless we try it.
The browser attempts to reconnect to the source roughly 3 seconds after each connection is closed. You can change that timeout by including a line beginning with "retry:", followed by the number of milliseconds to wait before trying to reconnect.
31,768,349
I tried an SSE (Server-Sent-Events) using java on tomcat 8.0. Here are few things I noticed. I click a button that automatically makes a request to the servlet. Servlet's GET method gets executed which returns an event stream. Once the full stream is received, the page again automatically makes another request which receives the same data again!!! I don't have an infinite loop there!!! 1. What is actually happening on the server? In normal scenarios, tomcat creates a thread to handle every request. What is happening now? 2. What is the correct way to ensure that the event stream is sent only once to the same connection/browser session? 3. What is the correct way to ensure that the event stream is closed and no resource overhead incurs on the server? 4. How to differentiate between GET and POST requests. Why did it choose GET? 5. Is it too early to use SSE on Tomcat? Any performance issues? Here is the code for the curious, ``` @WebServlet("/TestServlet") public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //content type must be set to text/event-stream response.setContentType("text/event-stream"); //cache must be set to no-cache response.setHeader("Cache-Control", "no-cache"); //encoding is set to UTF-8 response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); for(int i=0; i<10; i++) { System.out.println(i); writer.write("data: "+ i +"\n\n"); writer.flush(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } writer.close(); } } ``` Javascript on the page (I don't have anything else on the page), ``` <button onclick="start()">Start</button> <script type="text/javascript"> function start() { var eventSource = new EventSource("TestServlet"); eventSource.onmessage = function(event) { console.log("data: "+event.data) document.getElementById('foo').innerHTML = event.data; }; } </script> ``` Tried this using CURL. And the response came just once. I'm using chrome, so this must be a issue with chorme?? **EDIT:** What I have learned and learning is now documented in my blog - [Server Sent Events](http://www.cs-repository.info/2016/08/server-sent-events.html)
2015/08/02
['https://Stackoverflow.com/questions/31768349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548634/']
I highly recommend first to read [Stream Updates with Server-Sent Events](http://www.html5rocks.com/en/tutorials/eventsource/basics/) to get a good general understanding of the technology. Then follow [Server-Sent Events with Async Servlet By Example](https://weblogs.java.net/blog/swchan2/archive/2014/05/21/server-sent-events-async-servlet-example) to see how SSE can be used specifically with the Servlet technology.
The browser attempts to reconnect to the source roughly 3 seconds after each connection is closed. You can change that timeout by including a line beginning with "retry:", followed by the number of milliseconds to wait before trying to reconnect.
36,656,845
I don't understand why an empty array, or an array with only 1 "numerical" value can be used in certain calculations. ``` [] * [] === 0 //true [2] * [2] === 4 //true ["2"] * ["2"] === 4 //true ``` However, it does not seem that is always the case with every operator. ``` [2] + [1] === 3 // false, actual result is "21" [2] - [1] === 1 // true ``` I also checked these, and saw expected results: ``` [4] === "4" // false [4] === 4 // false ``` In most cases, I would expect `NaN` in any of these mathematical operations. What is it about JavaScript arrays that allows this? Is it because the array `toString` method is being used somehow internally?
2016/04/15
['https://Stackoverflow.com/questions/36656845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2056157/']
The arrays are coerced into strings, such that `[] == ""`, `[1] == "1"`, and `[1, 2] == "1,2"`. When you do certain mathematical operations on strings, they are coerced into `Number` types. For example, when you do `[2] * [2]` it becomes `"2" * "2"` which becomes `2 * 2`. You can even mix types and do `[2] * 2` or `"2" * [2]`. When you try to use `+`, it attempts to concatenate the strings instead of coercing the strings to numbers. That's why `"2" + "2"`, `"2" + [2]`, and `[2] + [2]` each give you `"22"`.
The same ol'problem of having `+` as string concatenation operator. An array in Javascript is an Object. When you try to coerce objects into primitive values, there is an order to follow: 1. `<obj>.toString()` 2. `<obj>.toNumber()` 3. `<obj>.toBoolean()` If you're using the `*` operator, coerce into string is not possible, so the interpreter goes to `toNumber()`. When you're using the `+` operator, the first attempt will be `toString()`. Since `+` is also the string concat operator, then the expression will be evaluated as an array. Yeah, [javascript](/questions/tagged/javascript "show questions tagged 'javascript'") can get ugly. Edit: ----- Some further details can be found [here](https://www.safaribooksonline.com/library/view/you-dont-know/9781491905159/ch04.html).
36,656,845
I don't understand why an empty array, or an array with only 1 "numerical" value can be used in certain calculations. ``` [] * [] === 0 //true [2] * [2] === 4 //true ["2"] * ["2"] === 4 //true ``` However, it does not seem that is always the case with every operator. ``` [2] + [1] === 3 // false, actual result is "21" [2] - [1] === 1 // true ``` I also checked these, and saw expected results: ``` [4] === "4" // false [4] === 4 // false ``` In most cases, I would expect `NaN` in any of these mathematical operations. What is it about JavaScript arrays that allows this? Is it because the array `toString` method is being used somehow internally?
2016/04/15
['https://Stackoverflow.com/questions/36656845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2056157/']
The arrays are coerced into strings, such that `[] == ""`, `[1] == "1"`, and `[1, 2] == "1,2"`. When you do certain mathematical operations on strings, they are coerced into `Number` types. For example, when you do `[2] * [2]` it becomes `"2" * "2"` which becomes `2 * 2`. You can even mix types and do `[2] * 2` or `"2" * [2]`. When you try to use `+`, it attempts to concatenate the strings instead of coercing the strings to numbers. That's why `"2" + "2"`, `"2" + [2]`, and `[2] + [2]` each give you `"22"`.
In regards to `+`, [`+` is a coercive operator on `Strings`](http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.1), irrespective of it being the `lvalue` and `rvalue`, I'll quote the specification here: > > If `Type(lprim`) is String or `Type(rprim`) is `String`, then Return the > `String` that is the result of concatenating `ToString(lprim`) followed by > `ToString(rprim`) > > > [Multiplication however doesn't follow the same rules](http://www.ecma-international.org/ecma-262/5.1/#sec-11.5), it does however apply [`ToNumber`](http://www.ecma-international.org/ecma-262/5.1/#sec-9.3), which as you've noticed, casts a `[Number]` to -> `Number` (`+` does this as well, but it is a later step in the operator's definition) Your last statement is answered by two rules of the `SameValue` algorithm defined in the spec, namely, if two values are of a different type, return `false`, alternatively, if two objects refer to the ptr, return true. Thus ``` a = [1]; b = [1]; a === b; // false ```
36,656,845
I don't understand why an empty array, or an array with only 1 "numerical" value can be used in certain calculations. ``` [] * [] === 0 //true [2] * [2] === 4 //true ["2"] * ["2"] === 4 //true ``` However, it does not seem that is always the case with every operator. ``` [2] + [1] === 3 // false, actual result is "21" [2] - [1] === 1 // true ``` I also checked these, and saw expected results: ``` [4] === "4" // false [4] === 4 // false ``` In most cases, I would expect `NaN` in any of these mathematical operations. What is it about JavaScript arrays that allows this? Is it because the array `toString` method is being used somehow internally?
2016/04/15
['https://Stackoverflow.com/questions/36656845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2056157/']
The arrays are coerced into strings, such that `[] == ""`, `[1] == "1"`, and `[1, 2] == "1,2"`. When you do certain mathematical operations on strings, they are coerced into `Number` types. For example, when you do `[2] * [2]` it becomes `"2" * "2"` which becomes `2 * 2`. You can even mix types and do `[2] * 2` or `"2" * [2]`. When you try to use `+`, it attempts to concatenate the strings instead of coercing the strings to numbers. That's why `"2" + "2"`, `"2" + [2]`, and `[2] + [2]` each give you `"22"`.
When you do mathematical operations on the arrays JavaScript converts them to the **strings**. But **string** doesn't have multiply operator and then JavaScript converts them to the **numbers** because you try to multiply them: ``` [] * [] === 0 // [] -> '' -> 0, result is 0 * 0 [2] * [2] === 4 // [2] -> '2' -> 2, result is 4 * 4 ["2"] * ["2"] === 4 // ["2"] -> '2' -> 2, result is 4 * 4 ``` **String** has a `+` operator: ``` [2] + [1] === 3 // '2' + '1', result is "21" ``` but doesn't have a `-` operator, therefore JavaScript converts them to the **numbers** too: ``` [2] - [1] === 1 // true, because they are numbers ``` `===` it's *strict equality*, means that the objects being compared must have the same type. ``` [4] === "4" // false, you are comparing array with a string [4] === 4 // false, you are comparing array with a number ```
15,029,537
I am creating a custom type calendar and I am trying to see if it is possible to store dates in an array without statically assigning each one. For example the 1st date in the array would be the day it was first created and it would save the next week lets say into the relevant indexes in the array. ``` NSMutableArray *thisWeek = [today, tomorrow, sunday(Feb 24), monday (Feb 25), etc]; ``` What would be the best way to go about storing the future dates?
2013/02/22
['https://Stackoverflow.com/questions/15029537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1220097/']
``` NSMutableArray *days; days = [[NSMutableArray alloc] init]; NSDate *todayDate = [NSDate Date]; [days addObject:todayDate]; for (int i = 1; i <= 6; i++) { NSDate *newDate = [[NSDate date] dateByAddingTimeInterval:60*60*24*i]; [days addObject:newDate]; } ``` In this way, you can add days in array.
Take a look at `dateByAddingTimeInterval:` in the `NSDate` docs ([link](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html)). It lets you add a given amount of seconds to a date.
15,029,537
I am creating a custom type calendar and I am trying to see if it is possible to store dates in an array without statically assigning each one. For example the 1st date in the array would be the day it was first created and it would save the next week lets say into the relevant indexes in the array. ``` NSMutableArray *thisWeek = [today, tomorrow, sunday(Feb 24), monday (Feb 25), etc]; ``` What would be the best way to go about storing the future dates?
2013/02/22
['https://Stackoverflow.com/questions/15029537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1220097/']
``` NSMutableArray *days = [[NSMutableArray alloc] init]; NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar]; NSDateComponents *tempCop = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]]; NSDate *today = [cal dateFromComponents:tempCop]; for (int i = 0; i < 8; i++) { NSDateComponents *comps = [[NSDateComponents alloc]init]; [comps setDay:i]; [days addObject:[cal dateByAddingComponents:comps toDate:today options:0]]; } ```
Take a look at `dateByAddingTimeInterval:` in the `NSDate` docs ([link](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html)). It lets you add a given amount of seconds to a date.
15,029,537
I am creating a custom type calendar and I am trying to see if it is possible to store dates in an array without statically assigning each one. For example the 1st date in the array would be the day it was first created and it would save the next week lets say into the relevant indexes in the array. ``` NSMutableArray *thisWeek = [today, tomorrow, sunday(Feb 24), monday (Feb 25), etc]; ``` What would be the best way to go about storing the future dates?
2013/02/22
['https://Stackoverflow.com/questions/15029537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1220097/']
``` NSMutableArray *days = [[NSMutableArray alloc] init]; NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar]; NSDateComponents *tempCop = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]]; NSDate *today = [cal dateFromComponents:tempCop]; for (int i = 0; i < 8; i++) { NSDateComponents *comps = [[NSDateComponents alloc]init]; [comps setDay:i]; [days addObject:[cal dateByAddingComponents:comps toDate:today options:0]]; } ```
``` NSMutableArray *days; days = [[NSMutableArray alloc] init]; NSDate *todayDate = [NSDate Date]; [days addObject:todayDate]; for (int i = 1; i <= 6; i++) { NSDate *newDate = [[NSDate date] dateByAddingTimeInterval:60*60*24*i]; [days addObject:newDate]; } ``` In this way, you can add days in array.
40,147,118
I am building an application for which i am using nodejs express to do rest api services. I hosted that application on windows server 2012 using iisnode module.Everything works perfect. The issue is that when i am returning 404(unauthorized) message from node application the end point is recieving the 401 http status with the error page of iis. Is there any other way to overcome this issue. here is my webconfig file ``` <!-- indicates that the hello.js file is a node.js application to be handled by the iisnode module --> <handlers> <add name="iisnode" path="app.js" verb="*" modules="iisnode" /> </handlers> <!-- use URL rewriting to redirect the entire branch of the URL namespace to hello.js node.js application; for example, the following URLs will all be handled by hello.js: http://localhost/node/express/myapp/foo http://localhost/node/express/myapp/bar --> <rewrite> <rules> <rule name="/"> <match url="/*" /> <action type="Rewrite" url="app.js" /> </rule> </rules> </rewrite> ``` My code in nodejs app is the following ``` if(clienttoken!=servertoken) { res.json(401, 'unauthorized'); res.end(); } ``` [![enter image description here](https://i.stack.imgur.com/AdTI1.png)](https://i.stack.imgur.com/AdTI1.png) Thanks in advance
2016/10/20
['https://Stackoverflow.com/questions/40147118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3079776/']
Using IIS, if you want to return the errors straight from your Node app to the requester without IIS intercepting them with default Error Pages, use the `<httpErrors>` element with the `existingResponse` attribute set to `PassThrough` ``` <configuration> <system.webServer> <httpErrors existingResponse="PassThrough" /> </system.webServer> </configuration> ```
IIS is obscuring the "detail" of the error (your json response) because by default errors are set to `DetailedLocalOnly`, meaning that the error detail will be shown for requests from the machine the website is running on, but show the generic IIS error page for that error code for any external requests. Setting the 401 error to `Detailed` instead should allow your json response through: ``` <configuration> <system.webServer> <httpErrors errorMode="DetailedLocalOnly"> <remove statusCode="401" /> <error statusCode="401" errorMode="Detailed"/> </httpErrors> </system.webServer> </configuration> ``` See <https://www.iis.net/configreference/system.webserver/httperrors> for details.
8,081,268
I've different divboxes and some pictures below them. If I hover the divboxes, they expand from 200px to 400px and the picture below slide. So I've the function "theRotation" and i call two external function in it like this: ``` function theRotation(){ opendivs(); //this expand the divbox to 400 px rotatePicture(); //this rotate the picture } ``` now my problem is, that I want the pictures to slide if the divbox is about 300px NOT before!! (remember it expand from 200px to 400px) So i need a event listener who tell me when the divbox.width() == 300px Is this possible? Kind Regards
2011/11/10
['https://Stackoverflow.com/questions/8081268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/831022/']
I had some issues with this process as well. I don't exactly recall what resolved this error, but I followed [This Tutorial](http://net.tutsplus.com/tutorials/php/how-to-authenticate-users-with-twitter-oauth/) (albeit a bit out of date) and made sure I explicitly set the callback URL in the twitter panel for my app. Also, and I believe this one also caused the `int 0` return for me, make sure that if you are going with a hosting provider they allow `CURL` requests.
step 1: <https://apps.twitter.com/app> or go to your app setting step 2: Unchecked the (Enable Callback Locking (It is recommended to enable callback locking to ensure apps cannot overwrite the callback url)) This box.. save and exit and check.. ThankYou..!
40,625,869
we started to develope an application with swift for iOS. when we started it latest version was developer target 9.3. now there is developer target 10 available. Can I install application that created with developer target 9.3 on iOS 10 ?
2016/11/16
['https://Stackoverflow.com/questions/40625869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4433550/']
In short - YES. You won't be able to do the opposite - install targeted as iOS 10 app to device, running with iOS 9.3 EDITED So, your purposes, I think, maintain as small version, as possible. If you maintain 9.3 version, for example, your app will be available for iPhone 4s, which is not updates to iOS 10. With this ver you will cover more users
**Deployment Target** is the **minimum required iOS version you application needs to run**. You can build an application with SDK 10 that runs under iOS 9. But then you have to take care to not use any function or method that is not available on iOS 9. Also Always check to see if you are using deprecated APIs; though still available, deprecated APIs are not guaranteed to be available in the future.
40,625,869
we started to develope an application with swift for iOS. when we started it latest version was developer target 9.3. now there is developer target 10 available. Can I install application that created with developer target 9.3 on iOS 10 ?
2016/11/16
['https://Stackoverflow.com/questions/40625869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4433550/']
Yes, You can install lower developer target on higher iOS version.
**Deployment Target** is the **minimum required iOS version you application needs to run**. You can build an application with SDK 10 that runs under iOS 9. But then you have to take care to not use any function or method that is not available on iOS 9. Also Always check to see if you are using deprecated APIs; though still available, deprecated APIs are not guaranteed to be available in the future.
3,326,203
I'm having a little difficulty wrapping my head around the difference between these two terms, so could someone verify if this is correct? I've struggle to find an answers or reference in a book or online. Component sequence: If you have a set $X \subset \mathbb{R}^m$ and a sequence $x \in X^\infty$ such that $$x = (x\_1, x\_2, \dots ) \in X^\infty = (\mathbb{R}^m)^\infty$$ Each $x\_i$ is itself a vector of $m$-terms, e.g., $x\_1 = (x\_{1,1}, x\_{1,2}, ... x\_{1,m})$, or for another notation: $x\_1 = (x\_1(1), x\_2(1), ... x\_m(1))$ i.e., each term of the sequence is itself an m-tuple. Then, a component sequence is defined as the $k-th$ component of each term $x(n)$, and hence, there are $m$ of these component sequences, a sequence for each component. But what does that actually mean, practically? If I have a sequence: $$ S = (x\_1, x\_2, x\_3 , ...)$$ where $x\_1 = (1,3,5,7,9)$, is one such component sequence of $S$ just $(1,3,5,7,9)$? As opposed to a subsequence which could be $(x\_1, x\_3, x\_5, ...) $ ?
2019/08/17
['https://math.stackexchange.com/questions/3326203', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/466286/']
Component sequences are projections of your sequences on the one dimensional axes of your space. Each component sequence is an infinite sequence of picking the sequence of terms in one dimension of the original sequence . For example if $$\{(1,4,5),(3,2,4),(5,3,6),...\}$$ is a sequence in $R^3$, then you have three component sequences namely $$\{1,3,5,....\}, \{4,2,3,....\},\{5,4,6,...\}$$
The answer to you example-question is no. A component-sequence takes only one component per term, always from the same position, and so for each term. So, if $x\_1 = (1,3,5,7,9)$ like you suggest, then there are exactly five component sequences of $x$, one of them starts with $1$ and takes the first coordinate of each term, another starts with $3$ and takes the second coordinate of each term, etc.
59,465,212
I recently migrated from c# to .net core. In c# I use to get CPU usage with this: ``` PerformanceCounter cpuCounter; PerformanceCounter ramCounter; cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); public string getCurrentCpuUsage(){ return cpuCounter.NextValue()+"%"; } ``` but in .net core `PerformanceCounter` is not available what is the solution ? please give me an advice.
2019/12/24
['https://Stackoverflow.com/questions/59465212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11589744/']
Performance counters are not in Linux thus not in NET Core. Alternative way: ``` private async Task<double> GetCpuUsageForProcess() { var startTime = DateTime.UtcNow; var startCpuUsage = Process.GetProcesses().Sum(a => a.TotalProcessorTime.TotalMilliseconds); await Task.Delay(500); var endTime = DateTime.UtcNow; var endCpuUsage = Process.GetProcesses().Sum(a => a.TotalProcessorTime.TotalMilliseconds); var cpuUsedMs = endCpuUsage - startCpuUsage; var totalMsPassed = (endTime - startTime).TotalMilliseconds; var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed); return cpuUsageTotal * 100; } ```
On Mac, I went the same route as [you already have to go to get memory usage](https://apple.stackexchange.com/questions/317483/how-to-calculate-used-memory-on-mac-os-by-command-line): shell out to a command-line utility, such as `top`, and parse the output. Here's my code: ``` private static string[] GetOsXTopOutput() { var info = new ProcessStartInfo("top"); info.Arguments = "-l 1 -n 0"; info.RedirectStandardOutput = true; string output; using (var process = Process.Start(info)) { output = process.StandardOutput.ReadToEnd(); } return output.Split('\n'); } public static double GetOverallCpuUsagePercentage() { if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var lines = GetOsXTopOutput(); // Example: "CPU usage: 8.69% user, 21.73% sys, 69.56% idle" var pattern = @"CPU usage: \d+\.\d+% user, \d+\.\d+% sys, (\d+\.\d+)% idle"; Regex r = new Regex(pattern, RegexOptions.IgnoreCase); foreach (var line in lines) { Match m = r.Match(line); if (m.Success) { var idle = double.Parse(m.Groups[1].Value); var used = 100 - idle; return used; } } // Or throw an exception return -1.0; } else { // E.g., Melih Altıntaş's solution: https://stackoverflow.com/a/59465268/132042 ... } } ```
26,469,017
I'm recreating the classic game 'Snake'. My idea is to firstly make a grid of 50 x 50 cells where each cell is a label of 10 x 10 pixels. However, I can't get this to work. I'm using GridLayout but somehow this doesn't really work, as I apparently can't set the site of each grid. I watched a video on Youtube where a guy made a tic tac toe game in which each the size of each grid automatically adapted to the size of the added images. What should I do if I use labels instead of images? Basically, what should I do to make each cell 10 by 10 pixels big, and put them in a grid of 50x50 cells? ``` import java.awt.*; import javax.swing.*; public class MainSnake { JFrame frame; JLabel[][] cells; MainSnake() { //Frame initializion frame = new JFrame("Snake"); frame.getContentPane().setBackground(Color.BLACK); frame.setSize(500, 500); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setLayout(new GridLayout(50, 50)); createCells(); } //End MainSnake public static void main(String[]a) { new MainSnake(); } //End main public void createCells(){ int a = 0; int i; cells = new JLabel[50][50]; for (i = 0; i < 50; i++){ if(i < 50){ cells[i][a] = new JLabel(""); cells[i][a].setOpaque(true); cells[i][a].setBackground(Color.white); cells[i][a].setBorder(BorderFactory.createLineBorder(Color.BLUE, 1)); cells[i][a].setPreferredSize(new Dimension(10,10)); frame.add(cells[i][a]); } if(i==49){ i = 0; aa++; } } //End for } } //End Class ``` This is what I get (I only added the borders to ble able to see how each cell looks like): ![enter image description here](https://i.stack.imgur.com/AKFNY.jpg)
2014/10/20
['https://Stackoverflow.com/questions/26469017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4017593/']
I found an solution my self, and sharing it here for some one else to use. The following codes should be placed inside the Wordpress loop. ``` <?php $fields = get_field('relationship_field_name'); ?> <?php if( $fields ): ?> <?php foreach( $fields as $field ): ?> <?php $name = get_field('field_name', $field->ID); ?> <?php $image = get_field('field_name', $field->ID); ?> <?php $email = get_field('field_name', $field->ID); ?> <?php $phone = get_field('field_name', $field->ID); ?> <h4><span><?php echo $name; ?></span></h4> <img style="width: 150px; height: auto;" src="<?php echo $image; ?>" alt="<?php echo $name; ?>"/> <ul class="fa-ul pad10"> <li><i class="fa-li fa fa-phone colour"></i><a href="tel:0045<?php echo str_replace(' ', '', $phone); ?>">+ 45 <?php echo $phone; ?></a></li> <li><i class="fa-li fa fa-envelope colour"></i><?php echo $email; ?></li> </ul> <div class="pad10"></div> <?php endforeach; ?> <?php endif; ?> ```
I understand, you want to set connection two different post types. You can this with custom fields. Create a selectbox and there options is post of your other custom post type. For be easy you can use Rilwis's meta box plugin (<https://github.com/rilwis/meta-box>). Your option value must post id. If you want get selected post, can use this: ``` $getIdWithField = get_post_meta($post->ID, 'custom_personel_field', true); $post = get_post($getIdWithField); ```
59,972,802
My aim was to use ajax to retrieve some data from my controller and append this to a table element in my view. However the javascript code only works until "$.ajax(" at which point it just stops. I placed some break points after the above mentioned point but the code never "broke" at those points. This is the javascript code ``` $(document).ready(function () { $("#DivisionId").change(function () { var OptionId = $('#DivisionId').val(); var position = 0; $.ajax( { type: 'POST', url: '@URL.Action("Division")', dataType: 'json', data: { DivisionId: OptionId }, success: function (data) { var LogStandings = ''; $.each(data, function (i, log) { position++; var Logs = "<tr>" + "<td>" + position + "</td>" + "<td>" + log.Logs1.Team.TeamName + "</td>" + "<td>" + log.Logs1.Played + "</td>" + "<td>" + log.Logs1.Win + "</td>" + "<td>" + log.Logs1.Draw + "</td>" + "<td>" + log.Logs1.Lost + "</td>" + "<td>" + log.Logs1.GoalsFor + "</td>" + "<td>" + log.Logs1.GoalsAgainst + "</td>" + "<td>" + log.Logs1.GoalDifference + "</td>" + "<td>" + log.Logs1.Points + "</td>" + "</tr>"; $('#TheLog').append(Logs); }); }, error: function (ex) { var r = jQuery.parseJSON(response.responseText); alert("Message: " + r.Message); alert("StackTrace: " + r.StackTrace); alert("ExceptionType: " + r.ExceptionType); } }); return false; }); // end of Division on change function })//End of document.ready function ``` This is the code in my controller ``` public JsonResult Division(int DivisionId) { int UnderId = db.Under.FirstOrDefault().UnderID; MainDivisionId = id; List<FixtureModel> Fixtures = db.Fixtures.Where(f => f.TeamModel.DivisionId == id && f.TeamModel.UnderId == UnderId).ToList(); List<ResultModel> Results = db.Results.Where(r => r.Fixtures.TeamModel.DivisionId == id && r.Fixtures.TeamModel.UnderId == UnderId).ToList(); List<LogModel> Logs = db.Logs.Where(l => l.Team.DivisionId == id && l.Team.UnderId == UnderId).ToList(); IndexViewModel IndexPage = new IndexViewModel(Fixtures, Results, Logs); return Json(IndexPage , JsonRequestBehavior.AllowGet); } ``` I searched a little on the internet and one source suggested that I place my jquery CDN at the top of my view within the head tag, this did not solve my problem though. Besides that I have not been able to find any other solutions after an hour of searching.
2020/01/29
['https://Stackoverflow.com/questions/59972802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12765810/']
You have 2 issues that I can see. First, you're making a `POST` request to a controller action that does not have the `[HttpPost]` annotation. It seems to me that you're getting/selecting data and a `GET` request would be more appropriate so I've used that in the example below. Second, you cannot use `@URL.Action("Division")` in a javascript string (or in javascript in general. If you really needed to then you could store some data in a hidden div and get the value with javascript/jquery) like you're attempting to do. On the script itself, this will render as you're making a request directly to `localhost:12345/@URL.Action("Division")` which is not a valid path. See the example below: Script: ``` $(document).ready(function () { $("#testButton").on("click", function () { var OptionId = 1; $.ajax( { type: 'GET', //this url assumes your controller action is in HomeController.cs url: '/Home/Division/' + OptionId, dataType: 'json', data: { DivisionId: OptionId }, success: function (data) { alert("success"); }, error: function (ex) { var r = jQuery.parseJSON(response.responseText); alert("Message: " + r.Message); alert("StackTrace: " + r.StackTrace); alert("ExceptionType: " + r.ExceptionType); } }); }); }); ``` HomeController.cs action: ``` public JsonResult Division(int DivisionId) { return Json(1, JsonRequestBehavior.AllowGet); } ``` and in my view for testing: `<button type="button" id="testButton" class="btn btn-primary btn-lg">TEST BUTTON</button>` The above test works as expected (receives the `DivisionID` param, returns data from the controller action and alerts success to the client). With the changed outlined above, breakpoints in your controller action will be hit as you're specifying a valid path and making the appropriate request type. Hope this helps.
I also had same problem like that. I did that in a `script` tag placed inside `head` tag. But I had to place that inside `body` tag. Then it worked fine. Try to use. It might help.
25,352,105
The following code doesn't loop: ``` -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { NSLog(@"Inside method, before for loop"); NSLog(@"dayBarArray.count = %lu", (unsigned long)dayBarArray.count); for (int i = 0; i < dayBarArray.count; i++) //*** I've tried it this way // for (DayChartBar *bar in dayBarArray) //*** I've tried it this way { NSLog(@"Inside for loop"); DayChartBar *bar = [dayBarArray objectAtIndex:i]; UIView *thisLabel = [self.scroller viewWithTag:(bar.tag + 100)]; CGRect visibleRect; visibleRect.origin = self.scroller.frame.origin; visibleRect.size = self.scroller.bounds.size; NSLog(@"bar.frame = %@",NSStringFromCGRect(bar.frame)); NSLog(@"visibleRect.frame = %@",NSStringFromCGRect(visibleRect)); if (CGRectIntersectsRect(visibleRect,bar.frame)) { NSLog(@"Inside if statement"); CGRect intersection = CGRectIntersection(visibleRect,bar.frame); NSLog(@"bar.Frame is %@",NSStringFromCGRect(bar.frame)); thisLabel.center = CGPointMake((thisLabel.center.x), CGRectGetMidY(intersection)); } else { thisLabel.center = thisLabel.center; NSLog(@"Inside else statement"); } } NSLog(@"Still inside method, after for loop"); } ``` Here are the results of the strategically placed `NSLog` statements: ``` 2014-08-17 10:07:37.221 WMDGx[54442:90b] Inside method, before for loop 2014-08-17 10:07:37.222 WMDGx[54442:90b] dayBarArray.count = 0 2014-08-17 10:07:37.223 WMDGx[54442:90b] Still inside method, after for loop ``` As you can see, I've tried both a traditional `for loop` and fast enumeration. Neither will execute. As the `NSLogs` indicate, I enter the method, but skip the loop, regardless of the approach I've taken. I'm pretty sure I've written good code since I've successfully used very similar syntax (both types) in many other places around this same app. And yes, I've looked at dozens of similar questions on SO, as well as consulting basic texts on Objective C `for` loops, but without resolution. As always, I'm open to the possibility that I've made a stupid mistake, but, if so, it eludes me. The code inside the `for` loop (I'm trying to relocate a `UILabel` in response to the scrolling of an associated `UIView`) is probably irrelevant, but I included it just in case. All help and observations appreciated! **Edit:** As kindly pointed out below, the answer to this question is that the relevant dayBarArray is empty. I just checked the code that adds the objects, and am perplexed. I certainly should have seen the obvious answer in my NSLogs, and have no excuse except that I had checked the add code before and the bars appeared to be added. I'll report back when I've straightened out whatever is wrong there. **Second edit:** OK, it was a dumbass mistake on my part--I hadn't initialized the array. Just the same, had I not posted the question, and since I believed I had checked the contents of the array (actually, I was checking to see if tags had been applied to the UIViews), I don't know how long it would have taken me to realize what the logs were telling me. Thanks to everyone who replied!
2014/08/17
['https://Stackoverflow.com/questions/25352105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2671035/']
`dayBarArray.count` is zero, and the condition in the loop is `i < dayBarArray.count`. Before entering the loop body, it tests `0 < 0`, which is false, so it never enters the body.
dayBarArray.count should return a number greater than 0, to be able for the loop to execute at least once. In you case, because (dayBarArray.count == 0), the condition-expression for the for loop: ``` i < dayBarArray.count ``` is false (because i == 0), and the the execution of the program will not go inside the loop.
25,352,105
The following code doesn't loop: ``` -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { NSLog(@"Inside method, before for loop"); NSLog(@"dayBarArray.count = %lu", (unsigned long)dayBarArray.count); for (int i = 0; i < dayBarArray.count; i++) //*** I've tried it this way // for (DayChartBar *bar in dayBarArray) //*** I've tried it this way { NSLog(@"Inside for loop"); DayChartBar *bar = [dayBarArray objectAtIndex:i]; UIView *thisLabel = [self.scroller viewWithTag:(bar.tag + 100)]; CGRect visibleRect; visibleRect.origin = self.scroller.frame.origin; visibleRect.size = self.scroller.bounds.size; NSLog(@"bar.frame = %@",NSStringFromCGRect(bar.frame)); NSLog(@"visibleRect.frame = %@",NSStringFromCGRect(visibleRect)); if (CGRectIntersectsRect(visibleRect,bar.frame)) { NSLog(@"Inside if statement"); CGRect intersection = CGRectIntersection(visibleRect,bar.frame); NSLog(@"bar.Frame is %@",NSStringFromCGRect(bar.frame)); thisLabel.center = CGPointMake((thisLabel.center.x), CGRectGetMidY(intersection)); } else { thisLabel.center = thisLabel.center; NSLog(@"Inside else statement"); } } NSLog(@"Still inside method, after for loop"); } ``` Here are the results of the strategically placed `NSLog` statements: ``` 2014-08-17 10:07:37.221 WMDGx[54442:90b] Inside method, before for loop 2014-08-17 10:07:37.222 WMDGx[54442:90b] dayBarArray.count = 0 2014-08-17 10:07:37.223 WMDGx[54442:90b] Still inside method, after for loop ``` As you can see, I've tried both a traditional `for loop` and fast enumeration. Neither will execute. As the `NSLogs` indicate, I enter the method, but skip the loop, regardless of the approach I've taken. I'm pretty sure I've written good code since I've successfully used very similar syntax (both types) in many other places around this same app. And yes, I've looked at dozens of similar questions on SO, as well as consulting basic texts on Objective C `for` loops, but without resolution. As always, I'm open to the possibility that I've made a stupid mistake, but, if so, it eludes me. The code inside the `for` loop (I'm trying to relocate a `UILabel` in response to the scrolling of an associated `UIView`) is probably irrelevant, but I included it just in case. All help and observations appreciated! **Edit:** As kindly pointed out below, the answer to this question is that the relevant dayBarArray is empty. I just checked the code that adds the objects, and am perplexed. I certainly should have seen the obvious answer in my NSLogs, and have no excuse except that I had checked the add code before and the bars appeared to be added. I'll report back when I've straightened out whatever is wrong there. **Second edit:** OK, it was a dumbass mistake on my part--I hadn't initialized the array. Just the same, had I not posted the question, and since I believed I had checked the contents of the array (actually, I was checking to see if tags had been applied to the UIViews), I don't know how long it would have taken me to realize what the logs were telling me. Thanks to everyone who replied!
2014/08/17
['https://Stackoverflow.com/questions/25352105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2671035/']
`dayBarArray.count` is zero, and the condition in the loop is `i < dayBarArray.count`. Before entering the loop body, it tests `0 < 0`, which is false, so it never enters the body.
Your for loop will only execute when dayBarArray.count is greater than i and your log is telling you that dayBarArray.count equals 0 when i also equals 0. Your code is working correctly. Check where you are adding items to dayBarArray.
18,849,257
I need to pass a model value item.ID to one of my javascript function how can I do that ? I tried`function("@item.ID")` but its not working
2013/09/17
['https://Stackoverflow.com/questions/18849257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1858684/']
It generally works this way, you just have to omit the `""` otherwise it gets interpreted as string. So you can write something like that in your JS: ``` var myinteger = @item.ID; ``` which renders as ``` var myinteger = 123; //for example ``` Edit: This makes sense when you id is an integer, of course, for strings you need to encapsulate it in `''` or `""`. And don't get annoyed by any syntax errors reported by intellisense, it seems to have a problem with that but it works out just nicely.
Try this...mind single quotes on parameter value while calling js function ``` function MyJsFunction(modelvalue) { alert("your model value: " + modelvalue); } <input type="button" onclick="MyJsFunction('@item.ID')" /> OR <input type="button" onclick="MyJsFunction('@(item.ID)')" /> ```
18,849,257
I need to pass a model value item.ID to one of my javascript function how can I do that ? I tried`function("@item.ID")` but its not working
2013/09/17
['https://Stackoverflow.com/questions/18849257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1858684/']
It generally works this way, you just have to omit the `""` otherwise it gets interpreted as string. So you can write something like that in your JS: ``` var myinteger = @item.ID; ``` which renders as ``` var myinteger = 123; //for example ``` Edit: This makes sense when you id is an integer, of course, for strings you need to encapsulate it in `''` or `""`. And don't get annoyed by any syntax errors reported by intellisense, it seems to have a problem with that but it works out just nicely.
The best solution is pass your textbox ID to javascrpit function and then in function retrieve the value form the ID, ``` @Html.TextBoxFor(model => model.DatemailedStart, new {id = "MailStartDate", placeholder = "MM/DD/YYYY", maxlength = "40", @class = "TextboxDates", @onblur = "isValidDate('MailStartDate');" }) function isValidDate(id) { var dateString = $('#'+id+'').val(); } ```
18,849,257
I need to pass a model value item.ID to one of my javascript function how can I do that ? I tried`function("@item.ID")` but its not working
2013/09/17
['https://Stackoverflow.com/questions/18849257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1858684/']
You can pass the model data into the java script file in these ways (1). Just set the value in hidden field and access the value of hidden field in java script. (2). And pass the value using function parameter. (3). ``` var LoginResourceKeyCollection = { UserName_Required: '<%= Model.UserName%>', Password_Required: '<%= Model.Password%>' } </script> ```
Try this...mind single quotes on parameter value while calling js function ``` function MyJsFunction(modelvalue) { alert("your model value: " + modelvalue); } <input type="button" onclick="MyJsFunction('@item.ID')" /> OR <input type="button" onclick="MyJsFunction('@(item.ID)')" /> ```
18,849,257
I need to pass a model value item.ID to one of my javascript function how can I do that ? I tried`function("@item.ID")` but its not working
2013/09/17
['https://Stackoverflow.com/questions/18849257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1858684/']
You can pass the model data into the java script file in these ways (1). Just set the value in hidden field and access the value of hidden field in java script. (2). And pass the value using function parameter. (3). ``` var LoginResourceKeyCollection = { UserName_Required: '<%= Model.UserName%>', Password_Required: '<%= Model.Password%>' } </script> ```
The best solution is pass your textbox ID to javascrpit function and then in function retrieve the value form the ID, ``` @Html.TextBoxFor(model => model.DatemailedStart, new {id = "MailStartDate", placeholder = "MM/DD/YYYY", maxlength = "40", @class = "TextboxDates", @onblur = "isValidDate('MailStartDate');" }) function isValidDate(id) { var dateString = $('#'+id+'').val(); } ```
18,849,257
I need to pass a model value item.ID to one of my javascript function how can I do that ? I tried`function("@item.ID")` but its not working
2013/09/17
['https://Stackoverflow.com/questions/18849257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1858684/']
Try this...mind single quotes on parameter value while calling js function ``` function MyJsFunction(modelvalue) { alert("your model value: " + modelvalue); } <input type="button" onclick="MyJsFunction('@item.ID')" /> OR <input type="button" onclick="MyJsFunction('@(item.ID)')" /> ```
The best solution is pass your textbox ID to javascrpit function and then in function retrieve the value form the ID, ``` @Html.TextBoxFor(model => model.DatemailedStart, new {id = "MailStartDate", placeholder = "MM/DD/YYYY", maxlength = "40", @class = "TextboxDates", @onblur = "isValidDate('MailStartDate');" }) function isValidDate(id) { var dateString = $('#'+id+'').val(); } ```
33,772,472
After someone has logged off (*Start button→Logoff*) for the night, at a certain time in the morning I want to have the Task Scheduler automatically log into the Windows 7 user account (the opposite of *Start button→Logoff*) that is password protected. The machine is 64 bit. I am doing this so systems (vbs, vba, etc.) can prep files prior to the user showing up to work. I was pretty sure this was possible, but I can't find it anywhere online, so I am wondering if it really is possible. I have to this in a VBScript. For security reasons I need to log him off at night, but I figured that part out (vbs from SO): ``` Set = wshell = Wscript.CreateObject(Wscript.Shell") wschell.exec("shutdown.exe -L -F") 'logoff and force shutdown programs ``` Edit1: Using an answer from Sujith, I attempted to set this up. First I must point out that this is NOT a remote computer or connection. I'm trying to get the local computer to log back in to the user account. I created logon.vbs with this vbs code: ``` Set = wshell = Wscript.CreateObject(Wscript.Shell") wschell.exec("shutdown.exe -L -F") 'logoff and force shutdown programs WScript.Sleep(5000) computer = "computername" username = "OTHERDOMAIN\user" password = "password" Set locator = CreateObject("WbemScripting.SWbemLocator") Set wmi = locator.ConnectServer(computer, "root\default", username, password) wmi.Security_.ImpersonationLevel = 3 ``` In other words, I am logging off and right back on (avoiding the Task Scheduler so things are simplified). I also tried a lot of variations on this trying to get it to work. It logs me off just fine, but nothing happens after that. I have to login manually. I also tried the Task Scheduler setting mentioned in Sujith's answer, but it never turned on that I could tell. Edit2: Or please tell me what you need to provide an answer?
2015/11/18
['https://Stackoverflow.com/questions/33772472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3524158/']
Please minus the half the stroke width from x position. you will get the correct path. eg. if stroke width is 20 mean minus the 10 from second MoveTo. **calculation** 254-(storkeWidth/2) = 244. if strokeWidth is 20. ``` <svg height="200" width="500"> <path fill='none' stroke-width="20" stroke="black" d="M 100 63.125 L 254 63.125 L 254 117.5 M 244 117.5 L 418 117.5"/> </svg> ``` [Fiddle](http://jsfiddle.net/3t8rspd1/3/)
[stroke-linejoin](http://www.w3.org/TR/SVG/painting.html#StrokeLinejoinProperty "Take this") ``` <svg height="200" width="500"> <path fill='none' stroke-width="30" stroke-linejoin="round" stroke="black" d="M 100 63.125 L 254 63.125 L 254 117.5 L 418 117.5"/> </svg> ```
50,589,825
I am currently looking at IdentityServer4 as an option for our web services. However, due to corporate compiler level policy, I am only able to use VisualStudio 15.0 which does not support .Net Core 2 (and ASP.NET core 2 therefore). So I am stuck with ASP.Net Core 1.x for the moment. Changing the compiler version is out of the question for the time being. IdentityServer4 does have a version based on ASP.NEt Core 1.x but doesn't seem to be maintained anymore. **My question is:** Will security vulnerabilities be fixed in Identityserver4 (ASP.NET Core 1.x)? The Github repository seemed to be still active 2 months ago. So I am wondering what kind of maintenance will be provided by the developers.
2018/05/29
['https://Stackoverflow.com/questions/50589825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1704574/']
Security vulnerabilities would be fixed on the 1.x branch - but no more feature work
Here is Brock Allen's answer : > > [...] if there are any security vulnerabilities reported we will fix them. But we won't be adding new features to the ASP.NET Core 1.x branch, as Microsoft themselves have moved on to ASP.NET Core 2.x and (in their eyes) ASP.NET Core 1.x is essentially deprecated. > > >