qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
19,087,013
If suppose, I have a `List` of type `Schedule` on my JSP page. I iterate through it and wants to send a particular object of the list to the action class. Is this possible to do that using Struts 2? What I have explored is that I can send the value of the identifier variable of the object to the action class and then fetch the row corresponding to it there. ```jsp <s:form action="FlightAction"> <s:iterator value="schedulelist" var="flight"> <s:if test="#flight.sid==10"> <s:hidden name="object" value="#flight"/> </s:if> </s:iterator> <s:submit value="Send"/> </s:form> ``` Now what I want is when value of SID is 10, then the whole Schedule object is sent to the action class. `schedulelist` refers to a list that contains object of type Schedule. SID is the identifier variable of the Schedule POJO. Is sending a complete object in this way possible in Struts 2?
2013/09/30
[ "https://Stackoverflow.com/questions/19087013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2818245/" ]
The try/finally blocks should be *inside* the function, like so: ``` public void GravaBanco(String nome, String telefone) { try { ... } finally { ... } } ```
Use below code, you are missing braces. ``` public void GravaBanco(String nome, String telefone){ try{ //Syntax error on token “try”, delete this token BancoDados = openOrCreateDatabase(NomeBanco, MODE_WORLD_READABLE, null); String SQL = "INSERT INTO tabcadastropessoa (nomepessoa, telefonepessoa) VALUES (nomepessoa = '"+NomePessoa+"', telefonepessoa = '"+TelefonePessoa+"')"; MensagemAlerta("Banco de Dados", "Registro gravado com sucesso!"); }catch(Exception erro){ //Syntax error on tokens, delete this tokens MensagemAlerta("Erro no Banco de Dados", "Não foi possivel gravar o registro!" + erro); } finally{ //Syntax error on token “finally”, delete this token BancoDados.close(); } } ```
19,087,013
If suppose, I have a `List` of type `Schedule` on my JSP page. I iterate through it and wants to send a particular object of the list to the action class. Is this possible to do that using Struts 2? What I have explored is that I can send the value of the identifier variable of the object to the action class and then fetch the row corresponding to it there. ```jsp <s:form action="FlightAction"> <s:iterator value="schedulelist" var="flight"> <s:if test="#flight.sid==10"> <s:hidden name="object" value="#flight"/> </s:if> </s:iterator> <s:submit value="Send"/> </s:form> ``` Now what I want is when value of SID is 10, then the whole Schedule object is sent to the action class. `schedulelist` refers to a list that contains object of type Schedule. SID is the identifier variable of the Schedule POJO. Is sending a complete object in this way possible in Struts 2?
2013/09/30
[ "https://Stackoverflow.com/questions/19087013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2818245/" ]
The try/finally blocks should be *inside* the function, like so: ``` public void GravaBanco(String nome, String telefone) { try { ... } finally { ... } } ```
I Think u missed the braces after method name try this code ``` public void GravaBanco(String nome, String telefone) { try { // Syntax error on token “try”, delete this token BancoDados = openOrCreateDatabase(NomeBanco, MODE_WORLD_READABLE, null); String SQL = "INSERT INTO tabcadastropessoa (nomepessoa, telefonepessoa) VALUES (nomepessoa = '" + NomePessoa + "', telefonepessoa = '" + TelefonePessoa + "')"; MensagemAlerta("Banco de Dados", "Registro gravado com sucesso!"); } catch (Exception erro) { // Syntax error on tokens, delete this tokens MensagemAlerta("Erro no Banco de Dados", "Não foi possivel gravar o registro!" + erro); } finally { // Syntax error on token “finally”, delete this token BancoDados.close(); } } ```
41,489,682
I am a new python user, and I have just been getting familiar with restructuring data with the zip function, however I am now faced with a challenging data set that i have to restructure. I have 3 json responses that I have to merge from my end, the data sets are identical in design and would have the same length, they just differ from environments they ran on. **Let 3 files be the same values for brevity: qa.json | dev.json | prod.json** *Note: This outer object is array/list of object, I just put one object for brevity* ``` [ { "elements": [ { "keyword": "Scenario", "name": "valid user can login site", "steps": [ { "name": "a valid user name and password", "result": { "status": "passed" } }, { "name": "a valid user clicking on the login button after typing in user name and password", "result": { "status": "passed" } }, { "name": "map should display", "result": { "status": "passed" } } ] } ], "keyword": "Feature", "name": "login", "status": "passed" } ] ``` **What I want to achieve:** *Note: i want to merge them in one set with different environments reflecting the status* ``` [ { "elements": [ { "keyword": "Scenario", "name": "valid user can login site", "steps": [ { "name": "a valid user name and password", "result": { "qa": "passed", "prod": "passed", "dev": "passed" } }, { "name": "a valid user clicking on the login button after typing in user name and password", "result": { "qa": "passed", "prod": "passed", "dev": "passed" } }, { "name": "map should display", "result": { "qa": "passed", "prod": "passed", "dev": "passed" } } ] } ], "keyword": "Feature", "name": "login", "qa": "passed", "prod": "passed", "dev": "passed" } ] ``` **What i have done so far:** *I come from a javascript background so i im still getting familiar with python logic* ``` import json with open('qa.json') as data_file: qa = json.load(data_file) with open('dev.json') as data_file: dev = json.load(data_file) with open('prod.json') as data_file: prod = json.load(data_file) json_list = [{SOME STRUCT} for q, d, p in zip(qa, dev, prod)] ```
2017/01/05
[ "https://Stackoverflow.com/questions/41489682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4971053/" ]
I don't have a lot of time so I'm posting what I believe is a working solution to your problem even if it's slightly messy. If I have time I'll edit it. **Code** ``` import json data = """ [ { "elements": [{ "keyword": "Scenario", "name": "valid user can login site", "steps": [{ "name": "a valid user name and password", "result": { "status": "passed" } }, { "name": "a valid user clicking on the login button after typing in user name and password", "result": { "status": "passed" } }, { "name": "map should display", "result": { "status": "passed" } }] }], "keyword": "Feature", "name": "login", "status": "passed" }, { "elements": [{ "keyword": "Scenario", "name": "valid user can login site", "steps": [{ "name": "a valid user name and password", "result": { "status": "passed" } }, { "name": "a valid user clicking on the login button after typing in user name and password", "result": { "status": "failed" } }, { "name": "map should display", "result": { "status": "passed" } }] }], "keyword": "Feature", "name": "login", "status": "passed" } ] """ def get_result(envData, objIndex, elementIndex, stepIndex): return envData[objIndex]['elements'][elementIndex]['steps'][stepIndex]['result']['status'] def set_combined_results(combinedData, objIndex, elementIndex, stepIndex, results): resultNode = combinedData[objIndex]['elements'][elementIndex]['steps'][stepIndex]['result'] resultNode.update({ 'qa': results[0], 'prod': results[1], 'dev': results[2] }) if __name__ == '__main__': qAData = json.loads(data) prodData = json.loads(data) devData = json.loads(data) combinedData = json.loads(data) for objIndex, obj in enumerate(combinedData): for elementIndex, element in enumerate(obj['elements']): for stepIndex, _ in enumerate(element['steps']): qAResult = get_result(qAData, objIndex, elementIndex, stepIndex) prodResult = get_result(prodData, objIndex, elementIndex, stepIndex) devResult = get_result(devData, objIndex, elementIndex, stepIndex) combinedResults = (qAResult, prodResult, devResult) set_combined_results(combinedData, objIndex, elementIndex, stepIndex, combinedResults) qAAggregateResult = qAData[objIndex]['status'] prodAggregateResult = prodData[objIndex]['status'] devAggregateResult = devData[objIndex]['status'] del combinedData[objIndex]['status'] combinedData[objIndex]['qa'] = qAAggregateResult combinedData[objIndex]['prod'] = prodAggregateResult combinedData[objIndex]['dev'] = devAggregateResult print(json.dumps(combinedData, indent=True)) ``` **Output** ``` [ { "keyword": "Feature", "name": "login", "elements": [ { "keyword": "Scenario", "name": "valid user can login site", "steps": [ { "result": { "qa": "passed", "status": "passed", "dev": "passed", "prod": "passed" }, "name": "a valid user name and password" }, { "result": { "qa": "passed", "status": "passed", "dev": "passed", "prod": "passed" }, "name": "a valid user clicking on the login button after typing in user name and password" }, { "result": { "qa": "passed", "status": "passed", "dev": "passed", "prod": "passed" }, "name": "map should display" } ] } ], "dev": "passed", "prod": "passed", "qa": "passed" }, { "keyword": "Feature", "name": "login", "elements": [ { "keyword": "Scenario", "name": "valid user can login site", "steps": [ { "result": { "qa": "passed", "status": "passed", "dev": "passed", "prod": "passed" }, "name": "a valid user name and password" }, { "result": { "qa": "failed", "status": "failed", "dev": "failed", "prod": "failed" }, "name": "a valid user clicking on the login button after typing in user name and password" }, { "result": { "qa": "passed", "status": "passed", "dev": "passed", "prod": "passed" }, "name": "map should display" } ] } ], "dev": "failed", "prod": "failed", "qa": "failed" } ] ```
Because each object in the `list` is a `dict` you can use `dict.update` mehthod to update a `dict`. f.e. ``` a = [{'one': 1}, {'three': 3}] b = [{'one': 1}, {'two': 2}] # {'one': 1} is duplicate with same value c = [{'a': 'aaa'}, {'two': 22}] # {'two': 22} is duplicate with different value for x, y, z in zip(a, b, c): x.update(y) x.update(z) ``` Now `x` would be `[{'a': 'aaa', 'one': 1}, {'three': 3, 'two': 22}]` For those json files you mentioned, it would be; ``` import json from pprint import pprint qa = ''' [ { "elements": [ { "keyword": "Scenario", "name": "valid user can login site", "steps": [ { "name": "a valid user name and password", "result": { "qa": "passed" } }, { "name": "a valid user clicking on the login button after typing in user name and password", "result": { "qa": "passed" } }, { "name": "map should display", "result": { "qa": "passed" } } ] } ], "keyword": "Feature", "name": "login", "qa": "passed" } ] ''' dev = ''' [ { "elements": [ { "keyword": "Scenario", "name": "valid user can login site", "steps": [ { "name": "a valid user name and password", "result": { "dev": "passed" } }, { "name": "a valid user clicking on the login button after typing in user name and password", "result": { "dev": "passed" } }, { "name": "map should display", "result": { "dev": "passed" } } ] } ], "keyword": "Feature", "name": "login", "dev": "passed" } ] ''' prod = ''' [ { "elements": [ { "keyword": "Scenario", "name": "valid user can login site", "steps": [ { "name": "a valid user name and password", "result": { "prod": "passed" } }, { "name": "a valid user clicking on the login button after typing in user name and password", "result": { "prod": "passed" } }, { "name": "map should display", "result": { "prod": "passed" } } ] } ], "keyword": "Feature", "name": "login", "prod": "passed" } ] ''' qa = json.loads(qa) dev = json.loads(dev) prod = json.loads(prod) for q, p, d in zip(qa, dev, prod): # update all keys but 'elements' q.update({k: v for k, v in p.items() if k != 'elements'}) q.update({k: v for k, v in d.items() if k != 'elements'}) # update the three 'result' dict for i in range(3): q['elements'][0]['steps'][i]['result'].update(p['elements'][0]['steps'][i]['result']) q['elements'][0]['steps'][i]['result'].update(d['elements'][0]['steps'][i]['result']) pprint(qa) ``` Output; ``` [{'dev': 'passed', 'elements': [{'keyword': 'Scenario', 'name': 'valid user can login site', 'steps': [{'name': 'a valid user name and password', 'result': {'dev': 'passed', 'prod': 'passed', 'qa': 'passed'}}, {'name': 'a valid user clicking on the login button ' 'after typing in user name and password', 'result': {'dev': 'passed', 'prod': 'passed', 'qa': 'passed'}}, {'name': 'map should display', 'result': {'dev': 'passed', 'prod': 'passed', 'qa': 'passed'}}]}], 'keyword': 'Feature', 'name': 'login', 'prod': 'passed', 'qa': 'passed'}] ```
41,489,682
I am a new python user, and I have just been getting familiar with restructuring data with the zip function, however I am now faced with a challenging data set that i have to restructure. I have 3 json responses that I have to merge from my end, the data sets are identical in design and would have the same length, they just differ from environments they ran on. **Let 3 files be the same values for brevity: qa.json | dev.json | prod.json** *Note: This outer object is array/list of object, I just put one object for brevity* ``` [ { "elements": [ { "keyword": "Scenario", "name": "valid user can login site", "steps": [ { "name": "a valid user name and password", "result": { "status": "passed" } }, { "name": "a valid user clicking on the login button after typing in user name and password", "result": { "status": "passed" } }, { "name": "map should display", "result": { "status": "passed" } } ] } ], "keyword": "Feature", "name": "login", "status": "passed" } ] ``` **What I want to achieve:** *Note: i want to merge them in one set with different environments reflecting the status* ``` [ { "elements": [ { "keyword": "Scenario", "name": "valid user can login site", "steps": [ { "name": "a valid user name and password", "result": { "qa": "passed", "prod": "passed", "dev": "passed" } }, { "name": "a valid user clicking on the login button after typing in user name and password", "result": { "qa": "passed", "prod": "passed", "dev": "passed" } }, { "name": "map should display", "result": { "qa": "passed", "prod": "passed", "dev": "passed" } } ] } ], "keyword": "Feature", "name": "login", "qa": "passed", "prod": "passed", "dev": "passed" } ] ``` **What i have done so far:** *I come from a javascript background so i im still getting familiar with python logic* ``` import json with open('qa.json') as data_file: qa = json.load(data_file) with open('dev.json') as data_file: dev = json.load(data_file) with open('prod.json') as data_file: prod = json.load(data_file) json_list = [{SOME STRUCT} for q, d, p in zip(qa, dev, prod)] ```
2017/01/05
[ "https://Stackoverflow.com/questions/41489682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4971053/" ]
I don't have a lot of time so I'm posting what I believe is a working solution to your problem even if it's slightly messy. If I have time I'll edit it. **Code** ``` import json data = """ [ { "elements": [{ "keyword": "Scenario", "name": "valid user can login site", "steps": [{ "name": "a valid user name and password", "result": { "status": "passed" } }, { "name": "a valid user clicking on the login button after typing in user name and password", "result": { "status": "passed" } }, { "name": "map should display", "result": { "status": "passed" } }] }], "keyword": "Feature", "name": "login", "status": "passed" }, { "elements": [{ "keyword": "Scenario", "name": "valid user can login site", "steps": [{ "name": "a valid user name and password", "result": { "status": "passed" } }, { "name": "a valid user clicking on the login button after typing in user name and password", "result": { "status": "failed" } }, { "name": "map should display", "result": { "status": "passed" } }] }], "keyword": "Feature", "name": "login", "status": "passed" } ] """ def get_result(envData, objIndex, elementIndex, stepIndex): return envData[objIndex]['elements'][elementIndex]['steps'][stepIndex]['result']['status'] def set_combined_results(combinedData, objIndex, elementIndex, stepIndex, results): resultNode = combinedData[objIndex]['elements'][elementIndex]['steps'][stepIndex]['result'] resultNode.update({ 'qa': results[0], 'prod': results[1], 'dev': results[2] }) if __name__ == '__main__': qAData = json.loads(data) prodData = json.loads(data) devData = json.loads(data) combinedData = json.loads(data) for objIndex, obj in enumerate(combinedData): for elementIndex, element in enumerate(obj['elements']): for stepIndex, _ in enumerate(element['steps']): qAResult = get_result(qAData, objIndex, elementIndex, stepIndex) prodResult = get_result(prodData, objIndex, elementIndex, stepIndex) devResult = get_result(devData, objIndex, elementIndex, stepIndex) combinedResults = (qAResult, prodResult, devResult) set_combined_results(combinedData, objIndex, elementIndex, stepIndex, combinedResults) qAAggregateResult = qAData[objIndex]['status'] prodAggregateResult = prodData[objIndex]['status'] devAggregateResult = devData[objIndex]['status'] del combinedData[objIndex]['status'] combinedData[objIndex]['qa'] = qAAggregateResult combinedData[objIndex]['prod'] = prodAggregateResult combinedData[objIndex]['dev'] = devAggregateResult print(json.dumps(combinedData, indent=True)) ``` **Output** ``` [ { "keyword": "Feature", "name": "login", "elements": [ { "keyword": "Scenario", "name": "valid user can login site", "steps": [ { "result": { "qa": "passed", "status": "passed", "dev": "passed", "prod": "passed" }, "name": "a valid user name and password" }, { "result": { "qa": "passed", "status": "passed", "dev": "passed", "prod": "passed" }, "name": "a valid user clicking on the login button after typing in user name and password" }, { "result": { "qa": "passed", "status": "passed", "dev": "passed", "prod": "passed" }, "name": "map should display" } ] } ], "dev": "passed", "prod": "passed", "qa": "passed" }, { "keyword": "Feature", "name": "login", "elements": [ { "keyword": "Scenario", "name": "valid user can login site", "steps": [ { "result": { "qa": "passed", "status": "passed", "dev": "passed", "prod": "passed" }, "name": "a valid user name and password" }, { "result": { "qa": "failed", "status": "failed", "dev": "failed", "prod": "failed" }, "name": "a valid user clicking on the login button after typing in user name and password" }, { "result": { "qa": "passed", "status": "passed", "dev": "passed", "prod": "passed" }, "name": "map should display" } ] } ], "dev": "failed", "prod": "failed", "qa": "failed" } ] ```
This is a recursive merge implementation. It will merge arbitrary types of Python objects, such that anything but `dicts` must be equal when merged. For `dicts`, it will allow merging if the same keys are associated with mergable values in those where the key is present. Any `dict` keys equalling the parameter `fieldname` will be suffixed with an index before merging: ``` from copy import deepcopy from itertools import chain def merge(field_name, *objs): # Make sure all objs are of same type types = list(set(map(type, objs))) if not len(set(map(type, objs))) == 1: raise Exception('Cannot merge objects of different types: {types}'.format(types=types)) first = objs[0] # for any random objects, make sure they are equal! if not isinstance(first, (list, tuple, dict)): if not len(set(objs)) == 1: raise Exception("Cannot merge non-equal objects that aren't dicts: {objs}".format(objs=objs)) return deepcopy(first) # for lists, tuples: zip 'em and merge the zipped elements if isinstance(first, (list, tuple)): return [merge(field_name, *zipped) for zipped in zip(*objs)] # dicts result_dict = {} keys = list(set(chain.from_iterable(d.keys() for d in objs))) try: keys.remove(field_name) except ValueError: pass for k in keys: # merge values from all dicts where key is present result_dict[k] = merge(field_name, *(d[k] for d in objs if k in d)) for i, d in enumerate(objs): if field_name in d: result_dict['{f}_{i}'.format(f=field_name, i=i)] = d[field_name] return result_dict ``` This can now be used on `dev, qa, prod` that are `dicts` of the structure given by th OP: ``` >>> from pprint import pprint >>> pprint(merge('status', qa, dev, prod)) [{'elements': [{'keyword': 'Scenario', 'name': 'valid user can login site', 'steps': [{'name': 'a valid user name and password', 'result': {'status_0': 'passed', 'status_1': 'passed', 'status_2': 'passed'}}, {'name': 'a valid user clicking on the login button after typing in user name and password', 'result': {'status_0': 'passed', 'status_1': 'passed', 'status_2': 'passed'}}, {'name': 'map should display', 'result': {'status_0': 'passed', 'status_1': 'passed', 'status_2': 'passed'}}]}], 'keyword': 'Feature', 'name': 'login', 'status_0': 'passed', 'status_1': 'passed', 'status_2': 'passed'}] ``` This is, of course, not fully generic, e.g. it only "deep" merges sequences when they are `lists` or `tuples`, but it should be decent enough for data structures loaded from json. I hope it helps you find a solution.
65,601,635
With [`pandas.date_range`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html) one can create time columns for one's dataframe with ease such as ``` df["Data"] = pd.date_range(start='2020-01-01 00:00', end='2020-01-05 02:00', freq='H') ``` Which something like this [![enter image description here](https://i.stack.imgur.com/5PTaZ.png)](https://i.stack.imgur.com/5PTaZ.png) I wonder if is it possible to use `date_range` to create, within the range defined (such as the above), 10 entries for each of the time periods. In other words, 10 cells with `2010-01-01 00:00:00`, 10 cells with `2010-01-01 01:00:00`, and so on. If not, how should one do that?
2021/01/06
[ "https://Stackoverflow.com/questions/65601635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7109869/" ]
You can spread props onto the component: ``` renderInput = () => { const props = { autoComplete: 'off', id: 'unique-id-2', 'aria-autocomplete': 'off' }; if (isLoading) { return ( <Input iconRight={( <Spinner /> )} {...props} /> ); } return ( <Input {...props} /> ); } } ``` But i'd suggest changing your `Input` component to accept a `loading` prop and let the `Input` component handle that logic. It'll make your consuming code a lot easier to read also.
I think your function can be shortened to the following; ``` renderInput = () => ( <Input iconRight={isLoading ? (<Spinner />) : null} autoComplete="off" id="unique-id-2" aria-autocomplete="both" /> ) ``` If you don't already, inside your `Input` component, you should check if the `iconRight` prop is not null, and only render it then.
65,601,635
With [`pandas.date_range`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html) one can create time columns for one's dataframe with ease such as ``` df["Data"] = pd.date_range(start='2020-01-01 00:00', end='2020-01-05 02:00', freq='H') ``` Which something like this [![enter image description here](https://i.stack.imgur.com/5PTaZ.png)](https://i.stack.imgur.com/5PTaZ.png) I wonder if is it possible to use `date_range` to create, within the range defined (such as the above), 10 entries for each of the time periods. In other words, 10 cells with `2010-01-01 00:00:00`, 10 cells with `2010-01-01 01:00:00`, and so on. If not, how should one do that?
2021/01/06
[ "https://Stackoverflow.com/questions/65601635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7109869/" ]
You can spread props onto the component: ``` renderInput = () => { const props = { autoComplete: 'off', id: 'unique-id-2', 'aria-autocomplete': 'off' }; if (isLoading) { return ( <Input iconRight={( <Spinner /> )} {...props} /> ); } return ( <Input {...props} /> ); } } ``` But i'd suggest changing your `Input` component to accept a `loading` prop and let the `Input` component handle that logic. It'll make your consuming code a lot easier to read also.
You can try this: ``` renderInput = () =>( <Input iconRight={ isLoading && ( <Spinner /> )} autoComplete="off" id="unique-id-2" aria-autocomplete="both" /> ) ```
47,723,253
When I run: javascript: ``` var inputs = document.getElementsByClassName('subscribe_follow'); for(var i=0;i<inputs.length;i++) { inputs[i].click(); } ``` to click all buttons with the class `class="subscribe_follow"`, it also clicks all buttons with the class `class="subscribe_follow ng-hide"`. How do I only click the exact class?
2017/12/08
[ "https://Stackoverflow.com/questions/47723253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9074654/" ]
You can use the `not` operator. ``` document.querySelectorAll('.subscribe_follow:not(.ng-hide)'); ``` `.subscribe_follow:not(.ng-hide)` selector selects all the elements with the class `subscribe_fellow` but which do not have the `ng-hide` class. **jQuery** ``` $('.subscribe_follow:not(.ng-hide)'); ```
You could use the `not` operator as suggested by Sushanth. The disadvantage here is that you'd have to mention every class that is supposed to be excluded, which may be a pain depending on the number of different classes that you might be using on the same elements. **I recommend declaring classes with the sole purpose of applying js, or targeting the elements by a different attribute that you could set in your HTML.** Here you can find more about alternative targeting: [Find an element in DOM based on an attribute value](https://stackoverflow.com/questions/2694640/find-an-element-in-dom-based-on-an-attribute-value)
4,215,066
This is easy for me to perform in TSQL, but I'm just sitting here banging my head against the desk trying to get it to work in EF4! I have a table, lets call it TestData. It has fields, say: DataTypeID, Name, DataValue. ``` DataTypeID, Name, DataValue 1,"Data 1","Value1" 1,"Data 1","Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` I want to group on DataID/Name, and concatenate DataValue into a CSV string. The desired result should contain - ``` DataTypeID, Name, DataValues 1,"Data 1","Value1,Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` Now, here's how I'm trying to do it - ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = (string)g.Aggregate("", (a, b) => (a != "" ? "," : "") + b.DataValue), }).ToList() ``` The problem is that LINQ to Entities does not know how to convert this into SQL. This is part of a union of 3 LINQ queries, and I'd really like it to keep it that way. I imagine that I could retrieve the data and then perform the aggregate later. For performance reasons, that wouldn't work for my app. I also considered using a SQL server function. But that just doesn't seem "right" in the EF4 world. Anyone care to take a crack at this?
2010/11/18
[ "https://Stackoverflow.com/questions/4215066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496083/" ]
You are so very close already. Try this: ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = String.Join(",", g), }).ToList() ``` Alternatively, you could do this, if EF doesn't allow the `String.Join` (which Linq-to-SQL does): ``` var qs = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = g }).ToArray(); var query = (from q in qs select new { q.DataTypeID, q.Name, DataValues = String.Join(",", q.DataValues), }).ToList(); ```
Maybe it's a good idea to create a view for this on the database (which concatenates the fields for you) and then make EF use this view instead of the original table? I'm quite sure it's not possible in a LINQ statement or in the Mapping Details.
4,215,066
This is easy for me to perform in TSQL, but I'm just sitting here banging my head against the desk trying to get it to work in EF4! I have a table, lets call it TestData. It has fields, say: DataTypeID, Name, DataValue. ``` DataTypeID, Name, DataValue 1,"Data 1","Value1" 1,"Data 1","Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` I want to group on DataID/Name, and concatenate DataValue into a CSV string. The desired result should contain - ``` DataTypeID, Name, DataValues 1,"Data 1","Value1,Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` Now, here's how I'm trying to do it - ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = (string)g.Aggregate("", (a, b) => (a != "" ? "," : "") + b.DataValue), }).ToList() ``` The problem is that LINQ to Entities does not know how to convert this into SQL. This is part of a union of 3 LINQ queries, and I'd really like it to keep it that way. I imagine that I could retrieve the data and then perform the aggregate later. For performance reasons, that wouldn't work for my app. I also considered using a SQL server function. But that just doesn't seem "right" in the EF4 world. Anyone care to take a crack at this?
2010/11/18
[ "https://Stackoverflow.com/questions/4215066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496083/" ]
If the `ToList()` is part of your original query and not just added for this example, then use LINQ to Objects on the resulting list to do the aggregation: ``` var query = (from t in context.TestData group t by new { DataTypeID = t.DataTypeID, Name = t.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, Data = g.AsEnumerable()}) .ToList() .Select (q => new { DataTypeID = q.DataTypeID, Name = q.Name, DataValues = q.Data.Aggregate ("", (acc, t) => (acc == "" ? "" : acc + ",") + t.DataValue) }); ``` Tested in LINQPad and it produces this result: ![alt text](https://i.stack.imgur.com/zhj90.jpg)
Maybe it's a good idea to create a view for this on the database (which concatenates the fields for you) and then make EF use this view instead of the original table? I'm quite sure it's not possible in a LINQ statement or in the Mapping Details.
4,215,066
This is easy for me to perform in TSQL, but I'm just sitting here banging my head against the desk trying to get it to work in EF4! I have a table, lets call it TestData. It has fields, say: DataTypeID, Name, DataValue. ``` DataTypeID, Name, DataValue 1,"Data 1","Value1" 1,"Data 1","Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` I want to group on DataID/Name, and concatenate DataValue into a CSV string. The desired result should contain - ``` DataTypeID, Name, DataValues 1,"Data 1","Value1,Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` Now, here's how I'm trying to do it - ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = (string)g.Aggregate("", (a, b) => (a != "" ? "," : "") + b.DataValue), }).ToList() ``` The problem is that LINQ to Entities does not know how to convert this into SQL. This is part of a union of 3 LINQ queries, and I'd really like it to keep it that way. I imagine that I could retrieve the data and then perform the aggregate later. For performance reasons, that wouldn't work for my app. I also considered using a SQL server function. But that just doesn't seem "right" in the EF4 world. Anyone care to take a crack at this?
2010/11/18
[ "https://Stackoverflow.com/questions/4215066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496083/" ]
Thanks to moi\_meme for the answer. What I was hoping to do is NOT POSSIBLE with LINQ to Entities. As others have suggested, you have to use LINQ to Objects to get access to string manipulation methods. See the link posted by moi\_meme for more info. **Update 8/27/2018** - Updated Link (again) - <https://web.archive.org/web/20141106094131/http://www.mythos-rini.com/blog/archives/4510> And since I'm taking flack for a link-only answer from 8 years ago, I'll clarify just in case the archived copy disappears some day. The basic gist of it is that you cannot access string.join in EF queries. You must create the LINQ query, then call ToList() in order to execute the query against the db. Then you have the data in memory (aka LINQ to Objects), so you can access string.join. The suggested code from the referenced link above is as follows - ``` var result1 = (from a in users b in roles where (a.RoleCollection.Any(x => x.RoleId = b.RoleId)) select new { UserName = a.UserName, RoleNames = b.RoleName) }); var result2 = (from a in result1.ToList() group a by a.UserName into userGroup select new { UserName = userGroup.FirstOrDefault().UserName, RoleNames = String.Join(", ", (userGroup.Select(x => x.RoleNames)).ToArray()) }); ``` The author further suggests replacing string.join with aggregate for better performance, like so - ``` RoleNames = (userGroup.Select(x => x.RoleNames)).Aggregate((a,b) => (a + ", " + b)) ```
Maybe it's a good idea to create a view for this on the database (which concatenates the fields for you) and then make EF use this view instead of the original table? I'm quite sure it's not possible in a LINQ statement or in the Mapping Details.
4,215,066
This is easy for me to perform in TSQL, but I'm just sitting here banging my head against the desk trying to get it to work in EF4! I have a table, lets call it TestData. It has fields, say: DataTypeID, Name, DataValue. ``` DataTypeID, Name, DataValue 1,"Data 1","Value1" 1,"Data 1","Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` I want to group on DataID/Name, and concatenate DataValue into a CSV string. The desired result should contain - ``` DataTypeID, Name, DataValues 1,"Data 1","Value1,Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` Now, here's how I'm trying to do it - ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = (string)g.Aggregate("", (a, b) => (a != "" ? "," : "") + b.DataValue), }).ToList() ``` The problem is that LINQ to Entities does not know how to convert this into SQL. This is part of a union of 3 LINQ queries, and I'd really like it to keep it that way. I imagine that I could retrieve the data and then perform the aggregate later. For performance reasons, that wouldn't work for my app. I also considered using a SQL server function. But that just doesn't seem "right" in the EF4 world. Anyone care to take a crack at this?
2010/11/18
[ "https://Stackoverflow.com/questions/4215066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496083/" ]
Some of the Answers suggest calling ToList() and then perform the calculation as LINQ to OBJECT. That's fine for a little amount of data, but what if I have a huge amount of data that I do not want to load into memory too early, then, ToList() may not be an option. So, the better idea would be to process/format the data in the presentation layer and let the Data Access layer do only loading or saving raw data that SQL likes. Moreover, in your presentation layer, most probably you are filtering the data by paging, or maybe you are showing one row in the details page, so, the data you will load into the memory is likely smaller than the data you load from the database. (Your situation/architecture may be different,.. but I am saying, most likely). I had a similar requirement. My problem was to get the list of items from the Entity Framework object and create a formatted string (comma separated value) 1. I created a property in my View Model which will hold the raw data from the repository and when populating that property, the LINQ query won't be a problem because you are simply querying what SQL understands. 2. Then, I created a get-only property in my ViewModel which reads that Raw entity property and formats the data before displaying. ``` public class MyViewModel { public IEnumerable<Entity> RawChildItems { get; set; } public string FormattedData { get { if (this.RawChildItems == null) return string.Empty; string[] theItems = this.RawChildItems.ToArray(); return theItems.Length > 0 ? string.Format("{0} ( {1} )", this.AnotherRegularProperty, String.Join(", ", theItems.Select(z => z.Substring(0, 1)))) : string.Empty; } } } ``` Ok, in that way, I loaded the Data from LINQ to Entity to this View Model easily without calling.ToList(). Example: ``` IQueryable<MyEntity> myEntities = _myRepository.GetData(); IQueryable<MyViewModel> viewModels = myEntities.Select(x => new MyViewModel() { RawChildItems = x.MyChildren }) ``` Now, I can call the FormattedData property of MyViewModel anytime when I need and the Getter will be executed only when the property is called, which is another benefit of this pattern (lazy processing). **An architecture recommendation:** I strongly recommend to keep the data access layer away from all formatting or view logic or anything that SQL does not understand. Your Entity Framework classes should be simple POCO that can directly map to a database column without any special mapper. And your Data Access layer (say a Repository that fetches data from your DbContext using LINQ to SQL) should get only the data that is directly stored in your database. No extra logic. Then, you should have a dedicated set of classes for your Presentation Layer (say ViewModels) which will contain all logic for formatting data that your user likes to see. In that way, you won't have to struggle with the limitation of Entity Framework LINQ. I will never pass my Entity Framework model directly to the View. Nor, I will let my Data Access layer creates the ViewModel for me. Creating ViewModel can be delegated to your domain service layer or application layer, which is an upper layer than your Data Access Layer.
Maybe it's a good idea to create a view for this on the database (which concatenates the fields for you) and then make EF use this view instead of the original table? I'm quite sure it's not possible in a LINQ statement or in the Mapping Details.
4,215,066
This is easy for me to perform in TSQL, but I'm just sitting here banging my head against the desk trying to get it to work in EF4! I have a table, lets call it TestData. It has fields, say: DataTypeID, Name, DataValue. ``` DataTypeID, Name, DataValue 1,"Data 1","Value1" 1,"Data 1","Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` I want to group on DataID/Name, and concatenate DataValue into a CSV string. The desired result should contain - ``` DataTypeID, Name, DataValues 1,"Data 1","Value1,Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` Now, here's how I'm trying to do it - ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = (string)g.Aggregate("", (a, b) => (a != "" ? "," : "") + b.DataValue), }).ToList() ``` The problem is that LINQ to Entities does not know how to convert this into SQL. This is part of a union of 3 LINQ queries, and I'd really like it to keep it that way. I imagine that I could retrieve the data and then perform the aggregate later. For performance reasons, that wouldn't work for my app. I also considered using a SQL server function. But that just doesn't seem "right" in the EF4 world. Anyone care to take a crack at this?
2010/11/18
[ "https://Stackoverflow.com/questions/4215066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496083/" ]
If the `ToList()` is part of your original query and not just added for this example, then use LINQ to Objects on the resulting list to do the aggregation: ``` var query = (from t in context.TestData group t by new { DataTypeID = t.DataTypeID, Name = t.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, Data = g.AsEnumerable()}) .ToList() .Select (q => new { DataTypeID = q.DataTypeID, Name = q.Name, DataValues = q.Data.Aggregate ("", (acc, t) => (acc == "" ? "" : acc + ",") + t.DataValue) }); ``` Tested in LINQPad and it produces this result: ![alt text](https://i.stack.imgur.com/zhj90.jpg)
You are so very close already. Try this: ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = String.Join(",", g), }).ToList() ``` Alternatively, you could do this, if EF doesn't allow the `String.Join` (which Linq-to-SQL does): ``` var qs = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = g }).ToArray(); var query = (from q in qs select new { q.DataTypeID, q.Name, DataValues = String.Join(",", q.DataValues), }).ToList(); ```
4,215,066
This is easy for me to perform in TSQL, but I'm just sitting here banging my head against the desk trying to get it to work in EF4! I have a table, lets call it TestData. It has fields, say: DataTypeID, Name, DataValue. ``` DataTypeID, Name, DataValue 1,"Data 1","Value1" 1,"Data 1","Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` I want to group on DataID/Name, and concatenate DataValue into a CSV string. The desired result should contain - ``` DataTypeID, Name, DataValues 1,"Data 1","Value1,Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` Now, here's how I'm trying to do it - ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = (string)g.Aggregate("", (a, b) => (a != "" ? "," : "") + b.DataValue), }).ToList() ``` The problem is that LINQ to Entities does not know how to convert this into SQL. This is part of a union of 3 LINQ queries, and I'd really like it to keep it that way. I imagine that I could retrieve the data and then perform the aggregate later. For performance reasons, that wouldn't work for my app. I also considered using a SQL server function. But that just doesn't seem "right" in the EF4 world. Anyone care to take a crack at this?
2010/11/18
[ "https://Stackoverflow.com/questions/4215066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496083/" ]
Thanks to moi\_meme for the answer. What I was hoping to do is NOT POSSIBLE with LINQ to Entities. As others have suggested, you have to use LINQ to Objects to get access to string manipulation methods. See the link posted by moi\_meme for more info. **Update 8/27/2018** - Updated Link (again) - <https://web.archive.org/web/20141106094131/http://www.mythos-rini.com/blog/archives/4510> And since I'm taking flack for a link-only answer from 8 years ago, I'll clarify just in case the archived copy disappears some day. The basic gist of it is that you cannot access string.join in EF queries. You must create the LINQ query, then call ToList() in order to execute the query against the db. Then you have the data in memory (aka LINQ to Objects), so you can access string.join. The suggested code from the referenced link above is as follows - ``` var result1 = (from a in users b in roles where (a.RoleCollection.Any(x => x.RoleId = b.RoleId)) select new { UserName = a.UserName, RoleNames = b.RoleName) }); var result2 = (from a in result1.ToList() group a by a.UserName into userGroup select new { UserName = userGroup.FirstOrDefault().UserName, RoleNames = String.Join(", ", (userGroup.Select(x => x.RoleNames)).ToArray()) }); ``` The author further suggests replacing string.join with aggregate for better performance, like so - ``` RoleNames = (userGroup.Select(x => x.RoleNames)).Aggregate((a,b) => (a + ", " + b)) ```
You are so very close already. Try this: ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = String.Join(",", g), }).ToList() ``` Alternatively, you could do this, if EF doesn't allow the `String.Join` (which Linq-to-SQL does): ``` var qs = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = g }).ToArray(); var query = (from q in qs select new { q.DataTypeID, q.Name, DataValues = String.Join(",", q.DataValues), }).ToList(); ```
4,215,066
This is easy for me to perform in TSQL, but I'm just sitting here banging my head against the desk trying to get it to work in EF4! I have a table, lets call it TestData. It has fields, say: DataTypeID, Name, DataValue. ``` DataTypeID, Name, DataValue 1,"Data 1","Value1" 1,"Data 1","Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` I want to group on DataID/Name, and concatenate DataValue into a CSV string. The desired result should contain - ``` DataTypeID, Name, DataValues 1,"Data 1","Value1,Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` Now, here's how I'm trying to do it - ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = (string)g.Aggregate("", (a, b) => (a != "" ? "," : "") + b.DataValue), }).ToList() ``` The problem is that LINQ to Entities does not know how to convert this into SQL. This is part of a union of 3 LINQ queries, and I'd really like it to keep it that way. I imagine that I could retrieve the data and then perform the aggregate later. For performance reasons, that wouldn't work for my app. I also considered using a SQL server function. But that just doesn't seem "right" in the EF4 world. Anyone care to take a crack at this?
2010/11/18
[ "https://Stackoverflow.com/questions/4215066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496083/" ]
Some of the Answers suggest calling ToList() and then perform the calculation as LINQ to OBJECT. That's fine for a little amount of data, but what if I have a huge amount of data that I do not want to load into memory too early, then, ToList() may not be an option. So, the better idea would be to process/format the data in the presentation layer and let the Data Access layer do only loading or saving raw data that SQL likes. Moreover, in your presentation layer, most probably you are filtering the data by paging, or maybe you are showing one row in the details page, so, the data you will load into the memory is likely smaller than the data you load from the database. (Your situation/architecture may be different,.. but I am saying, most likely). I had a similar requirement. My problem was to get the list of items from the Entity Framework object and create a formatted string (comma separated value) 1. I created a property in my View Model which will hold the raw data from the repository and when populating that property, the LINQ query won't be a problem because you are simply querying what SQL understands. 2. Then, I created a get-only property in my ViewModel which reads that Raw entity property and formats the data before displaying. ``` public class MyViewModel { public IEnumerable<Entity> RawChildItems { get; set; } public string FormattedData { get { if (this.RawChildItems == null) return string.Empty; string[] theItems = this.RawChildItems.ToArray(); return theItems.Length > 0 ? string.Format("{0} ( {1} )", this.AnotherRegularProperty, String.Join(", ", theItems.Select(z => z.Substring(0, 1)))) : string.Empty; } } } ``` Ok, in that way, I loaded the Data from LINQ to Entity to this View Model easily without calling.ToList(). Example: ``` IQueryable<MyEntity> myEntities = _myRepository.GetData(); IQueryable<MyViewModel> viewModels = myEntities.Select(x => new MyViewModel() { RawChildItems = x.MyChildren }) ``` Now, I can call the FormattedData property of MyViewModel anytime when I need and the Getter will be executed only when the property is called, which is another benefit of this pattern (lazy processing). **An architecture recommendation:** I strongly recommend to keep the data access layer away from all formatting or view logic or anything that SQL does not understand. Your Entity Framework classes should be simple POCO that can directly map to a database column without any special mapper. And your Data Access layer (say a Repository that fetches data from your DbContext using LINQ to SQL) should get only the data that is directly stored in your database. No extra logic. Then, you should have a dedicated set of classes for your Presentation Layer (say ViewModels) which will contain all logic for formatting data that your user likes to see. In that way, you won't have to struggle with the limitation of Entity Framework LINQ. I will never pass my Entity Framework model directly to the View. Nor, I will let my Data Access layer creates the ViewModel for me. Creating ViewModel can be delegated to your domain service layer or application layer, which is an upper layer than your Data Access Layer.
You are so very close already. Try this: ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = String.Join(",", g), }).ToList() ``` Alternatively, you could do this, if EF doesn't allow the `String.Join` (which Linq-to-SQL does): ``` var qs = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = g }).ToArray(); var query = (from q in qs select new { q.DataTypeID, q.Name, DataValues = String.Join(",", q.DataValues), }).ToList(); ```
4,215,066
This is easy for me to perform in TSQL, but I'm just sitting here banging my head against the desk trying to get it to work in EF4! I have a table, lets call it TestData. It has fields, say: DataTypeID, Name, DataValue. ``` DataTypeID, Name, DataValue 1,"Data 1","Value1" 1,"Data 1","Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` I want to group on DataID/Name, and concatenate DataValue into a CSV string. The desired result should contain - ``` DataTypeID, Name, DataValues 1,"Data 1","Value1,Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` Now, here's how I'm trying to do it - ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = (string)g.Aggregate("", (a, b) => (a != "" ? "," : "") + b.DataValue), }).ToList() ``` The problem is that LINQ to Entities does not know how to convert this into SQL. This is part of a union of 3 LINQ queries, and I'd really like it to keep it that way. I imagine that I could retrieve the data and then perform the aggregate later. For performance reasons, that wouldn't work for my app. I also considered using a SQL server function. But that just doesn't seem "right" in the EF4 world. Anyone care to take a crack at this?
2010/11/18
[ "https://Stackoverflow.com/questions/4215066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496083/" ]
If the `ToList()` is part of your original query and not just added for this example, then use LINQ to Objects on the resulting list to do the aggregation: ``` var query = (from t in context.TestData group t by new { DataTypeID = t.DataTypeID, Name = t.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, Data = g.AsEnumerable()}) .ToList() .Select (q => new { DataTypeID = q.DataTypeID, Name = q.Name, DataValues = q.Data.Aggregate ("", (acc, t) => (acc == "" ? "" : acc + ",") + t.DataValue) }); ``` Tested in LINQPad and it produces this result: ![alt text](https://i.stack.imgur.com/zhj90.jpg)
Some of the Answers suggest calling ToList() and then perform the calculation as LINQ to OBJECT. That's fine for a little amount of data, but what if I have a huge amount of data that I do not want to load into memory too early, then, ToList() may not be an option. So, the better idea would be to process/format the data in the presentation layer and let the Data Access layer do only loading or saving raw data that SQL likes. Moreover, in your presentation layer, most probably you are filtering the data by paging, or maybe you are showing one row in the details page, so, the data you will load into the memory is likely smaller than the data you load from the database. (Your situation/architecture may be different,.. but I am saying, most likely). I had a similar requirement. My problem was to get the list of items from the Entity Framework object and create a formatted string (comma separated value) 1. I created a property in my View Model which will hold the raw data from the repository and when populating that property, the LINQ query won't be a problem because you are simply querying what SQL understands. 2. Then, I created a get-only property in my ViewModel which reads that Raw entity property and formats the data before displaying. ``` public class MyViewModel { public IEnumerable<Entity> RawChildItems { get; set; } public string FormattedData { get { if (this.RawChildItems == null) return string.Empty; string[] theItems = this.RawChildItems.ToArray(); return theItems.Length > 0 ? string.Format("{0} ( {1} )", this.AnotherRegularProperty, String.Join(", ", theItems.Select(z => z.Substring(0, 1)))) : string.Empty; } } } ``` Ok, in that way, I loaded the Data from LINQ to Entity to this View Model easily without calling.ToList(). Example: ``` IQueryable<MyEntity> myEntities = _myRepository.GetData(); IQueryable<MyViewModel> viewModels = myEntities.Select(x => new MyViewModel() { RawChildItems = x.MyChildren }) ``` Now, I can call the FormattedData property of MyViewModel anytime when I need and the Getter will be executed only when the property is called, which is another benefit of this pattern (lazy processing). **An architecture recommendation:** I strongly recommend to keep the data access layer away from all formatting or view logic or anything that SQL does not understand. Your Entity Framework classes should be simple POCO that can directly map to a database column without any special mapper. And your Data Access layer (say a Repository that fetches data from your DbContext using LINQ to SQL) should get only the data that is directly stored in your database. No extra logic. Then, you should have a dedicated set of classes for your Presentation Layer (say ViewModels) which will contain all logic for formatting data that your user likes to see. In that way, you won't have to struggle with the limitation of Entity Framework LINQ. I will never pass my Entity Framework model directly to the View. Nor, I will let my Data Access layer creates the ViewModel for me. Creating ViewModel can be delegated to your domain service layer or application layer, which is an upper layer than your Data Access Layer.
4,215,066
This is easy for me to perform in TSQL, but I'm just sitting here banging my head against the desk trying to get it to work in EF4! I have a table, lets call it TestData. It has fields, say: DataTypeID, Name, DataValue. ``` DataTypeID, Name, DataValue 1,"Data 1","Value1" 1,"Data 1","Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` I want to group on DataID/Name, and concatenate DataValue into a CSV string. The desired result should contain - ``` DataTypeID, Name, DataValues 1,"Data 1","Value1,Value2" 2,"Data 1","Value3" 3,"Data 1","Value4" ``` Now, here's how I'm trying to do it - ``` var query = (from t in context.TestData group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g select new { DataTypeID = g.Key.DataTypeID, Name = g.Key.Name, DataValues = (string)g.Aggregate("", (a, b) => (a != "" ? "," : "") + b.DataValue), }).ToList() ``` The problem is that LINQ to Entities does not know how to convert this into SQL. This is part of a union of 3 LINQ queries, and I'd really like it to keep it that way. I imagine that I could retrieve the data and then perform the aggregate later. For performance reasons, that wouldn't work for my app. I also considered using a SQL server function. But that just doesn't seem "right" in the EF4 world. Anyone care to take a crack at this?
2010/11/18
[ "https://Stackoverflow.com/questions/4215066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496083/" ]
Thanks to moi\_meme for the answer. What I was hoping to do is NOT POSSIBLE with LINQ to Entities. As others have suggested, you have to use LINQ to Objects to get access to string manipulation methods. See the link posted by moi\_meme for more info. **Update 8/27/2018** - Updated Link (again) - <https://web.archive.org/web/20141106094131/http://www.mythos-rini.com/blog/archives/4510> And since I'm taking flack for a link-only answer from 8 years ago, I'll clarify just in case the archived copy disappears some day. The basic gist of it is that you cannot access string.join in EF queries. You must create the LINQ query, then call ToList() in order to execute the query against the db. Then you have the data in memory (aka LINQ to Objects), so you can access string.join. The suggested code from the referenced link above is as follows - ``` var result1 = (from a in users b in roles where (a.RoleCollection.Any(x => x.RoleId = b.RoleId)) select new { UserName = a.UserName, RoleNames = b.RoleName) }); var result2 = (from a in result1.ToList() group a by a.UserName into userGroup select new { UserName = userGroup.FirstOrDefault().UserName, RoleNames = String.Join(", ", (userGroup.Select(x => x.RoleNames)).ToArray()) }); ``` The author further suggests replacing string.join with aggregate for better performance, like so - ``` RoleNames = (userGroup.Select(x => x.RoleNames)).Aggregate((a,b) => (a + ", " + b)) ```
Some of the Answers suggest calling ToList() and then perform the calculation as LINQ to OBJECT. That's fine for a little amount of data, but what if I have a huge amount of data that I do not want to load into memory too early, then, ToList() may not be an option. So, the better idea would be to process/format the data in the presentation layer and let the Data Access layer do only loading or saving raw data that SQL likes. Moreover, in your presentation layer, most probably you are filtering the data by paging, or maybe you are showing one row in the details page, so, the data you will load into the memory is likely smaller than the data you load from the database. (Your situation/architecture may be different,.. but I am saying, most likely). I had a similar requirement. My problem was to get the list of items from the Entity Framework object and create a formatted string (comma separated value) 1. I created a property in my View Model which will hold the raw data from the repository and when populating that property, the LINQ query won't be a problem because you are simply querying what SQL understands. 2. Then, I created a get-only property in my ViewModel which reads that Raw entity property and formats the data before displaying. ``` public class MyViewModel { public IEnumerable<Entity> RawChildItems { get; set; } public string FormattedData { get { if (this.RawChildItems == null) return string.Empty; string[] theItems = this.RawChildItems.ToArray(); return theItems.Length > 0 ? string.Format("{0} ( {1} )", this.AnotherRegularProperty, String.Join(", ", theItems.Select(z => z.Substring(0, 1)))) : string.Empty; } } } ``` Ok, in that way, I loaded the Data from LINQ to Entity to this View Model easily without calling.ToList(). Example: ``` IQueryable<MyEntity> myEntities = _myRepository.GetData(); IQueryable<MyViewModel> viewModels = myEntities.Select(x => new MyViewModel() { RawChildItems = x.MyChildren }) ``` Now, I can call the FormattedData property of MyViewModel anytime when I need and the Getter will be executed only when the property is called, which is another benefit of this pattern (lazy processing). **An architecture recommendation:** I strongly recommend to keep the data access layer away from all formatting or view logic or anything that SQL does not understand. Your Entity Framework classes should be simple POCO that can directly map to a database column without any special mapper. And your Data Access layer (say a Repository that fetches data from your DbContext using LINQ to SQL) should get only the data that is directly stored in your database. No extra logic. Then, you should have a dedicated set of classes for your Presentation Layer (say ViewModels) which will contain all logic for formatting data that your user likes to see. In that way, you won't have to struggle with the limitation of Entity Framework LINQ. I will never pass my Entity Framework model directly to the View. Nor, I will let my Data Access layer creates the ViewModel for me. Creating ViewModel can be delegated to your domain service layer or application layer, which is an upper layer than your Data Access Layer.
33,232,940
``` #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int reverse(int a[20],int n); int main() { int a[20]; int n; printf("enter the number of elements \n"); scanf("%d",&n); printf("enter the array elements\n"); for(int i=0;i<n;i++) { scanf("%d ",&a[i]); } reverse(a,n); return 0; } int reverse(int a[20],int n) { for(int i=n-1;i>=0;i--) { printf("%d ",a[i]); } return 0; } ``` here if I input n=4 then during runtime i have to take 5 elements and then it reverses.For eg if i take n=4 and then for no of elements i have to take 1,2,3,4,5 and then only output is coming as 4 3 2 1.Why? is my logic wrong? also in this code I am unable to take the number of elements of arrays in a straight line, like 1 2 3 4.When I am entering the number each number is entering in new line .I am a novice programmer in C and thus having these doubts.Please anyone explain...
2015/10/20
[ "https://Stackoverflow.com/questions/33232940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5450448/" ]
You should save your file as .php and run it on a server with php installed on it. check [XAMP](https://www.apachefriends.org/index.html) to install a local server EDIT Just saw that you're running Tomcat, just make sure php is installed, that your server is running, you're running your file from the server And your file is save as .php
You change file name from trial.html to trial.php
33,232,940
``` #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int reverse(int a[20],int n); int main() { int a[20]; int n; printf("enter the number of elements \n"); scanf("%d",&n); printf("enter the array elements\n"); for(int i=0;i<n;i++) { scanf("%d ",&a[i]); } reverse(a,n); return 0; } int reverse(int a[20],int n) { for(int i=n-1;i>=0;i--) { printf("%d ",a[i]); } return 0; } ``` here if I input n=4 then during runtime i have to take 5 elements and then it reverses.For eg if i take n=4 and then for no of elements i have to take 1,2,3,4,5 and then only output is coming as 4 3 2 1.Why? is my logic wrong? also in this code I am unable to take the number of elements of arrays in a straight line, like 1 2 3 4.When I am entering the number each number is entering in new line .I am a novice programmer in C and thus having these doubts.Please anyone explain...
2015/10/20
[ "https://Stackoverflow.com/questions/33232940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5450448/" ]
Rename "Trial.html" to "Trial.php" this is essential when you try to run php code.
You change file name from trial.html to trial.php
23,164,933
So I want to write a small app for my e-ink Kindle. I know it's possible -- Amazon has released a [Kindle Developer's Kit](http://kdk.amazon.com/gp/public/gateway), but I can't figure out how to signup (I followed a signup link on another SO post that redirected to the useless homepage). I've also seen people doing it on the [MobileRead Forums](http://www.mobileread.com/). The app I want to make is pretty simple, but I can't figure out what language it would need to be in. What languages are native to the older Kindles (not Kindle Fire)?
2014/04/19
[ "https://Stackoverflow.com/questions/23164933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2714746/" ]
It's written in Java, specifically Java 1.4.2.
Personal Basis Profile 1.1 and Java 1.4 It seams you cannot register as a developer for the old Kindle anymore, so you need to jailbreak it and use a key (that you create yourself) to sign your jars. You can find instructions what to do and several resources at the URL mentioned below. There is also a tool to create your own Kindle developer key. You need to install the public key on your Kindle. To be able to use your jars that you sign with it. A Hello-World example is also included on the website. It is also explained how to use [retroweaver](http://retroweaver.sourceforge.net/) that makes it possible to use java 1.5 and than convert it to 1.4. <http://cowlark.com/kindle/getting-started.html> --- *P.s. Please add a comment as soon as you successfully wrote your first app that runs on your kindle.*
41,848,678
How do i pass additional arguments to next "step" of promise? ``` new Promise((resolve, reject) => { const a = // do stuff and return a string return Promise.all([ // execute another promise, // execute yet another promise ]) }) .then(([resultFromPromise_1, resultFromPromise_2]) => { // how do i pass `const a` here? }) ``` I can add something like `new Promise(resolve => resolve(a))` into `Promise.all` array, but this looks ugly. Is there better way to pass data in such cases?
2017/01/25
[ "https://Stackoverflow.com/questions/41848678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4845952/" ]
> > I can add something like `new Promise(resolve => resolve(a))` into `Promise.all` array, but this looks ugly. Is there better way to pass data in such cases? > > > Yes: Use `then`. If you already have a promise, using `new Promise` is never needed. `then` creates a promise, which waits for the resolution of the one you called it on, and then gets resolved with what you return from the `then` callback or gets rejected if you throw an exception. One of the keys of promises is how using `then` (and `catch`) *transforms* things at each link in the chain. In that specific case, you'd use `then` on the original promise and use its callback to transform the result using `a` (although if you want to wait until they're all done, you can do that too; covered later). Side note: The `new Promise` line at the beginning of the code of your question shouldn't be there, you don't *return* a promise out of the promise executor (the callback you pass to `new Promise`). Example: ```js const a = "some string"; Promise.all([ getPromise("one").then(result => result + " - " + a), // *** getPromise("two") ]) .then(results => { console.log(results); }); function getPromise(str) { // (Could use Promise.resolve here; emphasizing asynchronousness) return new Promise(resolve => { setTimeout(() => { resolve(str); }, 250); }); } ``` Alternately, if you really only want to use `a` when all of the promises you're passing to `Promise.all` have resolved, you can do that, too: ```js const a = "some string"; Promise.all([ getPromise("one"), getPromise("two") ]) .then(([result1, result2]) => { return [result1 + " - " + a, result2]; // *** }) .then(results => { console.log(results); }); function getPromise(str) { // (Could use Promise.resolve here; emphasizing asynchronousness) return new Promise(resolve => { setTimeout(() => { resolve(str); }, 250); }); } ```
First off, your first promise has an error, you're not resolving it. You should do something like this: ``` new Promise((resolve, reject) => { const a = 1; resolve(Promise.all([ ... ])) }) ``` And as for your question, instead of `new Promise(resolve => resolve(a))` you can just pass `a` directly to the `all` array. ie: ``` new Promise((resolve, reject) => { const a = 1; resolve(Promise.all([ Promise.resolve("a"), Promise.resolve("b"), a, ])) }) .then(([resultFromPromise_1, resultFromPromise_2, a]) => { console.log(a); }) ```
28,536,876
When trying to compile a class, I am getting the following error; ``` ExcelReportServlet.java:341: error: not a statement /* 302 */ for (Iterator localIterator = keyset.iterator();localIterator.hasNext(); i < j) ^ 1 error ``` The particular code is as follows; ``` int j; int i; for (Iterator localIterator = keyset.iterator(); localIterator.hasNext(); i < j) ``` What am I doing wrong? Please help...
2015/02/16
[ "https://Stackoverflow.com/questions/28536876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3017739/" ]
If `(i<j)` is a condition that controls the termination of the for loop, it should be in the second part of the for statement. For example (not sure if that's the required logic) : ``` for (Iterator localIterator = keyset.iterator(); localIterator.hasNext() && i < j;) ```
One of the for sintax is `for(declaration; condition; statement)` where the third argument must be a statement that will be executed in each loop. In your case, the third argument is a condition (i is lower than j). This is the reason for you compile error. It should be like `for (Iterator localIterator = keyset.iterator();localIterator.hasNext() && i < j)`
28,536,876
When trying to compile a class, I am getting the following error; ``` ExcelReportServlet.java:341: error: not a statement /* 302 */ for (Iterator localIterator = keyset.iterator();localIterator.hasNext(); i < j) ^ 1 error ``` The particular code is as follows; ``` int j; int i; for (Iterator localIterator = keyset.iterator(); localIterator.hasNext(); i < j) ``` What am I doing wrong? Please help...
2015/02/16
[ "https://Stackoverflow.com/questions/28536876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3017739/" ]
If `(i<j)` is a condition that controls the termination of the for loop, it should be in the second part of the for statement. For example (not sure if that's the required logic) : ``` for (Iterator localIterator = keyset.iterator(); localIterator.hasNext() && i < j;) ```
`i < j` is not a *StatementExpression*. And according to [JLS(§14.14)](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14), the rightmost part of for loop is defined as [ForUpdate](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-ForUpdate) which is in return a [StatementExpressionList](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-StatementExpressionList) (a list of [StatementExpression](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-StatementExpression)).
28,536,876
When trying to compile a class, I am getting the following error; ``` ExcelReportServlet.java:341: error: not a statement /* 302 */ for (Iterator localIterator = keyset.iterator();localIterator.hasNext(); i < j) ^ 1 error ``` The particular code is as follows; ``` int j; int i; for (Iterator localIterator = keyset.iterator(); localIterator.hasNext(); i < j) ``` What am I doing wrong? Please help...
2015/02/16
[ "https://Stackoverflow.com/questions/28536876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3017739/" ]
`i < j` is not a *StatementExpression*. And according to [JLS(§14.14)](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14), the rightmost part of for loop is defined as [ForUpdate](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-ForUpdate) which is in return a [StatementExpressionList](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-StatementExpressionList) (a list of [StatementExpression](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-StatementExpression)).
One of the for sintax is `for(declaration; condition; statement)` where the third argument must be a statement that will be executed in each loop. In your case, the third argument is a condition (i is lower than j). This is the reason for you compile error. It should be like `for (Iterator localIterator = keyset.iterator();localIterator.hasNext() && i < j)`
9,067,196
When I run a feature file in RubyMine it will randomly crash with this error. Sometimes it will run one scenario other times it will run a couple before giving this error but it always does. We thought it had something to do with the version of IE we were using but it seems to occur with all versions. Also this issue doesn't seem to affect everyone and we're unsure as to what causes it because the settings on each environment are the same... Any ideas?
2012/01/30
[ "https://Stackoverflow.com/questions/9067196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214162/" ]
There shoudn't be any crashes in Ruby. If that's the case then there is a bug deep down in the Ruby Interpreter of your choice where there shouldn't be one. Try to get a debug report for this and report on Ruby Redmine or the equivalent issue tracker.
I don't think that this is the solution but so far it seems to have fixed my code... In my hooks file I have an after block that among other things has the line @browser.quit I've tracked the failure down to this line and when I comment this line out I don't get the error. Like I said I don't know if this is actually the cause of the problem but so far it seems to have resolved it... Just thought I'd share. Edit: Ok I found out the *real* solution. Apparently somewhere in the command "quit" there's a bug that causes the -1073... error. Instead of using "quit" I switched it to ".close" and that seems to have resolved it. The close command will cleanly close out of the browser instance without any errors.
1,445,354
> > Evaluation of $\displaystyle \int\frac{1}{\sin^2 x+\sin x+1}dx$ > > > $\bf{My\; Try::}$ Using $$\; \bullet\; x^2+x+1 = (x-\omega)\cdot (x-\omega^2)\;,$$ where $\omega,\omega^2$ are cube root of unity So we can write Integal $$\displaystyle I = \int\frac{1}{(\sin x-\omega)\cdot (\sin x-\omega^2)}dx$$ So we get $$\displaystyle I = \frac{1}{\omega-\omega^2}\int\frac{(\sin x-\omega^2)-(\sin x-\omega)}{(\sin x-\omega)\cdot (\sin x-\omega^2)}dx$$ So $$\displaystyle I = \frac{1}{\omega-\omega^2}\int \left[\frac{1}{\sin x-\omega}-\frac{1}{\sin x-\omega^2}\right]dx$$ Now Substitute $$\displaystyle \sin x= \frac{2\tan \frac{x}{2}}{1+\tan^2 \frac{x}{2}}$$ Can we solve it above method our we directly put $$\displaystyle \sin x= \frac{2\tan \frac{x}{2}}{1+\tan^2 \frac{x}{2}}$$ in $$\displaystyle \int\frac{1}{\sin^2 x+\sin x+1}dx$$ and then solve it. Or is there is any other process by which we can solve it. Help me , Thanks
2015/09/21
[ "https://math.stackexchange.com/questions/1445354", "https://math.stackexchange.com", "https://math.stackexchange.com/users/14311/" ]
There are $\binom{98}{50}$ committees that *do not* represent California, hence the answer is given by: $$ 1-\frac{\binom{98}{50}}{\binom{100}{50}}=1-\frac{50\cdot 49}{100\cdot 99}=\frac{149}{198}\approx\color{red}{75,25\%}. $$
I'm not sure why you have $\_2C\_1$. I am a little bit inclined to suspect it has to do with choosing one senator from California. But in fact it is possible that both are chosen. Not taking into account the possibility that both are chosen is an error. One way to proceed is as in Jack d'Aurizio's answer. Here's another: The probability that Senator $A$ is chosen is $1/2$. One way to see that is that the number of times Senator A is chosen is either $0$ or $1$, and the probability that he is chosen is the *expected value* of that number, and the sum of the expected values over all $100$ senators is the expected value of the sum, and that is $50$. But now what is the conditional probability that Senator B is **not** chosen, given that Senator A is **not** chosen? Given that Senator A is not chosen, the problem becomes that of choosing $50$ out of $99$, and an argument like that in the paragraph above then shows that the conditional probability that Senator B is **not** chosen is $49/99$. So: \begin{align} & \Pr(\text{Senators A and B are both excluded}) \\[10pt] = {} & \Pr(\text{Senator A is excluded}) \times \Pr(\text{Senator B is excluded} \mid \text{Senator A is excluded}) \\[10pt] = {} & \frac 1 2 \times \frac{49}{99} = \frac{49}{198} = 0.2474747\ldots \end{align} So the probability that California is represented is $$ 0.7525252\ldots $$
46,622,752
I have xml file which I am trying to parse: > > This is the xml file content > > > ```xml <MYSTUFF> <COMPANYNAMES> <COMPANYNAME>JUMPIN (JIMMY) LIMITED</COMPANYNAME> <COMPANYNAME>BLADE RUNNER'S TRANSPORT</COMPANYNAME> <COMPANYNAME>P Griffiths & Sons</COMPANYNAME> <COMPANYNAME>SOMETIMES, NEVER</COMPANYNAME> <COMPANYNAME>MASTER/CLASS</COMPANYNAME> </COMPANYNAMES> <FIRSTNAMES> <FIRSTNAME>Richard</FIRSTNAME> <FIRSTNAME>Jo & hn</FIRSTNAME> <FIRSTNAME>Paul</FIRSTNAME> <FIRSTNAME>Geo, rge</FIRSTNAME> <FIRSTNAME>Ringo</FIRSTNAME> </FIRSTNAMES> <LASTNAMES> <LASTNAME>Davies'</LASTNAME> <LASTNAME>Lennon</LASTNAME> <LASTNAME>McCartney(3)</LASTNAME> <LASTNAME>Harrison</LASTNAME> <LASTNAME>St/ar</LASTNAME> </LASTNAMES> </MYSTUFF> ``` This is the Code: ```vb Dim XDoc As Object Set XDoc = CreateObject("MSXML2.DOMDocument") XDoc.async = False: XDoc.validateOnParse = False XDoc.Load (ThisWorkbook.Path & "\test.xml") 'Get Document Elements Set lists = XDoc.DocumentElement 'Traverse all elements 2 branches deep For Each listNode In lists.ChildNodes For Each fieldNode In listNode.ChildNodes Debug.Print "[" & fieldNode.BaseName & "] = [" & fieldNode.Text & "]" Next fieldNode Next listNode Set XDoc = Nothing ``` I am getting object variable with or with block not set on this line: ```vb For Each listNode In lists.ChildNodes ```
2017/10/07
[ "https://Stackoverflow.com/questions/46622752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7713366/" ]
Your XML file doesn't load correctly. a) I suppose your XML file starts with something like `<?xml version="1.0" encoding="utf-8"?>`, so that it can be identified as XML. b) It's preferable to declare your object settings (always use `Option Explicit` in the declaration head). As you are using so called late binding, it's sufficient to write as follows: ```vb Dim XDoc As Object Dim lists As Object Dim listNode As Object Dim fieldNode As Object ``` **Hint** If you set your XDoc object to memory with `Set XDoc = CreateObject("MSXML2.DOMDocument")` generally you are getting an older Version (3.0), so in most cases it's preferrable to use explicitly `Set XDoc = CreateObject("MSXML2.DOMDocument.6.0")` instead, which includes XPath automatically. If not you should complete your code as follows: ```vb Set XDoc = CreateObject("MSXML2.DOMDocument") XDoc.async = False: XDoc.validateOnParse = False XDoc.setProperty "SelectionLanguage", "XPath" ' << XPath functionality ``` c) Your XML file isn't loaded successfully because it contains a non readable character called ampersand ("&") within *P Griffiths & Sons* and *Jo & hn*, which has to be changed to "`&#38;`". The ampersand character is used as general prefix for special characters, so you can't be contained alone in the file. You can test loading with the following code instead of simply using `XDoc.Load (ThisWorkbook.Path & "\test.xml")`: ```vb If XDoc.Load(ThisWorkbook.Path & "\test.xml") Then MsgBox "Loaded successfully" Else Dim xPE As Object ' Set xPE = CreateObject("MSXML2.IXMLDOMParseError") Dim strErrText As String Set xPE = XDoc.parseError With xPE strErrText = "Load error " & .ErrorCode & " xml file " & vbCrLf & _ Replace(.URL, "file:///", "") & vbCrLf & vbCrLf & _ xPE.reason & _ "Source Text: " & .srcText & vbCrLf & vbCrLf & _ "Line No.: " & .Line & vbCrLf & _ "Line Pos.: " & .linepos & vbCrLf & _ "File Pos.: " & .filepos & vbCrLf & vbCrLf End With MsgBox strErrText, vbExclamation Set xPE = Nothing Exit Sub End If ``` d) BTW, there are other and more complete ways to loop through your nodes (recursive calls). Sure you'll find some at the SO site.
Your code ran fine for me. As @FlorentB. suggested, the document probably failed to parse. I suspect their is an error in the file name. Adding some error handling will help catch these errors. ```vb Sub PrintXML() Dim FilePath As String Dim XDoc As Object FilePath = ThisWorkbook.Path & "\test.xml" If Len(Dir(FilePath)) = 0 Then MsgBox "File not Found:" & vbCrLf & FilePath, vbCritical Exit Sub End If Set XDoc = CreateObject("MSXML2.DOMDocument") XDoc.async = False: XDoc.validateOnParse = False XDoc.Load ("C:\Users\norkiosk\Documents\Fax\test.xml") 'Get Document Elements Set lists = XDoc.DocumentElement If lists Is Nothing Then MsgBox "Failed to Parse File:" & vbCrLf & FilePath, vbCritical Exit Sub End If 'Traverse all elements 2 branches deep For Each listNode In lists.ChildNodes For Each fieldNode In listNode.ChildNodes Debug.Print "[" & fieldNode.BaseName & "] = [" & fieldNode.Text & "]" Next fieldNode Next listNode Set XDoc = Nothing End Sub ```
41,277,193
[![Image of skills required](https://i.stack.imgur.com/dxol7.png)](https://i.stack.imgur.com/dxol7.png) From the above image i have added more functionality, So my question is for every skill GD (or) PI (or) both checkboxes has to be mandatory.(Atleast one checkbox has to be selected) how can i achieve that.? this is my html: ``` <a class="text-center btn btn-danger addSkills">+ Add Skills</a> <input class="selectGdSkill" type="checkbox" count="0" id="skill[0][gdskill]" name="skill[0][gdskill]"> <input class="selectPiSkill" type="checkbox" count="0" id="skill[0][piskill]" name="skill[0][piskill]"> ``` this is add more functionality code: ``` var skillcount = 1; $(".addSkills").click(function () { $('#jobSkills tr:last').after('<tr> <td><input class="searchskill" count="' + skillcount + '" id="skill_' + skillcount + '_title" name="skill[' + skillcount + '][title]" type="text" autocomplete="off"></td><td><input count="' + skillcount + '" id="skill_' + skillcount + '_weightage" name="skill[' + skillcount + '][weightage]" type="text" autocomplete="off"></td> <td><select class="wp-form-control" name="skill[' + skillcount + '][type]"><option value="0">Select Test Type</option><option value="1">Practice Test</option><option value="2">Qualifying</option></select></td> <td><input class="selectGdSkill" type="checkbox" count="' + skillcount + '" id="skill[' + skillcount + '][gdskill]" name="skill[' + skillcount + '][gdskill]"></td> <td> <input class="selectPiSkill" type="checkbox" count="' + skillcount + '" id="skill[' + skillcount + '][piskill]" name="skill[' + skillcount + '][piskill]"></td> <td><span class="removeSkill" id="' + skillcount + '" ><a style="color:red">Remove</a></span></td> </tr>'); skillcount++; }); ``` help me in fiddle: <https://jsfiddle.net/r359b453/6/>
2016/12/22
[ "https://Stackoverflow.com/questions/41277193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6382509/" ]
Give same class name to all checkbox and try this one ``` $(document).ready(function() { $("#submitBTN").click(function(e) { if($('.case:checkbox:checked').length==0){ alert("Please select"); } }); }); ```
**If Both checkboxes are empty for every skill say select atleast on checkbox** ``` var rows = document.getElementsByTagName('tr'); var isTableValid = true; for(var i=0;i<rows.length;i++) { var checkboxs=rows[i].getElementsByClassName("selectGdSkill");//add "selectPiSkill" class in this var okay=false; for(var j=0;j<checkboxs.length;j++){ console.log('here' + checkboxs[j].checked); if(checkboxs[j].checked){ okay=true; break; } } if(!okay && checkboxs.length > 0) { isTableValid = false; break; } } if(isTableValid) return true; else { alert("Please select atleast one checkbox every skill either GD or PI"); return false; } ``` it is workking for every `<tr>` but only for `selectGdSkill` And > > i am looking for Anyone from the two checkboxes GD (or) PI > > >
41,277,193
[![Image of skills required](https://i.stack.imgur.com/dxol7.png)](https://i.stack.imgur.com/dxol7.png) From the above image i have added more functionality, So my question is for every skill GD (or) PI (or) both checkboxes has to be mandatory.(Atleast one checkbox has to be selected) how can i achieve that.? this is my html: ``` <a class="text-center btn btn-danger addSkills">+ Add Skills</a> <input class="selectGdSkill" type="checkbox" count="0" id="skill[0][gdskill]" name="skill[0][gdskill]"> <input class="selectPiSkill" type="checkbox" count="0" id="skill[0][piskill]" name="skill[0][piskill]"> ``` this is add more functionality code: ``` var skillcount = 1; $(".addSkills").click(function () { $('#jobSkills tr:last').after('<tr> <td><input class="searchskill" count="' + skillcount + '" id="skill_' + skillcount + '_title" name="skill[' + skillcount + '][title]" type="text" autocomplete="off"></td><td><input count="' + skillcount + '" id="skill_' + skillcount + '_weightage" name="skill[' + skillcount + '][weightage]" type="text" autocomplete="off"></td> <td><select class="wp-form-control" name="skill[' + skillcount + '][type]"><option value="0">Select Test Type</option><option value="1">Practice Test</option><option value="2">Qualifying</option></select></td> <td><input class="selectGdSkill" type="checkbox" count="' + skillcount + '" id="skill[' + skillcount + '][gdskill]" name="skill[' + skillcount + '][gdskill]"></td> <td> <input class="selectPiSkill" type="checkbox" count="' + skillcount + '" id="skill[' + skillcount + '][piskill]" name="skill[' + skillcount + '][piskill]"></td> <td><span class="removeSkill" id="' + skillcount + '" ><a style="color:red">Remove</a></span></td> </tr>'); skillcount++; }); ``` help me in fiddle: <https://jsfiddle.net/r359b453/6/>
2016/12/22
[ "https://Stackoverflow.com/questions/41277193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6382509/" ]
Here Your HTML I have changed input box IDs and put your table `<div id="myDiv"> <table id="tableID"> <tr> GD<input class="selectGdSkill" type="checkbox" id="selectGdSkill_0"> PI<input class="selectPiSkill" type="checkbox" id="selectPiSkill_1"> </tr> <br> <tr> GD<input class="selectGdSkill" type="checkbox" id="selectGdSkill_1"> PI<input class="selectPiSkill" type="checkbox" id="selectPiSkill_1"> </tr> </table> <button id="JobSubmit" class="btn btn-success text-center">SUBMIT JOB</button> </div>` Here is javascript code for check. ``` $(document).ready(function(){ $("#JobSubmit").on("click",function(){ var IDs = []; $("#myDiv").find("input").each(function(){ IDs.push(this.id); }); console.log(IDs); $.each(IDs, function(i, value) { if(!($("#"+value ).is(":checked"))){ alert("Atleast one checkbox has to select from every tr"); return false; } }); }) }) ```
**If Both checkboxes are empty for every skill say select atleast on checkbox** ``` var rows = document.getElementsByTagName('tr'); var isTableValid = true; for(var i=0;i<rows.length;i++) { var checkboxs=rows[i].getElementsByClassName("selectGdSkill");//add "selectPiSkill" class in this var okay=false; for(var j=0;j<checkboxs.length;j++){ console.log('here' + checkboxs[j].checked); if(checkboxs[j].checked){ okay=true; break; } } if(!okay && checkboxs.length > 0) { isTableValid = false; break; } } if(isTableValid) return true; else { alert("Please select atleast one checkbox every skill either GD or PI"); return false; } ``` it is workking for every `<tr>` but only for `selectGdSkill` And > > i am looking for Anyone from the two checkboxes GD (or) PI > > >
63,719,614
I have a date object `1/10/2021` and when I set date minus 1. It will return `31/10/2021`. What I expect here is 30/9/2021. Here is my simulate of code: ```js const _date = new Date(2021, 10, 1); _date.setDate(_date.getDate() - 1); console.log(_date) // Sun Oct 31 2021 00:00:00 GMT+0800 (Singapore Standard Time) ``` Anyone can explain what wrong with my code? and how to fix this case? I really need your help in this issue.
2020/09/03
[ "https://Stackoverflow.com/questions/63719614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4344732/" ]
Months are 0-indexed. Your first statement initiates the date to be November 1st. ```js const _date = new Date(2021, 10, 1); console.log(_date) // Nov 1, 2021 ``` More documentation on the Date object here: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date>
Months are 0-indexed, so you need to change this to 9 for October. Or use something more intuitive like this: ``` var _date = new Date('October 1 2021'); ``` Also consider using toString() methods. ```js var _date = new Date(2021, 9, 1); _date.setDate(_date.getDate() - 1); console.log(_date.toLocaleString()); ```
41,291,351
I have a route that just shows some form: ``` Route::get('/form/{form}', 'FormController@show'); ``` In the `FormController`, thanks to type injection I automagically convert form id (from `{form}`) to `App\Form` object and display it in the view: ``` public function show(Form $form){ return view('form', compact('form')); } ``` When I get a `Form` object through Eloquent query builder, I can eager load related elements/models like that: ``` $form = App\Form::where('id', '1497')->with('subform')->get() ``` Is there a way to automatically eager-autoload `$form` object with `subform` related object, or do I need to do it manually like that: ``` public function show($id){ $form = App\Form::where('id', $id)->with('subform')->get(); return view('form', compact('form')); } ```
2016/12/22
[ "https://Stackoverflow.com/questions/41291351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177167/" ]
To automatically lazy load the subform when it is resolved in a route you can customize your route model binding. Define the custom resolution in the `boot()` method of `App\Providers\RouteServiceProvider` like: ``` public function boot() { parent::boot(); Route::bind('form', function ($id) { return App\Form::with('subform')->find($id);; }); } ``` This will resolve your route parameter `{form}` to the given form while automatically loading your subform.
You can add relation by using [`load()`](https://laravel.com/docs/5.3/eloquent-relationships#lazy-eager-loading) method: ``` public function show(Form $form) { return view('form', ['form' => $form->load('subform')]); } ```
30,295
Why is the phrase [Across the pond](http://en.wiktionary.org/wiki/across_the_pond) used to refer to the opposite side of the Atlantic Ocean? Considering the size of the Atlantic Ocean is vast, is it suggesting the ocean is only a small hindrance? Considering that in the modern world it has become easier to communicate and travel?
2011/06/17
[ "https://english.stackexchange.com/questions/30295", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5693/" ]
I feel that the aspect "the world is smaller now" is really not that relevant: indeed, the phrase is far too old for that to be the case. Rather, it's a perfect example of typical understated, dry, English humour. I'm afraid I don't know about earliest usage although PHenry mentioned it could have been used as early as the 1800s. In that era, the "Sun never set on the British empire." Britain was the biggest-ever world empire: indeed, that was largely based on naval power. So in the 1800s, you can see that because of extreme British naval power - combined with the typical British gift for understatement - it would be natural to refer to the Atlantic as merely a silly *pond*. Note: as John below points out, this phrase is certainly used in both the USA and in the UK. (It's used on both sides of the pond.) It originated in the UK: I would suggest in the USA the phrase is used mainly on the East Coast (New York City and so on). The phrase is dropping out of use in the UK, so it sounds a hair archaic. Indeed, generally the idea of being a "witty understated Englishman" is something that belongs more to older people there; the yoof have Snapchat.
It's a humorous understatement, like calling the United States "the colonies." The expression seems to have come into being in the late 19th century. On Google Books I find [a use of it from 1885](http://books.google.com/books?id=CskhAQAAIAAJ&printsec=frontcover#v=onepage&q=%22across%20the%20pond%22&f=false), but nothing before that.
30,295
Why is the phrase [Across the pond](http://en.wiktionary.org/wiki/across_the_pond) used to refer to the opposite side of the Atlantic Ocean? Considering the size of the Atlantic Ocean is vast, is it suggesting the ocean is only a small hindrance? Considering that in the modern world it has become easier to communicate and travel?
2011/06/17
[ "https://english.stackexchange.com/questions/30295", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5693/" ]
It's a humorous understatement, like calling the United States "the colonies." The expression seems to have come into being in the late 19th century. On Google Books I find [a use of it from 1885](http://books.google.com/books?id=CskhAQAAIAAJ&printsec=frontcover#v=onepage&q=%22across%20the%20pond%22&f=false), but nothing before that.
As an aviator, we refer to the Pacific as the "pond" and the Atlantic as the "puddle". A girlfriend of mine, most recently a captain on American Eagle, now retired, used to ferry planes across the Pacific, aka the pond, to NZ or Aus from California and she also ferried quite a few across the puddle from California to the UK. You can see how the names are so apt. Every time I see "pond" applied to the Atlantic, I cringe.
30,295
Why is the phrase [Across the pond](http://en.wiktionary.org/wiki/across_the_pond) used to refer to the opposite side of the Atlantic Ocean? Considering the size of the Atlantic Ocean is vast, is it suggesting the ocean is only a small hindrance? Considering that in the modern world it has become easier to communicate and travel?
2011/06/17
[ "https://english.stackexchange.com/questions/30295", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5693/" ]
I feel that the aspect "the world is smaller now" is really not that relevant: indeed, the phrase is far too old for that to be the case. Rather, it's a perfect example of typical understated, dry, English humour. I'm afraid I don't know about earliest usage although PHenry mentioned it could have been used as early as the 1800s. In that era, the "Sun never set on the British empire." Britain was the biggest-ever world empire: indeed, that was largely based on naval power. So in the 1800s, you can see that because of extreme British naval power - combined with the typical British gift for understatement - it would be natural to refer to the Atlantic as merely a silly *pond*. Note: as John below points out, this phrase is certainly used in both the USA and in the UK. (It's used on both sides of the pond.) It originated in the UK: I would suggest in the USA the phrase is used mainly on the East Coast (New York City and so on). The phrase is dropping out of use in the UK, so it sounds a hair archaic. Indeed, generally the idea of being a "witty understated Englishman" is something that belongs more to older people there; the yoof have Snapchat.
The reason phenry couldn't find matches from before 1885 in a Google Books search for "the pond" may have been that in many early references the expression contains a qualifying modifier: "the big pond," "the great pond," "the herring pond," "the salt pond," or some combination of these characterizations. At least one fairly early reference to the Atlantic Ocean as "the big pond" comes up in a Google Books search, from [*Eliza Cook's Journal*](https://books.google.com/books?id=Br8CAAAAIAAJ&pg=PA335&dq=%22across+the+big+pond%22&hl=en&sa=X&ved=0ahUKEwj55NqiqrrPAhUUTmMKHfPuDvUQ6AEILjAD#v=onepage&q=%22across%20the%20big%20pond%22&f=false) (March 20, 1852), a London periodical. The earliest Google Books match for "across the great pond" is even earlier—from a U.S. publication called [Holden's Dollar Magazine](https://books.google.com/books?id=4HtHAAAAYAAJ&pg=PA414&dq=%22across+the+great+pond%22&hl=en&sa=X&ved=0ahUKEwihnImErLrPAhUUTmMKHfPuDvUQ6AEIIzAB#v=onepage&q=%22across%20the%20great%20pond%22&f=false) (July 1849). --- ***Identifying 'the herring pond'*** The earliest and most common variation on "across the pond" in Google Books search results, however, takes the form "across the herring pond." Here are two such examples. From "[Sketches of Society,—No. III](https://books.google.com/books?id=EcxNAQAAMAAJ&pg=RA1-PA1&dq=%22have+been+sent+across+the+herring+pond%22&hl=en&sa=X&ved=0ahUKEwiNsZebtbrPAhUY_WMKHTQYAlMQ6AEIIzAB#v=onepage&q=%22have%20been%20sent%20across%20the%20herring%20pond%22&f=false)," in *La Belle Assemblée: or, Bell's Court and Fashionable Magazine* (July 1824): > > There—those two, now walking off arm-in-arm, are two of the greatest sharpers on the turf. He in the short green jacket, white, hat, buff waistcoat, and cossack trowsers, is Jack Dauntless, who would, not very long since, have been sent **across the herring-pond**, if fortune had not stood his friend, and by means of a flaw in the indictment procured his acquittal of a charge of swindling; ... > > > And from "[Chit Chat](https://books.google.com/books?id=Jow0AQAAMAAJ&pg=PA290&dq=%22been+across+the+herring+pond+once%22&hl=en&sa=X&ved=0ahUKEwjny8rlt7rPAhXHKWMKHV2pBywQ6AEIHjAA#v=onepage&q=%22been%20across%20the%20herring%20pond%20once%22&f=false)," in *The Metropolitan* (August 1833): > > *Mr. Volage.* "Nonsense," said the Doctor, "I mean to say that you're a loose character." —— "D——n," says Jarvey, "bating that I've been **across the herring pond** once, and had a spell at the hulks twice, who can say a word agin my carracter ; for being had up now and then goes for nicks, every gemmen knows that ere. But, my precious eyes! I does'nt think as how you're no gemmen at all!" > > > Both of these instances evidently refer to transportation—the punishment of being sent off to a distant penal colony in Australia or elsewhere as punishment for a crime in England—and by the 1800s few convicts were being sent across the Atlantic. Similar usage appears in instances from [1840](https://books.google.com/books?id=NMdUAAAAYAAJ&pg=PA291&dq=%22across+the+herring+pond%22&hl=en&sa=X&ved=0ahUKEwjCiZLjrLrPAhWFMGMKHUJvB54Q6AEIHjAA#v=onepage&q=%22across%20the%20herring%20pond%22&f=false) and [1841](https://books.google.com/books?id=TcNlAAAAMAAJ&pg=PA215&dq=%22across+the+herring+pond%22&hl=en&sa=X&ved=0ahUKEwjCiZLjrLrPAhWFMGMKHUJvB54Q6AEIJDAB#v=onepage&q=%22across%20the%20herring%20pond%22&f=false), suggesting that this term remained a common slang expression at least into the 1840s. A search for earlier instances of "herring pond" for "the sea" (not further differentiated) finds William Perry, [*The London Guide and Stranger's Safeguard Against Cheats, Swindlers, and Pickpockets That Abound Within the Bills of Mortality; Forming a Picture of London, as Regards Active Life*](https://books.google.com/books?id=rJABAAAAYAAJ&printsec=frontcover&dq=%22London+Guide+and+Stranger%27s+Safeguard%22&hl=en&sa=X&ved=0ahUKEwjzo__61PjNAhUH9GMKHXOVCpsQ6AEIHjAA#v=onepage&q=pond&f=false) (1818) uses the term in passing with regard to a swindler: > > Next in high sounding firm was the Piccadilly bank, Sir Sir John William Thomas Lathrop Murray, Bart. *and Co.* who is now on his journey across "***the herring pond***" for no good. > > > In that book the author identified himself on the title page as "A Gentleman who has made the Police of the Metropolis, an object of enquiry twenty-two years." And Francis Grose, [*A Classical Dictionary of the Vulgar Tongue*](https://books.google.com/books?id=zLAJs0_prpwC&pg=PT129&dq=%22lingo%22&hl=en&sa=X&ei=eAhtU7r1A5ChogTl2IGYBA#v=onepage&q=%22herring%20pond%22&f=false) (1785) has this entry for *herring pond*: > > HERRING POND. The sea; to **cross the herring pond** at the king's expense, to be transported. > > > Earliest of all is this mention in [*The True Anti-Pamela: Or, Memoirs of Mr. James Parry*](https://books.google.com/books?id=ZCs6AAAAcAAJ&pg=PA290&dq=%22over+the+Herring+Pond%22&hl=en&sa=X&ved=0ahUKEwix-PO84PnPAhVJrFQKHU9aDEY4FBDoAQghMAE#v=onepage&q=%22over%20the%20Herring%20Pond%22&f=false), second edition (1742): > > In short I expected nothing less than Transportation ; altho' I had no Way injured any one. Well, thinks I, if I must go **over the Herring Pond**, there is no avoiding it. I have been at Sea, and am not unacquainted with some Part of *America*, so that if I am obliged to quit my native Shore, I'll not be confined to what Province my Adversaries please; but will reach *Carolina*, where I am acquainted. > > > At this early date, the American penal colony at Georgia was indeed a common destination of transported criminals, and appears to be the destination Mr. Parry contemplates for himself, making "the Herring Pond" of this mention (once again) the Atlantic Ocean. In other early use, "the herring-pond" may to refer to smaller bodies of seawater such as the English Channel or the Irish Sea. From a review of "[The Frantic Conduct of John Bull for a Century Past](https://books.google.com/books?id=H2FAAQAAMAAJ&pg=PA101&dq=%22antagonist+across+the+herring-pond%22&hl=en&sa=X&ved=0ahUKEwjw3__2sbrPAhUG3GMKHWyMBMIQ6AEIHjAA#v=onepage&q=%22antagonist%20across%20the%20herring-pond%22&f=false)," in *The Monthly Review* (May 1803): > > Though these doggerel rhimes are often hobbling, vulgar, and ungrammatical, they bear the features of true satire, and prove the author to be gifted with some penetration. If his mode of treating his subject is not quite new, his work certainly is not tedious. Poor John Bull is treated with very little ceremony; and his past conduct, in needlessly pushing his head into quarrels, squandering his money, and entailing debts on his children, is adduced to prove him mad, or 'governed by Old Nick.' On the other hand, his antagonist **across the herring-pond** does not escape castigation, but is represented as having weakly sported with the name of Liberty: > > > > > > > Thy cause, indeed, was like to fail,/ Thou'dst neither ballast, rope, nor sail;/ Drov'st without compass, anchor, helm,/ Thy miscreants delug'd all the realm./ At murder, guillotine, and dagger,/ Thy injur'd friends began to stagger;/ No longer could maintain thy cause,/ When thou had'st thus blasphem'd its laws;/ ... > > > > > > > > > And from [*Fatherless Fanny; or, A Young Lady's First Entrance into Life, Being the Memoirs of a Little Mendicant, and Her Benefactors*](https://books.google.com/books?id=nb4BAAAAQAAJ&pg=PA205&dq=%22little+mendicant,+and+her+benefactors%22&hl=en&sa=X&ved=0ahUKEwj9ornyrbrPAhUJ2GMKHakiA90Q6AEIQzAH#v=onepage&q=herring-pond&f=false) (1811), in which little Fanny, after being abducted, is conveyed by ship from the west coast of England to Ireland: > > "Miss looks terrible well now," exclaimed Franklyn, to one of the other men, "it is only my whimpering wife made her bad before; I wish I had sent her back sooner, we should have been **across the herring-pond** by this time." > > > Eventually "across the herring pond," like other formulations of "across the pond" most often meant "across the Atlantic Ocean"—as it appears to have done in its 1742 instance in *The True Anti-Pamela*. --- ***Early newspaper instances in which 'the pond' = 'the Atlantic Ocean'*** A search of the Library of Congress's Chronicling America database for instances where *across the pond* means "across the ocean" go back to 1837. In the earliest matches, the pond in question is the Atlantic Ocean, but later instances (beginning in 1857) use it in connection with the Pacific Ocean. To show the range of the expression as used in the 1830s 1840s, and 1850s by U.S. newspapers to refer to the Atlantic Ocean, I reproduce examples through the year 1854. From [a letter](http://chroniclingamerica.loc.gov/lccn/sn83030312/1837-07-25/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=5&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4) in the *[New York] Morning Herald* (July 25, 1837): > > A packet had just put her passengers on board of the steamer, and it afforded us infinite gratification to see the wondering faces of the women, and the astonishment of the men, to see so beautiful a spot **across the big pond**, as they call the wide Atlantic. > > > From "[Varieties](http://chroniclingamerica.loc.gov/lccn/sn83030313/1845-06-02/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=18&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4)," in the *New York Herald* (June 2, 1845): > > The editor of the Cincinnati Commercial, who claims to be the inventor of the project for extending Morse's telegraph across the Atlantic, intends at no very distant day, to organize a company to purchase the wire and take other steps to stretch it **across the "big pond."** > > > From the [*St. Landry [Louisiana] Whig*](http://chroniclingamerica.loc.gov/lccn/sn83016702/1845-08-28/ed-1/seq-1/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=7&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4) (August 28, 1845): > > In the prairies here, we can beat the Jews or Gentiles in raising horses, Cattle, Sheep, Hogs, Fowls, Corm, Cotton, Sugar, and even Grapes to make Wine from, or any of those gentlemen **across the "big pond"** who want to make us subservient to their wishes. Keep up the Tariff, sir, and in a few years we will produce every thing the most fastidious taste could desire, and become a perfect world within ourselves! > > > From a [letter to the editor](http://chroniclingamerica.loc.gov/lccn/sn82003410/1846-05-16/ed-1/seq-3/#date1=1846&index=0&rows=20&words=across+big+pond&searchType=basic&sequence=0&state=&date2=1846&proxtext=%22across+a+big+pond%22&y=14&x=15&dateFilterType=yearRange&page=1) dated May 6, 1846, published in the *[Washington, D.C.] Daily Union* (May 16, 1846): > > Before I conclude, allow me to state the case of two shoemakers not far from this. They live in the same street opposite each other; one is a good cutter, has money, buys the best leather at the first hand, employs the best workmen, pays them regularly and promptly, and gets his work done low; consequently he produces a superior article at a moderate price, and as a matter of course takes the bulk of the trade. The other man has no capital, gets his materials on credit at high prices, pays his workmen uncertainly, does not produce as good an article for the same money, and cannot get along. Now, why should not this man have a bill passed to protect him? The manufacturers get bills passed to protect them against English manufacturers; and the only difference is that they are **across a big pond**, and the shoemakers across the street; for we are all brothers. > > > From "[New York Correspondence of the Crescent](http://chroniclingamerica.loc.gov/lccn/sn82015378/1848-06-10/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=2&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=6)," in the *[New Orleans, Louisiana] Daily Crescent* (June 10, 1848): > > E. K. Collins is going ahead with his large ocean steamers, for which he has selected the names: "Palo Alto," "Buena Vista," "Cerro Gordo," and Contreras." We have already five or six ocean steamers plying from this city [New York City] **across the "big pond."** > > > From the [*Evansville [Indiana] Daily Journal*](http://chroniclingamerica.loc.gov/lccn/sn82015672/1848-06-24/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=4&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4) (June 24, 1848): > > It is stated that the new British steamship Niagara made the first half of her passage across the Atlantic, within sixty or seventy mi[l]es, in four days. Tremendous westerly winds impeded her progress for the next *four days*, or she would have made the quickest passage **across the great pond** ever heard of. > > > From "[Another Holy Alliance](http://chroniclingamerica.loc.gov/lccn/sn86053240/1849-06-20/ed-1/seq-3/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=8&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4)," in the *[Sumterville, South Carolina] Sumter Banner* (June 20, 1849): > > England can protest, but can afford to do no more.---Russia and Austria, with a million of soldiers, will give the law to Europe. Every arrival from **across the "big herring pond"** increases the interest of the news it conveys. > > > From a [letter to the editor](http://chroniclingamerica.loc.gov/lccn/sn82003410/1850-11-23/ed-1/seq-3/#date1=1789&sort=relevance&rows=20&words=across+Pond&searchType=basic&sequence=0&index=3&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=6) dated November 18, 1850, of the *[Washington, D.C.] Daily Union* (November 23, 1850): > > But Mr. Garrison is probably not satisfied with his [anti-slavery] force here: he sends **across the "Big Pond,"** and brings over to his aid the celebrated George Thompson, a Britisher, who, on his former visit to his bosom friend, came very near o getting an extra red coat, and escaped to the British provinces with an extra cup of tea. > > > From "[Shortest Passage Ever Made Across the Atlantic](http://chroniclingamerica.loc.gov/lccn/sn85026203/1851-05-05/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+Pond&searchType=basic&sequence=0&index=3&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4)," in the *Portsmouth [Ohio] Inquirer* (May 5, 1851): > > The American Republican Mail Steamship "Pacific" arrived in port on Saturday at 10 A. M., after a passage of 9 days and 20 hours from Liverpool, the shortest on record. The Pacific has made the two shortest passages ever made **across the Big Pond**. > > > From "[The Release of Kossuth](http://chroniclingamerica.loc.gov/lccn/sn83030313/1851-10-04/ed-1/seq-1/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=12&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=6)," in the *New York Herald* (October 4, 1851): > > She [the steamship *Mississippi*] now lies snugly at anchor in the Golden Horn, much admired and visited by all classes of people—Moslem, Christian, and Jew—and busily engaged preparing for her long journey **across the "great pond."** > > > From "[The New Primer](http://chroniclingamerica.loc.gov/lccn/sn83045784/1851-10-18/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=16&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=2)," in the *[Washington, D.C.] National Intelligencer* (October 18, 1851): > > It will be seen by the following paragraph from the "European Times" that this invention [of the Maynard primer as a replacement for the percussion cap in firearms] is attracting some notice **across the *pond***: [quotation from the European newspaper omitted]. > > > From "[American Example Abroad](http://chroniclingamerica.loc.gov/lccn/sn84024738/1852-04-12/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=3&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=5)," in the *[Richmond, Virginia] Daily Dispatch* (April 12, 1852): > > There was a grand debate in the British House of Commons on the 26th March, relative to the extension of the right of suffrage.—From this debate which is too long for publication in this paper, it is evident that, in spite of themselves, republican ideas are advancing very rapidly with our cousins **across the herring pond**. > > > From "[The Address of the Ladies of England](http://chroniclingamerica.loc.gov/lccn/sn86071377/1852-12-30/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=6&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4)," in the *[Ebensburg, Pennsylvania] Mountain Sentinel* (December 30, 1852): > > These ["*quasi* benevolent"] ladies [of England] need not look **across the "big pond"** to rescue shattered constitutions and broken-hearts from bondage > > > From a [letter by "Hopeful"](http://chroniclingamerica.loc.gov/lccn/sn83035172/1853-06-08/ed-1/seq-3/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=12&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=2) from Washington, D.C., dated May 26, 1853, in the *[Ashland] Ohio Union* (June 8, 1853): > > "To be or not to be" *has been*, the question; but the President has pretty effectually settled it, by giving to "his flock" the results of his labors in relation to "Foreign Appointments." The city has been full of applicants, for places abroad, but, all at once, "a change comes over the spirit of their dreams" and they "*mizzled*." One prominent gentleman who had been here for ten weeks pressing claims for a place at the "Lobos Islands," or some other "fertile spot" **across the pond**, left in such a hurry as to entirely overlook his night shirt, which was under his pillow. > > > From "[When Newspapers Please](http://chroniclingamerica.loc.gov/lccn/sn84022366/1853-06-18/ed-1/seq-1/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=5&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=6)," in the *Rutland [Vermont] County Herald* (June 18, 1853): > > The London Leader—one of the most piquant journals that reach us from **across the great "herring pond"**—thus felicitously explains the secret of newspaper popularity: [quotstion omitted. > > > From "[A Traveller](http://chroniclingamerica.loc.gov/lccn/sn83045450/1853-09-03/ed-1/seq-3/#date1=1789&sort=relevance&rows=20&words=Across+pond&searchType=basic&sequence=0&index=16&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=5)," in the *[Raleigh, North Carolina] Weekly North Carolina Standard* (September 3, 1853): > > I have visited every great curiosity, nearly every state capital, and every State in the Union, except California and Texas. **Across the "herring pond"** I travelled through almost every kingdom, and saw nearly every crowned head in Europe; wandered over the highlands of Scotland, stoned the cormorants in Fingal's Cave, shot sea gulls in Shetland, eat plovers and other wild birds in Iceland, cooked my dinner in the geysers, cooled my punch with the snows of Mt. Hekla, and toasted my shins at the burning crater on its summit. > > > From "[Changing the Fashions](http://chroniclingamerica.loc.gov/lccn/sn84024738/1854-11-24/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=17&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=5)," in the *[Richmond, Virginia] Daily Dispatch* {November 24, 1854): > > In this country, where the ladies are worshipped as something superior, men never think of asking them to perform menial offices, or to do anything inconsistent with their delicate, angelic natures. Not so with some of our neighbors who hail from **across the big salt pond**, if we are to judge from what is frequently seen in our city. > > > --- ***Early instances where 'the pond' = 'the Pacific'*** From "[Where do the days Die?](http://chroniclingamerica.loc.gov/lccn/sn84023127/1857-04-17/ed-1/seq-1/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=11&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=3)" in the *Burlington [Vermont] Free Press* (April 17, 1857): > > The shipmaster who does not make this rectification, always finds his reckoning a day in advance of or a day behind that of the port he sails to : for when it is Monday afternoon at San Francisco it is Tuesday afternoon **across the pond** at Canton [China]. > > > The [*[Honolulu, Hawaii] Polynesian*](http://chroniclingamerica.loc.gov/lccn/sn82015408/1858-04-24/ed-1/seq-5/#date1=1789&index=1&rows=20&words=across+pond&searchType=basic&sequence=0&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=1) (April 24, 1858) quotes an editorial comment from *San Francisco Prices Current* to the effect that the U.S. government should ensure that U.S. commerce with the Hawaiian Kingdom of the Sandwich Islands not be "interrupted" by competition from European nations (in particular France, which was known to be negotiating a trade deal with Hawaii), and then the *Polynesian* comments as follows: > > How the French treaty does trouble our neighbor **across the pond**! Do they not know that any privilege which the French, or any of "the most favored nation" may have obtained, will by their own treaty be granted to them? And do they for a moment suppose that the U.S. Commissioner is not better posted on these subjects than any "on dits" of San Francisco? > > > From "[H. R. H. Prince Kamehameha](http://chroniclingamerica.loc.gov/lccn/sn82015408/1860-08-18/ed-1/seq-3/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=10&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=2)," in the *[Honolulu, Hawaii] Polynesian* (August 18, 1860): > > We know that it will afford our readers as much pleasure to learn, as it gives us to inform them, that H. R. H. Prince Kamehameha, has now so far recovered from his late severe sickness as to be able to take some gentle exercise on horseback during the morning hours. We learn further that, upon the advice of the physicians, the Prince has concluded to try a trip to Victoria, V[ancouver] I[sland], perhaps California, and the effects of a sea voyage and change of climate, in order fully to re-establish his health. > > > That the prayers and best wishes of every inhabitant of this land go with him. we need not assure him, and that the kindliest reception awaits him **across the pond**, we are equally certain. The Prince takes passage on board the clipper schooner *Emma Rooke* for Victoria, V. I., and will leave about the 28th inst. > > > From "[Interesting from Japan](http://chroniclingamerica.loc.gov/lccn/sn84026547/1860-10-02/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=6&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=3)," in the *Newbern [North Carolina] Weekly Progress* (October 2, 1860): > > We make the following extracts, says the Washington States, of a letter dated Yokohama, Japan, July 18th, and which we find in the [San Francisco] Alta Californian: > > > The Japanese steam Candinmarrah, which left this port last February, ... conveying the intelligence of the departure of the Japanese Ambassadors to America, arrived here from Honolulu, after a passage of eighteen days. From the Americans who came in her, we learned that the Japanese conducted themselves admirably on board, taking the position of the vessel daily by the sun, and brought her, in seamanlike manner, into this bay without accident. > > > The appearance of the Japanese steamer, from America, with news from the Ambassadors, created a great excitement both amongst the Americans and Japanese. The foreigners were anxious to hear how the Japanese had been received in America, and the Japanese were fearful lest the Ambassadors would not survive the great trip **across the pond**. However, all doubts were dispelled when the great mail was distributed. > > > --- ***Conclusions*** The earliest instance that my Chronicling America search yielded for the unadorned expression "across the pond" for "across the Atlantic Ocean" is from a Washington, D.C. newspaper article published in October 1851. But use of "the herring pond" for "the Atlantic Ocean" or generically for "the sea" or for one or another smaller specific seas goes back much farther. The earliest match I've been able to find for "the herring pond" as a slang expression for "Atlantic Ocean" is from the second edition of *The True Anti-Pamela*, published in 1742 (the first edition appeared a year earlier, but I haven't found a searchable copy of it online).
30,295
Why is the phrase [Across the pond](http://en.wiktionary.org/wiki/across_the_pond) used to refer to the opposite side of the Atlantic Ocean? Considering the size of the Atlantic Ocean is vast, is it suggesting the ocean is only a small hindrance? Considering that in the modern world it has become easier to communicate and travel?
2011/06/17
[ "https://english.stackexchange.com/questions/30295", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5693/" ]
I feel that the aspect "the world is smaller now" is really not that relevant: indeed, the phrase is far too old for that to be the case. Rather, it's a perfect example of typical understated, dry, English humour. I'm afraid I don't know about earliest usage although PHenry mentioned it could have been used as early as the 1800s. In that era, the "Sun never set on the British empire." Britain was the biggest-ever world empire: indeed, that was largely based on naval power. So in the 1800s, you can see that because of extreme British naval power - combined with the typical British gift for understatement - it would be natural to refer to the Atlantic as merely a silly *pond*. Note: as John below points out, this phrase is certainly used in both the USA and in the UK. (It's used on both sides of the pond.) It originated in the UK: I would suggest in the USA the phrase is used mainly on the East Coast (New York City and so on). The phrase is dropping out of use in the UK, so it sounds a hair archaic. Indeed, generally the idea of being a "witty understated Englishman" is something that belongs more to older people there; the yoof have Snapchat.
Put quite simply, "the Pond" is an expression of the relationship that exists, still to this day, between the United States of America and Great Britain. It's a linguistic way of reducing the 3000 miles that physically exist between our two countries and recognising how much we actually have in common. By far and away the most common language spoken in the United States is English. Ask yourself why that is and look it up in the history books!
30,295
Why is the phrase [Across the pond](http://en.wiktionary.org/wiki/across_the_pond) used to refer to the opposite side of the Atlantic Ocean? Considering the size of the Atlantic Ocean is vast, is it suggesting the ocean is only a small hindrance? Considering that in the modern world it has become easier to communicate and travel?
2011/06/17
[ "https://english.stackexchange.com/questions/30295", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5693/" ]
It's a humorous understatement, like calling the United States "the colonies." The expression seems to have come into being in the late 19th century. On Google Books I find [a use of it from 1885](http://books.google.com/books?id=CskhAQAAIAAJ&printsec=frontcover#v=onepage&q=%22across%20the%20pond%22&f=false), but nothing before that.
I first saw it myself from Brits when speaking of America. I believe it was probably originally a jokey reference to how easy it was for them to cross large bodies of water, back in the day when their Navy ruled the world's oceans. Now that the US Navy is in that position, I've seen a few of us USAsians using back at the Brits. :-) I've also heard it said (in reference to the Chunnel) that a lot of Brits would rather they were closer to America and further from Europe. A verbal attempt to minimize the rhetorical distance between the two nations would help serve that purpose. I suspect that attitude may have changed a bit in the last decade or so though...
30,295
Why is the phrase [Across the pond](http://en.wiktionary.org/wiki/across_the_pond) used to refer to the opposite side of the Atlantic Ocean? Considering the size of the Atlantic Ocean is vast, is it suggesting the ocean is only a small hindrance? Considering that in the modern world it has become easier to communicate and travel?
2011/06/17
[ "https://english.stackexchange.com/questions/30295", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5693/" ]
The reason phenry couldn't find matches from before 1885 in a Google Books search for "the pond" may have been that in many early references the expression contains a qualifying modifier: "the big pond," "the great pond," "the herring pond," "the salt pond," or some combination of these characterizations. At least one fairly early reference to the Atlantic Ocean as "the big pond" comes up in a Google Books search, from [*Eliza Cook's Journal*](https://books.google.com/books?id=Br8CAAAAIAAJ&pg=PA335&dq=%22across+the+big+pond%22&hl=en&sa=X&ved=0ahUKEwj55NqiqrrPAhUUTmMKHfPuDvUQ6AEILjAD#v=onepage&q=%22across%20the%20big%20pond%22&f=false) (March 20, 1852), a London periodical. The earliest Google Books match for "across the great pond" is even earlier—from a U.S. publication called [Holden's Dollar Magazine](https://books.google.com/books?id=4HtHAAAAYAAJ&pg=PA414&dq=%22across+the+great+pond%22&hl=en&sa=X&ved=0ahUKEwihnImErLrPAhUUTmMKHfPuDvUQ6AEIIzAB#v=onepage&q=%22across%20the%20great%20pond%22&f=false) (July 1849). --- ***Identifying 'the herring pond'*** The earliest and most common variation on "across the pond" in Google Books search results, however, takes the form "across the herring pond." Here are two such examples. From "[Sketches of Society,—No. III](https://books.google.com/books?id=EcxNAQAAMAAJ&pg=RA1-PA1&dq=%22have+been+sent+across+the+herring+pond%22&hl=en&sa=X&ved=0ahUKEwiNsZebtbrPAhUY_WMKHTQYAlMQ6AEIIzAB#v=onepage&q=%22have%20been%20sent%20across%20the%20herring%20pond%22&f=false)," in *La Belle Assemblée: or, Bell's Court and Fashionable Magazine* (July 1824): > > There—those two, now walking off arm-in-arm, are two of the greatest sharpers on the turf. He in the short green jacket, white, hat, buff waistcoat, and cossack trowsers, is Jack Dauntless, who would, not very long since, have been sent **across the herring-pond**, if fortune had not stood his friend, and by means of a flaw in the indictment procured his acquittal of a charge of swindling; ... > > > And from "[Chit Chat](https://books.google.com/books?id=Jow0AQAAMAAJ&pg=PA290&dq=%22been+across+the+herring+pond+once%22&hl=en&sa=X&ved=0ahUKEwjny8rlt7rPAhXHKWMKHV2pBywQ6AEIHjAA#v=onepage&q=%22been%20across%20the%20herring%20pond%20once%22&f=false)," in *The Metropolitan* (August 1833): > > *Mr. Volage.* "Nonsense," said the Doctor, "I mean to say that you're a loose character." —— "D——n," says Jarvey, "bating that I've been **across the herring pond** once, and had a spell at the hulks twice, who can say a word agin my carracter ; for being had up now and then goes for nicks, every gemmen knows that ere. But, my precious eyes! I does'nt think as how you're no gemmen at all!" > > > Both of these instances evidently refer to transportation—the punishment of being sent off to a distant penal colony in Australia or elsewhere as punishment for a crime in England—and by the 1800s few convicts were being sent across the Atlantic. Similar usage appears in instances from [1840](https://books.google.com/books?id=NMdUAAAAYAAJ&pg=PA291&dq=%22across+the+herring+pond%22&hl=en&sa=X&ved=0ahUKEwjCiZLjrLrPAhWFMGMKHUJvB54Q6AEIHjAA#v=onepage&q=%22across%20the%20herring%20pond%22&f=false) and [1841](https://books.google.com/books?id=TcNlAAAAMAAJ&pg=PA215&dq=%22across+the+herring+pond%22&hl=en&sa=X&ved=0ahUKEwjCiZLjrLrPAhWFMGMKHUJvB54Q6AEIJDAB#v=onepage&q=%22across%20the%20herring%20pond%22&f=false), suggesting that this term remained a common slang expression at least into the 1840s. A search for earlier instances of "herring pond" for "the sea" (not further differentiated) finds William Perry, [*The London Guide and Stranger's Safeguard Against Cheats, Swindlers, and Pickpockets That Abound Within the Bills of Mortality; Forming a Picture of London, as Regards Active Life*](https://books.google.com/books?id=rJABAAAAYAAJ&printsec=frontcover&dq=%22London+Guide+and+Stranger%27s+Safeguard%22&hl=en&sa=X&ved=0ahUKEwjzo__61PjNAhUH9GMKHXOVCpsQ6AEIHjAA#v=onepage&q=pond&f=false) (1818) uses the term in passing with regard to a swindler: > > Next in high sounding firm was the Piccadilly bank, Sir Sir John William Thomas Lathrop Murray, Bart. *and Co.* who is now on his journey across "***the herring pond***" for no good. > > > In that book the author identified himself on the title page as "A Gentleman who has made the Police of the Metropolis, an object of enquiry twenty-two years." And Francis Grose, [*A Classical Dictionary of the Vulgar Tongue*](https://books.google.com/books?id=zLAJs0_prpwC&pg=PT129&dq=%22lingo%22&hl=en&sa=X&ei=eAhtU7r1A5ChogTl2IGYBA#v=onepage&q=%22herring%20pond%22&f=false) (1785) has this entry for *herring pond*: > > HERRING POND. The sea; to **cross the herring pond** at the king's expense, to be transported. > > > Earliest of all is this mention in [*The True Anti-Pamela: Or, Memoirs of Mr. James Parry*](https://books.google.com/books?id=ZCs6AAAAcAAJ&pg=PA290&dq=%22over+the+Herring+Pond%22&hl=en&sa=X&ved=0ahUKEwix-PO84PnPAhVJrFQKHU9aDEY4FBDoAQghMAE#v=onepage&q=%22over%20the%20Herring%20Pond%22&f=false), second edition (1742): > > In short I expected nothing less than Transportation ; altho' I had no Way injured any one. Well, thinks I, if I must go **over the Herring Pond**, there is no avoiding it. I have been at Sea, and am not unacquainted with some Part of *America*, so that if I am obliged to quit my native Shore, I'll not be confined to what Province my Adversaries please; but will reach *Carolina*, where I am acquainted. > > > At this early date, the American penal colony at Georgia was indeed a common destination of transported criminals, and appears to be the destination Mr. Parry contemplates for himself, making "the Herring Pond" of this mention (once again) the Atlantic Ocean. In other early use, "the herring-pond" may to refer to smaller bodies of seawater such as the English Channel or the Irish Sea. From a review of "[The Frantic Conduct of John Bull for a Century Past](https://books.google.com/books?id=H2FAAQAAMAAJ&pg=PA101&dq=%22antagonist+across+the+herring-pond%22&hl=en&sa=X&ved=0ahUKEwjw3__2sbrPAhUG3GMKHWyMBMIQ6AEIHjAA#v=onepage&q=%22antagonist%20across%20the%20herring-pond%22&f=false)," in *The Monthly Review* (May 1803): > > Though these doggerel rhimes are often hobbling, vulgar, and ungrammatical, they bear the features of true satire, and prove the author to be gifted with some penetration. If his mode of treating his subject is not quite new, his work certainly is not tedious. Poor John Bull is treated with very little ceremony; and his past conduct, in needlessly pushing his head into quarrels, squandering his money, and entailing debts on his children, is adduced to prove him mad, or 'governed by Old Nick.' On the other hand, his antagonist **across the herring-pond** does not escape castigation, but is represented as having weakly sported with the name of Liberty: > > > > > > > Thy cause, indeed, was like to fail,/ Thou'dst neither ballast, rope, nor sail;/ Drov'st without compass, anchor, helm,/ Thy miscreants delug'd all the realm./ At murder, guillotine, and dagger,/ Thy injur'd friends began to stagger;/ No longer could maintain thy cause,/ When thou had'st thus blasphem'd its laws;/ ... > > > > > > > > > And from [*Fatherless Fanny; or, A Young Lady's First Entrance into Life, Being the Memoirs of a Little Mendicant, and Her Benefactors*](https://books.google.com/books?id=nb4BAAAAQAAJ&pg=PA205&dq=%22little+mendicant,+and+her+benefactors%22&hl=en&sa=X&ved=0ahUKEwj9ornyrbrPAhUJ2GMKHakiA90Q6AEIQzAH#v=onepage&q=herring-pond&f=false) (1811), in which little Fanny, after being abducted, is conveyed by ship from the west coast of England to Ireland: > > "Miss looks terrible well now," exclaimed Franklyn, to one of the other men, "it is only my whimpering wife made her bad before; I wish I had sent her back sooner, we should have been **across the herring-pond** by this time." > > > Eventually "across the herring pond," like other formulations of "across the pond" most often meant "across the Atlantic Ocean"—as it appears to have done in its 1742 instance in *The True Anti-Pamela*. --- ***Early newspaper instances in which 'the pond' = 'the Atlantic Ocean'*** A search of the Library of Congress's Chronicling America database for instances where *across the pond* means "across the ocean" go back to 1837. In the earliest matches, the pond in question is the Atlantic Ocean, but later instances (beginning in 1857) use it in connection with the Pacific Ocean. To show the range of the expression as used in the 1830s 1840s, and 1850s by U.S. newspapers to refer to the Atlantic Ocean, I reproduce examples through the year 1854. From [a letter](http://chroniclingamerica.loc.gov/lccn/sn83030312/1837-07-25/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=5&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4) in the *[New York] Morning Herald* (July 25, 1837): > > A packet had just put her passengers on board of the steamer, and it afforded us infinite gratification to see the wondering faces of the women, and the astonishment of the men, to see so beautiful a spot **across the big pond**, as they call the wide Atlantic. > > > From "[Varieties](http://chroniclingamerica.loc.gov/lccn/sn83030313/1845-06-02/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=18&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4)," in the *New York Herald* (June 2, 1845): > > The editor of the Cincinnati Commercial, who claims to be the inventor of the project for extending Morse's telegraph across the Atlantic, intends at no very distant day, to organize a company to purchase the wire and take other steps to stretch it **across the "big pond."** > > > From the [*St. Landry [Louisiana] Whig*](http://chroniclingamerica.loc.gov/lccn/sn83016702/1845-08-28/ed-1/seq-1/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=7&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4) (August 28, 1845): > > In the prairies here, we can beat the Jews or Gentiles in raising horses, Cattle, Sheep, Hogs, Fowls, Corm, Cotton, Sugar, and even Grapes to make Wine from, or any of those gentlemen **across the "big pond"** who want to make us subservient to their wishes. Keep up the Tariff, sir, and in a few years we will produce every thing the most fastidious taste could desire, and become a perfect world within ourselves! > > > From a [letter to the editor](http://chroniclingamerica.loc.gov/lccn/sn82003410/1846-05-16/ed-1/seq-3/#date1=1846&index=0&rows=20&words=across+big+pond&searchType=basic&sequence=0&state=&date2=1846&proxtext=%22across+a+big+pond%22&y=14&x=15&dateFilterType=yearRange&page=1) dated May 6, 1846, published in the *[Washington, D.C.] Daily Union* (May 16, 1846): > > Before I conclude, allow me to state the case of two shoemakers not far from this. They live in the same street opposite each other; one is a good cutter, has money, buys the best leather at the first hand, employs the best workmen, pays them regularly and promptly, and gets his work done low; consequently he produces a superior article at a moderate price, and as a matter of course takes the bulk of the trade. The other man has no capital, gets his materials on credit at high prices, pays his workmen uncertainly, does not produce as good an article for the same money, and cannot get along. Now, why should not this man have a bill passed to protect him? The manufacturers get bills passed to protect them against English manufacturers; and the only difference is that they are **across a big pond**, and the shoemakers across the street; for we are all brothers. > > > From "[New York Correspondence of the Crescent](http://chroniclingamerica.loc.gov/lccn/sn82015378/1848-06-10/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=2&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=6)," in the *[New Orleans, Louisiana] Daily Crescent* (June 10, 1848): > > E. K. Collins is going ahead with his large ocean steamers, for which he has selected the names: "Palo Alto," "Buena Vista," "Cerro Gordo," and Contreras." We have already five or six ocean steamers plying from this city [New York City] **across the "big pond."** > > > From the [*Evansville [Indiana] Daily Journal*](http://chroniclingamerica.loc.gov/lccn/sn82015672/1848-06-24/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=4&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4) (June 24, 1848): > > It is stated that the new British steamship Niagara made the first half of her passage across the Atlantic, within sixty or seventy mi[l]es, in four days. Tremendous westerly winds impeded her progress for the next *four days*, or she would have made the quickest passage **across the great pond** ever heard of. > > > From "[Another Holy Alliance](http://chroniclingamerica.loc.gov/lccn/sn86053240/1849-06-20/ed-1/seq-3/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=8&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4)," in the *[Sumterville, South Carolina] Sumter Banner* (June 20, 1849): > > England can protest, but can afford to do no more.---Russia and Austria, with a million of soldiers, will give the law to Europe. Every arrival from **across the "big herring pond"** increases the interest of the news it conveys. > > > From a [letter to the editor](http://chroniclingamerica.loc.gov/lccn/sn82003410/1850-11-23/ed-1/seq-3/#date1=1789&sort=relevance&rows=20&words=across+Pond&searchType=basic&sequence=0&index=3&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=6) dated November 18, 1850, of the *[Washington, D.C.] Daily Union* (November 23, 1850): > > But Mr. Garrison is probably not satisfied with his [anti-slavery] force here: he sends **across the "Big Pond,"** and brings over to his aid the celebrated George Thompson, a Britisher, who, on his former visit to his bosom friend, came very near o getting an extra red coat, and escaped to the British provinces with an extra cup of tea. > > > From "[Shortest Passage Ever Made Across the Atlantic](http://chroniclingamerica.loc.gov/lccn/sn85026203/1851-05-05/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+Pond&searchType=basic&sequence=0&index=3&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4)," in the *Portsmouth [Ohio] Inquirer* (May 5, 1851): > > The American Republican Mail Steamship "Pacific" arrived in port on Saturday at 10 A. M., after a passage of 9 days and 20 hours from Liverpool, the shortest on record. The Pacific has made the two shortest passages ever made **across the Big Pond**. > > > From "[The Release of Kossuth](http://chroniclingamerica.loc.gov/lccn/sn83030313/1851-10-04/ed-1/seq-1/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=12&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=6)," in the *New York Herald* (October 4, 1851): > > She [the steamship *Mississippi*] now lies snugly at anchor in the Golden Horn, much admired and visited by all classes of people—Moslem, Christian, and Jew—and busily engaged preparing for her long journey **across the "great pond."** > > > From "[The New Primer](http://chroniclingamerica.loc.gov/lccn/sn83045784/1851-10-18/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=16&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=2)," in the *[Washington, D.C.] National Intelligencer* (October 18, 1851): > > It will be seen by the following paragraph from the "European Times" that this invention [of the Maynard primer as a replacement for the percussion cap in firearms] is attracting some notice **across the *pond***: [quotation from the European newspaper omitted]. > > > From "[American Example Abroad](http://chroniclingamerica.loc.gov/lccn/sn84024738/1852-04-12/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=3&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=5)," in the *[Richmond, Virginia] Daily Dispatch* (April 12, 1852): > > There was a grand debate in the British House of Commons on the 26th March, relative to the extension of the right of suffrage.—From this debate which is too long for publication in this paper, it is evident that, in spite of themselves, republican ideas are advancing very rapidly with our cousins **across the herring pond**. > > > From "[The Address of the Ladies of England](http://chroniclingamerica.loc.gov/lccn/sn86071377/1852-12-30/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=6&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=4)," in the *[Ebensburg, Pennsylvania] Mountain Sentinel* (December 30, 1852): > > These ["*quasi* benevolent"] ladies [of England] need not look **across the "big pond"** to rescue shattered constitutions and broken-hearts from bondage > > > From a [letter by "Hopeful"](http://chroniclingamerica.loc.gov/lccn/sn83035172/1853-06-08/ed-1/seq-3/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=12&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=2) from Washington, D.C., dated May 26, 1853, in the *[Ashland] Ohio Union* (June 8, 1853): > > "To be or not to be" *has been*, the question; but the President has pretty effectually settled it, by giving to "his flock" the results of his labors in relation to "Foreign Appointments." The city has been full of applicants, for places abroad, but, all at once, "a change comes over the spirit of their dreams" and they "*mizzled*." One prominent gentleman who had been here for ten weeks pressing claims for a place at the "Lobos Islands," or some other "fertile spot" **across the pond**, left in such a hurry as to entirely overlook his night shirt, which was under his pillow. > > > From "[When Newspapers Please](http://chroniclingamerica.loc.gov/lccn/sn84022366/1853-06-18/ed-1/seq-1/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=5&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=6)," in the *Rutland [Vermont] County Herald* (June 18, 1853): > > The London Leader—one of the most piquant journals that reach us from **across the great "herring pond"**—thus felicitously explains the secret of newspaper popularity: [quotstion omitted. > > > From "[A Traveller](http://chroniclingamerica.loc.gov/lccn/sn83045450/1853-09-03/ed-1/seq-3/#date1=1789&sort=relevance&rows=20&words=Across+pond&searchType=basic&sequence=0&index=16&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=5)," in the *[Raleigh, North Carolina] Weekly North Carolina Standard* (September 3, 1853): > > I have visited every great curiosity, nearly every state capital, and every State in the Union, except California and Texas. **Across the "herring pond"** I travelled through almost every kingdom, and saw nearly every crowned head in Europe; wandered over the highlands of Scotland, stoned the cormorants in Fingal's Cave, shot sea gulls in Shetland, eat plovers and other wild birds in Iceland, cooked my dinner in the geysers, cooled my punch with the snows of Mt. Hekla, and toasted my shins at the burning crater on its summit. > > > From "[Changing the Fashions](http://chroniclingamerica.loc.gov/lccn/sn84024738/1854-11-24/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=17&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=5)," in the *[Richmond, Virginia] Daily Dispatch* {November 24, 1854): > > In this country, where the ladies are worshipped as something superior, men never think of asking them to perform menial offices, or to do anything inconsistent with their delicate, angelic natures. Not so with some of our neighbors who hail from **across the big salt pond**, if we are to judge from what is frequently seen in our city. > > > --- ***Early instances where 'the pond' = 'the Pacific'*** From "[Where do the days Die?](http://chroniclingamerica.loc.gov/lccn/sn84023127/1857-04-17/ed-1/seq-1/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=11&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=3)" in the *Burlington [Vermont] Free Press* (April 17, 1857): > > The shipmaster who does not make this rectification, always finds his reckoning a day in advance of or a day behind that of the port he sails to : for when it is Monday afternoon at San Francisco it is Tuesday afternoon **across the pond** at Canton [China]. > > > The [*[Honolulu, Hawaii] Polynesian*](http://chroniclingamerica.loc.gov/lccn/sn82015408/1858-04-24/ed-1/seq-5/#date1=1789&index=1&rows=20&words=across+pond&searchType=basic&sequence=0&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=1) (April 24, 1858) quotes an editorial comment from *San Francisco Prices Current* to the effect that the U.S. government should ensure that U.S. commerce with the Hawaiian Kingdom of the Sandwich Islands not be "interrupted" by competition from European nations (in particular France, which was known to be negotiating a trade deal with Hawaii), and then the *Polynesian* comments as follows: > > How the French treaty does trouble our neighbor **across the pond**! Do they not know that any privilege which the French, or any of "the most favored nation" may have obtained, will by their own treaty be granted to them? And do they for a moment suppose that the U.S. Commissioner is not better posted on these subjects than any "on dits" of San Francisco? > > > From "[H. R. H. Prince Kamehameha](http://chroniclingamerica.loc.gov/lccn/sn82015408/1860-08-18/ed-1/seq-3/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=10&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=2)," in the *[Honolulu, Hawaii] Polynesian* (August 18, 1860): > > We know that it will afford our readers as much pleasure to learn, as it gives us to inform them, that H. R. H. Prince Kamehameha, has now so far recovered from his late severe sickness as to be able to take some gentle exercise on horseback during the morning hours. We learn further that, upon the advice of the physicians, the Prince has concluded to try a trip to Victoria, V[ancouver] I[sland], perhaps California, and the effects of a sea voyage and change of climate, in order fully to re-establish his health. > > > That the prayers and best wishes of every inhabitant of this land go with him. we need not assure him, and that the kindliest reception awaits him **across the pond**, we are equally certain. The Prince takes passage on board the clipper schooner *Emma Rooke* for Victoria, V. I., and will leave about the 28th inst. > > > From "[Interesting from Japan](http://chroniclingamerica.loc.gov/lccn/sn84026547/1860-10-02/ed-1/seq-2/#date1=1789&sort=relevance&rows=20&words=across+pond&searchType=basic&sequence=0&index=6&state=&date2=1860&proxtext=%22across+the+pond%22&y=13&x=16&dateFilterType=yearRange&page=3)," in the *Newbern [North Carolina] Weekly Progress* (October 2, 1860): > > We make the following extracts, says the Washington States, of a letter dated Yokohama, Japan, July 18th, and which we find in the [San Francisco] Alta Californian: > > > The Japanese steam Candinmarrah, which left this port last February, ... conveying the intelligence of the departure of the Japanese Ambassadors to America, arrived here from Honolulu, after a passage of eighteen days. From the Americans who came in her, we learned that the Japanese conducted themselves admirably on board, taking the position of the vessel daily by the sun, and brought her, in seamanlike manner, into this bay without accident. > > > The appearance of the Japanese steamer, from America, with news from the Ambassadors, created a great excitement both amongst the Americans and Japanese. The foreigners were anxious to hear how the Japanese had been received in America, and the Japanese were fearful lest the Ambassadors would not survive the great trip **across the pond**. However, all doubts were dispelled when the great mail was distributed. > > > --- ***Conclusions*** The earliest instance that my Chronicling America search yielded for the unadorned expression "across the pond" for "across the Atlantic Ocean" is from a Washington, D.C. newspaper article published in October 1851. But use of "the herring pond" for "the Atlantic Ocean" or generically for "the sea" or for one or another smaller specific seas goes back much farther. The earliest match I've been able to find for "the herring pond" as a slang expression for "Atlantic Ocean" is from the second edition of *The True Anti-Pamela*, published in 1742 (the first edition appeared a year earlier, but I haven't found a searchable copy of it online).
Put quite simply, "the Pond" is an expression of the relationship that exists, still to this day, between the United States of America and Great Britain. It's a linguistic way of reducing the 3000 miles that physically exist between our two countries and recognising how much we actually have in common. By far and away the most common language spoken in the United States is English. Ask yourself why that is and look it up in the history books!
30,295
Why is the phrase [Across the pond](http://en.wiktionary.org/wiki/across_the_pond) used to refer to the opposite side of the Atlantic Ocean? Considering the size of the Atlantic Ocean is vast, is it suggesting the ocean is only a small hindrance? Considering that in the modern world it has become easier to communicate and travel?
2011/06/17
[ "https://english.stackexchange.com/questions/30295", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5693/" ]
I feel that the aspect "the world is smaller now" is really not that relevant: indeed, the phrase is far too old for that to be the case. Rather, it's a perfect example of typical understated, dry, English humour. I'm afraid I don't know about earliest usage although PHenry mentioned it could have been used as early as the 1800s. In that era, the "Sun never set on the British empire." Britain was the biggest-ever world empire: indeed, that was largely based on naval power. So in the 1800s, you can see that because of extreme British naval power - combined with the typical British gift for understatement - it would be natural to refer to the Atlantic as merely a silly *pond*. Note: as John below points out, this phrase is certainly used in both the USA and in the UK. (It's used on both sides of the pond.) It originated in the UK: I would suggest in the USA the phrase is used mainly on the East Coast (New York City and so on). The phrase is dropping out of use in the UK, so it sounds a hair archaic. Indeed, generally the idea of being a "witty understated Englishman" is something that belongs more to older people there; the yoof have Snapchat.
I first saw it myself from Brits when speaking of America. I believe it was probably originally a jokey reference to how easy it was for them to cross large bodies of water, back in the day when their Navy ruled the world's oceans. Now that the US Navy is in that position, I've seen a few of us USAsians using back at the Brits. :-) I've also heard it said (in reference to the Chunnel) that a lot of Brits would rather they were closer to America and further from Europe. A verbal attempt to minimize the rhetorical distance between the two nations would help serve that purpose. I suspect that attitude may have changed a bit in the last decade or so though...
30,295
Why is the phrase [Across the pond](http://en.wiktionary.org/wiki/across_the_pond) used to refer to the opposite side of the Atlantic Ocean? Considering the size of the Atlantic Ocean is vast, is it suggesting the ocean is only a small hindrance? Considering that in the modern world it has become easier to communicate and travel?
2011/06/17
[ "https://english.stackexchange.com/questions/30295", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5693/" ]
It's a humorous understatement, like calling the United States "the colonies." The expression seems to have come into being in the late 19th century. On Google Books I find [a use of it from 1885](http://books.google.com/books?id=CskhAQAAIAAJ&printsec=frontcover#v=onepage&q=%22across%20the%20pond%22&f=false), but nothing before that.
Put quite simply, "the Pond" is an expression of the relationship that exists, still to this day, between the United States of America and Great Britain. It's a linguistic way of reducing the 3000 miles that physically exist between our two countries and recognising how much we actually have in common. By far and away the most common language spoken in the United States is English. Ask yourself why that is and look it up in the history books!
30,295
Why is the phrase [Across the pond](http://en.wiktionary.org/wiki/across_the_pond) used to refer to the opposite side of the Atlantic Ocean? Considering the size of the Atlantic Ocean is vast, is it suggesting the ocean is only a small hindrance? Considering that in the modern world it has become easier to communicate and travel?
2011/06/17
[ "https://english.stackexchange.com/questions/30295", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5693/" ]
I feel that the aspect "the world is smaller now" is really not that relevant: indeed, the phrase is far too old for that to be the case. Rather, it's a perfect example of typical understated, dry, English humour. I'm afraid I don't know about earliest usage although PHenry mentioned it could have been used as early as the 1800s. In that era, the "Sun never set on the British empire." Britain was the biggest-ever world empire: indeed, that was largely based on naval power. So in the 1800s, you can see that because of extreme British naval power - combined with the typical British gift for understatement - it would be natural to refer to the Atlantic as merely a silly *pond*. Note: as John below points out, this phrase is certainly used in both the USA and in the UK. (It's used on both sides of the pond.) It originated in the UK: I would suggest in the USA the phrase is used mainly on the East Coast (New York City and so on). The phrase is dropping out of use in the UK, so it sounds a hair archaic. Indeed, generally the idea of being a "witty understated Englishman" is something that belongs more to older people there; the yoof have Snapchat.
As an aviator, we refer to the Pacific as the "pond" and the Atlantic as the "puddle". A girlfriend of mine, most recently a captain on American Eagle, now retired, used to ferry planes across the Pacific, aka the pond, to NZ or Aus from California and she also ferried quite a few across the puddle from California to the UK. You can see how the names are so apt. Every time I see "pond" applied to the Atlantic, I cringe.
30,295
Why is the phrase [Across the pond](http://en.wiktionary.org/wiki/across_the_pond) used to refer to the opposite side of the Atlantic Ocean? Considering the size of the Atlantic Ocean is vast, is it suggesting the ocean is only a small hindrance? Considering that in the modern world it has become easier to communicate and travel?
2011/06/17
[ "https://english.stackexchange.com/questions/30295", "https://english.stackexchange.com", "https://english.stackexchange.com/users/5693/" ]
I first saw it myself from Brits when speaking of America. I believe it was probably originally a jokey reference to how easy it was for them to cross large bodies of water, back in the day when their Navy ruled the world's oceans. Now that the US Navy is in that position, I've seen a few of us USAsians using back at the Brits. :-) I've also heard it said (in reference to the Chunnel) that a lot of Brits would rather they were closer to America and further from Europe. A verbal attempt to minimize the rhetorical distance between the two nations would help serve that purpose. I suspect that attitude may have changed a bit in the last decade or so though...
As an aviator, we refer to the Pacific as the "pond" and the Atlantic as the "puddle". A girlfriend of mine, most recently a captain on American Eagle, now retired, used to ferry planes across the Pacific, aka the pond, to NZ or Aus from California and she also ferried quite a few across the puddle from California to the UK. You can see how the names are so apt. Every time I see "pond" applied to the Atlantic, I cringe.
45,343,814
Hi I am developing print functionality in angularjs. I followed [this](http://jsfiddle.net/95ezN/121/). I have one button and clicking on that i want to take print. For example i want to print below content. ``` <div id="printThis" > This should BE printed! <div class="modifyMe">old</div> </div> ``` The problem I'm facing is I do not want to display `printThis` in web page. Practically I am having page with i am binding values through scope variable. If i hide that div using bg-show or any other ways i am getting blank in print preview! So may i get some help to fix this? I am planning to implement the way it is implemented [here](https://www.rayafinancing.com/Calculator.aspx). Any help would be appreciated. Thank you.
2017/07/27
[ "https://Stackoverflow.com/questions/45343814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4542527/" ]
You can either use Bootstrap class **.hidden-print** to hide div from print or you can use following css code: ``` @media print { .no-print, .no-print * { display: none !important; } } ``` You have to use **.no-print** class to div which you want to hide.
this is complete solution(snippet will not work here because i think SO doesn't allow to open popup windows from snippet): ```js var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.printDiv = function(divName) { var printContents = document.getElementById(divName).innerHTML; var popupWin = window.open('', 'Print', 'height=600,width=1200'); popupWin.document.open(); popupWin.document.write('<html><head><title>ATLAS SEARCH</title></head><body class="print-screen" onload="window.print()"><table width="100%"><tr><td>&nbsp;</td></tr></table>' + printContents + '</body></html>'); popupWin.document.close(); } }); ``` ```css @media print { .print-btn { display: none ; } } ``` ```html <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <body> <div ng-app="myApp" ng-controller="myCtrl"> <div id="printThis" > This should BE printed! <div class="modifyMe">old</div> </div> <a class="print-btn btn btn-success" ng-click="printDiv()">Print</a> </div> ```
45,343,814
Hi I am developing print functionality in angularjs. I followed [this](http://jsfiddle.net/95ezN/121/). I have one button and clicking on that i want to take print. For example i want to print below content. ``` <div id="printThis" > This should BE printed! <div class="modifyMe">old</div> </div> ``` The problem I'm facing is I do not want to display `printThis` in web page. Practically I am having page with i am binding values through scope variable. If i hide that div using bg-show or any other ways i am getting blank in print preview! So may i get some help to fix this? I am planning to implement the way it is implemented [here](https://www.rayafinancing.com/Calculator.aspx). Any help would be appreciated. Thank you.
2017/07/27
[ "https://Stackoverflow.com/questions/45343814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4542527/" ]
You can use `ng-click` to toggle like this ``` <div id="printThis" ng-if="showPrint" ng-init="showPrint=false"> This should BE printed! <div class="modifyMe">old</div> </div> <button type="button" ng-click="showPrint=!showPrint"></button> ``` If you don't want to use angular, try this **HTML** ``` <div class="hiddenVal"> This should NOT be printed! <button id="btnPrint">Print (this button should also be NOT be printed)!</button> </div> ``` **CSS** ``` @media screen { .hiddenVal { display: none !important; } } ``` **Working Demo** :<http://jsfiddle.net/95ezN/1659/>
this is complete solution(snippet will not work here because i think SO doesn't allow to open popup windows from snippet): ```js var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.printDiv = function(divName) { var printContents = document.getElementById(divName).innerHTML; var popupWin = window.open('', 'Print', 'height=600,width=1200'); popupWin.document.open(); popupWin.document.write('<html><head><title>ATLAS SEARCH</title></head><body class="print-screen" onload="window.print()"><table width="100%"><tr><td>&nbsp;</td></tr></table>' + printContents + '</body></html>'); popupWin.document.close(); } }); ``` ```css @media print { .print-btn { display: none ; } } ``` ```html <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <body> <div ng-app="myApp" ng-controller="myCtrl"> <div id="printThis" > This should BE printed! <div class="modifyMe">old</div> </div> <a class="print-btn btn btn-success" ng-click="printDiv()">Print</a> </div> ```
297,061
Usually we say that the partition function of CFTs on a torus is modular invariant, because we define theory on a torus. If I have a non-conformal field the theory on a torus, is its partition function still modular invariant?
2016/12/07
[ "https://physics.stackexchange.com/questions/297061", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/45232/" ]
No, a generic theory on a torus is not modular invariant. A conformal field theory cannot depend on the metric of the space it is defined on but only on its conformal equivalence class. It is a fact that the space of such classes for the torus is given by a complex parameter $\tau$, the (conformal) modulus, defining the lattice we quotient out of $\mathbb{R}^2$ to get the 2-torus: The basic lattice vectors are $(1,0)$ and the vector in the plane corresponding to the complex number $\tau$, i.e. $\tau$ is the "ratio" between the two fundamental circles on the torus. If we did not have conformal invariance of the theory we would not be allowed to identify the lattice given by $(1,0)$ and $\tau$ with the lattice given by $(2,0)$ and $2\tau$ because while related by a rescaling the area of these parallelograms and hence the resulting torus is different, so we would not have only this one parameter $\tau$ describing the relevant torus structure. The modular group $\mathrm{PSL}(2,\mathbb{Z})$ sends $\tau$ to values that are equivalent in the sense that they define the same lattice after rescaling one of the basis vectors to $(1,0)$ as allowed by conformal invariance, and so the partition functions, as a function of $\tau$, must be modular invariant since $\tau$ related by modular transformation define tori with the same conformal equivalence class.
Let $T = \mathbb{C}/\left( {\mathbb{Z} \oplus \tau \mathbb{Z}} \right)$. This torus is conformally equivalent to any torus $T' = \mathbb{C}/\left( {\mathbb{Z} \oplus \tau '\mathbb{Z}} \right)$ with $\tau ' = \frac{{a\tau + b}}{{c\tau + \operatorname{d} }}$ such that a,b,c,d integral and $\left| {\begin{array}{\*{20}{c}} a&b \\ c&\operatorname{d} \end{array}} \right| = 1$. This is a modular transformation. We you take a partition function in a 2D CFT like you would see in String Theory, you are integrating over the moduli space of conformally inequivalent Riemann surfaces. So it is important that your Partition function has modular invariance so it does not distinguish between tori which are conformally equivalent. If you are working with a QFT which is not conformal, then this argument is not really relevant.
42,441,914
I'm working with files with this format: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22491.xml;spectrum=1074 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=2950 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22493.xml;spectrum=473 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22493.xml;spectrum=473 true ``` As you can see, every SPEC line is different, except two where number of the string spectrum is repeated. What I'd like to do is take every chunk of information between the pattern `=Cluster=` and check if there are lines with spectrum value repeated. In case there are several lines repeated, removes all of them except one. The output file should be like this: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22491.xml;spectrum=1074 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=2950 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22493.xml;spectrum=473 true ``` I was using `groupby` from itertools module. I assume my input file is called f\_input.txt and the output file is called new\_file.txt, but this script remove the words SPEC as well... And I don't know what I can change in order to don't do this. ``` from itertools import groupby data = (k.rstrip().split("=Cluster=") for k in open("f_input.txt", 'r')) final = list(k for k,_ in groupby(list(data))) with open("new_file.txt", 'a') as f: for k in final: if k == ['','']: f.write("=Cluster=\n") elif k == ['']: f.write("\n\n") else: f.write("{}\n".join(k)) ``` EDIT: New conditional. Sometimes part of the line number can change, for example: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true SPEC PRD000682;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true ``` As you can see, the last line has changed the part PRDnumber. One solution would be check the spectrum number, and remove the line based in repeated spectrum. This would be a solution: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true ```
2017/02/24
[ "https://Stackoverflow.com/questions/42441914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5794310/" ]
This will open your file containing your original code as well as a new file that will output the unique lines per group. `seen` is a `set` and is great for seeing if something exists within it already. `data` is a `list` and will keep track of the iterations of `"=Cluster="` groups. Then you simply review each line of each of the groups (designated as `i` within `data`). If the line does not exist within `seen` it is added. ``` with open ("input file", 'r') as in_file, open("output file", 'w') as out_file: data = [k.rstrip().split("=Cluster=") for k in in_file] for i in data: seen = set() for line in i: if line in seen: continue seen.add(line) out_file.write(line) ``` **EDIT**: Moved `seen=set()` to within the `for i in data` to reset the set each time otherwise `"=Cluster="` would always exist and would not print for each group within `data`.
The solution using [***re.search()***](https://docs.python.org/3/library/re.html#re.search) function and custom `spectrums` set object for keeping only unique `spectrum` numbers: ``` with open('f_input.txt') as oldfile, open('new_file.txt', 'w') as newfile: spectrums = set() for line in oldfile: if '=Cluster=' in line or not line.strip(): newfile.write(line) else: m = re.search(r'spectrum=(\d+)', line) spectrum = m.group(1) if spectrum not in spectrums: spectrums.add(spectrum) newfile.write(line) ```
42,441,914
I'm working with files with this format: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22491.xml;spectrum=1074 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=2950 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22493.xml;spectrum=473 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22493.xml;spectrum=473 true ``` As you can see, every SPEC line is different, except two where number of the string spectrum is repeated. What I'd like to do is take every chunk of information between the pattern `=Cluster=` and check if there are lines with spectrum value repeated. In case there are several lines repeated, removes all of them except one. The output file should be like this: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22491.xml;spectrum=1074 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=2950 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22493.xml;spectrum=473 true ``` I was using `groupby` from itertools module. I assume my input file is called f\_input.txt and the output file is called new\_file.txt, but this script remove the words SPEC as well... And I don't know what I can change in order to don't do this. ``` from itertools import groupby data = (k.rstrip().split("=Cluster=") for k in open("f_input.txt", 'r')) final = list(k for k,_ in groupby(list(data))) with open("new_file.txt", 'a') as f: for k in final: if k == ['','']: f.write("=Cluster=\n") elif k == ['']: f.write("\n\n") else: f.write("{}\n".join(k)) ``` EDIT: New conditional. Sometimes part of the line number can change, for example: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true SPEC PRD000682;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true ``` As you can see, the last line has changed the part PRDnumber. One solution would be check the spectrum number, and remove the line based in repeated spectrum. This would be a solution: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true ```
2017/02/24
[ "https://Stackoverflow.com/questions/42441914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5794310/" ]
This is how I would do it. ``` file_in = r'someFile.txt' file_out = r'someOtherFile.txt' with open(file_in, 'r') as f_in, open(file_out, 'w') as f_out: seen_spectra = set() for line in f_in: if '=Cluster=' in line or line.strip() == '': seen_spectra = set() f_out.write(line) else: new_spectrum = line.rstrip().split('=')[-1].split()[0] if new_spectrum in seen_spectra: continue else: f_out.write(line) seen_spectra.add(new_spectrum) ``` This is not a `groupby` solution but a solution that you can easily follow and debug if you have to. As you mentioned in the comments, this file of yours is 16GB big and loading it to memory is probably not the best idea.. > > EDIT: *"Each cluster has a specific spectrum. It is not possible to have one spec in one cluster and the same in another"* > > > ``` file_in = r'someFile.txt' file_out = r'someOtherFile.txt' with open(file_in, 'r') as f_in, open(file_out, 'w') as f_out: seen_spectra = set() for line in f_in: if line.startswith('SPEC'): new_spectrum = line.rstrip().split('=')[-1].split()[0] if spectrum in seen_spectra: continue else: seen_spectra.add(new_spectrum) f_out.write(line) else: f_out.write(line) ```
The solution using [***re.search()***](https://docs.python.org/3/library/re.html#re.search) function and custom `spectrums` set object for keeping only unique `spectrum` numbers: ``` with open('f_input.txt') as oldfile, open('new_file.txt', 'w') as newfile: spectrums = set() for line in oldfile: if '=Cluster=' in line or not line.strip(): newfile.write(line) else: m = re.search(r'spectrum=(\d+)', line) spectrum = m.group(1) if spectrum not in spectrums: spectrums.add(spectrum) newfile.write(line) ```
42,441,914
I'm working with files with this format: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22491.xml;spectrum=1074 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=2950 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22493.xml;spectrum=473 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22493.xml;spectrum=473 true ``` As you can see, every SPEC line is different, except two where number of the string spectrum is repeated. What I'd like to do is take every chunk of information between the pattern `=Cluster=` and check if there are lines with spectrum value repeated. In case there are several lines repeated, removes all of them except one. The output file should be like this: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22491.xml;spectrum=1074 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=2950 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22493.xml;spectrum=473 true ``` I was using `groupby` from itertools module. I assume my input file is called f\_input.txt and the output file is called new\_file.txt, but this script remove the words SPEC as well... And I don't know what I can change in order to don't do this. ``` from itertools import groupby data = (k.rstrip().split("=Cluster=") for k in open("f_input.txt", 'r')) final = list(k for k,_ in groupby(list(data))) with open("new_file.txt", 'a') as f: for k in final: if k == ['','']: f.write("=Cluster=\n") elif k == ['']: f.write("\n\n") else: f.write("{}\n".join(k)) ``` EDIT: New conditional. Sometimes part of the line number can change, for example: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true SPEC PRD000682;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true ``` As you can see, the last line has changed the part PRDnumber. One solution would be check the spectrum number, and remove the line based in repeated spectrum. This would be a solution: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true ```
2017/02/24
[ "https://Stackoverflow.com/questions/42441914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5794310/" ]
Shortest solution in Python :p ``` import os os.system("""awk 'line != $0; { line = $0 }' originalfile.txt > dedup.txt""") ``` output: ``` =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22491.xml;spectrum=1074 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=2950 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true =Cluster= SPEC PRD000681;PRIDE_Exp_Complete_Ac_22493.xml;spectrum=473 true ``` (if you are on Windows, awk can be installed easily with [Gow](https://github.com/bmatzelle/gow/wiki).)
The solution using [***re.search()***](https://docs.python.org/3/library/re.html#re.search) function and custom `spectrums` set object for keeping only unique `spectrum` numbers: ``` with open('f_input.txt') as oldfile, open('new_file.txt', 'w') as newfile: spectrums = set() for line in oldfile: if '=Cluster=' in line or not line.strip(): newfile.write(line) else: m = re.search(r'spectrum=(\d+)', line) spectrum = m.group(1) if spectrum not in spectrums: spectrums.add(spectrum) newfile.write(line) ```
50,194,629
javascript newbie here again. I don't need to know *how* to do something, I just need help *understanding* something. I just completed a coding challenge in a beginner book I am reading that asks you to make a game in which the user has to search for the "buried treasure" on a treasure map. The game calculates the distance of each click from the randomly chosen location of the "treasure" and displays a different hotter/colder message until the player wins. What I do not understand is why all the functions that I define outside the click event handler function need to be saved as new variables inside the event handler function. This totally confuses me. Why can't I just call those functions? See my entire script below: ``` <script src="https://code.jquery.com/jquery-2.1.0.js"></script> <script type="text/javascript"> //This function returns a random number that will be used as an argument to determine random coordinates for the location of the buried treasure. var randomNumber = function (size) { return Math.floor(Math.random()*size); } //Variables used as arguments for the randomNumber function. var width = 400; var height = 400; //Click counter variable. var clicks = 0; //Object representing the location of the buried treasure on the map. var target = { x: randomNumber(width), y: randomNumber(height) } /* This function takes the event object and the buried treasure location object and uses the Pythagorean theorem to determine a straight line between the click event and the treasure location. Locations on the page and events on the page are always objects, never simple variables containing a string or integer. */ var getDistance = function (event, target) { var diffX = event.offsetX - target.x; var diffY = event.offsetY - target.y; return Math.sqrt((diffX*diffX) + (diffY*diffY)); } //This function takes distance as an argument and returns a message to the user depending on how far from the treasure location their click is. var hints = function (distance) { if (distance < 10) { return "Red hot!"; } else if (distance < 20) { return "Very hot!"; } else if (distance < 40) { return "Hot"; } else if (distance < 80) { return "Warm"; } else if (distance < 160) { return "Cold"; } else if (distance < 300) { return "Very cold!"; } else { return "Ice cold! Brrrr"; } } //Click handler function. $("#map").click(function () { clicks++; /* If you simply call the functions defined outside of the click handler function, the program will not run correctly. Instead, the functions defined outside of the click handler function must be saved in new variables and those variables used in the place of the functions in order for the program to execute properly. This is what confuses me. */ var distance = getDistance(event, target); var distanceHint = hints(distance); $("#hints").text(distanceHint); if (distance < 9) { alert("Treasure found in " + clicks + " clicks!"); } }); </script> ``` As you can see, the `getDistance` function and the `hints` function are saved in new variables inside the event handler. If I tried to simply call those functions inside the event handler without saving them to new variables first, the game would not work as intended. The same if I defined those functions inside the event handler and then called them. Could someone help me understand why this is the case? Many, many thanks.
2018/05/05
[ "https://Stackoverflow.com/questions/50194629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9616976/" ]
You aren't assigning the function to the variable inside the event handler....you are assigning what the call of that function ***returns***. In the case of the function reference assigned to variable `getDistance` when you call that function and pass in an `event` and a `target` it *returns* a calculated number. It is that calcualted number you are assigning to variable named `distance` to use elsewhere
The variables `distance` and `distanceHint` are saved or to be more specific, assigned inside the event handler, not `getDistance` and `hints`. In the following, `distance` and `distanceHint` are the new variables here and the following simply means their values are assigned to `getDistance`'s and `hints`'s value and whenever the values of `getDistance` and `hints` are updated, they pass down the values to the `distance` and `distanceHint` variables respectively. ``` var distance = getDistance(event, target); // if getDistance(event, target) = ABC, then distance is now also equal to ABC var distanceHint = hints(distance);// if hints(distance) = XYZ, then distanceHint is now also equal to XYZ ```
71,439,776
I have a function that takes a vector ``` function foo(x::Vector{Int64}) x end ``` How can I make it work also for scalars (i.e. turn them into one-element vectors)? I know that I can do this: ``` foo(x::Int64) = foo([x]) ``` but this stops being cool when there are more arguments, because you're writing multiple methods to achieve only one thing. I think I something like `foo(x::Union{Int64, Vector{Int64}})`, but I don't know where or how it works or if it is the right thing to do. Can anyone help?
2022/03/11
[ "https://Stackoverflow.com/questions/71439776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7210250/" ]
You can assign new title to the document like this: ``` document.getElementById("titleSumbitBtn").onclick = function (){ var newTitle = document.getElementById("newTitle").value; document.title = newTitle; } ``` This is actual implementation but keep in mind that it must run after the DOM element with id `newTitle`. If you put your `<script>` tag inside `<head>`, you'll need `DOMContentLoaded`: ``` document.addEventListener('DOMContentLoaded', () => { document.getElementById("titleSumbitBtn").onclick = function (){ var newTitle = document.getElementById("newTitle").value; document.title = newTitle; } }) ```
try this: ``` document.getElementById("titleSumbitBtn").addEventListener("click", function (){ var newTitle = document.getElementById("newTitle").value; document.getElementById("title").innerText = newTitle; ``` })
52,318,615
In my Spring Boot web app, there is an HTML form, which populates a `Blueprint` object: ``` data class Blueprint( // relevant part, validation omitted var items: List<Long> = emptyList() // List of ids // ... ) ``` Later on, I intend to use this `Blueprint` to create a `Product`, which would be a data class of similar structure: ``` data class Product( val items: List<Item> /* Here 'items' is a list of Item objects which are fetched from DB by */ /* their ids. Item is data class too. */ ) ``` I would like `Product` to take a `Blueprint` object as a constructor argument. I tried to go with secondary constructor, but it requires me to call primary constructor right away, before I have a chance to process blueprint and possibly filter out some item ids. There are of course workarounds, such as a factory function, but it seems reasonable to expect that I can just pass a blueprint to a constructor. Is there a way to do that?
2018/09/13
[ "https://Stackoverflow.com/questions/52318615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8041935/" ]
Try using a Handler().postDelayed() like below - ``` new Handler().postDelayed(new Runnable() { @Override public void run() { //hide progressbar onBackPressed(); } }, 5000); ```
onBackPressed() should be called from the UI Thread. What Darshan has suggested is the correct answer. When you want to update UI from a background thread (in this case the thread that waits for your timer to finish) you should use Handler. In place of the thread, replace ``` new Handler().postDelayed(new Runnable() { @Override public void run() { //Do your work here } }, /*Delay in miliseconds*/ ); ```
60,044,584
On [FreeBSD](https://www.freebsd.org/), I need `NODE_ENV=production` and other systemwide environment variables to be set on startup, before nginx fires up. Which is the right place i.e. file I do that?
2020/02/03
[ "https://Stackoverflow.com/questions/60044584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/716568/" ]
One option could be to add your environment variables to `/etc/login.conf` in the `setenv` capability, for example: ``` default:\ :passwd_format=sha512:\ :copyright=/etc/COPYRIGHT:\ :welcome=/etc/motd:\ :setenv=MAIL=/var/mail/$,BLOCKSIZE=K,NODE_ENV=production:\ ... ``` From the [login.conf](https://www.freebsd.org/cgi/man.cgi?login.conf(5)) man: > > > ``` > setenv list A comma-separated list of > environment variables and > values to which they are to > be set. > > ``` > > If you modity the `/etc/login.conf` file, don't forget to run: ``` cap_mkdb /etc/login.conf ```
Also, if you'd like to set some environment variables for an [rc(8)](https://www.freebsd.org/cgi/man.cgi?rc) service then you might also take a look at the `${name}_env` and `${name}_env_file` variables described in [rc.subr(8)](https://www.freebsd.org/cgi/man.cgi?rc.subr). They allow you to set environment variables for services on FreeBSD in [rc.conf(5)](https://www.freebsd.org/cgi/man.cgi?rc.conf), e.g.: ```sh nginx_enable="YES" nginx_env="NODE_ENV=production" ```
694,413
I'd like to know how to convert prices -- $\$20$ per month is how much in one year? For example: "Tim pays $\$20$ a month for his cell phone bill. How much will he pay in one year?"
2014/02/28
[ "https://math.stackexchange.com/questions/694413", "https://math.stackexchange.com", "https://math.stackexchange.com/users/109399/" ]
In science classes at least, there's a concept called dimensional analysis, which lets you get from one set of units to another set of units. $$\require{cancel} \frac{\$20}{1\text{ month}}=\frac{\$20}{1\cancel{\text{ month}}}\times \frac{12\cancel{\text{ months}}}{1\text{ year}}=\frac{\$20\times12}{1\text{ year}}=\frac{\$240}{1\text{ year}}$$ What I did is that we had months, but we wanted years, so I related months and years together. You can see that the 'months' units cancel each other out.
Multiply the the amount of change per unit(change in money, per month) by total units (12 months)
8,186,299
When I need to view a table's schema, I use `sp_help`, which will give me something like: ``` Column Name Type Length My_COLUMN nvarchar 50 ``` But if I open up the table in Design Mode, I'll get ``` MY_COLUMN nvarchar(25) ``` Why?
2011/11/18
[ "https://Stackoverflow.com/questions/8186299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194931/" ]
25 is the maximum length in characters. 50 is the maximum length in bytes. `n[var]char` columns consume 2 bytes per character.
The "length" you're seeing in the `sp_help` listing is the length in bytes and, since nvarchar is a double-byte data type, it is double what was declared in the table creation.
18,282,210
I have a CSV file of ID numbers that I need as an `IEnumberable<int>`. I was trying to get from A to B as simply as possible, and came up with the following idea: ``` Global.migrated = File.ReadAllText(Global.migrationList).Split(',').Cast<int>().ToList<int>(); ``` When I run this, though, I'm told that the Cast is invalid. I also tried reading to a String list and casting to int: ``` List<string> myTemp = File.ReadAllText(Global.migrationList).Split(',').ToList<string>(); Global.migrated = myTemp.Cast<int>(); ``` But this raises the following error: ``` Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'System.Collections.List<int>.' An explicit conversion exists. Are you missing a cast? ``` I don't understand. The object I'm trying to cast isn't an `IEnumerable<int>` in this case. It should be a `List<string>`. I'm afraid I'm missing something important about how casting works.
2013/08/16
[ "https://Stackoverflow.com/questions/18282210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638627/" ]
Instead of property/value pair implement this structure as an array of objects. Arrays you can sort by any property of objects it contains.
One way to get the keys in sorted order would be to use the method defined here to generate an array of the keys: [Getting JavaScript object key list](https://stackoverflow.com/questions/3068534/getting-javascript-object-key-list) Then you could use the javascript `sort` function: <http://www.w3schools.com/jsref/jsref_sort.asp> Or write your own if you feel inclined. Then just loop through the array of keys, using `object[key]` to extract the value.
18,282,210
I have a CSV file of ID numbers that I need as an `IEnumberable<int>`. I was trying to get from A to B as simply as possible, and came up with the following idea: ``` Global.migrated = File.ReadAllText(Global.migrationList).Split(',').Cast<int>().ToList<int>(); ``` When I run this, though, I'm told that the Cast is invalid. I also tried reading to a String list and casting to int: ``` List<string> myTemp = File.ReadAllText(Global.migrationList).Split(',').ToList<string>(); Global.migrated = myTemp.Cast<int>(); ``` But this raises the following error: ``` Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'System.Collections.List<int>.' An explicit conversion exists. Are you missing a cast? ``` I don't understand. The object I'm trying to cast isn't an `IEnumerable<int>` in this case. It should be a `List<string>`. I'm afraid I'm missing something important about how casting works.
2013/08/16
[ "https://Stackoverflow.com/questions/18282210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638627/" ]
Because objects are unordered collections, it's up to you to enforce the ordering you want. One way is to get an Array of the object properties, sort them, then iterate the Array. ``` Object.keys(data) .sort(function(a, b) { return +b - +a; }) .forEach(function(key) { var item = data[key]; }); ``` This assumes that you wanted a simple descending order.
One way to get the keys in sorted order would be to use the method defined here to generate an array of the keys: [Getting JavaScript object key list](https://stackoverflow.com/questions/3068534/getting-javascript-object-key-list) Then you could use the javascript `sort` function: <http://www.w3schools.com/jsref/jsref_sort.asp> Or write your own if you feel inclined. Then just loop through the array of keys, using `object[key]` to extract the value.
18,282,210
I have a CSV file of ID numbers that I need as an `IEnumberable<int>`. I was trying to get from A to B as simply as possible, and came up with the following idea: ``` Global.migrated = File.ReadAllText(Global.migrationList).Split(',').Cast<int>().ToList<int>(); ``` When I run this, though, I'm told that the Cast is invalid. I also tried reading to a String list and casting to int: ``` List<string> myTemp = File.ReadAllText(Global.migrationList).Split(',').ToList<string>(); Global.migrated = myTemp.Cast<int>(); ``` But this raises the following error: ``` Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'System.Collections.List<int>.' An explicit conversion exists. Are you missing a cast? ``` I don't understand. The object I'm trying to cast isn't an `IEnumerable<int>` in this case. It should be a `List<string>`. I'm afraid I'm missing something important about how casting works.
2013/08/16
[ "https://Stackoverflow.com/questions/18282210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638627/" ]
When you iterate over object properties, there is no guarantee on the order. You can add your objects to an array, and sort the array instead: ``` var obj = {"2012" : {}, "2011" : {}, "2013" : {}}; var arr = []; for (var year in obj) { arr.push({year : year, data : obj[year]}); } arr.sort(function(a,b) { return b.year - a.year; }); ``` <http://jsfiddle.net/wK5KE/>
One way to get the keys in sorted order would be to use the method defined here to generate an array of the keys: [Getting JavaScript object key list](https://stackoverflow.com/questions/3068534/getting-javascript-object-key-list) Then you could use the javascript `sort` function: <http://www.w3schools.com/jsref/jsref_sort.asp> Or write your own if you feel inclined. Then just loop through the array of keys, using `object[key]` to extract the value.
21,281,212
I have a little problem with my binary search function inside a class definition: ``` def searchExactIndex(self, key): bottom = 0 top = self.keyc found = False while bottom <= top and not found: middle = (bottom+top)/2 if self.keys[middle] == key: found = True elif self.keys[middle] < key: bottom = middle + 1 else: top = middle-1 return middle ``` Everything else here is working except When running the program I get an error: > > `while bottom <= top and not found:` > > > IndentationError: unexpected indent > > > Why is this?
2014/01/22
[ "https://Stackoverflow.com/questions/21281212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3223137/" ]
With the error you are seeing, ``` IndentationError: unexpected indent ``` Python is trying to tell you that something is wrong with the way you indented your code, and indeed there is, you need to look at the indentation before the first three lines in the `searchExactIndex` method. Your code looks fine, except for the indentation, which is significant in Python. The function should look like this: ``` def searchExactIndex(self, key): bottom = 0 top = self.keyc found = False while bottom <= top and not found: middle = (bottom+top)/2 if self.keys[middle] == key: found = True elif self.keys[middle] < key: bottom = middle + 1 else: top = middle-1 return middle ``` Note the lines where `bottom`, `top`, and `found` are being set: they are indented to be inside the `searchExactIndex` method. Make sure you use one type of indentation (i.e. only spaces), and keep it consistent.
How do you enter this code in python ? According to your code, you should have thoses syntax errors: If enter in a file : ``` File "test.py", line 4 bottom = 0 ^ IndentationError: expected an indented block ``` If enter in interactive python: ``` >>> def searchExactIndex(self, key): ... File "<stdin>", line 2 ^ IndentationError: expected an indented block ``` The solution is to ident **all** the content of the function : ``` def searchExactIndex(self, key): bottom = 0 top = self.keyc found = False while bottom <= top and not found: middle = (bottom+top)/2 if self.keys[middle] == key: found = True elif self.keys[middle] < key: bottom = middle + 1 else: top = middle-1 return middle ``` Also, you should take care of the case when the key is not present. For now, you always return middle.
25,640,719
I am trying to write an app, that will be scheduled to autodownload one page from a Sharepoint server every hour. It is an xml file. Everything works so far, except I do not like storing the password needed to connect to Sharepoint in plaintext in my app. Sample code here: ``` WebClient client = new WebClient(); String username = "myusername"; String password = "mypassword" String filename = "C:\\Temp\\" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".xml"; client.Credentials = new System.Net.NetworkCredential(username, password); string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)); client.DownloadFile("myurl", filename); ``` Is there a way how to make it harder to read my password if someone got the executabe file from my server and disassembled it e.g. with Reflector? I have found this: [How to store passwords in Winforms application?](https://stackoverflow.com/questions/40853/how-to-store-passwords-in-winforms-application) but I did not really figure out how to use it in my app.
2014/09/03
[ "https://Stackoverflow.com/questions/25640719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4003279/" ]
In fact you'd better not use passwords. If the service runs under the right credentials, you can use that one by using the [`DefaultNetworkCredentials`](http://msdn.microsoft.com/en-us/library/system.net.credentialcache.defaultnetworkcredentials(v=vs.110).aspx): So in your sample: ``` client.Credentials = CredentialCache.DefaultNetworkCredentials; ``` This will get you the credentials of the current network user, like `DOMAIN\USER`.
If you must store the password with the app, put it in the config file and then encrypt the appropriate section(s) of that using [Protected Configuration](http://msdn.microsoft.com/en-us/library/53tyfkaw.aspx).
3,025,763
Suppose a is an integer. If 5|2a then 5|a. Prove So i just suppose that 5|2a and so 2a=5b for some b in the integers but i dont know where to go from here. Thanks for help
2018/12/04
[ "https://math.stackexchange.com/questions/3025763", "https://math.stackexchange.com", "https://math.stackexchange.com/users/622342/" ]
The integral that you actually computed corresponds to the area of a rectangle. You should actually compute$$\int\_0^t\int\_0^{\frac x2}\,\mathrm dy\,\mathrm dx.$$
I think you made a mistake, the bounds on the inner integral should not be constant: $$ \int\_0^t \int\_0^{v/2} dudv = \int\_0^t \frac{v}{2} dv = \left. \frac{v^2}{4} \right|\_0^t = \frac{t^2}{4}. $$
64,127,200
I have navlink defined as follows `<NavLink href="/intro"></NavLink>` In dev it works fine as the root of the site is at the same level as the blazor app. In prod I have to put the blazor site inside a folder in the default iis website. So my url becomes something like this `http://something/apps/cor/` So the `<NavLink href="/intro"></NavLink>` ends up trying to go to `http://something/intro` instead `http://something/apps/cor/intro` I tried both `/intro` and `intro` and the both result in the wrong behavior. I am not getting how to make those links relative to blazor root not iis root.
2020/09/29
[ "https://Stackoverflow.com/questions/64127200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2501497/" ]
Dot before the path. `./intro` is how you do it
on `index.html` you should have `<base href="/apps/cor/" />`
64,127,200
I have navlink defined as follows `<NavLink href="/intro"></NavLink>` In dev it works fine as the root of the site is at the same level as the blazor app. In prod I have to put the blazor site inside a folder in the default iis website. So my url becomes something like this `http://something/apps/cor/` So the `<NavLink href="/intro"></NavLink>` ends up trying to go to `http://something/intro` instead `http://something/apps/cor/intro` I tried both `/intro` and `intro` and the both result in the wrong behavior. I am not getting how to make those links relative to blazor root not iis root.
2020/09/29
[ "https://Stackoverflow.com/questions/64127200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2501497/" ]
Dot before the path. `./intro` is how you do it
I had to do this trick in `_Layout.cshtml`: ``` @inject IWebHostEnvironment Environment; // in <head> : @if (Environment.IsDevelopment()) { <base href="~/" /> } else { <base href="~/myApp" /> } ``` then either `<NavLink href="page"></NavLink>` or `<NavLink href="./page"></NavLink>` works. * On localhost: `https://localhost:44393/page` * On server: `https://example.com/myApp/page`
64,127,200
I have navlink defined as follows `<NavLink href="/intro"></NavLink>` In dev it works fine as the root of the site is at the same level as the blazor app. In prod I have to put the blazor site inside a folder in the default iis website. So my url becomes something like this `http://something/apps/cor/` So the `<NavLink href="/intro"></NavLink>` ends up trying to go to `http://something/intro` instead `http://something/apps/cor/intro` I tried both `/intro` and `intro` and the both result in the wrong behavior. I am not getting how to make those links relative to blazor root not iis root.
2020/09/29
[ "https://Stackoverflow.com/questions/64127200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2501497/" ]
on `index.html` you should have `<base href="/apps/cor/" />`
I had to do this trick in `_Layout.cshtml`: ``` @inject IWebHostEnvironment Environment; // in <head> : @if (Environment.IsDevelopment()) { <base href="~/" /> } else { <base href="~/myApp" /> } ``` then either `<NavLink href="page"></NavLink>` or `<NavLink href="./page"></NavLink>` works. * On localhost: `https://localhost:44393/page` * On server: `https://example.com/myApp/page`
14,240,003
* No `websockets` on [Heroku](http://www.heroku.com/), * no `thin` on [Engineyard](http://www.engineyard.com/), * gave [OpenShift](https://openshift.redhat.com/) a try, but they are quite far from being ready for production. If I want to host a Ruby/Rails app which uses `websockets` via `faye`, where can I do that?
2013/01/09
[ "https://Stackoverflow.com/questions/14240003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341929/" ]
Not sure what you are trying to spend, but your best option is proably going to be looking into a VPS hosting solution, such as [Linode](http://www.linode.com/). This way you have the freedom to install the software that you need. **Edit:** (based on your comment) You could also try [the free tier of Amazon EC2](http://aws.amazon.com/free/ "AWS Free Usage Tier") but you only get one year of free service.
Roll your own vserver, costs just a few bucks nowadays. You can run there everything you want and have full control over it.
14,240,003
* No `websockets` on [Heroku](http://www.heroku.com/), * no `thin` on [Engineyard](http://www.engineyard.com/), * gave [OpenShift](https://openshift.redhat.com/) a try, but they are quite far from being ready for production. If I want to host a Ruby/Rails app which uses `websockets` via `faye`, where can I do that?
2013/01/09
[ "https://Stackoverflow.com/questions/14240003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341929/" ]
Roll your own vserver, costs just a few bucks nowadays. You can run there everything you want and have full control over it.
There's a company called Blue Box in Seattle you might look into. I work there, so there's that shameless plug aspect going on. But I think they'll be your best bet.
14,240,003
* No `websockets` on [Heroku](http://www.heroku.com/), * no `thin` on [Engineyard](http://www.engineyard.com/), * gave [OpenShift](https://openshift.redhat.com/) a try, but they are quite far from being ready for production. If I want to host a Ruby/Rails app which uses `websockets` via `faye`, where can I do that?
2013/01/09
[ "https://Stackoverflow.com/questions/14240003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341929/" ]
Roll your own vserver, costs just a few bucks nowadays. You can run there everything you want and have full control over it.
Here's an [example OpenShift DIY instance](https://github.com/jweissman/zephyr-faye-diy) that's currently running a prod Faye instance in the cloud for me. As you say, OpenShift isn't really ready for primetime -- so I'm actually talking to this box from my main app running on Heroku! One note here might be that websockets secure protocol (wss) is supported on 8443 for OpenShift.
14,240,003
* No `websockets` on [Heroku](http://www.heroku.com/), * no `thin` on [Engineyard](http://www.engineyard.com/), * gave [OpenShift](https://openshift.redhat.com/) a try, but they are quite far from being ready for production. If I want to host a Ruby/Rails app which uses `websockets` via `faye`, where can I do that?
2013/01/09
[ "https://Stackoverflow.com/questions/14240003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341929/" ]
Heroku now supports WebSockets (finally!): <https://devcenter.heroku.com/articles/heroku-labs-websockets>
Roll your own vserver, costs just a few bucks nowadays. You can run there everything you want and have full control over it.
14,240,003
* No `websockets` on [Heroku](http://www.heroku.com/), * no `thin` on [Engineyard](http://www.engineyard.com/), * gave [OpenShift](https://openshift.redhat.com/) a try, but they are quite far from being ready for production. If I want to host a Ruby/Rails app which uses `websockets` via `faye`, where can I do that?
2013/01/09
[ "https://Stackoverflow.com/questions/14240003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341929/" ]
Not sure what you are trying to spend, but your best option is proably going to be looking into a VPS hosting solution, such as [Linode](http://www.linode.com/). This way you have the freedom to install the software that you need. **Edit:** (based on your comment) You could also try [the free tier of Amazon EC2](http://aws.amazon.com/free/ "AWS Free Usage Tier") but you only get one year of free service.
There's a company called Blue Box in Seattle you might look into. I work there, so there's that shameless plug aspect going on. But I think they'll be your best bet.
14,240,003
* No `websockets` on [Heroku](http://www.heroku.com/), * no `thin` on [Engineyard](http://www.engineyard.com/), * gave [OpenShift](https://openshift.redhat.com/) a try, but they are quite far from being ready for production. If I want to host a Ruby/Rails app which uses `websockets` via `faye`, where can I do that?
2013/01/09
[ "https://Stackoverflow.com/questions/14240003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341929/" ]
Not sure what you are trying to spend, but your best option is proably going to be looking into a VPS hosting solution, such as [Linode](http://www.linode.com/). This way you have the freedom to install the software that you need. **Edit:** (based on your comment) You could also try [the free tier of Amazon EC2](http://aws.amazon.com/free/ "AWS Free Usage Tier") but you only get one year of free service.
Here's an [example OpenShift DIY instance](https://github.com/jweissman/zephyr-faye-diy) that's currently running a prod Faye instance in the cloud for me. As you say, OpenShift isn't really ready for primetime -- so I'm actually talking to this box from my main app running on Heroku! One note here might be that websockets secure protocol (wss) is supported on 8443 for OpenShift.
14,240,003
* No `websockets` on [Heroku](http://www.heroku.com/), * no `thin` on [Engineyard](http://www.engineyard.com/), * gave [OpenShift](https://openshift.redhat.com/) a try, but they are quite far from being ready for production. If I want to host a Ruby/Rails app which uses `websockets` via `faye`, where can I do that?
2013/01/09
[ "https://Stackoverflow.com/questions/14240003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341929/" ]
Heroku now supports WebSockets (finally!): <https://devcenter.heroku.com/articles/heroku-labs-websockets>
There's a company called Blue Box in Seattle you might look into. I work there, so there's that shameless plug aspect going on. But I think they'll be your best bet.
14,240,003
* No `websockets` on [Heroku](http://www.heroku.com/), * no `thin` on [Engineyard](http://www.engineyard.com/), * gave [OpenShift](https://openshift.redhat.com/) a try, but they are quite far from being ready for production. If I want to host a Ruby/Rails app which uses `websockets` via `faye`, where can I do that?
2013/01/09
[ "https://Stackoverflow.com/questions/14240003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341929/" ]
Heroku now supports WebSockets (finally!): <https://devcenter.heroku.com/articles/heroku-labs-websockets>
Here's an [example OpenShift DIY instance](https://github.com/jweissman/zephyr-faye-diy) that's currently running a prod Faye instance in the cloud for me. As you say, OpenShift isn't really ready for primetime -- so I'm actually talking to this box from my main app running on Heroku! One note here might be that websockets secure protocol (wss) is supported on 8443 for OpenShift.
36,169,360
I'm trying to learn VIM editor , and I'm going to test some small code for ruby here is question.. When I compile and launch my small ruby code, 1. Command-mode, `:!ruby %` 2. Or Open another terminal, `$ruby filename.rb` I did , but.. its really stressful and I cannot focus.... Is there any magical things?? , config .vimrc file then make a hot-key or... make some script by rubyself...??
2016/03/23
[ "https://Stackoverflow.com/questions/36169360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6048318/" ]
If your vim distribution has `ruby` support, can be confirmed using `vim --version |grep ruby`, Then ``` nnoremap <F9> :rubyfile %<CR> ``` This is will be more faster as this does not invoke an external command using `!ruby` and hence no shell launch. More details at `:help ruby`. Another way to complete the work irrespective of `ruby support`. Your vim distribution will come with `$VIMRUNTIME/compiler/ruby.vim` for `compiler` setting. If so, you can set it `:compiler ruby` for ruby files in your vimrc. This will allow you to just do `make` to accomplish what you are doing. But output looks somewhat clumsy. Hence, Having a some keybinding will help ``` nnoremap <f9> :make<CR> :copen<CR> ``` This will open a `quickfix` for error. You can just press `F9` or any other key that you have mapped. You might also like to review quickfix commands at `:help quickfix`
You can try doing this to your `.vimrc`. It's not exactly sophisticated, but may be good enough for your needs: ``` " Run current file as Ruby program nnoremap <C-r> :!ruby %<CR> ```
36,169,360
I'm trying to learn VIM editor , and I'm going to test some small code for ruby here is question.. When I compile and launch my small ruby code, 1. Command-mode, `:!ruby %` 2. Or Open another terminal, `$ruby filename.rb` I did , but.. its really stressful and I cannot focus.... Is there any magical things?? , config .vimrc file then make a hot-key or... make some script by rubyself...??
2016/03/23
[ "https://Stackoverflow.com/questions/36169360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6048318/" ]
You can use `:!!` to repeat the last `:!{cmd}`. You can type `:!ruby %` once, and then run `:!!`, which can of course be mapped to a key like: ``` nnoremap <F8> :!!<CR> ``` Or to write and run it (saves typing `:w`): ``` nnoremap <F8> :w<CR>:!!<CR> ``` This is a flexible solution, since you can replace `:!ruby %` with anything else (e.g. `:!coffee -c %`, `:!python %`, etc.).
You can try doing this to your `.vimrc`. It's not exactly sophisticated, but may be good enough for your needs: ``` " Run current file as Ruby program nnoremap <C-r> :!ruby %<CR> ```
36,169,360
I'm trying to learn VIM editor , and I'm going to test some small code for ruby here is question.. When I compile and launch my small ruby code, 1. Command-mode, `:!ruby %` 2. Or Open another terminal, `$ruby filename.rb` I did , but.. its really stressful and I cannot focus.... Is there any magical things?? , config .vimrc file then make a hot-key or... make some script by rubyself...??
2016/03/23
[ "https://Stackoverflow.com/questions/36169360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6048318/" ]
You can use `:!!` to repeat the last `:!{cmd}`. You can type `:!ruby %` once, and then run `:!!`, which can of course be mapped to a key like: ``` nnoremap <F8> :!!<CR> ``` Or to write and run it (saves typing `:w`): ``` nnoremap <F8> :w<CR>:!!<CR> ``` This is a flexible solution, since you can replace `:!ruby %` with anything else (e.g. `:!coffee -c %`, `:!python %`, etc.).
If your vim distribution has `ruby` support, can be confirmed using `vim --version |grep ruby`, Then ``` nnoremap <F9> :rubyfile %<CR> ``` This is will be more faster as this does not invoke an external command using `!ruby` and hence no shell launch. More details at `:help ruby`. Another way to complete the work irrespective of `ruby support`. Your vim distribution will come with `$VIMRUNTIME/compiler/ruby.vim` for `compiler` setting. If so, you can set it `:compiler ruby` for ruby files in your vimrc. This will allow you to just do `make` to accomplish what you are doing. But output looks somewhat clumsy. Hence, Having a some keybinding will help ``` nnoremap <f9> :make<CR> :copen<CR> ``` This will open a `quickfix` for error. You can just press `F9` or any other key that you have mapped. You might also like to review quickfix commands at `:help quickfix`
123,336
i want select query for multiple checkbox but I am getting an error > > System.QueryException: unexpected token: 'true' Error is in expression > '{!dochar}' in component in page cc: > Class.actionSupportController.dochar: line 24, column 1 > > > ``` public class actionSupportController { public List<PCS_Household__c> lstQuery{get;set;} public List<PCS_Household__c> OnlstQuery{get;set;} public List<Characteristics__c> selctchr{get;set;} public Characteristics__c sct{get;set;} public string ID_c{get;set;} public string test{get;set;} public string Good_with_Cats_c{get;set;} public string Active_c{get;set;} public string HighNeed_c{get;set;} public string kid_friendly_c{get;set;} public string Non_shedder_c{get;set;} public string Predatory_Tendencies_c{get;set;} public List<Pets_Information__c> selctpet{get;set;} Public Boolean Good{get;set;} public void dochar(){ string query=''; system.debug('==Good_with_Cats_c=='+Good_with_Cats_c); query='SELECT Name,ID,Good_with_Cats__c,Pet_ID__r.Gender__c,Pet_ID__r.Height__c,Pet_ID__r.Name__c,Pet_ID__r.pet__c,Pet_ID__r.Pet_Photo__c,Pet_ID__r.Status__c FROM Characteristics__c where Good_with_Cats__c\''+Good_with_Cats_c+'\''; system.debug('==query=='+query); selctchr=Database.query(query); system.debug('==selctchr=='+selctchr); } public PageReference incrementCounter() { string Query=''; Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where ID=:test'; system.debug('==Query=='+Query); OnlstQuery=Database.query(Query); system.debug('==OnlstQuery=='+OnlstQuery); return null; } public Void doSearch(){ string Query=''; Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where Household__c LIKE \'%'+ID_c+'%\''; system.debug('==ID_c=='+ID_c); system.debug('==Query=='+Query); lstQuery=Database.query(Query); system.debug('==lstQuery=='+lstQuery); } public void nullify(){ lstQuery.clear(); } public PageReference nextpage() { upsert OnlstQuery; return Page.cc; } } ```
2016/05/25
[ "https://salesforce.stackexchange.com/questions/123336", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/-1/" ]
There is already another answer with shorter solution but I still wanted to answer. Below validation rule should work for your situation, too. ``` OR( OR( LEN( Phone ) <= 9 , LEN( Phone ) >= 13 ), NOT( OR( REGEX(Phone, "[0-9 ]+"), REGEX(Phone, "\\+[0-9 ]+")) ) ) ```
You can use following RegEx for making sure the phone number has 10 to 12 digits and starts with a `+` sign, ``` REGEX(<Phone Field Name>, "\\+{0,1}[0-9]{10,12}") ``` Hope this helps. Best Regards!
123,336
i want select query for multiple checkbox but I am getting an error > > System.QueryException: unexpected token: 'true' Error is in expression > '{!dochar}' in component in page cc: > Class.actionSupportController.dochar: line 24, column 1 > > > ``` public class actionSupportController { public List<PCS_Household__c> lstQuery{get;set;} public List<PCS_Household__c> OnlstQuery{get;set;} public List<Characteristics__c> selctchr{get;set;} public Characteristics__c sct{get;set;} public string ID_c{get;set;} public string test{get;set;} public string Good_with_Cats_c{get;set;} public string Active_c{get;set;} public string HighNeed_c{get;set;} public string kid_friendly_c{get;set;} public string Non_shedder_c{get;set;} public string Predatory_Tendencies_c{get;set;} public List<Pets_Information__c> selctpet{get;set;} Public Boolean Good{get;set;} public void dochar(){ string query=''; system.debug('==Good_with_Cats_c=='+Good_with_Cats_c); query='SELECT Name,ID,Good_with_Cats__c,Pet_ID__r.Gender__c,Pet_ID__r.Height__c,Pet_ID__r.Name__c,Pet_ID__r.pet__c,Pet_ID__r.Pet_Photo__c,Pet_ID__r.Status__c FROM Characteristics__c where Good_with_Cats__c\''+Good_with_Cats_c+'\''; system.debug('==query=='+query); selctchr=Database.query(query); system.debug('==selctchr=='+selctchr); } public PageReference incrementCounter() { string Query=''; Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where ID=:test'; system.debug('==Query=='+Query); OnlstQuery=Database.query(Query); system.debug('==OnlstQuery=='+OnlstQuery); return null; } public Void doSearch(){ string Query=''; Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where Household__c LIKE \'%'+ID_c+'%\''; system.debug('==ID_c=='+ID_c); system.debug('==Query=='+Query); lstQuery=Database.query(Query); system.debug('==lstQuery=='+lstQuery); } public void nullify(){ lstQuery.clear(); } public PageReference nextpage() { upsert OnlstQuery; return Page.cc; } } ```
2016/05/25
[ "https://salesforce.stackexchange.com/questions/123336", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/-1/" ]
You can use following RegEx for making sure the phone number has 10 to 12 digits and starts with a `+` sign, ``` REGEX(<Phone Field Name>, "\\+{0,1}[0-9]{10,12}") ``` Hope this helps. Best Regards!
``` not(isnumber(your phone number field))||len(your phone number field)<>**10**) ``` As I'm an Indian My mobile number should be equal to 10 you can add any number over there
123,336
i want select query for multiple checkbox but I am getting an error > > System.QueryException: unexpected token: 'true' Error is in expression > '{!dochar}' in component in page cc: > Class.actionSupportController.dochar: line 24, column 1 > > > ``` public class actionSupportController { public List<PCS_Household__c> lstQuery{get;set;} public List<PCS_Household__c> OnlstQuery{get;set;} public List<Characteristics__c> selctchr{get;set;} public Characteristics__c sct{get;set;} public string ID_c{get;set;} public string test{get;set;} public string Good_with_Cats_c{get;set;} public string Active_c{get;set;} public string HighNeed_c{get;set;} public string kid_friendly_c{get;set;} public string Non_shedder_c{get;set;} public string Predatory_Tendencies_c{get;set;} public List<Pets_Information__c> selctpet{get;set;} Public Boolean Good{get;set;} public void dochar(){ string query=''; system.debug('==Good_with_Cats_c=='+Good_with_Cats_c); query='SELECT Name,ID,Good_with_Cats__c,Pet_ID__r.Gender__c,Pet_ID__r.Height__c,Pet_ID__r.Name__c,Pet_ID__r.pet__c,Pet_ID__r.Pet_Photo__c,Pet_ID__r.Status__c FROM Characteristics__c where Good_with_Cats__c\''+Good_with_Cats_c+'\''; system.debug('==query=='+query); selctchr=Database.query(query); system.debug('==selctchr=='+selctchr); } public PageReference incrementCounter() { string Query=''; Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where ID=:test'; system.debug('==Query=='+Query); OnlstQuery=Database.query(Query); system.debug('==OnlstQuery=='+OnlstQuery); return null; } public Void doSearch(){ string Query=''; Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where Household__c LIKE \'%'+ID_c+'%\''; system.debug('==ID_c=='+ID_c); system.debug('==Query=='+Query); lstQuery=Database.query(Query); system.debug('==lstQuery=='+lstQuery); } public void nullify(){ lstQuery.clear(); } public PageReference nextpage() { upsert OnlstQuery; return Page.cc; } } ```
2016/05/25
[ "https://salesforce.stackexchange.com/questions/123336", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/-1/" ]
There is already another answer with shorter solution but I still wanted to answer. Below validation rule should work for your situation, too. ``` OR( OR( LEN( Phone ) <= 9 , LEN( Phone ) >= 13 ), NOT( OR( REGEX(Phone, "[0-9 ]+"), REGEX(Phone, "\\+[0-9 ]+")) ) ) ```
``` not(isnumber(your phone number field))||len(your phone number field)<>**10**) ``` As I'm an Indian My mobile number should be equal to 10 you can add any number over there
2,162,953
Evaluate $$\int\_0^\infty xI\_0(2x)e^{-x^2}\,dx$$ where $$I\_0(x) = \frac 1\pi \int\_0^\pi e^{x\cos\theta}\,d\theta$$ is a Bessel Function. Source: Berkeley Math Tournament This question was on a math contest for high school students, so I am looking for other methods that preferably do not involve higher mathematics than Calc II. However, I am also interested in other ways to solve this problem that goes beyond the normal calculus curriculum. My solution is posted below as an answer.
2017/02/26
[ "https://math.stackexchange.com/questions/2162953", "https://math.stackexchange.com", "https://math.stackexchange.com/users/190244/" ]
A simpler way is to exploit Fubini's theorem and polar coordinates: $$ \int\_{0}^{+\infty}x\,I\_0(2x) e^{-x^2}\,dx = \frac{1}{\pi}\int\_{0}^{\pi}\int\_{0}^{+\infty}\rho e^{-2\rho\cos\theta} e^{-\rho^2}\,d\rho\,d\theta $$ where the last integral equals: $$ \frac{1}{\pi}\int\_{0}^{+\infty}\int\_{-\infty}^{+\infty} e^{-2x} e^{-x^2-y^2}\,dx\,dy \stackrel{x\mapsto x-1}{=}\frac{e}{\pi}\int\_{0}^{+\infty}\int\_{-\infty}^{+\infty}e^{-x^2-y^2}\,dx\,dy$$ that simplifies to: $$ \frac{e}{2\pi}\iint\_{\mathbb{R}^2} e^{-x^2-y^2}\,dx\,dy = \color{red}{\frac{e}{2}}.$$ --- This also gives the straightforward generalization $$ \int\_{0}^{+\infty} x\,I\_0(\rho x)e^{-x^2}\,dx = \color{red}{\frac{1}{2}\,e^{\rho^2/4}}.$$
$$I = \int\_0^\infty xI\_0(2x)e^{-x^2}\,dx$$ $$I\_0(x)=\frac 1\pi\int\_0^\pi e^{x\cos\theta}d\theta \stackrel{\theta\rightarrow\theta/2}{=}\frac 1{2\pi}\int\_0^{2\pi} e^{x\cos(\theta/2)}d\theta \stackrel{z=\exp(i\theta/2)}{=}\frac 1{2\pi i}\int\_{|z|=1} \frac{xe^{[z+1/z]/2}}{z}dz$$ To evaluate this, we proceed by expanding the function as a series and finding the residue, using the residue theorem. We have that $$I\_0(x)=\text{Res}(\frac{{e^{x[z+1/z]/2}}}z,z=0) = \text{constant term of } 1+x\frac{z+z^{-1}}2+x^2\frac{(z+z^{-1})^2}{2^{2} 2!}+x^3\frac{(z+z^{-1})^3}{2^3 3!} +\cdots$$ Noting that we only get a constant term contribution from the even terms, and the constant of $(z+z^{-1})^{2n}$ is $\binom{2n}n,$ we have that $$I\_0(x)=\text{Res}(\frac{{e^{z+1/z}}}z,z=0) = \sum\_{n\geq0} \frac{x^{2n}}{2^{2n}(2n)!}\binom{2n}{n}=\sum\_{n\geq0} \frac{x^{2n}}{2^{2n}(n!)^2}$$ Then $$I\_0(2x)=\sum\_{n\geq0} \frac{x^{2n}}{(n!)^2}$$ So $$I = \int\_0^\infty \sum\_{n\geq0} \frac{x^{2n}}{(n!)^2} xe^{-x^2}\,dx\stackrel{\text{terms are all positive}}= \sum\_{n\geq0}\frac{1}{(n!)^2} \int\_0^\infty{x^{2n+1}}e^{-x^2}\,dx\stackrel{u=x^2}=\frac12 \sum\_{n\geq0}\frac{1}{(n!)^2} \int\_0^\infty{x^{n}}e^{-u}\,du = \frac 12\sum\_{n\geq0}\frac{1}{(n!)^2} \Gamma(n+1) = \frac 12\sum\_{n\geq0}\frac{1}{(n!)} =\boxed{\frac e2}$$
2,162,953
Evaluate $$\int\_0^\infty xI\_0(2x)e^{-x^2}\,dx$$ where $$I\_0(x) = \frac 1\pi \int\_0^\pi e^{x\cos\theta}\,d\theta$$ is a Bessel Function. Source: Berkeley Math Tournament This question was on a math contest for high school students, so I am looking for other methods that preferably do not involve higher mathematics than Calc II. However, I am also interested in other ways to solve this problem that goes beyond the normal calculus curriculum. My solution is posted below as an answer.
2017/02/26
[ "https://math.stackexchange.com/questions/2162953", "https://math.stackexchange.com", "https://math.stackexchange.com/users/190244/" ]
Note that $$I=\int\_{0}^{\infty}xI\_{0}\left(2x\right)e^{-x^{2}}dx\stackrel{e^{-x^{2}}=u}{=}\frac{1}{2}\int\_{0}^{1}I\_{0}\left(2\sqrt{-\log\left(u\right)}\right)du$$ $$=\frac{1}{2}\sum\_{k\geq0}\frac{\left(-1\right)^{k}}{\left(k!\right)^{2}}\int\_{0}^{1}\log^{k}\left(u\right)du=\frac{1}{2}\sum\_{k\geq0}\frac{1}{k!}=\color{red}{\frac{e}{2}}.$$
$$I = \int\_0^\infty xI\_0(2x)e^{-x^2}\,dx$$ $$I\_0(x)=\frac 1\pi\int\_0^\pi e^{x\cos\theta}d\theta \stackrel{\theta\rightarrow\theta/2}{=}\frac 1{2\pi}\int\_0^{2\pi} e^{x\cos(\theta/2)}d\theta \stackrel{z=\exp(i\theta/2)}{=}\frac 1{2\pi i}\int\_{|z|=1} \frac{xe^{[z+1/z]/2}}{z}dz$$ To evaluate this, we proceed by expanding the function as a series and finding the residue, using the residue theorem. We have that $$I\_0(x)=\text{Res}(\frac{{e^{x[z+1/z]/2}}}z,z=0) = \text{constant term of } 1+x\frac{z+z^{-1}}2+x^2\frac{(z+z^{-1})^2}{2^{2} 2!}+x^3\frac{(z+z^{-1})^3}{2^3 3!} +\cdots$$ Noting that we only get a constant term contribution from the even terms, and the constant of $(z+z^{-1})^{2n}$ is $\binom{2n}n,$ we have that $$I\_0(x)=\text{Res}(\frac{{e^{z+1/z}}}z,z=0) = \sum\_{n\geq0} \frac{x^{2n}}{2^{2n}(2n)!}\binom{2n}{n}=\sum\_{n\geq0} \frac{x^{2n}}{2^{2n}(n!)^2}$$ Then $$I\_0(2x)=\sum\_{n\geq0} \frac{x^{2n}}{(n!)^2}$$ So $$I = \int\_0^\infty \sum\_{n\geq0} \frac{x^{2n}}{(n!)^2} xe^{-x^2}\,dx\stackrel{\text{terms are all positive}}= \sum\_{n\geq0}\frac{1}{(n!)^2} \int\_0^\infty{x^{2n+1}}e^{-x^2}\,dx\stackrel{u=x^2}=\frac12 \sum\_{n\geq0}\frac{1}{(n!)^2} \int\_0^\infty{x^{n}}e^{-u}\,du = \frac 12\sum\_{n\geq0}\frac{1}{(n!)^2} \Gamma(n+1) = \frac 12\sum\_{n\geq0}\frac{1}{(n!)} =\boxed{\frac e2}$$
2,162,953
Evaluate $$\int\_0^\infty xI\_0(2x)e^{-x^2}\,dx$$ where $$I\_0(x) = \frac 1\pi \int\_0^\pi e^{x\cos\theta}\,d\theta$$ is a Bessel Function. Source: Berkeley Math Tournament This question was on a math contest for high school students, so I am looking for other methods that preferably do not involve higher mathematics than Calc II. However, I am also interested in other ways to solve this problem that goes beyond the normal calculus curriculum. My solution is posted below as an answer.
2017/02/26
[ "https://math.stackexchange.com/questions/2162953", "https://math.stackexchange.com", "https://math.stackexchange.com/users/190244/" ]
A simpler way is to exploit Fubini's theorem and polar coordinates: $$ \int\_{0}^{+\infty}x\,I\_0(2x) e^{-x^2}\,dx = \frac{1}{\pi}\int\_{0}^{\pi}\int\_{0}^{+\infty}\rho e^{-2\rho\cos\theta} e^{-\rho^2}\,d\rho\,d\theta $$ where the last integral equals: $$ \frac{1}{\pi}\int\_{0}^{+\infty}\int\_{-\infty}^{+\infty} e^{-2x} e^{-x^2-y^2}\,dx\,dy \stackrel{x\mapsto x-1}{=}\frac{e}{\pi}\int\_{0}^{+\infty}\int\_{-\infty}^{+\infty}e^{-x^2-y^2}\,dx\,dy$$ that simplifies to: $$ \frac{e}{2\pi}\iint\_{\mathbb{R}^2} e^{-x^2-y^2}\,dx\,dy = \color{red}{\frac{e}{2}}.$$ --- This also gives the straightforward generalization $$ \int\_{0}^{+\infty} x\,I\_0(\rho x)e^{-x^2}\,dx = \color{red}{\frac{1}{2}\,e^{\rho^2/4}}.$$
Note that $$I=\int\_{0}^{\infty}xI\_{0}\left(2x\right)e^{-x^{2}}dx\stackrel{e^{-x^{2}}=u}{=}\frac{1}{2}\int\_{0}^{1}I\_{0}\left(2\sqrt{-\log\left(u\right)}\right)du$$ $$=\frac{1}{2}\sum\_{k\geq0}\frac{\left(-1\right)^{k}}{\left(k!\right)^{2}}\int\_{0}^{1}\log^{k}\left(u\right)du=\frac{1}{2}\sum\_{k\geq0}\frac{1}{k!}=\color{red}{\frac{e}{2}}.$$
2,162,953
Evaluate $$\int\_0^\infty xI\_0(2x)e^{-x^2}\,dx$$ where $$I\_0(x) = \frac 1\pi \int\_0^\pi e^{x\cos\theta}\,d\theta$$ is a Bessel Function. Source: Berkeley Math Tournament This question was on a math contest for high school students, so I am looking for other methods that preferably do not involve higher mathematics than Calc II. However, I am also interested in other ways to solve this problem that goes beyond the normal calculus curriculum. My solution is posted below as an answer.
2017/02/26
[ "https://math.stackexchange.com/questions/2162953", "https://math.stackexchange.com", "https://math.stackexchange.com/users/190244/" ]
A simpler way is to exploit Fubini's theorem and polar coordinates: $$ \int\_{0}^{+\infty}x\,I\_0(2x) e^{-x^2}\,dx = \frac{1}{\pi}\int\_{0}^{\pi}\int\_{0}^{+\infty}\rho e^{-2\rho\cos\theta} e^{-\rho^2}\,d\rho\,d\theta $$ where the last integral equals: $$ \frac{1}{\pi}\int\_{0}^{+\infty}\int\_{-\infty}^{+\infty} e^{-2x} e^{-x^2-y^2}\,dx\,dy \stackrel{x\mapsto x-1}{=}\frac{e}{\pi}\int\_{0}^{+\infty}\int\_{-\infty}^{+\infty}e^{-x^2-y^2}\,dx\,dy$$ that simplifies to: $$ \frac{e}{2\pi}\iint\_{\mathbb{R}^2} e^{-x^2-y^2}\,dx\,dy = \color{red}{\frac{e}{2}}.$$ --- This also gives the straightforward generalization $$ \int\_{0}^{+\infty} x\,I\_0(\rho x)e^{-x^2}\,dx = \color{red}{\frac{1}{2}\,e^{\rho^2/4}}.$$
> > I thought it might be instructive to present a way forward the relies on only the series expansion of the exponential function, evaluating two integrals using reduction formulae, and straightforward arithmetic. To that end, we proceed. > > > Using the Taylor series for $e^t=\sum\_{n=0}^\infty \frac{t^n}{n!}$, with $t=2x\cos(\theta)$, we can write $I\_0(2x)$ as $$\begin{align} I\_0(2x)&=\frac1\pi \int\_0^\pi e^{2x\cos(\theta)}\,d\theta\\\\ &=\frac1\pi \sum\_{n=0}^\infty \frac{(2x)^n}{n!}\int\_0^\pi \cos^n(\theta)\,d\theta\tag 1 \end{align}$$ Next, using the reduction formula for $\int\_0^\pi \cos^n(\theta)\,d\theta=\frac{n-1}{n}\int\_0^\pi \cos^{n-2}(\theta)\,d\theta$ reveals $$\int\_0^\pi \cos^n(\theta)\,d\theta=\begin{cases}\pi\frac{n!}{(n!!)^2}&,n\,\text{even}\\\\0&,n\,\text{odd}\tag2\end{cases}$$ Using $(1)$ and $(2)$, we find that $$\begin{align} \int\_0^\infty xe^{-x^2}I\_0(2x)\,dx&= \frac1\pi\sum\_{n=0}^\infty \underbrace{\frac{4^n}{(2n)!}\left(\pi\,\frac{(2n)!}{((2n)!!)^2}\right)}\_{=\frac{\pi}{(n!)^2}}\,\,\underbrace{\int\_0^\infty x^{2n+1}e^{-x^2}\,dx}\_{=\frac12 n!}\\\\ &=\frac12\sum\_{n=0}^\infty \frac{1}{n!}\\\\ &=\frac{e}{2} \end{align}$$ where we used the reduction formula $\int\_0^\infty x^{2n+1}e^{-x^2}\,dx=n\int\_0^\infty x^{2n-1}e^{-x^2}\,dx$, along with the elementary integral $\int\_0^\infty xe^{-x^2}\,dx=\frac12$, to establish $\int\_0^\infty x^{2n+1}e^{-x^2}\,dx=\frac12 n!$. > > **Tools Used: The Taylor Series for $e^x$, the reduction formula for $\int\_0^\pi \cos^n(x)\,dx$, and the reduction formula for $\int\_0^\infty x^{2n+1}e^{-x^2}\,dx$** > > >
2,162,953
Evaluate $$\int\_0^\infty xI\_0(2x)e^{-x^2}\,dx$$ where $$I\_0(x) = \frac 1\pi \int\_0^\pi e^{x\cos\theta}\,d\theta$$ is a Bessel Function. Source: Berkeley Math Tournament This question was on a math contest for high school students, so I am looking for other methods that preferably do not involve higher mathematics than Calc II. However, I am also interested in other ways to solve this problem that goes beyond the normal calculus curriculum. My solution is posted below as an answer.
2017/02/26
[ "https://math.stackexchange.com/questions/2162953", "https://math.stackexchange.com", "https://math.stackexchange.com/users/190244/" ]
Note that $$I=\int\_{0}^{\infty}xI\_{0}\left(2x\right)e^{-x^{2}}dx\stackrel{e^{-x^{2}}=u}{=}\frac{1}{2}\int\_{0}^{1}I\_{0}\left(2\sqrt{-\log\left(u\right)}\right)du$$ $$=\frac{1}{2}\sum\_{k\geq0}\frac{\left(-1\right)^{k}}{\left(k!\right)^{2}}\int\_{0}^{1}\log^{k}\left(u\right)du=\frac{1}{2}\sum\_{k\geq0}\frac{1}{k!}=\color{red}{\frac{e}{2}}.$$
> > I thought it might be instructive to present a way forward the relies on only the series expansion of the exponential function, evaluating two integrals using reduction formulae, and straightforward arithmetic. To that end, we proceed. > > > Using the Taylor series for $e^t=\sum\_{n=0}^\infty \frac{t^n}{n!}$, with $t=2x\cos(\theta)$, we can write $I\_0(2x)$ as $$\begin{align} I\_0(2x)&=\frac1\pi \int\_0^\pi e^{2x\cos(\theta)}\,d\theta\\\\ &=\frac1\pi \sum\_{n=0}^\infty \frac{(2x)^n}{n!}\int\_0^\pi \cos^n(\theta)\,d\theta\tag 1 \end{align}$$ Next, using the reduction formula for $\int\_0^\pi \cos^n(\theta)\,d\theta=\frac{n-1}{n}\int\_0^\pi \cos^{n-2}(\theta)\,d\theta$ reveals $$\int\_0^\pi \cos^n(\theta)\,d\theta=\begin{cases}\pi\frac{n!}{(n!!)^2}&,n\,\text{even}\\\\0&,n\,\text{odd}\tag2\end{cases}$$ Using $(1)$ and $(2)$, we find that $$\begin{align} \int\_0^\infty xe^{-x^2}I\_0(2x)\,dx&= \frac1\pi\sum\_{n=0}^\infty \underbrace{\frac{4^n}{(2n)!}\left(\pi\,\frac{(2n)!}{((2n)!!)^2}\right)}\_{=\frac{\pi}{(n!)^2}}\,\,\underbrace{\int\_0^\infty x^{2n+1}e^{-x^2}\,dx}\_{=\frac12 n!}\\\\ &=\frac12\sum\_{n=0}^\infty \frac{1}{n!}\\\\ &=\frac{e}{2} \end{align}$$ where we used the reduction formula $\int\_0^\infty x^{2n+1}e^{-x^2}\,dx=n\int\_0^\infty x^{2n-1}e^{-x^2}\,dx$, along with the elementary integral $\int\_0^\infty xe^{-x^2}\,dx=\frac12$, to establish $\int\_0^\infty x^{2n+1}e^{-x^2}\,dx=\frac12 n!$. > > **Tools Used: The Taylor Series for $e^x$, the reduction formula for $\int\_0^\pi \cos^n(x)\,dx$, and the reduction formula for $\int\_0^\infty x^{2n+1}e^{-x^2}\,dx$** > > >
28,618,037
I'm trying to combine if else inside my regular expression, basically if some patterns exists in the string, capture one pattern, if not, capture another. The string is: '<https://www.searchpage.com/searchcompany.aspx?companyId=41490234&page=0&leftlink=true>" and I want to extract staff around the '?" So if '?' is detected inside the string, the regular expression should capture everything after the '?' mark; if not, then just capture from the beginning. I used:`'(.*\?.*)?(\?.*&.*)|(^&.*)'` But it didn't work... Any suggestion? Thanks!
2015/02/19
[ "https://Stackoverflow.com/questions/28618037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2209904/" ]
This regex: ``` (^[^?]*$|(?<=\?).*) ``` captures: * `^[^?]*$` everything, if there's no `?`, or * `(?<=\?).*` everything after the `?`, if there is one However, you should look into [`urllib.parse`](https://docs.python.org/3/library/urllib.parse.html) (Python 3) or [`urlparse`](https://docs.python.org/2/library/urlparse.html) (Python 2) if you're working with URLs.
regex might not be the best solution to this problem ...why not just `my_url.split("?",1)` if that is truly all you wish to do or as others have suggested ``` from urlparse import urlparse print urlparse(my_url) ```
28,618,037
I'm trying to combine if else inside my regular expression, basically if some patterns exists in the string, capture one pattern, if not, capture another. The string is: '<https://www.searchpage.com/searchcompany.aspx?companyId=41490234&page=0&leftlink=true>" and I want to extract staff around the '?" So if '?' is detected inside the string, the regular expression should capture everything after the '?' mark; if not, then just capture from the beginning. I used:`'(.*\?.*)?(\?.*&.*)|(^&.*)'` But it didn't work... Any suggestion? Thanks!
2015/02/19
[ "https://Stackoverflow.com/questions/28618037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2209904/" ]
Use [urlparse](https://docs.python.org/2/library/urlparse.html): ``` >>> import urlparse >>> parse_result = urlparse.urlparse('https://www.searchpage.com/searchcompany.aspx? companyId=41490234&page=0&leftlink=true') >>> parse_result ParseResult(scheme='https', netloc='www.searchpage.com', path='/searchcompany.aspx', params='', query='companyId=41490234&page=0&leftlink=true', fragment='') >>> urlparse.parse_qs(parse_result.query) {'leftlink': ['true'], 'page': ['0'], 'companyId': ['41490234']} ``` The last line is a dictionary of key/value pairs.
regex might not be the best solution to this problem ...why not just `my_url.split("?",1)` if that is truly all you wish to do or as others have suggested ``` from urlparse import urlparse print urlparse(my_url) ```
967,634
Is there a way to get a standard Windows Forms application to detect if the `Shift` key is being held down on application startup - without using Windows hooks? I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
2009/06/09
[ "https://Stackoverflow.com/questions/967634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96854/" ]
Check Control.ModifierKeys ... ``` [STAThread] static void Main(string[] args) { if (Control.ModifierKeys == Keys.ShiftKey) { // Do something special } } ```
[Here is an article](http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state) about reading the key states (and mouse) directly.
967,634
Is there a way to get a standard Windows Forms application to detect if the `Shift` key is being held down on application startup - without using Windows hooks? I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
2009/06/09
[ "https://Stackoverflow.com/questions/967634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96854/" ]
The ModifierKeys property looks ideal: ``` private void Form1_Load(object sender, EventArgs e) { if ( (ModifierKeys & Keys.Shift) != 0) { MessageBox.Show("Shift is pressed"); } } ```
[Here is an article](http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state) about reading the key states (and mouse) directly.
967,634
Is there a way to get a standard Windows Forms application to detect if the `Shift` key is being held down on application startup - without using Windows hooks? I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
2009/06/09
[ "https://Stackoverflow.com/questions/967634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96854/" ]
I know this post is rather old but I ran into this issue and fixed it by modifying Jamie's code: ``` [STAThread] static void Main(string[] args) { if (Control.ModifierKeys.ToString() == "Shift") { // Do something special } } ```
[Here is an article](http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state) about reading the key states (and mouse) directly.
967,634
Is there a way to get a standard Windows Forms application to detect if the `Shift` key is being held down on application startup - without using Windows hooks? I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
2009/06/09
[ "https://Stackoverflow.com/questions/967634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96854/" ]
I realize this is super old, but it bothered me a little bit to see people struggling with this. ModifierKeys is a bit field, so relying on .ToString() or == to see if the Shift key is pressed is, at best, unreliable and isn't the correct use of a bit field: ``` public enum ModifierKeys { /// <summary>No modifiers are pressed.</summary> None = 0, /// <summary>The ALT key.</summary> Alt = 1, /// <summary>The CTRL key.</summary> Control = 2, /// <summary>The SHIFT key.</summary> Shift = 4, /// <summary>The Windows logo key.</summary> // Windows = 8, No longer leaked } ``` Either none or any combination of Alt, Control, or Shift may be pressed, so the check should be: ``` if ((ModifierKeys & Keys.Shift) != 0) { MessageBox.Show("Shift is pressed"); } ``` I will up-vote Dan's answer as soon as I earn the right to do so :-) .Net 4+ includes the HasFlag() method as well, but I am accustomed to bitwise operations so I haven't used it. For more information on bitwise operations, flags, (with) truth tables, and other tidbits see: <http://geekswithblogs.net/BlackRabbitCoder/archive/2010/07/22/c-fundamentals-combining-enum-values-with-bit-flags.aspx> What you see in the source is even more intriguing: ``` /// <devdoc> /// Retrieves the current state of the modifier keys. This will check the /// current state of the shift, control, and alt keys. /// </devdoc> public static Keys ModifierKeys { get { Keys modifiers = 0; // SECURITYNOTE : only let state of Shift-Control-Alt out... // if (UnsafeNativeMethods.GetKeyState((int)Keys.ShiftKey) < 0) modifiers |= Keys.Shift; if (UnsafeNativeMethods.GetKeyState((int)Keys.ControlKey) < 0) modifiers |= Keys.Control; if (UnsafeNativeMethods.GetKeyState((int)Keys.Menu) < 0) modifiers |= Keys.Alt; return modifiers; } } ``` This implementation ONLY emits the state of Shift, Control, and Alt. The Windows' key state is not included. If you want to detect the key state BEFORE a form or control is created, maybe in the Main() method, you can go crazy. Maybe you want to to this: ``` if (VirtualKeyState.VK_SHIFT.IsKeyPressed()) { Debugger.Launch(); } ``` Create a simple extension method: ``` public static class KeyAssist { public const int KEY_PRESSED = 0x8000; public static bool IsKeyPressed(this VirtualKeyState key) => Convert.ToBoolean(Native.GetKeyState(key) & KEY_PRESSED); } ``` Import: ``` [DllImport("user32.dll")] public static extern short GetKeyState(VirtualKeyState virtualKeyState); ``` Create the following enum (or some sub-section if you please) (from PInvoke): ``` public enum VirtualKeyState { VK_LBUTTON = 0x01, VK_RBUTTON = 0x02, VK_CANCEL = 0x03, VK_MBUTTON = 0x04, VK_XBUTTON1 = 0x05, VK_XBUTTON2 = 0x06, VK_BACK = 0x08, VK_TAB = 0x09, VK_CLEAR = 0x0C, VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12, VK_PAUSE = 0x13, VK_CAPITAL = 0x14, VK_KANA = 0x15, VK_HANGEUL = 0x15, VK_HANGUL = 0x15, VK_JUNJA = 0x17, VK_FINAL = 0x18, VK_HANJA = 0x19, VK_KANJI = 0x19, VK_ESCAPE = 0x1B, VK_CONVERT = 0x1C, VK_NONCONVERT = 0x1D, VK_ACCEPT = 0x1E, VK_MODECHANGE = 0x1F, VK_SPACE = 0x20, VK_PRIOR = 0x21, VK_NEXT = 0x22, VK_END = 0x23, VK_HOME = 0x24, VK_LEFT = 0x25, VK_UP = 0x26, VK_RIGHT = 0x27, VK_DOWN = 0x28, VK_SELECT = 0x29, VK_PRINT = 0x2A, VK_EXECUTE = 0x2B, VK_SNAPSHOT = 0x2C, VK_INSERT = 0x2D, VK_DELETE = 0x2E, VK_HELP = 0x2F, VK_LWIN = 0x5B, VK_RWIN = 0x5C, VK_APPS = 0x5D, VK_SLEEP = 0x5F, VK_NUMPAD0 = 0x60, VK_NUMPAD1 = 0x61, VK_NUMPAD2 = 0x62, VK_NUMPAD3 = 0x63, VK_NUMPAD4 = 0x64, VK_NUMPAD5 = 0x65, VK_NUMPAD6 = 0x66, VK_NUMPAD7 = 0x67, VK_NUMPAD8 = 0x68, VK_NUMPAD9 = 0x69, VK_MULTIPLY = 0x6A, VK_ADD = 0x6B, VK_SEPARATOR = 0x6C, VK_SUBTRACT = 0x6D, VK_DECIMAL = 0x6E, VK_DIVIDE = 0x6F, VK_F1 = 0x70, VK_F2 = 0x71, VK_F3 = 0x72, VK_F4 = 0x73, VK_F5 = 0x74, VK_F6 = 0x75, VK_F7 = 0x76, VK_F8 = 0x77, VK_F9 = 0x78, VK_F10 = 0x79, VK_F11 = 0x7A, VK_F12 = 0x7B, VK_F13 = 0x7C, VK_F14 = 0x7D, VK_F15 = 0x7E, VK_F16 = 0x7F, VK_F17 = 0x80, VK_F18 = 0x81, VK_F19 = 0x82, VK_F20 = 0x83, VK_F21 = 0x84, VK_F22 = 0x85, VK_F23 = 0x86, VK_F24 = 0x87, VK_NUMLOCK = 0x90, VK_SCROLL = 0x91, VK_OEM_NEC_EQUAL = 0x92, VK_OEM_FJ_JISHO = 0x92, VK_OEM_FJ_MASSHOU = 0x93, VK_OEM_FJ_TOUROKU = 0x94, VK_OEM_FJ_LOYA = 0x95, VK_OEM_FJ_ROYA = 0x96, VK_LSHIFT = 0xA0, VK_RSHIFT = 0xA1, VK_LCONTROL = 0xA2, VK_RCONTROL = 0xA3, VK_LMENU = 0xA4, VK_RMENU = 0xA5, VK_BROWSER_BACK = 0xA6, VK_BROWSER_FORWARD = 0xA7, VK_BROWSER_REFRESH = 0xA8, VK_BROWSER_STOP = 0xA9, VK_BROWSER_SEARCH = 0xAA, VK_BROWSER_FAVORITES = 0xAB, VK_BROWSER_HOME = 0xAC, VK_VOLUME_MUTE = 0xAD, VK_VOLUME_DOWN = 0xAE, VK_VOLUME_UP = 0xAF, VK_MEDIA_NEXT_TRACK = 0xB0, VK_MEDIA_PREV_TRACK = 0xB1, VK_MEDIA_STOP = 0xB2, VK_MEDIA_PLAY_PAUSE = 0xB3, VK_LAUNCH_MAIL = 0xB4, VK_LAUNCH_MEDIA_SELECT = 0xB5, VK_LAUNCH_APP1 = 0xB6, VK_LAUNCH_APP2 = 0xB7, VK_OEM_1 = 0xBA, VK_OEM_PLUS = 0xBB, VK_OEM_COMMA = 0xBC, VK_OEM_MINUS = 0xBD, VK_OEM_PERIOD = 0xBE, VK_OEM_2 = 0xBF, VK_OEM_3 = 0xC0, VK_OEM_4 = 0xDB, VK_OEM_5 = 0xDC, VK_OEM_6 = 0xDD, VK_OEM_7 = 0xDE, VK_OEM_8 = 0xDF, VK_OEM_AX = 0xE1, VK_OEM_102 = 0xE2, VK_ICO_HELP = 0xE3, VK_ICO_00 = 0xE4, VK_PROCESSKEY = 0xE5, VK_ICO_CLEAR = 0xE6, VK_PACKET = 0xE7, VK_OEM_RESET = 0xE9, VK_OEM_JUMP = 0xEA, VK_OEM_PA1 = 0xEB, VK_OEM_PA2 = 0xEC, VK_OEM_PA3 = 0xED, VK_OEM_WSCTRL = 0xEE, VK_OEM_CUSEL = 0xEF, VK_OEM_ATTN = 0xF0, VK_OEM_FINISH = 0xF1, VK_OEM_COPY = 0xF2, VK_OEM_AUTO = 0xF3, VK_OEM_ENLW = 0xF4, VK_OEM_BACKTAB = 0xF5, VK_ATTN = 0xF6, VK_CRSEL = 0xF7, VK_EXSEL = 0xF8, VK_EREOF = 0xF9, VK_PLAY = 0xFA, VK_ZOOM = 0xFB, VK_NONAME = 0xFC, VK_PA1 = 0xFD, VK_OEM_CLEAR = 0xFE } ``` Anyway, this is just for reference so there isn't so much guessing going on. HTH, Colby
[Here is an article](http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state) about reading the key states (and mouse) directly.
967,634
Is there a way to get a standard Windows Forms application to detect if the `Shift` key is being held down on application startup - without using Windows hooks? I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
2009/06/09
[ "https://Stackoverflow.com/questions/967634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96854/" ]
The ModifierKeys property looks ideal: ``` private void Form1_Load(object sender, EventArgs e) { if ( (ModifierKeys & Keys.Shift) != 0) { MessageBox.Show("Shift is pressed"); } } ```
Check Control.ModifierKeys ... ``` [STAThread] static void Main(string[] args) { if (Control.ModifierKeys == Keys.ShiftKey) { // Do something special } } ```
967,634
Is there a way to get a standard Windows Forms application to detect if the `Shift` key is being held down on application startup - without using Windows hooks? I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
2009/06/09
[ "https://Stackoverflow.com/questions/967634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96854/" ]
Check Control.ModifierKeys ... ``` [STAThread] static void Main(string[] args) { if (Control.ModifierKeys == Keys.ShiftKey) { // Do something special } } ```
I know this post is rather old but I ran into this issue and fixed it by modifying Jamie's code: ``` [STAThread] static void Main(string[] args) { if (Control.ModifierKeys.ToString() == "Shift") { // Do something special } } ```
967,634
Is there a way to get a standard Windows Forms application to detect if the `Shift` key is being held down on application startup - without using Windows hooks? I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
2009/06/09
[ "https://Stackoverflow.com/questions/967634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96854/" ]
I realize this is super old, but it bothered me a little bit to see people struggling with this. ModifierKeys is a bit field, so relying on .ToString() or == to see if the Shift key is pressed is, at best, unreliable and isn't the correct use of a bit field: ``` public enum ModifierKeys { /// <summary>No modifiers are pressed.</summary> None = 0, /// <summary>The ALT key.</summary> Alt = 1, /// <summary>The CTRL key.</summary> Control = 2, /// <summary>The SHIFT key.</summary> Shift = 4, /// <summary>The Windows logo key.</summary> // Windows = 8, No longer leaked } ``` Either none or any combination of Alt, Control, or Shift may be pressed, so the check should be: ``` if ((ModifierKeys & Keys.Shift) != 0) { MessageBox.Show("Shift is pressed"); } ``` I will up-vote Dan's answer as soon as I earn the right to do so :-) .Net 4+ includes the HasFlag() method as well, but I am accustomed to bitwise operations so I haven't used it. For more information on bitwise operations, flags, (with) truth tables, and other tidbits see: <http://geekswithblogs.net/BlackRabbitCoder/archive/2010/07/22/c-fundamentals-combining-enum-values-with-bit-flags.aspx> What you see in the source is even more intriguing: ``` /// <devdoc> /// Retrieves the current state of the modifier keys. This will check the /// current state of the shift, control, and alt keys. /// </devdoc> public static Keys ModifierKeys { get { Keys modifiers = 0; // SECURITYNOTE : only let state of Shift-Control-Alt out... // if (UnsafeNativeMethods.GetKeyState((int)Keys.ShiftKey) < 0) modifiers |= Keys.Shift; if (UnsafeNativeMethods.GetKeyState((int)Keys.ControlKey) < 0) modifiers |= Keys.Control; if (UnsafeNativeMethods.GetKeyState((int)Keys.Menu) < 0) modifiers |= Keys.Alt; return modifiers; } } ``` This implementation ONLY emits the state of Shift, Control, and Alt. The Windows' key state is not included. If you want to detect the key state BEFORE a form or control is created, maybe in the Main() method, you can go crazy. Maybe you want to to this: ``` if (VirtualKeyState.VK_SHIFT.IsKeyPressed()) { Debugger.Launch(); } ``` Create a simple extension method: ``` public static class KeyAssist { public const int KEY_PRESSED = 0x8000; public static bool IsKeyPressed(this VirtualKeyState key) => Convert.ToBoolean(Native.GetKeyState(key) & KEY_PRESSED); } ``` Import: ``` [DllImport("user32.dll")] public static extern short GetKeyState(VirtualKeyState virtualKeyState); ``` Create the following enum (or some sub-section if you please) (from PInvoke): ``` public enum VirtualKeyState { VK_LBUTTON = 0x01, VK_RBUTTON = 0x02, VK_CANCEL = 0x03, VK_MBUTTON = 0x04, VK_XBUTTON1 = 0x05, VK_XBUTTON2 = 0x06, VK_BACK = 0x08, VK_TAB = 0x09, VK_CLEAR = 0x0C, VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12, VK_PAUSE = 0x13, VK_CAPITAL = 0x14, VK_KANA = 0x15, VK_HANGEUL = 0x15, VK_HANGUL = 0x15, VK_JUNJA = 0x17, VK_FINAL = 0x18, VK_HANJA = 0x19, VK_KANJI = 0x19, VK_ESCAPE = 0x1B, VK_CONVERT = 0x1C, VK_NONCONVERT = 0x1D, VK_ACCEPT = 0x1E, VK_MODECHANGE = 0x1F, VK_SPACE = 0x20, VK_PRIOR = 0x21, VK_NEXT = 0x22, VK_END = 0x23, VK_HOME = 0x24, VK_LEFT = 0x25, VK_UP = 0x26, VK_RIGHT = 0x27, VK_DOWN = 0x28, VK_SELECT = 0x29, VK_PRINT = 0x2A, VK_EXECUTE = 0x2B, VK_SNAPSHOT = 0x2C, VK_INSERT = 0x2D, VK_DELETE = 0x2E, VK_HELP = 0x2F, VK_LWIN = 0x5B, VK_RWIN = 0x5C, VK_APPS = 0x5D, VK_SLEEP = 0x5F, VK_NUMPAD0 = 0x60, VK_NUMPAD1 = 0x61, VK_NUMPAD2 = 0x62, VK_NUMPAD3 = 0x63, VK_NUMPAD4 = 0x64, VK_NUMPAD5 = 0x65, VK_NUMPAD6 = 0x66, VK_NUMPAD7 = 0x67, VK_NUMPAD8 = 0x68, VK_NUMPAD9 = 0x69, VK_MULTIPLY = 0x6A, VK_ADD = 0x6B, VK_SEPARATOR = 0x6C, VK_SUBTRACT = 0x6D, VK_DECIMAL = 0x6E, VK_DIVIDE = 0x6F, VK_F1 = 0x70, VK_F2 = 0x71, VK_F3 = 0x72, VK_F4 = 0x73, VK_F5 = 0x74, VK_F6 = 0x75, VK_F7 = 0x76, VK_F8 = 0x77, VK_F9 = 0x78, VK_F10 = 0x79, VK_F11 = 0x7A, VK_F12 = 0x7B, VK_F13 = 0x7C, VK_F14 = 0x7D, VK_F15 = 0x7E, VK_F16 = 0x7F, VK_F17 = 0x80, VK_F18 = 0x81, VK_F19 = 0x82, VK_F20 = 0x83, VK_F21 = 0x84, VK_F22 = 0x85, VK_F23 = 0x86, VK_F24 = 0x87, VK_NUMLOCK = 0x90, VK_SCROLL = 0x91, VK_OEM_NEC_EQUAL = 0x92, VK_OEM_FJ_JISHO = 0x92, VK_OEM_FJ_MASSHOU = 0x93, VK_OEM_FJ_TOUROKU = 0x94, VK_OEM_FJ_LOYA = 0x95, VK_OEM_FJ_ROYA = 0x96, VK_LSHIFT = 0xA0, VK_RSHIFT = 0xA1, VK_LCONTROL = 0xA2, VK_RCONTROL = 0xA3, VK_LMENU = 0xA4, VK_RMENU = 0xA5, VK_BROWSER_BACK = 0xA6, VK_BROWSER_FORWARD = 0xA7, VK_BROWSER_REFRESH = 0xA8, VK_BROWSER_STOP = 0xA9, VK_BROWSER_SEARCH = 0xAA, VK_BROWSER_FAVORITES = 0xAB, VK_BROWSER_HOME = 0xAC, VK_VOLUME_MUTE = 0xAD, VK_VOLUME_DOWN = 0xAE, VK_VOLUME_UP = 0xAF, VK_MEDIA_NEXT_TRACK = 0xB0, VK_MEDIA_PREV_TRACK = 0xB1, VK_MEDIA_STOP = 0xB2, VK_MEDIA_PLAY_PAUSE = 0xB3, VK_LAUNCH_MAIL = 0xB4, VK_LAUNCH_MEDIA_SELECT = 0xB5, VK_LAUNCH_APP1 = 0xB6, VK_LAUNCH_APP2 = 0xB7, VK_OEM_1 = 0xBA, VK_OEM_PLUS = 0xBB, VK_OEM_COMMA = 0xBC, VK_OEM_MINUS = 0xBD, VK_OEM_PERIOD = 0xBE, VK_OEM_2 = 0xBF, VK_OEM_3 = 0xC0, VK_OEM_4 = 0xDB, VK_OEM_5 = 0xDC, VK_OEM_6 = 0xDD, VK_OEM_7 = 0xDE, VK_OEM_8 = 0xDF, VK_OEM_AX = 0xE1, VK_OEM_102 = 0xE2, VK_ICO_HELP = 0xE3, VK_ICO_00 = 0xE4, VK_PROCESSKEY = 0xE5, VK_ICO_CLEAR = 0xE6, VK_PACKET = 0xE7, VK_OEM_RESET = 0xE9, VK_OEM_JUMP = 0xEA, VK_OEM_PA1 = 0xEB, VK_OEM_PA2 = 0xEC, VK_OEM_PA3 = 0xED, VK_OEM_WSCTRL = 0xEE, VK_OEM_CUSEL = 0xEF, VK_OEM_ATTN = 0xF0, VK_OEM_FINISH = 0xF1, VK_OEM_COPY = 0xF2, VK_OEM_AUTO = 0xF3, VK_OEM_ENLW = 0xF4, VK_OEM_BACKTAB = 0xF5, VK_ATTN = 0xF6, VK_CRSEL = 0xF7, VK_EXSEL = 0xF8, VK_EREOF = 0xF9, VK_PLAY = 0xFA, VK_ZOOM = 0xFB, VK_NONAME = 0xFC, VK_PA1 = 0xFD, VK_OEM_CLEAR = 0xFE } ``` Anyway, this is just for reference so there isn't so much guessing going on. HTH, Colby
Check Control.ModifierKeys ... ``` [STAThread] static void Main(string[] args) { if (Control.ModifierKeys == Keys.ShiftKey) { // Do something special } } ```
967,634
Is there a way to get a standard Windows Forms application to detect if the `Shift` key is being held down on application startup - without using Windows hooks? I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
2009/06/09
[ "https://Stackoverflow.com/questions/967634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96854/" ]
The ModifierKeys property looks ideal: ``` private void Form1_Load(object sender, EventArgs e) { if ( (ModifierKeys & Keys.Shift) != 0) { MessageBox.Show("Shift is pressed"); } } ```
I know this post is rather old but I ran into this issue and fixed it by modifying Jamie's code: ``` [STAThread] static void Main(string[] args) { if (Control.ModifierKeys.ToString() == "Shift") { // Do something special } } ```
967,634
Is there a way to get a standard Windows Forms application to detect if the `Shift` key is being held down on application startup - without using Windows hooks? I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
2009/06/09
[ "https://Stackoverflow.com/questions/967634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96854/" ]
The ModifierKeys property looks ideal: ``` private void Form1_Load(object sender, EventArgs e) { if ( (ModifierKeys & Keys.Shift) != 0) { MessageBox.Show("Shift is pressed"); } } ```
I realize this is super old, but it bothered me a little bit to see people struggling with this. ModifierKeys is a bit field, so relying on .ToString() or == to see if the Shift key is pressed is, at best, unreliable and isn't the correct use of a bit field: ``` public enum ModifierKeys { /// <summary>No modifiers are pressed.</summary> None = 0, /// <summary>The ALT key.</summary> Alt = 1, /// <summary>The CTRL key.</summary> Control = 2, /// <summary>The SHIFT key.</summary> Shift = 4, /// <summary>The Windows logo key.</summary> // Windows = 8, No longer leaked } ``` Either none or any combination of Alt, Control, or Shift may be pressed, so the check should be: ``` if ((ModifierKeys & Keys.Shift) != 0) { MessageBox.Show("Shift is pressed"); } ``` I will up-vote Dan's answer as soon as I earn the right to do so :-) .Net 4+ includes the HasFlag() method as well, but I am accustomed to bitwise operations so I haven't used it. For more information on bitwise operations, flags, (with) truth tables, and other tidbits see: <http://geekswithblogs.net/BlackRabbitCoder/archive/2010/07/22/c-fundamentals-combining-enum-values-with-bit-flags.aspx> What you see in the source is even more intriguing: ``` /// <devdoc> /// Retrieves the current state of the modifier keys. This will check the /// current state of the shift, control, and alt keys. /// </devdoc> public static Keys ModifierKeys { get { Keys modifiers = 0; // SECURITYNOTE : only let state of Shift-Control-Alt out... // if (UnsafeNativeMethods.GetKeyState((int)Keys.ShiftKey) < 0) modifiers |= Keys.Shift; if (UnsafeNativeMethods.GetKeyState((int)Keys.ControlKey) < 0) modifiers |= Keys.Control; if (UnsafeNativeMethods.GetKeyState((int)Keys.Menu) < 0) modifiers |= Keys.Alt; return modifiers; } } ``` This implementation ONLY emits the state of Shift, Control, and Alt. The Windows' key state is not included. If you want to detect the key state BEFORE a form or control is created, maybe in the Main() method, you can go crazy. Maybe you want to to this: ``` if (VirtualKeyState.VK_SHIFT.IsKeyPressed()) { Debugger.Launch(); } ``` Create a simple extension method: ``` public static class KeyAssist { public const int KEY_PRESSED = 0x8000; public static bool IsKeyPressed(this VirtualKeyState key) => Convert.ToBoolean(Native.GetKeyState(key) & KEY_PRESSED); } ``` Import: ``` [DllImport("user32.dll")] public static extern short GetKeyState(VirtualKeyState virtualKeyState); ``` Create the following enum (or some sub-section if you please) (from PInvoke): ``` public enum VirtualKeyState { VK_LBUTTON = 0x01, VK_RBUTTON = 0x02, VK_CANCEL = 0x03, VK_MBUTTON = 0x04, VK_XBUTTON1 = 0x05, VK_XBUTTON2 = 0x06, VK_BACK = 0x08, VK_TAB = 0x09, VK_CLEAR = 0x0C, VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12, VK_PAUSE = 0x13, VK_CAPITAL = 0x14, VK_KANA = 0x15, VK_HANGEUL = 0x15, VK_HANGUL = 0x15, VK_JUNJA = 0x17, VK_FINAL = 0x18, VK_HANJA = 0x19, VK_KANJI = 0x19, VK_ESCAPE = 0x1B, VK_CONVERT = 0x1C, VK_NONCONVERT = 0x1D, VK_ACCEPT = 0x1E, VK_MODECHANGE = 0x1F, VK_SPACE = 0x20, VK_PRIOR = 0x21, VK_NEXT = 0x22, VK_END = 0x23, VK_HOME = 0x24, VK_LEFT = 0x25, VK_UP = 0x26, VK_RIGHT = 0x27, VK_DOWN = 0x28, VK_SELECT = 0x29, VK_PRINT = 0x2A, VK_EXECUTE = 0x2B, VK_SNAPSHOT = 0x2C, VK_INSERT = 0x2D, VK_DELETE = 0x2E, VK_HELP = 0x2F, VK_LWIN = 0x5B, VK_RWIN = 0x5C, VK_APPS = 0x5D, VK_SLEEP = 0x5F, VK_NUMPAD0 = 0x60, VK_NUMPAD1 = 0x61, VK_NUMPAD2 = 0x62, VK_NUMPAD3 = 0x63, VK_NUMPAD4 = 0x64, VK_NUMPAD5 = 0x65, VK_NUMPAD6 = 0x66, VK_NUMPAD7 = 0x67, VK_NUMPAD8 = 0x68, VK_NUMPAD9 = 0x69, VK_MULTIPLY = 0x6A, VK_ADD = 0x6B, VK_SEPARATOR = 0x6C, VK_SUBTRACT = 0x6D, VK_DECIMAL = 0x6E, VK_DIVIDE = 0x6F, VK_F1 = 0x70, VK_F2 = 0x71, VK_F3 = 0x72, VK_F4 = 0x73, VK_F5 = 0x74, VK_F6 = 0x75, VK_F7 = 0x76, VK_F8 = 0x77, VK_F9 = 0x78, VK_F10 = 0x79, VK_F11 = 0x7A, VK_F12 = 0x7B, VK_F13 = 0x7C, VK_F14 = 0x7D, VK_F15 = 0x7E, VK_F16 = 0x7F, VK_F17 = 0x80, VK_F18 = 0x81, VK_F19 = 0x82, VK_F20 = 0x83, VK_F21 = 0x84, VK_F22 = 0x85, VK_F23 = 0x86, VK_F24 = 0x87, VK_NUMLOCK = 0x90, VK_SCROLL = 0x91, VK_OEM_NEC_EQUAL = 0x92, VK_OEM_FJ_JISHO = 0x92, VK_OEM_FJ_MASSHOU = 0x93, VK_OEM_FJ_TOUROKU = 0x94, VK_OEM_FJ_LOYA = 0x95, VK_OEM_FJ_ROYA = 0x96, VK_LSHIFT = 0xA0, VK_RSHIFT = 0xA1, VK_LCONTROL = 0xA2, VK_RCONTROL = 0xA3, VK_LMENU = 0xA4, VK_RMENU = 0xA5, VK_BROWSER_BACK = 0xA6, VK_BROWSER_FORWARD = 0xA7, VK_BROWSER_REFRESH = 0xA8, VK_BROWSER_STOP = 0xA9, VK_BROWSER_SEARCH = 0xAA, VK_BROWSER_FAVORITES = 0xAB, VK_BROWSER_HOME = 0xAC, VK_VOLUME_MUTE = 0xAD, VK_VOLUME_DOWN = 0xAE, VK_VOLUME_UP = 0xAF, VK_MEDIA_NEXT_TRACK = 0xB0, VK_MEDIA_PREV_TRACK = 0xB1, VK_MEDIA_STOP = 0xB2, VK_MEDIA_PLAY_PAUSE = 0xB3, VK_LAUNCH_MAIL = 0xB4, VK_LAUNCH_MEDIA_SELECT = 0xB5, VK_LAUNCH_APP1 = 0xB6, VK_LAUNCH_APP2 = 0xB7, VK_OEM_1 = 0xBA, VK_OEM_PLUS = 0xBB, VK_OEM_COMMA = 0xBC, VK_OEM_MINUS = 0xBD, VK_OEM_PERIOD = 0xBE, VK_OEM_2 = 0xBF, VK_OEM_3 = 0xC0, VK_OEM_4 = 0xDB, VK_OEM_5 = 0xDC, VK_OEM_6 = 0xDD, VK_OEM_7 = 0xDE, VK_OEM_8 = 0xDF, VK_OEM_AX = 0xE1, VK_OEM_102 = 0xE2, VK_ICO_HELP = 0xE3, VK_ICO_00 = 0xE4, VK_PROCESSKEY = 0xE5, VK_ICO_CLEAR = 0xE6, VK_PACKET = 0xE7, VK_OEM_RESET = 0xE9, VK_OEM_JUMP = 0xEA, VK_OEM_PA1 = 0xEB, VK_OEM_PA2 = 0xEC, VK_OEM_PA3 = 0xED, VK_OEM_WSCTRL = 0xEE, VK_OEM_CUSEL = 0xEF, VK_OEM_ATTN = 0xF0, VK_OEM_FINISH = 0xF1, VK_OEM_COPY = 0xF2, VK_OEM_AUTO = 0xF3, VK_OEM_ENLW = 0xF4, VK_OEM_BACKTAB = 0xF5, VK_ATTN = 0xF6, VK_CRSEL = 0xF7, VK_EXSEL = 0xF8, VK_EREOF = 0xF9, VK_PLAY = 0xFA, VK_ZOOM = 0xFB, VK_NONAME = 0xFC, VK_PA1 = 0xFD, VK_OEM_CLEAR = 0xFE } ``` Anyway, this is just for reference so there isn't so much guessing going on. HTH, Colby
967,634
Is there a way to get a standard Windows Forms application to detect if the `Shift` key is being held down on application startup - without using Windows hooks? I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
2009/06/09
[ "https://Stackoverflow.com/questions/967634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96854/" ]
I realize this is super old, but it bothered me a little bit to see people struggling with this. ModifierKeys is a bit field, so relying on .ToString() or == to see if the Shift key is pressed is, at best, unreliable and isn't the correct use of a bit field: ``` public enum ModifierKeys { /// <summary>No modifiers are pressed.</summary> None = 0, /// <summary>The ALT key.</summary> Alt = 1, /// <summary>The CTRL key.</summary> Control = 2, /// <summary>The SHIFT key.</summary> Shift = 4, /// <summary>The Windows logo key.</summary> // Windows = 8, No longer leaked } ``` Either none or any combination of Alt, Control, or Shift may be pressed, so the check should be: ``` if ((ModifierKeys & Keys.Shift) != 0) { MessageBox.Show("Shift is pressed"); } ``` I will up-vote Dan's answer as soon as I earn the right to do so :-) .Net 4+ includes the HasFlag() method as well, but I am accustomed to bitwise operations so I haven't used it. For more information on bitwise operations, flags, (with) truth tables, and other tidbits see: <http://geekswithblogs.net/BlackRabbitCoder/archive/2010/07/22/c-fundamentals-combining-enum-values-with-bit-flags.aspx> What you see in the source is even more intriguing: ``` /// <devdoc> /// Retrieves the current state of the modifier keys. This will check the /// current state of the shift, control, and alt keys. /// </devdoc> public static Keys ModifierKeys { get { Keys modifiers = 0; // SECURITYNOTE : only let state of Shift-Control-Alt out... // if (UnsafeNativeMethods.GetKeyState((int)Keys.ShiftKey) < 0) modifiers |= Keys.Shift; if (UnsafeNativeMethods.GetKeyState((int)Keys.ControlKey) < 0) modifiers |= Keys.Control; if (UnsafeNativeMethods.GetKeyState((int)Keys.Menu) < 0) modifiers |= Keys.Alt; return modifiers; } } ``` This implementation ONLY emits the state of Shift, Control, and Alt. The Windows' key state is not included. If you want to detect the key state BEFORE a form or control is created, maybe in the Main() method, you can go crazy. Maybe you want to to this: ``` if (VirtualKeyState.VK_SHIFT.IsKeyPressed()) { Debugger.Launch(); } ``` Create a simple extension method: ``` public static class KeyAssist { public const int KEY_PRESSED = 0x8000; public static bool IsKeyPressed(this VirtualKeyState key) => Convert.ToBoolean(Native.GetKeyState(key) & KEY_PRESSED); } ``` Import: ``` [DllImport("user32.dll")] public static extern short GetKeyState(VirtualKeyState virtualKeyState); ``` Create the following enum (or some sub-section if you please) (from PInvoke): ``` public enum VirtualKeyState { VK_LBUTTON = 0x01, VK_RBUTTON = 0x02, VK_CANCEL = 0x03, VK_MBUTTON = 0x04, VK_XBUTTON1 = 0x05, VK_XBUTTON2 = 0x06, VK_BACK = 0x08, VK_TAB = 0x09, VK_CLEAR = 0x0C, VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12, VK_PAUSE = 0x13, VK_CAPITAL = 0x14, VK_KANA = 0x15, VK_HANGEUL = 0x15, VK_HANGUL = 0x15, VK_JUNJA = 0x17, VK_FINAL = 0x18, VK_HANJA = 0x19, VK_KANJI = 0x19, VK_ESCAPE = 0x1B, VK_CONVERT = 0x1C, VK_NONCONVERT = 0x1D, VK_ACCEPT = 0x1E, VK_MODECHANGE = 0x1F, VK_SPACE = 0x20, VK_PRIOR = 0x21, VK_NEXT = 0x22, VK_END = 0x23, VK_HOME = 0x24, VK_LEFT = 0x25, VK_UP = 0x26, VK_RIGHT = 0x27, VK_DOWN = 0x28, VK_SELECT = 0x29, VK_PRINT = 0x2A, VK_EXECUTE = 0x2B, VK_SNAPSHOT = 0x2C, VK_INSERT = 0x2D, VK_DELETE = 0x2E, VK_HELP = 0x2F, VK_LWIN = 0x5B, VK_RWIN = 0x5C, VK_APPS = 0x5D, VK_SLEEP = 0x5F, VK_NUMPAD0 = 0x60, VK_NUMPAD1 = 0x61, VK_NUMPAD2 = 0x62, VK_NUMPAD3 = 0x63, VK_NUMPAD4 = 0x64, VK_NUMPAD5 = 0x65, VK_NUMPAD6 = 0x66, VK_NUMPAD7 = 0x67, VK_NUMPAD8 = 0x68, VK_NUMPAD9 = 0x69, VK_MULTIPLY = 0x6A, VK_ADD = 0x6B, VK_SEPARATOR = 0x6C, VK_SUBTRACT = 0x6D, VK_DECIMAL = 0x6E, VK_DIVIDE = 0x6F, VK_F1 = 0x70, VK_F2 = 0x71, VK_F3 = 0x72, VK_F4 = 0x73, VK_F5 = 0x74, VK_F6 = 0x75, VK_F7 = 0x76, VK_F8 = 0x77, VK_F9 = 0x78, VK_F10 = 0x79, VK_F11 = 0x7A, VK_F12 = 0x7B, VK_F13 = 0x7C, VK_F14 = 0x7D, VK_F15 = 0x7E, VK_F16 = 0x7F, VK_F17 = 0x80, VK_F18 = 0x81, VK_F19 = 0x82, VK_F20 = 0x83, VK_F21 = 0x84, VK_F22 = 0x85, VK_F23 = 0x86, VK_F24 = 0x87, VK_NUMLOCK = 0x90, VK_SCROLL = 0x91, VK_OEM_NEC_EQUAL = 0x92, VK_OEM_FJ_JISHO = 0x92, VK_OEM_FJ_MASSHOU = 0x93, VK_OEM_FJ_TOUROKU = 0x94, VK_OEM_FJ_LOYA = 0x95, VK_OEM_FJ_ROYA = 0x96, VK_LSHIFT = 0xA0, VK_RSHIFT = 0xA1, VK_LCONTROL = 0xA2, VK_RCONTROL = 0xA3, VK_LMENU = 0xA4, VK_RMENU = 0xA5, VK_BROWSER_BACK = 0xA6, VK_BROWSER_FORWARD = 0xA7, VK_BROWSER_REFRESH = 0xA8, VK_BROWSER_STOP = 0xA9, VK_BROWSER_SEARCH = 0xAA, VK_BROWSER_FAVORITES = 0xAB, VK_BROWSER_HOME = 0xAC, VK_VOLUME_MUTE = 0xAD, VK_VOLUME_DOWN = 0xAE, VK_VOLUME_UP = 0xAF, VK_MEDIA_NEXT_TRACK = 0xB0, VK_MEDIA_PREV_TRACK = 0xB1, VK_MEDIA_STOP = 0xB2, VK_MEDIA_PLAY_PAUSE = 0xB3, VK_LAUNCH_MAIL = 0xB4, VK_LAUNCH_MEDIA_SELECT = 0xB5, VK_LAUNCH_APP1 = 0xB6, VK_LAUNCH_APP2 = 0xB7, VK_OEM_1 = 0xBA, VK_OEM_PLUS = 0xBB, VK_OEM_COMMA = 0xBC, VK_OEM_MINUS = 0xBD, VK_OEM_PERIOD = 0xBE, VK_OEM_2 = 0xBF, VK_OEM_3 = 0xC0, VK_OEM_4 = 0xDB, VK_OEM_5 = 0xDC, VK_OEM_6 = 0xDD, VK_OEM_7 = 0xDE, VK_OEM_8 = 0xDF, VK_OEM_AX = 0xE1, VK_OEM_102 = 0xE2, VK_ICO_HELP = 0xE3, VK_ICO_00 = 0xE4, VK_PROCESSKEY = 0xE5, VK_ICO_CLEAR = 0xE6, VK_PACKET = 0xE7, VK_OEM_RESET = 0xE9, VK_OEM_JUMP = 0xEA, VK_OEM_PA1 = 0xEB, VK_OEM_PA2 = 0xEC, VK_OEM_PA3 = 0xED, VK_OEM_WSCTRL = 0xEE, VK_OEM_CUSEL = 0xEF, VK_OEM_ATTN = 0xF0, VK_OEM_FINISH = 0xF1, VK_OEM_COPY = 0xF2, VK_OEM_AUTO = 0xF3, VK_OEM_ENLW = 0xF4, VK_OEM_BACKTAB = 0xF5, VK_ATTN = 0xF6, VK_CRSEL = 0xF7, VK_EXSEL = 0xF8, VK_EREOF = 0xF9, VK_PLAY = 0xFA, VK_ZOOM = 0xFB, VK_NONAME = 0xFC, VK_PA1 = 0xFD, VK_OEM_CLEAR = 0xFE } ``` Anyway, this is just for reference so there isn't so much guessing going on. HTH, Colby
I know this post is rather old but I ran into this issue and fixed it by modifying Jamie's code: ``` [STAThread] static void Main(string[] args) { if (Control.ModifierKeys.ToString() == "Shift") { // Do something special } } ```
39,197,849
I added a dependency to my pom.xml file but cannot find the option to import the dependency. I'm not able to use the library in my program. I've looked online and many suggest going to Settings -> Maven -> .... but this option simply does not exist for me. I have also seen other solutions of simply right clicking the pom.xml -> Maven -> Reimport. Again, I don't have this option. I am pretty sure this is a Maven project. Does anyone know what might be the problem?
2016/08/29
[ "https://Stackoverflow.com/questions/39197849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4364070/" ]
You might need to configure Auto-Import for Maven projects. You can enable such feature going to `File > Settings > Maven > Importing`. There is a checkbox that says "Import Maven projects automatically". If you can't find that option, try using `Ctrl+Shift+A` that helps you to find actions by name. Just write "maven" and check what alternative suits you the best. If this do not work, open my "Maven Project" Panel. Find it at the right side of your IDE. There you have the reimport button. [![Maven Projects Panel](https://i.stack.imgur.com/XgVPO.png)](https://i.stack.imgur.com/XgVPO.png) **EDIT:** A few weeks ago, I faced the same problem when reimporting a project. It was due to Intellij didn't remember the setting for the maven setting file. I needed to override the default "User settings file" (see the picture below) with my valid ~/.m2 path. [![User settings](https://i.stack.imgur.com/GCoMj.jpg)](https://i.stack.imgur.com/GCoMj.jpg)
The maven will automatically download the jar file from public repository after you save the pom file. If you find that it doesn't exist in your maven dependencies, you can try to check below: 1. Check your network connectivity, whether it's able to connect to public repository. 2. Check whether the required dependency exist in public. 3. If it's a local dependency, please make sure you have done the Maven Install.
39,197,849
I added a dependency to my pom.xml file but cannot find the option to import the dependency. I'm not able to use the library in my program. I've looked online and many suggest going to Settings -> Maven -> .... but this option simply does not exist for me. I have also seen other solutions of simply right clicking the pom.xml -> Maven -> Reimport. Again, I don't have this option. I am pretty sure this is a Maven project. Does anyone know what might be the problem?
2016/08/29
[ "https://Stackoverflow.com/questions/39197849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4364070/" ]
You might need to configure Auto-Import for Maven projects. You can enable such feature going to `File > Settings > Maven > Importing`. There is a checkbox that says "Import Maven projects automatically". If you can't find that option, try using `Ctrl+Shift+A` that helps you to find actions by name. Just write "maven" and check what alternative suits you the best. If this do not work, open my "Maven Project" Panel. Find it at the right side of your IDE. There you have the reimport button. [![Maven Projects Panel](https://i.stack.imgur.com/XgVPO.png)](https://i.stack.imgur.com/XgVPO.png) **EDIT:** A few weeks ago, I faced the same problem when reimporting a project. It was due to Intellij didn't remember the setting for the maven setting file. I needed to override the default "User settings file" (see the picture below) with my valid ~/.m2 path. [![User settings](https://i.stack.imgur.com/GCoMj.jpg)](https://i.stack.imgur.com/GCoMj.jpg)
IntelliJ should download and add all your dependencies to the project's classpath automatically as long as your POM is compliant and all the dependencies are available. When importing Maven projects into IntelliJ an information box usually comes up asking you if you want to configure Auto-Import for Maven projects. That means that if you make any changes to your POM those changes will be loaded automatically. You can enable such feature going to `File > Settings > Maven > Importing`, there is a checkbox that says "Import Maven projects automatically". If that doesn't help, then I would suggest to make a full clean-up and start again: * Close your project window (and IntelliJ) and remove all `*.iml` files and all `.idea` folders (there should be one per module). * Run `mvn clean` install from the command line * Re-import the project into IntelliJ and pay attention when it asks you to enable auto-import Check this [post](https://stackoverflow.com/questions/11454822/import-maven-dependencies-in-intellij-idea) for more Information
204,277
I have a card game, where I'd like to be able to zoom in on a card if it's right clicked. I coded to make sure that if the zoomed card would go over a screen boundary, instead we would anchor it such that the full card is displayed. I initially hardcoded everything for 1920x1080 resolution, then I wanted to get it to work for an arbitrary resolution. The logic seems to work for all resolutions except for `QHD` and `4k UHD`. I feel like I have a fundamental misunderstanding of resolutions, or I'm missing something with either how `RectTransform` scaling works, or how the units for width/height correspond to resolutions, or how the interaction between `Canvas` and `CanvasScaler` work with resolutions. The math seems simple, but it's not working for these resolutions, so I'm obviously missing something. For reference: [![Canvas Settings](https://i.stack.imgur.com/AG95F.png)](https://i.stack.imgur.com/AG95F.png) ``` using UnityEngine; using UnityEngine.EventSystems; public class Zoomable : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { private GameObject _popOutCard; private bool _enabled; // Works for all resolutions except QHD and 4k UHD. // Calculations: Card Dimensions are 150 x 200. // So, if we're, for example, scaling by a factor of 2, the zoomed cards are 300 x 400. // We're using the (x,y) coordinates of the cursor. // So for 1920 x 1080, for example: // To display a zoomed card, its center with respect to x can never be less than 155 (300/2, with an offset of 5). // The same logic is applied to the other 3 boundaries. private const int _offset = 5; private const int _cardHeightHalfed = 100; private const int _cardWidthHalfed = 75; private float _topBoundary; private float _bottomBoundary; private float _leftBoundary; private float _rightBoundary; [SerializeField] private float _scaleFactor = 2.5f; private Transform _canvasTransform; void Awake() { // We're mixing ints and floats here, but it's fine. _canvasTransform = transform.root; _topBoundary = Screen.height - _scaleFactor * _cardHeightHalfed - _offset; _bottomBoundary =_scaleFactor * _cardHeightHalfed + _offset; _leftBoundary = _scaleFactor * _cardWidthHalfed + _offset; _rightBoundary = Screen.width - _scaleFactor * _cardWidthHalfed - _offset; var resolution = Screen.currentResolution; Debug.Log($"Resolution height: {resolution.height}, resolution width: {resolution.width}"); Debug.Log($"Screen height: {Screen.height}, resolution width: {Screen.width}"); } public void OnPointerDown(PointerEventData eventData) { if (eventData.button == PointerEventData.InputButton.Right) { ZoomPopOut(); } } public void OnPointerUp(PointerEventData eventData) { Debug.Log("OnPointerUp called"); if (_enabled) { OnZoomPopOutExit(); } } private void ZoomPopOut() { float xPosition = Input.mousePosition.x; float yPosition = Input.mousePosition.y; Debug.Log($"x position: {xPosition}, y position: {yPosition}"); float popOutXPosition = xPosition; float popOutYPosition = yPosition; if (xPosition < _leftBoundary) { popOutXPosition = _leftBoundary; } if (xPosition > _rightBoundary) { popOutXPosition = _rightBoundary; } if (yPosition < _bottomBoundary) { popOutYPosition = _bottomBoundary; } if (yPosition > _topBoundary) { popOutYPosition = _topBoundary; } Debug.Log($"Pop out x position: {popOutXPosition}, pop out y position: {popOutYPosition}"); _popOutCard = Instantiate(gameObject, new Vector2(popOutXPosition, popOutYPosition), Quaternion.identity); _popOutCard.transform.SetParent(_canvasTransform); _popOutCard.transform.SetAsLastSibling(); RectTransform rect = _popOutCard.GetComponent<RectTransform>(); rect.localScale = new Vector3(_scaleFactor, _scaleFactor, _scaleFactor); _enabled = true; } private void OnZoomPopOutExit() { Debug.Log("OnZoomPopOutExit() called"); _enabled = false; Destroy(_popOutCard); } } ```
2023/01/28
[ "https://gamedev.stackexchange.com/questions/204277", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/78465/" ]
I have no idea what answer is expected but if I'm asked on an interview I would say the "problem" is that GC requires freezing of the state of the program but games are usually very dynamic. This makes those freezes much easier to spot with games where there are constant movements on the screen (stuttering). Until recently GC used by Unity was not incremental, meaning it must do all its job in single game freeze. And that may make those freezes long enough to be noticed. Now there is an option for incremental GC (i.e. staged GC, freezes more often for shorter times) but it must be profiled if it brings improvement for the current game. Incremental GC have this problem of the state of the game changing between GC stages which can force the GC to re-analyse the changed state over and over from scratch and ultimately be slower than the non-incremental one.
Garbage collection in Unity refers to the .NET GC. There is no "problem" with GC other than what you would expect to find with the pros and cons of a GC, and you can read about .NET GC on the web easily. What they are probably expecting to hear, is that Unity does not do a garbage collection cycle until you call LoadScene and switch to another scene. LoadAdditive does not call GC.
204,277
I have a card game, where I'd like to be able to zoom in on a card if it's right clicked. I coded to make sure that if the zoomed card would go over a screen boundary, instead we would anchor it such that the full card is displayed. I initially hardcoded everything for 1920x1080 resolution, then I wanted to get it to work for an arbitrary resolution. The logic seems to work for all resolutions except for `QHD` and `4k UHD`. I feel like I have a fundamental misunderstanding of resolutions, or I'm missing something with either how `RectTransform` scaling works, or how the units for width/height correspond to resolutions, or how the interaction between `Canvas` and `CanvasScaler` work with resolutions. The math seems simple, but it's not working for these resolutions, so I'm obviously missing something. For reference: [![Canvas Settings](https://i.stack.imgur.com/AG95F.png)](https://i.stack.imgur.com/AG95F.png) ``` using UnityEngine; using UnityEngine.EventSystems; public class Zoomable : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { private GameObject _popOutCard; private bool _enabled; // Works for all resolutions except QHD and 4k UHD. // Calculations: Card Dimensions are 150 x 200. // So, if we're, for example, scaling by a factor of 2, the zoomed cards are 300 x 400. // We're using the (x,y) coordinates of the cursor. // So for 1920 x 1080, for example: // To display a zoomed card, its center with respect to x can never be less than 155 (300/2, with an offset of 5). // The same logic is applied to the other 3 boundaries. private const int _offset = 5; private const int _cardHeightHalfed = 100; private const int _cardWidthHalfed = 75; private float _topBoundary; private float _bottomBoundary; private float _leftBoundary; private float _rightBoundary; [SerializeField] private float _scaleFactor = 2.5f; private Transform _canvasTransform; void Awake() { // We're mixing ints and floats here, but it's fine. _canvasTransform = transform.root; _topBoundary = Screen.height - _scaleFactor * _cardHeightHalfed - _offset; _bottomBoundary =_scaleFactor * _cardHeightHalfed + _offset; _leftBoundary = _scaleFactor * _cardWidthHalfed + _offset; _rightBoundary = Screen.width - _scaleFactor * _cardWidthHalfed - _offset; var resolution = Screen.currentResolution; Debug.Log($"Resolution height: {resolution.height}, resolution width: {resolution.width}"); Debug.Log($"Screen height: {Screen.height}, resolution width: {Screen.width}"); } public void OnPointerDown(PointerEventData eventData) { if (eventData.button == PointerEventData.InputButton.Right) { ZoomPopOut(); } } public void OnPointerUp(PointerEventData eventData) { Debug.Log("OnPointerUp called"); if (_enabled) { OnZoomPopOutExit(); } } private void ZoomPopOut() { float xPosition = Input.mousePosition.x; float yPosition = Input.mousePosition.y; Debug.Log($"x position: {xPosition}, y position: {yPosition}"); float popOutXPosition = xPosition; float popOutYPosition = yPosition; if (xPosition < _leftBoundary) { popOutXPosition = _leftBoundary; } if (xPosition > _rightBoundary) { popOutXPosition = _rightBoundary; } if (yPosition < _bottomBoundary) { popOutYPosition = _bottomBoundary; } if (yPosition > _topBoundary) { popOutYPosition = _topBoundary; } Debug.Log($"Pop out x position: {popOutXPosition}, pop out y position: {popOutYPosition}"); _popOutCard = Instantiate(gameObject, new Vector2(popOutXPosition, popOutYPosition), Quaternion.identity); _popOutCard.transform.SetParent(_canvasTransform); _popOutCard.transform.SetAsLastSibling(); RectTransform rect = _popOutCard.GetComponent<RectTransform>(); rect.localScale = new Vector3(_scaleFactor, _scaleFactor, _scaleFactor); _enabled = true; } private void OnZoomPopOutExit() { Debug.Log("OnZoomPopOutExit() called"); _enabled = false; Destroy(_popOutCard); } } ```
2023/01/28
[ "https://gamedev.stackexchange.com/questions/204277", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/78465/" ]
Based on the documentation for [memory management & garbage collection](https://docs.unity3d.com/Manual/webgl-memory.html#garbage): Allocating managed memory is time-consuming for the CPU, so memory management (including garbage collection) impacts runtime performance. At an extreme, garbage collection can prevent the CPU from doing other work until it completes. Note: I take this to mean "completes some task". As others have noted, the GC is incremental, but while it might not need to stop everything to solve everything (see [prior versions of memory management](https://docs.unity3d.com/550/Documentation/Manual/webgl-memory.html) for details), it may still need to consume CPU time in a way that is noticeable. Unity's memory management can lead to memory fragmentation, meaning the available & allocated blocks of memory are interspersed. Basically, "gaps" of available memory form as garbage collection releases memory that's no longer needed. As a result you can have situations where sufficient amount of memory available in the managed heap for some allocation, but it is only available in the "gaps" between allocated objects that are still in use. In that case the managed heap can't find a large enough single block of contiguous memory to perform the assignment. Here's an illustration: [![fragmented memory example](https://i.stack.imgur.com/bS11I.jpg)](https://i.stack.imgur.com/bS11I.jpg) `A` shows the allocation that we want to make `B` shows available memory: a block from a previously deallocated `string`, a block from a previously deallocated `int[]` & a free block. If the garbage collector runs & cannot find enough contiguous space, it expands the heaps. Expansion is platform-dependent, so it's not a learn it once apply it everywhere sort of thing - you should consider each separately. The typical expansion is double the amount of the previous expansion. Eventually Unity releases empty portions of the managed heap back to the operating system, but it doesn't do so at reliable intervals. Summarizing: * Memory management & garbage collection require CPU time. * Garbage collection can lead to fragmentation. * Fragmentation can lead to not having enough *continuous* memory. * Lack of continuous memory triggers expansion. * Expansion rules vary by platform. * Memory isn't returned back to the OS at predictable intervals.
Garbage collection in Unity refers to the .NET GC. There is no "problem" with GC other than what you would expect to find with the pros and cons of a GC, and you can read about .NET GC on the web easily. What they are probably expecting to hear, is that Unity does not do a garbage collection cycle until you call LoadScene and switch to another scene. LoadAdditive does not call GC.
204,277
I have a card game, where I'd like to be able to zoom in on a card if it's right clicked. I coded to make sure that if the zoomed card would go over a screen boundary, instead we would anchor it such that the full card is displayed. I initially hardcoded everything for 1920x1080 resolution, then I wanted to get it to work for an arbitrary resolution. The logic seems to work for all resolutions except for `QHD` and `4k UHD`. I feel like I have a fundamental misunderstanding of resolutions, or I'm missing something with either how `RectTransform` scaling works, or how the units for width/height correspond to resolutions, or how the interaction between `Canvas` and `CanvasScaler` work with resolutions. The math seems simple, but it's not working for these resolutions, so I'm obviously missing something. For reference: [![Canvas Settings](https://i.stack.imgur.com/AG95F.png)](https://i.stack.imgur.com/AG95F.png) ``` using UnityEngine; using UnityEngine.EventSystems; public class Zoomable : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { private GameObject _popOutCard; private bool _enabled; // Works for all resolutions except QHD and 4k UHD. // Calculations: Card Dimensions are 150 x 200. // So, if we're, for example, scaling by a factor of 2, the zoomed cards are 300 x 400. // We're using the (x,y) coordinates of the cursor. // So for 1920 x 1080, for example: // To display a zoomed card, its center with respect to x can never be less than 155 (300/2, with an offset of 5). // The same logic is applied to the other 3 boundaries. private const int _offset = 5; private const int _cardHeightHalfed = 100; private const int _cardWidthHalfed = 75; private float _topBoundary; private float _bottomBoundary; private float _leftBoundary; private float _rightBoundary; [SerializeField] private float _scaleFactor = 2.5f; private Transform _canvasTransform; void Awake() { // We're mixing ints and floats here, but it's fine. _canvasTransform = transform.root; _topBoundary = Screen.height - _scaleFactor * _cardHeightHalfed - _offset; _bottomBoundary =_scaleFactor * _cardHeightHalfed + _offset; _leftBoundary = _scaleFactor * _cardWidthHalfed + _offset; _rightBoundary = Screen.width - _scaleFactor * _cardWidthHalfed - _offset; var resolution = Screen.currentResolution; Debug.Log($"Resolution height: {resolution.height}, resolution width: {resolution.width}"); Debug.Log($"Screen height: {Screen.height}, resolution width: {Screen.width}"); } public void OnPointerDown(PointerEventData eventData) { if (eventData.button == PointerEventData.InputButton.Right) { ZoomPopOut(); } } public void OnPointerUp(PointerEventData eventData) { Debug.Log("OnPointerUp called"); if (_enabled) { OnZoomPopOutExit(); } } private void ZoomPopOut() { float xPosition = Input.mousePosition.x; float yPosition = Input.mousePosition.y; Debug.Log($"x position: {xPosition}, y position: {yPosition}"); float popOutXPosition = xPosition; float popOutYPosition = yPosition; if (xPosition < _leftBoundary) { popOutXPosition = _leftBoundary; } if (xPosition > _rightBoundary) { popOutXPosition = _rightBoundary; } if (yPosition < _bottomBoundary) { popOutYPosition = _bottomBoundary; } if (yPosition > _topBoundary) { popOutYPosition = _topBoundary; } Debug.Log($"Pop out x position: {popOutXPosition}, pop out y position: {popOutYPosition}"); _popOutCard = Instantiate(gameObject, new Vector2(popOutXPosition, popOutYPosition), Quaternion.identity); _popOutCard.transform.SetParent(_canvasTransform); _popOutCard.transform.SetAsLastSibling(); RectTransform rect = _popOutCard.GetComponent<RectTransform>(); rect.localScale = new Vector3(_scaleFactor, _scaleFactor, _scaleFactor); _enabled = true; } private void OnZoomPopOutExit() { Debug.Log("OnZoomPopOutExit() called"); _enabled = false; Destroy(_popOutCard); } } ```
2023/01/28
[ "https://gamedev.stackexchange.com/questions/204277", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/78465/" ]
I have no idea what answer is expected but if I'm asked on an interview I would say the "problem" is that GC requires freezing of the state of the program but games are usually very dynamic. This makes those freezes much easier to spot with games where there are constant movements on the screen (stuttering). Until recently GC used by Unity was not incremental, meaning it must do all its job in single game freeze. And that may make those freezes long enough to be noticed. Now there is an option for incremental GC (i.e. staged GC, freezes more often for shorter times) but it must be profiled if it brings improvement for the current game. Incremental GC have this problem of the state of the game changing between GC stages which can force the GC to re-analyse the changed state over and over from scratch and ultimately be slower than the non-incremental one.
Based on the documentation for [memory management & garbage collection](https://docs.unity3d.com/Manual/webgl-memory.html#garbage): Allocating managed memory is time-consuming for the CPU, so memory management (including garbage collection) impacts runtime performance. At an extreme, garbage collection can prevent the CPU from doing other work until it completes. Note: I take this to mean "completes some task". As others have noted, the GC is incremental, but while it might not need to stop everything to solve everything (see [prior versions of memory management](https://docs.unity3d.com/550/Documentation/Manual/webgl-memory.html) for details), it may still need to consume CPU time in a way that is noticeable. Unity's memory management can lead to memory fragmentation, meaning the available & allocated blocks of memory are interspersed. Basically, "gaps" of available memory form as garbage collection releases memory that's no longer needed. As a result you can have situations where sufficient amount of memory available in the managed heap for some allocation, but it is only available in the "gaps" between allocated objects that are still in use. In that case the managed heap can't find a large enough single block of contiguous memory to perform the assignment. Here's an illustration: [![fragmented memory example](https://i.stack.imgur.com/bS11I.jpg)](https://i.stack.imgur.com/bS11I.jpg) `A` shows the allocation that we want to make `B` shows available memory: a block from a previously deallocated `string`, a block from a previously deallocated `int[]` & a free block. If the garbage collector runs & cannot find enough contiguous space, it expands the heaps. Expansion is platform-dependent, so it's not a learn it once apply it everywhere sort of thing - you should consider each separately. The typical expansion is double the amount of the previous expansion. Eventually Unity releases empty portions of the managed heap back to the operating system, but it doesn't do so at reliable intervals. Summarizing: * Memory management & garbage collection require CPU time. * Garbage collection can lead to fragmentation. * Fragmentation can lead to not having enough *continuous* memory. * Lack of continuous memory triggers expansion. * Expansion rules vary by platform. * Memory isn't returned back to the OS at predictable intervals.
14,012,272
I have a jaxws WebService which allows to downloadImage (or atleast it should...) The cod of webservice: ``` @WebService(name = "SimpleWebService") @MTOM @SOAPBinding(style = Style.RPC) public class SimpleWebService { @WebMethod public Image getImage(String imgName) throws IOException{ System.out.println("Image name "+imgName); File fajl = new File(imgName); return ImageIO.read(new File(imgName)); } } ``` And I have generated client. package edu.pdfbookshelf.wsclient; ``` import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.activation.DataHandler; import javax.imageio.ImageIO; public class Client { /** * @param args * @throws IOException_Exception */ public static void main(String[] args) throws IOException_Exception { SimpleWebServiceService service = new SimpleWebServiceService(); SimpleWebService port = service.getSimpleWebServicePort(); byte[] imageIS = port.getImage("rainbow.jpg"); ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream fis = new ByteArrayInputStream(imageIS); DataHandler image = new DataHandler(new IStoDataSource(fis)); dump(image); } private static void dump(DataHandler dh) { System.out.println(); try { System.out.println("MIME type: " + dh.getContentType()); System.out.println("Content: " + dh.getContent()); InputStream in = dh.getInputStream(); BufferedImage buffferedImage = ImageIO.read(in); ImageIO.write(buffferedImage, "jpg", new File("test.jpg")); } catch(IOException e) { System.err.println(e); } } } ``` When I try to run client I have an exception: ``` SEVERE: Can't read input file! javax.imageio.IIOException: Can't read input file! at javax.imageio.ImageIO.read(ImageIO.java:1291) at edu.pdfbookshelf.ws.SimpleWebService.getImage(SimpleWebService.java:143) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at com.sun.xml.ws.api.server.InstanceResolver$1.invoke(InstanceResolver.java:250) at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149) at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:88) at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1063) at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:979) at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:950) at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:825) at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:380) at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:651) at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:264) at com.sun.xml.ws.transport.http.servlet.ServletAdapter.invokeAsync(ServletAdapter.java:218) at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doGet(WSServletDelegate.java:159) at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doPost(WSServletDelegate.java:194) at com.sun.xml.ws.transport.http.servlet.WSServlet.doPost(WSServlet.java:80) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Thread.java:679) ``` I don't know why I get that exception. File in in the root folder. There's not file not found exception so I think the path if good. Any ideas what can be wrong? To create the WebService and Client I used <http://ojitha.blogspot.com/2012/02/jax-ws-binary-data-passing-using-mtom.html> .
2012/12/23
[ "https://Stackoverflow.com/questions/14012272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1909775/" ]
I think the error is in ``` byte[] imageIS = port.getImage("rainbow.jpg"); ``` Should be ``` byte[] imageIS = port.getImage("/rainbow.jpg"); ``` otherwise it will be interpreted as a path relative to the startup directory of the application server.
check if the `imgName` is correct path to a file: ``` log.info("File exists?: " + new File(imgName).exists()); //or System.out.println(...); log.info(imgName); log.info(new File(imgName).getAbsolutePath()); ``` If everything is ok - then your image is probably corrupted. If you can open this file in your favourite image editing tool - resave and override it.
2,502,590
Question -------- > > Let $n = m!$. Which of the following is TRUE? > > > $a)m = \Theta (\frac{\log n}{\log \log n})$ $b)m = \Omega (\frac{\log n}{\log \log n})$ but not $m = O(\frac{\log n}{\log \log n})$ $c)m = \Theta (\log^2 n)$ $m = \Omega (\log^2 n)$ but not $m = Ο( (\log^2 n)$ $d)m = \Theta (\log^{1.5} n)$ Let me Clear that this is not a homework question, i have learnt asymptotic growth and trying to solve some good question.During Practicing, i found this beautiful question but i am stuck at one point and unable to move on to conclude the answer. My approach ----------- > > Given $n = m!$ > > > $\Rightarrow \log n=(\log m!)=m \log m$ $\Rightarrow m=\frac{\log n }{\log m}$ I am stuck how to move forward .What value should i give to $\log m$? Please help
2017/11/03
[ "https://math.stackexchange.com/questions/2502590", "https://math.stackexchange.com", "https://math.stackexchange.com/users/384817/" ]
The first issue with what you wrote is that you write an equality instead of an asymptotic equivalence: you *cannot* write $\log m! = m\log m$. You *can* write $$\log m! \operatorname\*{\sim}\_{m\to\infty} m\log m$$, which is equivalent to writing $\log m! = m\log m + o(m\log m)$; or, more precise, $$ \ln m! = m\ln m - m + O(\log m) $$ (this is [Stirling's approximation](https://en.wikipedia.org/wiki/Stirling%27s_approximation)). --- Now, let us start from there. Since $n=m!$, we have $$ \log n = m\log m +o(m\log m) \tag{1} $$ by the above. Let us write $m = f(n)\log n$ for some $f>0$ we are trying to figure out (asymptotically). (1) becomes $$ \log n = f(n)\log n\log f(n) + f(n)\log n\log \log n +o(f(n)\log n\log (f(n)\log n)) $$ or equivalently $$ 1 = f(n)\log f(n) + f(n)\log \log n +o(f(n)\log (f(n)\log n)) \tag{2} $$ From this, it is clear that we must have $f(n)=o(1)$ (as otherwise $f(n)\log \log n$ is unbounded). That allows us to simplify (2) as $$ 1 = o(1) + f(n)\log \log n +o(f(n)\log\log n) \tag{3} $$ which implies (for the equality to hold) that we must have $f(n)\log \log n = 1+o(1)$, and thus $$f(n) \operatorname\*{\sim}\_{n\to\infty} \frac{1}{\log\log n}\,.$$ Putting it all together, $$ \boxed{m \operatorname\*{\sim}\_{n\to\infty} \frac{\log n}{\log\log n}\,.} $$
Well, we first observe that (c) is incorrect because $m = \mathcal{O}(m^2 \log^2 m) = \mathcal{O}((m \log m)^2) = \mathcal{O}(\log^2 m!) = \mathcal{O}(\log^2 n)$ using the fact that $\log m! = \Theta(m \log m)$. Similarly, one can show $\Theta(\log^{1.5}n) = \Theta(m^{1.5} \log^{1.5} m)$ using similar method. But we know $m = o(m^{1.5} \log^{1.5} m)$ so (d) cannot be true. Therefore, the right answer should be (a) or (b). Now we try to evaluate $$\Theta\left(\frac{\log n}{\log \log n}\right) = \Theta\left(\frac{\log m!}{\log \log m!}\right)$$ Since $\log m! = \Theta(m \log m)$, by definition, there is $C\_1, C\_2 > 0, N\_1 \in \mathbb{N}$ such that for all $m \ge N\_1$ $$C\_1 m \log m \le \log m! \le C\_2 m \log m$$ Taking $\log$ on the equation, we have that for all $m \ge N\_1$ $$\log(C\_1 m \log m) \le \log \log m! \le \log(C\_2 m \log m)$$ Applying the $\log$ laws give $$\log C\_1 + \log m + \log \log m \le \log \log m! \le \log C\_2 + \log m + \log \log m$$ Clearly $$\log m \le \log C\_1 + \log m + \log \log m$$ On the other hand, since $\log C\_2 + \log \log m = \mathcal{O}(\log m)$, we can find $C\_3 > 0, N\_2 \in \mathbb{N}$ such that for all $m \ge N\_2$ $$\log C\_2 + \log \log m \le C\_3 \log m$$ Now let $N = \max\{N\_1, N\_2\}$. Then for all $m \ge N$, we have $$\log m \le \log \log m! \le (C\_3 + 1) \log m$$ Therefore, by definition, $$\log \log m! = \Theta(\log m)$$ Finally, it is party-time, $$\Theta\left(\frac{\log n}{\log \log n}\right) = \Theta\left(\frac{\log m!}{\log \log m!}\right) = \Theta\left(\frac{m \log m}{\log m}\right) = \Theta(m)$$ Now clearly $$m = \Theta(m) = \Theta\left(\frac{\log n}{\log \log n}\right)$$ So (a) is correct!
30,196,145
I'm trying to build a very simple Angular app in order to learn the ropes. I'm using Yeoman's `angular-generator` for scaffolding, which uses a predefined `.config` with `$routeProvider`, that I adapted to my needs as follows: ``` angular .module('raidersApp', [ 'ngRoute', 'ngTouch' ]) .config(function ($routeProvider) { $routeProvider .when('/:langID/:proverbID', { templateUrl: 'views/proverb.html', controller: 'ProverbCtrl' }) .when('/:langID', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .otherwise({ redirectTo: '/en' }); }); ``` I created several templates to be included in my app's `index.html` in an attempt to keep things organized, as follows: ``` <header class="header" ng-controller="HeaderCtrl"> <div ng-include="'views/header.html'"></div> </header> <main class="container"> <div ng-view=""></div> </main> <footer class="footer"> <div ng-include="'views/footer.html'"></div> </footer> ``` Within the header view, I have a simple Bootstrap navbar with values that I would want to update based on user input, namely the ID (or name) of the selected language, which is obtained through `$routeParams`: ``` <li class="dropdown"> <a href class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">{{langID}}<span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#/{{language}}" ng-repeat="language in languages">{{language}}</a></li> </ul> </li> ``` I created a `data` factory to store this value and make it accessible to more than one controller: ``` angular.module('raidersApp') .factory('data', function () { var langID = "en"; return { getLang: function() { return langID; }, setLang: function(newlangID) { langID = newlangID; } } }); ``` I also created a separate controller, `HeaderCtrl`, to handle the navbar: ``` angular.module('raidersApp') .controller('HeaderCtrl', function (data, $http, $scope, $routeParams) { $scope.langID = data.getLang(); $scope.languages = [ 'en', 'pt', 'se' ]; }); ``` However, this controller is getting called only **once**. Which means that whichever language or `langID` is set as the default by my service (in this case, `"en"`), will always be the value that my navbar displays on the dropdown menu, never to be updated again. Everything else works as expected (The URLs do work, and the selected language is in fact updated through `$routeParams` on my main controller, just not on the header controller). I suspect this has to do with the fact that my `HeaderCtrl` is being defined outside of the scope of the `ng-view`, as seen in the `index.html` snippet above, and so my app's `$routeProvider` will happily ignore it forever while caring only about the controllers defined within it. How can I go about solving this problem without having to repeat the navbar in each and every one of the views that I would want in my app? I thought about using `ng-include` in every template, but that too, feels dirty. Is there a "cleaner" or more elegant solution?
2015/05/12
[ "https://Stackoverflow.com/questions/30196145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2887078/" ]
In your controller, change this line: ``` $scope.langID = data.getLang(); ``` to ``` $scope.langID = function () { return data.getLang(); } ``` Then change the binding in your header to: `{{langID()}}` This will cause it to get the value from the factory on every $digest. What I believe is happening here is that the controller is setting your $scope.langID to the value of data.getLang(); data.getLang()'s value changes, but your scope variable won't. Wrap it in a function instead and it should work as expected.
Because you need to set the $scope.language property every time the value updates, one way you could do it is to set a $watch on the value in the factory. Whenever it changes, you can have your header controller grab the new value. Here is some example code: HTML: ``` <div ng-controller="HeaderCtrl">Language: {{language}}</div> <div ng-controller="MainCtrl"><button ng-click="randomNum()">Set</button></div> ``` JS: ``` app.controller('MainCtrl', function($scope, myFactory) { $scope.randomNum = function() { myFactory.set(Math.random()) console.log(myFactory.get()) } }); app.controller('HeaderCtrl', function($scope, myFactory) { $scope.language =''; $scope.$watch(function() { return myFactory.get()}, function(newVal, oldVal) { if(newVal != oldVal) { $scope.language = newVal; } }) }) app.factory('myFactory', function() { var myVal = ''; return { get: function() { return myVal; }, set: function(val) { myVal = val; } } }) ``` Essentially, whenever we click the button attached to `MainCtrl`, it sets a random value to the factory's `myVal`. But `HeaderCtrl` has no way of knowing that the value has changed unless we manually call (or set an interval - don't do that) the factory get function again. We create a $watch function that checks to see if the value in the factory changes, and then if it does we can trigger some additional logic - in this case we want the new value. Another solution would be to do a $rootScope.$broadcast from the first controller and set up a $scope.$on listener on the second controller. Whenever that listener fires we can tell it to do a get from the factory. I am not aware of either solution being necessarily better than the other, though I think the one I have proposed here involves a little less code. [Demo](http://plnkr.co/edit/kohcs3LqXL8y6sqacicu?p=preview)