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
8,211,128
Is there any way to have multiple distinct HTML pages contained within a single HTML file? For example, suppose I have a website with two pages: ``` Page 1 : click here for page 2 ``` and ``` Page 2 : click here for page 1 ``` Can I create a single HTML file that embeds simple static HTML for both pages but only displays one at a time? My actual pages are of course more complicated with images, tables and javascript to expand table rows. I would prefer to avoid too much script code. Thanks!
2011/11/21
[ "https://Stackoverflow.com/questions/8211128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674683/" ]
[Screen Rec](https://a.pomf.cat/kyyeea.webm) You could use [Colker](https://www.reddit.com/r/web_design/comments/6ta3b1/a_single_html_file_which_uses_url_parameters_to/), which is built for this, but you'll have to remove the search box, and search feature code, because searching isn't compatible with the type of content you intend to use. Page contents are stored in a `java-script array`, and the "`page`" (eg: ?`page=pagename`) URL parameter determines which page content to serve.
```html <html> <head> <script> function show(shown, hidden) { document.getElementById(shown).style.display='block'; document.getElementById(hidden).style.display='none'; return false; } </script> </head> <body> <a href="#" onclick="return show('Page1','Page2');">Show page 1</a> <a href="#" onclick="return show('Page2','Page1');">Show page 2</a> <div id="Page1"> Content of page 1 </div> <div id="Page2" style="display:none"> Content of page 2 </div> </body> </html> ```
8,211,128
Is there any way to have multiple distinct HTML pages contained within a single HTML file? For example, suppose I have a website with two pages: ``` Page 1 : click here for page 2 ``` and ``` Page 2 : click here for page 1 ``` Can I create a single HTML file that embeds simple static HTML for both pages but only displays one at a time? My actual pages are of course more complicated with images, tables and javascript to expand table rows. I would prefer to avoid too much script code. Thanks!
2011/11/21
[ "https://Stackoverflow.com/questions/8211128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674683/" ]
JQuery Mobile has [multipage](http://jquerymobile.com/demos/1.2.0-pre/docs/pages/page-anatomy.html) feature. But I am not sure about Desktop Web Applications.
going along with @binz-nakama, here's an update on his jsfiddle with a very small amount of javascript. also incoporates this [very good article on css navigation](http://css-snippets.com/simple-horizontal-navigation/ "very good article") [update on the jsfiddle](https://jsfiddle.net/seanmcdon/x2ybsvz6/ "jsfiddle") ``` Array.from(document.querySelectorAll("a")) .map(x => x.addEventListener("click", function(e){ Array.from(document.querySelectorAll("a")) .map(x => x.classList.remove("active")); e.target.classList.add("active"); } )); ```
8,211,128
Is there any way to have multiple distinct HTML pages contained within a single HTML file? For example, suppose I have a website with two pages: ``` Page 1 : click here for page 2 ``` and ``` Page 2 : click here for page 1 ``` Can I create a single HTML file that embeds simple static HTML for both pages but only displays one at a time? My actual pages are of course more complicated with images, tables and javascript to expand table rows. I would prefer to avoid too much script code. Thanks!
2011/11/21
[ "https://Stackoverflow.com/questions/8211128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674683/" ]
Well, you *could*, but you probably just want to have two sets of content in the same page, and switch between them. Example: ```html <html> <head> <script> function show(shown, hidden) { document.getElementById(shown).style.display='block'; document.getElementById(hidden).style.display='none'; return false; } </script> </head> <body> <div id="Page1"> Content of page 1 <a href="#" onclick="return show('Page2','Page1');">Show page 2</a> </div> <div id="Page2" style="display:none"> Content of page 2 <a href="#" onclick="return show('Page1','Page2');">Show page 1</a> </div> </body> </html> ``` (Simplified HTML code, should of course have doctype, etc.)
This is kind of overriding the thing of one page, but... You could use iframes in HTML. ``` <html> <body> <iframe src="page1.html" border="0"></iframe> </body> </html> ``` And page1.html would be your base page. Your still making multiple pages, but your browser just doesn't move. So lets say thats your index.html. You have tabs, you click page 2, your url wont change, but the page will. All in iframes. The only thing different, is that you can view the frame source as well.
8,211,128
Is there any way to have multiple distinct HTML pages contained within a single HTML file? For example, suppose I have a website with two pages: ``` Page 1 : click here for page 2 ``` and ``` Page 2 : click here for page 1 ``` Can I create a single HTML file that embeds simple static HTML for both pages but only displays one at a time? My actual pages are of course more complicated with images, tables and javascript to expand table rows. I would prefer to avoid too much script code. Thanks!
2011/11/21
[ "https://Stackoverflow.com/questions/8211128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674683/" ]
[Twine](https://twinery.org/) is an open-source tool for telling interactive, nonlinear stories. It generates a single html with multiples pages. Maybe it is not the right tool for you but it could be useful for someone else looking for something similar.
going along with @binz-nakama, here's an update on his jsfiddle with a very small amount of javascript. also incoporates this [very good article on css navigation](http://css-snippets.com/simple-horizontal-navigation/ "very good article") [update on the jsfiddle](https://jsfiddle.net/seanmcdon/x2ybsvz6/ "jsfiddle") ``` Array.from(document.querySelectorAll("a")) .map(x => x.addEventListener("click", function(e){ Array.from(document.querySelectorAll("a")) .map(x => x.classList.remove("active")); e.target.classList.add("active"); } )); ```
8,211,128
Is there any way to have multiple distinct HTML pages contained within a single HTML file? For example, suppose I have a website with two pages: ``` Page 1 : click here for page 2 ``` and ``` Page 2 : click here for page 1 ``` Can I create a single HTML file that embeds simple static HTML for both pages but only displays one at a time? My actual pages are of course more complicated with images, tables and javascript to expand table rows. I would prefer to avoid too much script code. Thanks!
2011/11/21
[ "https://Stackoverflow.com/questions/8211128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674683/" ]
Have you considered [iframes](https://developer.mozilla.org/en/HTML/Element/iframe) or segregating your content and using a simple show/hide? **Edit** If you want to use an iframe, you can have the contents of page1 and page2 in one html file. Then you can decide what to show or hide by reading the `location.search` property of the iframe. So your code can be like this : For Page 1 : `iframe.src = "mypage.html?show=1"` For Page 2 : `iframe.src = "mypage.html?show=2"` Now, when your iframe loads, you can use the `location.search.split("=")[1]`, to get the value of the page number and show the contents accordingly. *This is just to show that iframes can also be used but the usage is **more complex** than the normal show/hide using div structures*.
going along with @binz-nakama, here's an update on his jsfiddle with a very small amount of javascript. also incoporates this [very good article on css navigation](http://css-snippets.com/simple-horizontal-navigation/ "very good article") [update on the jsfiddle](https://jsfiddle.net/seanmcdon/x2ybsvz6/ "jsfiddle") ``` Array.from(document.querySelectorAll("a")) .map(x => x.addEventListener("click", function(e){ Array.from(document.querySelectorAll("a")) .map(x => x.classList.remove("active")); e.target.classList.add("active"); } )); ```
8,211,128
Is there any way to have multiple distinct HTML pages contained within a single HTML file? For example, suppose I have a website with two pages: ``` Page 1 : click here for page 2 ``` and ``` Page 2 : click here for page 1 ``` Can I create a single HTML file that embeds simple static HTML for both pages but only displays one at a time? My actual pages are of course more complicated with images, tables and javascript to expand table rows. I would prefer to avoid too much script code. Thanks!
2011/11/21
[ "https://Stackoverflow.com/questions/8211128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674683/" ]
[Screen Rec](https://a.pomf.cat/kyyeea.webm) You could use [Colker](https://www.reddit.com/r/web_design/comments/6ta3b1/a_single_html_file_which_uses_url_parameters_to/), which is built for this, but you'll have to remove the search box, and search feature code, because searching isn't compatible with the type of content you intend to use. Page contents are stored in a `java-script array`, and the "`page`" (eg: ?`page=pagename`) URL parameter determines which page content to serve.
Solution 1 ========== One solution for this, not requiring any JavaScript, is simply to create a single page in which the multiple pages are simply regular content that is separated by a lot of white space. They can be wrapped into `div` containers, and an inline style sheet can endow them with the margin: ``` <style> .subpage { margin-bottom: 2048px; } </style> ... main page ... <div class="subpage"> <!-- first one is empty on purpose: just a place holder for margin; alternative is to use this for the main part of the page also! --> </div> <div class="subpage"> </div> <div class="subpage"> </div> ``` You get the picture. Each "page" is just a section followed by a whopping amount of vertical space so that the next one doesn't show. I'm using this trick to add "disambiguation navigation links" into a large document (more than 430 pages long in its letter-sized PDF form), which I would greatly prefer to keep as a single `.html` file. I emphasize that this is not a web site, but a document. When the user clicks on a key word hyperlink in the document for which there are multiple possible topics associated with word, the user is taken a small navigation menu presenting several topic choices. This menu appears at top of what looks like a blank browser window, and so effectively looks like a page. The only clue that the menu isn't a separate page is the state of the browser's vertical scroll bar, which is largely irrelevant in this navigation use case. If the user notices that, and starts scrolling around, the whole ruse is revealed, at which point the user will smile and appreciate not having been required to unpack a `.zip` file full of little pages and go hunting for the `index.html`. Solution 2 ========== It's actually possible to embed a HTML page within HTML. It can be done using the somewhat obscure `data:` URL in the `href` attribute. As a simple test, try sticking this somewhere in a HTML page: ``` <a href="data:text/html;charset=utf-8,<h3>FOO</h3>">blah</a> ``` In Firefox, I get a "blah" hyperlink, which navigates to a page showing the **FOO** heading. (Note that I don't have a fully formed HTML page here, just a HTML snippet; it's just a hello-world example). The downside of this technique is that the entire target page is in the URL, which is stuffed into the browser's address input box. If it is large, it could run into some issues, perhaps browser-specific; I don't have much experience with it. Another disadvantage is that the entire HTML has to be properly escaped so that it can appear as the argument of the `href` attribute. Obviously, it cannot contain a plain double quote character anywhere. A third disadvantage is that each such link has to replicates the `data:` material, since it isn't semantically a link at all, but a copy and paste embedding. It's not an attractive solution if the page-to-be-embeddded is large, and there are to be numerous links to it.
8,211,128
Is there any way to have multiple distinct HTML pages contained within a single HTML file? For example, suppose I have a website with two pages: ``` Page 1 : click here for page 2 ``` and ``` Page 2 : click here for page 1 ``` Can I create a single HTML file that embeds simple static HTML for both pages but only displays one at a time? My actual pages are of course more complicated with images, tables and javascript to expand table rows. I would prefer to avoid too much script code. Thanks!
2011/11/21
[ "https://Stackoverflow.com/questions/8211128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674683/" ]
have all the pages in distinct div areas ``` <div style="" id="page1"> First Page Contents </div> <div style="display:none" id="page2"> Second Page Contents </div> ``` then use a js script to workout what you are viewing (like within an hashtag style) to navigate. Either that, or ajax to get the response from a specific file (like `/pages/page1.html`) ``` var $prehashval = ""; function loop() { if (location.hash.slice(1)!=$prehashval) hashChanged(); $prehashval = location.hash.slice(1); setTimeout("loop()", 100); } function hashChanged() { var $output; switch (location.hash.slice(1)) { case "page1": document.getElementById('page1').style.display = ""; document.getElementById('page2').style.display = "none"; break; case "page2": document.getElementById('page1').style.display = "none"; document.getElementById('page2').style.display = ""; break; default: $output = location.hash.slice(1); } } loop(); ```
It is, in theory, possible using `data:` scheme URIs and frames, but that is rather a long way from practical. You can fake it by hiding some content with JS and then revealing it when something is clicked (in the style of [tabtastic](http://phrogz.net/js/tabtastic/index.html)).
45,471,370
I'm currently working with an action package that declares it will handle the following intents: * actions.intent.MAIN * actions.intent.TEXT * actions.intent.OPTION I've started with the first two, and proxying this to my own NLP/response gathering I'm able to get basic functionality working. I'm now trying to move forward with showing the user lists using [askWithList](https://developers.google.com/actions/reference/nodejs/ActionsSdkApp#askWithList). My Action Package is defined as follows: ``` { "actions": [ { "name": "MAIN", "fulfillment": { "conversationName": "JamesTest" }, "intent": { "name": "actions.intent.MAIN" } }, { "name": "TEXT", "fulfillment": { "conversationName": "JamesTest" }, "intent": { "name": "actions.intent.TEXT" } }, { "name": "OPTION", "fulfillment": { "conversationName": "JamesTest" }, "intent": { "name": "actions.intent.OPTION" } } ], "conversations": { "JamesTest": { "name": "JamesTest", "url": "myngrok" } } } ``` When I try to respond with `askWithList` and test in the simulator I get the following error: ``` { "name": "ResponseValidation", "subDebugEntry": [{ "name": "MalformedResponse", "debugInfo": "expected_inputs[0].possible_intents[0]: intent 'actions.intent.OPTION' is only supported for version 2 and above." }] } ``` Per the documentation my understanding was that all projects created after May 17 2017 would be using version 2 SDK by default. I also cannot seem to find any indication that I would be able to explicitly declare what version I would like to use in the Action Package definition. Has anyone run into this? Is this just a limitation of the simulator, or am I missing something obvious?
2017/08/02
[ "https://Stackoverflow.com/questions/45471370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4131557/" ]
You don't have to actually modify the data permanently, but you do have to adjust it for the join. One way would be to replace `/articles/` with `''` for example: ``` SELECT ... FROM articles a JOIN log l ON REPLACE(l.paths, '/articles/', '') = a.slugs ``` This won't use indexes and is not ideal, but works perfectly fine in ad-hoc scenarios. If you need to do this join a lot, you should consider a schema change.
You can just do: ``` SELECT a.slugs /*, l.visited_at */ FROM articles a JOIN logs l ON substr(l.path, length('/articles/')+1) = a.slugs ; ``` The `substr` function should be quite fast to execute. You can obviously change `length('/articles/')+1` by the constant `11`; but I think that leaving it there is much more informative of what you're actually doing... If the last bit of performance is needed, put the `11`. You will probably take benefit of having the following computed index: ``` CREATE INDEX idx_logs_slug_from_path ON logs ((substr(path, length('/articles/')+1))) ; ``` Check the whole setup at *dbfiddle [here](http://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=a507e3bd900a63891f3a9fcade81887e)*
249,029
Can I just omit the subject directly in informal sentence,or I should omit it and start with ing? `For example: (I) Sing in the middle of storms/ Singing in the middle of storms.`
2020/05/30
[ "https://ell.stackexchange.com/questions/249029", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/113404/" ]
An English sentence with a root verb but without an **explicit** subject is an order to someone unspecified who is not the person speaking. So > > Sing in the middle of storms > > > is grammatical and means that someone **other then the speaker** must sing during storms. If that is what you want to say, then the sentence is perfect. But it does **NOT, IN ANY WAY WHATSOEVER.** mean > > I sing in the middle of storms. > > > When an explicit subject is missing, the implied subject is "you." > > Singing in the middle of storms > > > lacks a verb. Without a verb, it is not a grammatically valid sentence. It is what is called a sentence fragment. Such fragments do occur, *e.g.* "Hi there," but they basically convey a very simple emotion rather than a thought. Most fragments are unintelligibly ambiguous, as indeed this one is. There are hundred of ways to complete this fragmentary thought. > > Singing in storms is what my mother says she did when she was a small child > > > Singing in storms causes cancer > > > Singing in storms is a sure sign of lunacy. > > > Which one is meant? No one listening or reading can tell. You have introduced a subject but then said **nothing** about it. **EDIT**: The comments to this answer are correct that sometimes context provides sufficient information to render a sentence fragment unambiguous. Knowing when there is sufficient context can be difficult even for a native speaker. I'd avoid sentence fragments when you have the slightest doubt. In the following video, it is quite clear who is singing and dancing in the rain. <https://video.search.yahoo.com/search/video?fr=mcafee&p=signing+in+the+rain#id=1&vid=89f2538b0ea04000a4a9f5512078a8a9&action=click>
Unlike some other languges, in English you can’t omit the subject in the sentence “I sing in the middle of the storms” without changing the meaning. Without the subject, it becomes imperative. It will be understood as an order “(you must) sing in the middle of the storms”.
249,029
Can I just omit the subject directly in informal sentence,or I should omit it and start with ing? `For example: (I) Sing in the middle of storms/ Singing in the middle of storms.`
2020/05/30
[ "https://ell.stackexchange.com/questions/249029", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/113404/" ]
In short isolated sentences in informal conversation, we often omit an initial subject pronoun and a following auxiliary: > > Going out? > > > Got some! > > > Don't know. > > > See any? > > > Spoken to him? > > > Heard it. > > > So if you were writing down a conversation like this (which can happen on text or Whatsapp etc) you would probably write just as above. But even in informal conversation, if an utterance consists of more than one sentence, we don't generally omit the subject or auxiliary. So your example is not idiomatic, spoken or written.
Unlike some other languges, in English you can’t omit the subject in the sentence “I sing in the middle of the storms” without changing the meaning. Without the subject, it becomes imperative. It will be understood as an order “(you must) sing in the middle of the storms”.
249,029
Can I just omit the subject directly in informal sentence,or I should omit it and start with ing? `For example: (I) Sing in the middle of storms/ Singing in the middle of storms.`
2020/05/30
[ "https://ell.stackexchange.com/questions/249029", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/113404/" ]
An English sentence with a root verb but without an **explicit** subject is an order to someone unspecified who is not the person speaking. So > > Sing in the middle of storms > > > is grammatical and means that someone **other then the speaker** must sing during storms. If that is what you want to say, then the sentence is perfect. But it does **NOT, IN ANY WAY WHATSOEVER.** mean > > I sing in the middle of storms. > > > When an explicit subject is missing, the implied subject is "you." > > Singing in the middle of storms > > > lacks a verb. Without a verb, it is not a grammatically valid sentence. It is what is called a sentence fragment. Such fragments do occur, *e.g.* "Hi there," but they basically convey a very simple emotion rather than a thought. Most fragments are unintelligibly ambiguous, as indeed this one is. There are hundred of ways to complete this fragmentary thought. > > Singing in storms is what my mother says she did when she was a small child > > > Singing in storms causes cancer > > > Singing in storms is a sure sign of lunacy. > > > Which one is meant? No one listening or reading can tell. You have introduced a subject but then said **nothing** about it. **EDIT**: The comments to this answer are correct that sometimes context provides sufficient information to render a sentence fragment unambiguous. Knowing when there is sufficient context can be difficult even for a native speaker. I'd avoid sentence fragments when you have the slightest doubt. In the following video, it is quite clear who is singing and dancing in the rain. <https://video.search.yahoo.com/search/video?fr=mcafee&p=signing+in+the+rain#id=1&vid=89f2538b0ea04000a4a9f5512078a8a9&action=click>
In short isolated sentences in informal conversation, we often omit an initial subject pronoun and a following auxiliary: > > Going out? > > > Got some! > > > Don't know. > > > See any? > > > Spoken to him? > > > Heard it. > > > So if you were writing down a conversation like this (which can happen on text or Whatsapp etc) you would probably write just as above. But even in informal conversation, if an utterance consists of more than one sentence, we don't generally omit the subject or auxiliary. So your example is not idiomatic, spoken or written.
60,665,715
I'm using angular's getLocaleDateTimeFormat function to display selected date-time in the input field. `getLocaleDateTimeFormat(this.injector.get(LOCALE_ID), FormatWidth.Short)` function shows `{1}, {0}` but when i use `getLocaleDateFormat(this.injector.get(LOCALE_ID), FormatWidth.Short)` and `getLocaleTimeFormat(this.injector.get(LOCALE_ID), FormatWidth.Short)` each separately they display date and time properly. Am i doing something wrong? My function is: ` formattingDate(date: Date): string { ``` if (!date || typeof date == 'string') { return ''; } let localeId = this.injector.get(LOCALE_ID); let localeDateFormat = getLocaleDateFormat(localeId, FormatWidth.Short); let localeTimeFormat = getLocaleTimeFormat(localeId, FormatWidth.Short); let localeDateTimeFormat = getLocaleDateTimeFormat(localeId, FormatWidth.Short); return formatDate(date, localeDateTimeFormat, localeId); ``` } ` the thing is getLocaleDateTimeFormat function is not getting date or time or both from date argument
2020/03/13
[ "https://Stackoverflow.com/questions/60665715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12224228/" ]
MongoDB is very fast in the execution of queries. But it also depends on how you write your query. For getting the first 10 documents and sort it descending order to the \_id from a collection. You need to use `limit` & `sort` in your query. ``` db.collectionName.find({}).limit(10).sort({_id:-1}) ```
Make sure it's not a connection issue. Try to run your query from MongoDB shell ``` mongo mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@cluster0-vuauc.mongodb.net/${process.env.MONGO_DB}?retryWrites=true&w=majority db.collection.find({condition}).limit(10) ``` If in MongoDB shell it responds *faster* than Mongoose: There is an issue for `Node.js` driver which uses pure Javascript [BSON serializer](https://stackoverflow.com/questions/36767310/why-is-json-faster-than-bson-in-node-js) which is very slow to serialize from BSON to JSON. Try to install `bson-ext` > > The `bson-ext` module is an alternative BSON parser that is written in `C++`. It delivers **better deserialization performance** and similar or somewhat better serialization performance to the pure javascript parser. > > > <https://mongodb.github.io/node-mongodb-native/3.5/installation-guide/installation-guide/#bson-ext-module>
60,665,715
I'm using angular's getLocaleDateTimeFormat function to display selected date-time in the input field. `getLocaleDateTimeFormat(this.injector.get(LOCALE_ID), FormatWidth.Short)` function shows `{1}, {0}` but when i use `getLocaleDateFormat(this.injector.get(LOCALE_ID), FormatWidth.Short)` and `getLocaleTimeFormat(this.injector.get(LOCALE_ID), FormatWidth.Short)` each separately they display date and time properly. Am i doing something wrong? My function is: ` formattingDate(date: Date): string { ``` if (!date || typeof date == 'string') { return ''; } let localeId = this.injector.get(LOCALE_ID); let localeDateFormat = getLocaleDateFormat(localeId, FormatWidth.Short); let localeTimeFormat = getLocaleTimeFormat(localeId, FormatWidth.Short); let localeDateTimeFormat = getLocaleDateTimeFormat(localeId, FormatWidth.Short); return formatDate(date, localeDateTimeFormat, localeId); ``` } ` the thing is getLocaleDateTimeFormat function is not getting date or time or both from date argument
2020/03/13
[ "https://Stackoverflow.com/questions/60665715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12224228/" ]
MongoDB is very fast in the execution of queries. But it also depends on how you write your query. For getting the first 10 documents and sort it descending order to the \_id from a collection. You need to use `limit` & `sort` in your query. ``` db.collectionName.find({}).limit(10).sort({_id:-1}) ```
**Use Projections to Return Only Necessary Data** When you need only a subset of fields from documents, you can achieve better performance by returning only the fields you need: For example, if in your query to the posts collection, you need only the timestamp, title, author, and abstract fields, you would issue the following command: ``` db.posts.find( {}, { timestamp : 1 , title : 1 , author : 1 , abstract : 1} ).sort( { timestamp : -1 } ).limit(10) ``` You can read for Query optimize [here](https://docs.mongodb.com/manual/tutorial/optimize-query-performance-with-indexes-and-projections/)
60,665,715
I'm using angular's getLocaleDateTimeFormat function to display selected date-time in the input field. `getLocaleDateTimeFormat(this.injector.get(LOCALE_ID), FormatWidth.Short)` function shows `{1}, {0}` but when i use `getLocaleDateFormat(this.injector.get(LOCALE_ID), FormatWidth.Short)` and `getLocaleTimeFormat(this.injector.get(LOCALE_ID), FormatWidth.Short)` each separately they display date and time properly. Am i doing something wrong? My function is: ` formattingDate(date: Date): string { ``` if (!date || typeof date == 'string') { return ''; } let localeId = this.injector.get(LOCALE_ID); let localeDateFormat = getLocaleDateFormat(localeId, FormatWidth.Short); let localeTimeFormat = getLocaleTimeFormat(localeId, FormatWidth.Short); let localeDateTimeFormat = getLocaleDateTimeFormat(localeId, FormatWidth.Short); return formatDate(date, localeDateTimeFormat, localeId); ``` } ` the thing is getLocaleDateTimeFormat function is not getting date or time or both from date argument
2020/03/13
[ "https://Stackoverflow.com/questions/60665715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12224228/" ]
**Use Projections to Return Only Necessary Data** When you need only a subset of fields from documents, you can achieve better performance by returning only the fields you need: For example, if in your query to the posts collection, you need only the timestamp, title, author, and abstract fields, you would issue the following command: ``` db.posts.find( {}, { timestamp : 1 , title : 1 , author : 1 , abstract : 1} ).sort( { timestamp : -1 } ).limit(10) ``` You can read for Query optimize [here](https://docs.mongodb.com/manual/tutorial/optimize-query-performance-with-indexes-and-projections/)
Make sure it's not a connection issue. Try to run your query from MongoDB shell ``` mongo mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@cluster0-vuauc.mongodb.net/${process.env.MONGO_DB}?retryWrites=true&w=majority db.collection.find({condition}).limit(10) ``` If in MongoDB shell it responds *faster* than Mongoose: There is an issue for `Node.js` driver which uses pure Javascript [BSON serializer](https://stackoverflow.com/questions/36767310/why-is-json-faster-than-bson-in-node-js) which is very slow to serialize from BSON to JSON. Try to install `bson-ext` > > The `bson-ext` module is an alternative BSON parser that is written in `C++`. It delivers **better deserialization performance** and similar or somewhat better serialization performance to the pure javascript parser. > > > <https://mongodb.github.io/node-mongodb-native/3.5/installation-guide/installation-guide/#bson-ext-module>
29,886,323
I'm installing and configuring the Android SDK. I follow this guide: <https://www.digitalocean.com/community/tutorials/how-to-build-android-apps-with-jenkins> First of all I did not found the /etc/profile.d/android.sh. That file did nog exist. But I had to add env-variables. So I made the android.sh manually. I hope this is the right way to do this. Later on came my real problem, I want to do this command: ``` android update sdk --no-ui ``` But I don't have the permissions to do this. Even not when I'm using sudo: ``` ubuntu@ip-172-31-33-139:/opt/android-sdk-linux$ android update sdk --no-ui -bash: /opt/android-sdk-linux/tools/android: Permission denied ``` This are the permissions on my folder. ``` drwxr-xr-x 3 root root 4096 Apr 27 02:17 . drwxr-xr-x 23 root root 4096 Apr 17 08:36 .. drwxrwxr-x 5 144773 5000 4096 Feb 27 22:04 android-sdk-linux ``` Will it be enough to change the permissions? I don't have experience with the 1447733 - 5000.
2015/04/27
[ "https://Stackoverflow.com/questions/29886323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4525448/" ]
Even with sudo it did not work but I found a solution: I had to change my permission with `sudo chmod -R 777 /opt/android-sdk-linux` After that I changed it back so my Jenkins could use it
Do you use root account to execute Android command? I suggest you use root account to do it.
29,886,323
I'm installing and configuring the Android SDK. I follow this guide: <https://www.digitalocean.com/community/tutorials/how-to-build-android-apps-with-jenkins> First of all I did not found the /etc/profile.d/android.sh. That file did nog exist. But I had to add env-variables. So I made the android.sh manually. I hope this is the right way to do this. Later on came my real problem, I want to do this command: ``` android update sdk --no-ui ``` But I don't have the permissions to do this. Even not when I'm using sudo: ``` ubuntu@ip-172-31-33-139:/opt/android-sdk-linux$ android update sdk --no-ui -bash: /opt/android-sdk-linux/tools/android: Permission denied ``` This are the permissions on my folder. ``` drwxr-xr-x 3 root root 4096 Apr 27 02:17 . drwxr-xr-x 23 root root 4096 Apr 17 08:36 .. drwxrwxr-x 5 144773 5000 4096 Feb 27 22:04 android-sdk-linux ``` Will it be enough to change the permissions? I don't have experience with the 1447733 - 5000.
2015/04/27
[ "https://Stackoverflow.com/questions/29886323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4525448/" ]
Even with sudo it did not work but I found a solution: I had to change my permission with `sudo chmod -R 777 /opt/android-sdk-linux` After that I changed it back so my Jenkins could use it
Try `sudo android update sdk --no-ui` or update it on the SDK Manager into the Android Studio.
50,308,709
I am trying to have hello.jsp page as an output but it goes to index.jsp page all the time. I tried searching various other things but failed, so finally decided to post here so any one of you can help. Below I have attached my project structure and all the files...and also the output what I am seeing when I run on tomcat server. [Project Structure](https://i.stack.imgur.com/M15Ra.jpg) **pom.xml** ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.gami</groupId> <artifactId>healthTracker</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>healthTracker Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>healthTracker</finalName> </build> </project> ``` **Web.xml** ``` <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>healthTrackerServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/servlet-config.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>healthTrackerServlet</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <display-name>Archetype Created Web Application</display-name> </web-app> ``` **servlet-config** ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <mvc:annotation-driven/> <context:component-scan base-package="com.gami.controller"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> --> </beans> ``` **HelloController.java** ``` package com.gami.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping(value ="greeting") public String sayHello (Model model) { model.addAttribute("greeting", "Hello World"); return "hello"; } ``` **hello.jsp** ``` <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1>${greeting}</h1> </body> </html> ``` **index.jsp** ``` <html> <body> <h2>This is index - Hello World!</h2> </body> </html> ``` [This is the output I get when I run the project on server](https://i.stack.imgur.com/qMgPg.jpg) [These are logs, server was started properly](https://i.stack.imgur.com/dLaPO.jpg)
2018/05/12
[ "https://Stackoverflow.com/questions/50308709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5774948/" ]
In C a value of 0 is considered "false", and any other (nonzero) value is considered "true". So one, very explicit way to convert an arbitrary `int` value to an explicitly true-or-false Boolean value is to use the (C99 and later) `bool` type: ``` #include <stdbool.h> int i; bool b; b = (i != 0) ? true : false; ``` But since the `!=` operator essentially "returns" a Boolean value, you can also do ``` b = (i != 0); ``` And since the zero/nonzero definition is built in to the language, you can also just do ``` b = i; ``` But you don't have to use type `bool`. If you have an arbitrary-value int and you want to force it to 0/1 "in place", you have the same sorts of options: ``` i = (i != 0) ? 1 : 0; ``` Or ``` i = (i != 0); ``` Or there's another common trick: ``` i = !!i; ``` This last is concise, popular, and somewhat obscure. It changes zero/nonzero to 1/0 and then back to 0/1. I've shown these examples using type `int`, but they would all work just as well with `short int` or `char` (i.e. byte). --- One more thing. In your question you wrote `val = (val == 1) ? 0 : 1`, but that's basically meaningless. In C, at least, everything (everything!) follows from whether a value is zero or nonzero. Explicit comparisons with 1 are almost always a bad idea, if not a downright error.
Adding to Summit's answer, you can also do this: ``` #define TRUE ~0U #define FALSE 0U #ifndef BOOL #define BOOL unsigned int; #endif int main() { BOOL var = TRUE; var = ~var; //Negate var and set it to false. var = ~var; //Negate var again and set it to true. return EXIT_SUCCESS; } ``` If you are using at least C99, then you can change ``` #ifndef BOOL #define BOOL unsigned int; #endif ``` to: ``` #include <stdint.h> #ifndef BOOL #define BOOL uint_fast8_t; #endif ```
50,308,709
I am trying to have hello.jsp page as an output but it goes to index.jsp page all the time. I tried searching various other things but failed, so finally decided to post here so any one of you can help. Below I have attached my project structure and all the files...and also the output what I am seeing when I run on tomcat server. [Project Structure](https://i.stack.imgur.com/M15Ra.jpg) **pom.xml** ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.gami</groupId> <artifactId>healthTracker</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>healthTracker Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>healthTracker</finalName> </build> </project> ``` **Web.xml** ``` <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>healthTrackerServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/servlet-config.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>healthTrackerServlet</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <display-name>Archetype Created Web Application</display-name> </web-app> ``` **servlet-config** ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <mvc:annotation-driven/> <context:component-scan base-package="com.gami.controller"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> --> </beans> ``` **HelloController.java** ``` package com.gami.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping(value ="greeting") public String sayHello (Model model) { model.addAttribute("greeting", "Hello World"); return "hello"; } ``` **hello.jsp** ``` <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1>${greeting}</h1> </body> </html> ``` **index.jsp** ``` <html> <body> <h2>This is index - Hello World!</h2> </body> </html> ``` [This is the output I get when I run the project on server](https://i.stack.imgur.com/qMgPg.jpg) [These are logs, server was started properly](https://i.stack.imgur.com/dLaPO.jpg)
2018/05/12
[ "https://Stackoverflow.com/questions/50308709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5774948/" ]
I posted one answer, but I may have misread the question. If you have an integer variable -- it might be `int`, `short int`, or `char` -- and you want to have it cycle back and forth 0, 1, 0, 1 (which you can interpret as false, true, false, true), there are two about equally good ways to do it. You could do: ``` i = !a; ``` This first way emphasize the "Boolean" nature of the variable. Or, you could do: ``` i = 1 - i; ``` This second way is purely numeric. But either way will work perfectly well. In either case, `i` is guaranteed to alternate 0, 1, 0, 1, ... You could also use ``` i = i ? 0 : 1; ``` or ``` i = (i == 0) ? 1 : 0; ``` Both of these will work, too, but they're basically equivalent to `i = !i`. In your question you suggested ``` i = (i == 1) ? 0 : 1; ``` This would mostly work, but it looks weird to my eye. Also it would do the wrong thing if `i` ever ended up containing 2 (or any value other than 0 or 1).
Adding to Summit's answer, you can also do this: ``` #define TRUE ~0U #define FALSE 0U #ifndef BOOL #define BOOL unsigned int; #endif int main() { BOOL var = TRUE; var = ~var; //Negate var and set it to false. var = ~var; //Negate var again and set it to true. return EXIT_SUCCESS; } ``` If you are using at least C99, then you can change ``` #ifndef BOOL #define BOOL unsigned int; #endif ``` to: ``` #include <stdint.h> #ifndef BOOL #define BOOL uint_fast8_t; #endif ```
26,067,811
The following bash and Perl scripts mysteriously give different results. Why? ``` #!/bin/bash hash=`echo -n 'abcd' | /usr/bin/shasum -a 256`; echo $hash; #!/usr/bin/perl $hash = `echo -n 'abcd' | /usr/bin/shasum -a 256`; print "$hash"; ``` The bash script: ``` $ ./tst.sh 88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589 - ``` The Perl script: ``` $ ./tst.pl 61799467ee1ab1f607764ab36c061f09cfac2f9c554e13f4c7442e66cbab9403 - ``` the heck?
2014/09/26
[ "https://Stackoverflow.com/questions/26067811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398461/" ]
Summary: In your Perl script, `-n` is being treated as an argument to include in the output of `echo`, not a flag to suppress the newline. ( Try ``` $hash = `echo -n 'abcd'`; ``` to confirm). Use `printf` instead. --- Perl uses `/bin/sh` to execute code in back tics. Even if `/bin/sh` is a link to `bash`, it will behave differently when invoked via that like. In POSIX mode, ``` echo -n 'abcd' ``` will output ``` -n abcd ``` that is, the `-n` option is not recognized as a flag to suppress a newline, but is treated as a regular argument to print. Replace `echo -n` with `printf` in each script, and you should get the same SHA hash from each script. (UPDATE: `bash` 3.2, when invoked as `sh`, displays this behavior. Newer versions of `bash` seem to continue treating `-n` as a flag when invoked as `sh`.) --- Even better, don't shell out to do things you can do in Perl. ``` use Digest::SHA; $hash = Digest::SHA::sha256('abcd'); ``` --- For the curious, here's what the POSIX spec [has to say](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html) about `echo`. I'm not sure what to make of XSI conformance; `bash` `echo` requires the `-e` option to treat the escape characters specially, but nearly every shell—*except* old versions of `bash`, and then only under special circumstances—treats `-n` as a flag, not a string. Oh well. ``` The following operands shall be supported: string A string to be written to standard output. If the first operand is -n, or if any of the operands contain a <backslash> character, the results are implementation-defined. On XSI-conformant systems, if the first operand is -n, it shall be treated as a string, not an option. The following character sequences shall be recognized on XSI-conformant systems within any of the arguments: \a Write an <alert>. \b Write a <backspace>. \c Suppress the <newline> that otherwise follows the final argument in the output. All characters following the '\c' in the arguments shall be ignored. \f Write a <form-feed>. \n Write a <newline>. \r Write a <carriage-return>. \t Write a <tab>. \v Write a <vertical-tab>. \\ Write a <backslash> character. \0num Write an 8-bit value that is the zero, one, two, or three-digit octal number num. ```
If you do: ``` printf "%s" 'abcd' | /usr/bin/shasum -a 256 ``` you get the 88d...589 hash. If you do: ``` printf "%s\n" '-n abcd' | /usr/bin/shasum -a 256 ``` you get the 617...403 hash. Therefore, I deduce that Perl is somehow running a different `echo` command, perhaps `/bin/echo` or `/usr/bin/echo` instead of the `bash` built-in `echo`, or maybe the built-in echo to `/bin/sh` (which might perhaps be `dash` rather than `bash`), and this other `echo` does not recognize the `-n` option as an option and outputs different data. I'm not sure which other `echo` it is finding; on my machine which is running an Ubuntu 14.04 LTE derivative, `bash`, `dash`, `sh` (linked to `bash`), `ksh`, `csh` and `tcsh` all treat `echo -n abcd` the same way. But somewhere along the line, I think that there is something along these lines happening; the hash checksums being identical strongly point to it. (Maybe you have a 3.2 `bash` linked to `sh`; see the notes in the comments.)
12,853,772
I'm trying to change from load-time-weaving to compile-time-weaving with my Spring 2.5 app. To do this, I did the following: 1. In my ant build file, I added ``` <path id="aspectPath"> <pathelement location="${lib.home}/spring-aspects.jar"/> </path> <taskdef resource="org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties"> <classpath> <pathelement location="${aspectj.home}/aspectjtools.jar"/> </classpath> </taskdef> ``` and replaced the reference to the javac compiler with the following ``` <iajc sourceroots="${src.home}" destdir="${build.home}/WEB-INF/classes" classpathRef="compile.classpath" aspectPathRef="compile.classpath" debug="${compile.debug}" deprecation="${compile.deprecation}" encoding="cp1252" source="1.6" target="1.6" showWeaveInfo="${compile.debug}"/> ``` In applicationContext.xml I then replaced ``` <context:load-time-weaver/> ``` with ``` <context:spring-configured/> ``` Other configuration settings in my app context file, BTW, include ``` <tx:annotation-driven/> <context:component-scan base-package="com.domain.somepackage"/> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> ``` In the context.xml file, I removed the following from the loader tag ``` loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader" ``` When I run the build script, it compiles without errors. I do get this warning however. ``` [iajc] warning at <Unknown>::0 Found @DeclareAnnotation while current release does not support it (see 'org.aspectj.weaver.bcel.AtAjAttributes') ``` at the top, and this warning at the bottom: ``` [iajc] warning at C:\server- lib\aspectjtools.jar!org\aspectj\ajdt\internal\compiler\ CompilerAdapter.class:121::0 advice defined in org.aspectj.ajdt.internal.compiler.CompilerAdapter has not been applied [Xlint:adviceDidNotMatch] ``` Most of the logging looks like: ``` [iajc] weaveinfo Join point 'method-execution(void com.kjconfigurator.upgra de.Upgrade1_07HelperImp.addServiceParticipation(com.kjconfigurator.core.domain.U ser, com.kjconfigurator.core.domain.ServiceAccount))' in Type 'com.kjconfigurato r.upgrade.Upgrade1_07HelperImp' (Upgrade1_07HelperImp.java:196) advised by after Returning advice from 'org.springframework.transaction.aspectj.AnnotationTransac tionAspect' (spring-aspects.jar!AbstractTransactionAspect.class:77(from Abstract TransactionAspect.aj)) ``` I removed the tomcatspringweaver jar from the tomcat lib. I am using aspectj1.7 When I start the app up, I get an error indicating that when a dao class is being injected into a service class there is an NPE at at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:104) ``` Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are: PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'dao' threw exception; nested exception is java.lang.NullPointerException ``` The Dao class extends an AbstractJpaDao class that looks like this: ``` public abstract class AbstractJpaDao<T> { private static Logger log = Logger.getLogger(AbstractJpaDao.class.getName()); private EntityManager entityManager; @PersistenceContext public void setEntityManager(EntityManager entityManager) { this. entityManager = entityManager; } ... } ``` It's been such a long time since all this was initially set up, I don't remember how all the configurations work. Nor do I understand class loaders or AspectJ very well. But something is not happening correctly, perhaps the Entitymanager is not being injected for some reason. Questions. 1. What might be causing this? 2. Is `<context:spring-configured/>` really needed? 3. The package referenced by `<context:component-scan base-package="com.domain.somepackage"/>` does not include the Dao class in question. When I do add another component-scan tag with the dao's package in it, nothing different happens. Is this necessary?
2012/10/12
[ "https://Stackoverflow.com/questions/12853772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/529806/" ]
Yes, you have to release for the Above two cases. **Case 1:** ``` SelectFrame *obj=[[SelectFrame alloc]initWithNibName:@"SelectFrame" bundle:nil]; [[self navigationController] pushViewController:obj animated:YES]; [obj release]; ``` **Case 2:** ``` UIView *barView=[[UIView alloc]initWithFrame:CGRectMake(0, 500, 200,50)]; barView.backgroundColor=[UIColor redColor]; [self.view addSubview:barView]; [barView release]; ``` **Case 3:** ``` NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:@"https://xxxxxxxxxxxxxxxxx"]]; [[NSURLConnection alloc] initWithRequest:request delegate:self]; ``` You don't need a release here, as the request object is in autoreleased mode. **Remember two things.** 1.) You have to manually release an object when you `retain` or `alloc-init` that object. 2.) Class methods which do not have alloc methods return an `autoreleased` object hence you don't need to release those objects. **Disadvantage of using `autorelease` :** Ok, so what does `autorelease` mean? Autorelease means , not us, but our App would decide when to release the object. Supposing case 2 of your question. After `barView` is added to `self.view` there is no need of this allocated object. Hence, we release it. But, if we had kept it in `autorelease` mode, the App would keep it for longer time, wasting some part of memory by still keeping that object. Hence, we shouldn't use autorelease here. **Advantage of using `autorelease` :** This over-popular example. ``` - (NSString*) getText { NSString* myText = [[NSString alloc] initWithFormat:@"Hello"]; return myText; } ``` Here, the 3rd line causes a leak because we do not release the memory allocated to `myText`. Hence, ``` - (NSString*) getText { NSString* myText = [[[NSString alloc] initWithFormat:@"Hello"] autorelease]; return myText; } ``` **SOLUTION** Use ARC, forget `retain` `release` :)
If using **ARC** in 3 cases then **no need to release** anything just use wisely (alloc if needed) If not using ARC then its needed to release Now case 1 : ``` SelectFrame *obj=[[SelectFrame alloc]initWithNibName:@"SelectFrame" bundle:nil]; [[self navigationController] pushViewController:obj animated:YES]; [obj release]; ``` Case 2: ``` UIView *barView=[[UIView alloc]initWithFrame:CGRectMake(0, 500, 200,50)]; barView.backgroundColor=[UIColor redColor]; [self.view addSubview:barView]; [barView release]; ``` Case 3: ``` NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:@"https://xxxxxxxxxxxxxxxxx"]]; [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; ``` Refere [How-to-avoid-memory-leaks-in-iPhone-applications](http://www.codeproject.com/Articles/107800/How-to-avoid-memory-leaks-in-iPhone-applications) link.
36,286,704
Given the following pseudo C# code: ``` public abstract class Worker { public void DoWork() { Prepare(); Work(); Cleanup(); } protected abstract void Work(); } ``` With this design, it is possible, that a derived class (which overrides the `Work()` method) calls the `Work()` method directly. I'm looking for design tips on how to prevent any subclass to do this call, or at least generate a compiler warning. Why I want to do this? The Worker actually dispatches the `Work()` to another thread. `DoWork()` takes care about the locking. --- I know, this is weird. The `Work()`-body might just consist of a method call to `DoMyWork()` and the object might call `DoMyWork()` somewhere else. It's impossible to intercept that. Anyways. I appreciate any thoughts on that issue.
2016/03/29
[ "https://Stackoverflow.com/questions/36286704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2879579/" ]
Thanks to Eris and Corey I think I figured it out. What about this way: ``` public abstract class Worker { public void DoWork() { if (Work != null) { Prepare(); Work(); Cleanup(); } } protected Action Work { private get; set; } } public class ImplWorker { public ImplWorker() { Work = //whatever } } ``` Still if he really wanted to he can store it somewhere else and stuff. But it goes as far as I can imagine.
If the Work is done using a resource (e.g. remote server, database connection), or it can be changed to be like that, then you could do it like this: ``` public interface IResource { } public abstract class Worker { private class TheResource : IResource { // implement } public void DoWork() { Prepare(); var resObj = new TheResource(); Work(resObj); // if needed, cleanup/dispose resObj here Cleanup(); } protected abstract void Work(IResource resourceObj); } ```
36,286,704
Given the following pseudo C# code: ``` public abstract class Worker { public void DoWork() { Prepare(); Work(); Cleanup(); } protected abstract void Work(); } ``` With this design, it is possible, that a derived class (which overrides the `Work()` method) calls the `Work()` method directly. I'm looking for design tips on how to prevent any subclass to do this call, or at least generate a compiler warning. Why I want to do this? The Worker actually dispatches the `Work()` to another thread. `DoWork()` takes care about the locking. --- I know, this is weird. The `Work()`-body might just consist of a method call to `DoMyWork()` and the object might call `DoMyWork()` somewhere else. It's impossible to intercept that. Anyways. I appreciate any thoughts on that issue.
2016/03/29
[ "https://Stackoverflow.com/questions/36286704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2879579/" ]
Thanks to Eris and Corey I think I figured it out. What about this way: ``` public abstract class Worker { public void DoWork() { if (Work != null) { Prepare(); Work(); Cleanup(); } } protected Action Work { private get; set; } } public class ImplWorker { public ImplWorker() { Work = //whatever } } ``` Still if he really wanted to he can store it somewhere else and stuff. But it goes as far as I can imagine.
This is somewhat of a hack, but you could change the method to be virtual, add a body which calls the new method, and then add an [ObsoleteAttribute](https://msdn.microsoft.com/en-us/library/22kk2b44(v=vs.90).aspx) to it. ``` protected void DoWork() { // New method } [Obsolete("This method is deprecated.")] protected virtual void Work() { DoWork(); } ``` Marking the method as virtual will prevent any existing child classes from breaking, since they were previously required to override Work().
41,863,595
I have some code that calls into AWS's Rekognition service. Sometimes it throws this exception: ``` An error occurred (InvalidParameterException) when calling the DetectLabels operation: Request has Invalid Parameters ``` I can't find the `InvalidParameterException` anywhere in the documentation or code, though, so I can't write a specific handler for when that occurs. Does anyone know what library module that exception lives in?
2017/01/25
[ "https://Stackoverflow.com/questions/41863595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442945/" ]
I found it in [`boto/cognito/identity/exceptions.py`](https://github.com/boto/boto/blob/master/boto/cognito/identity/exceptions.py): ``` from boto.exception import BotoServerError class InvalidParameterException(BotoServerError): pass ```
In Python3 with boto3 you can do: ``` from botocore.exceptions import ClientError catch ClientError as e: ```
41,863,595
I have some code that calls into AWS's Rekognition service. Sometimes it throws this exception: ``` An error occurred (InvalidParameterException) when calling the DetectLabels operation: Request has Invalid Parameters ``` I can't find the `InvalidParameterException` anywhere in the documentation or code, though, so I can't write a specific handler for when that occurs. Does anyone know what library module that exception lives in?
2017/01/25
[ "https://Stackoverflow.com/questions/41863595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442945/" ]
I found it in [`boto/cognito/identity/exceptions.py`](https://github.com/boto/boto/blob/master/boto/cognito/identity/exceptions.py): ``` from boto.exception import BotoServerError class InvalidParameterException(BotoServerError): pass ```
This is a misleading error by AWS, this error comes when the source image did not contain any detectable faces. Make sure your source image has a detectable face.
41,863,595
I have some code that calls into AWS's Rekognition service. Sometimes it throws this exception: ``` An error occurred (InvalidParameterException) when calling the DetectLabels operation: Request has Invalid Parameters ``` I can't find the `InvalidParameterException` anywhere in the documentation or code, though, so I can't write a specific handler for when that occurs. Does anyone know what library module that exception lives in?
2017/01/25
[ "https://Stackoverflow.com/questions/41863595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442945/" ]
I found it in [`boto/cognito/identity/exceptions.py`](https://github.com/boto/boto/blob/master/boto/cognito/identity/exceptions.py): ``` from boto.exception import BotoServerError class InvalidParameterException(BotoServerError): pass ```
jarmod's answer should work perfect, if you use boto3. To more explicitly answer the question regarding where the `InvalidParameterException` lives (in `boto3`): It can be acessed via a class instance of the `boto3` rekognition client: ``` import boto3 client = boto3.client('rekognition') ``` Now, the exception can be accessed via `client.exceptions.InvalidParameterException` (see jarmod's answer for a specific example). Stéphane Bruckert's suggestion of using an import from `boto` did not work for me as the exception does not appear to be caught by a specific handler using this import (but I did not tested it extensively).
41,863,595
I have some code that calls into AWS's Rekognition service. Sometimes it throws this exception: ``` An error occurred (InvalidParameterException) when calling the DetectLabels operation: Request has Invalid Parameters ``` I can't find the `InvalidParameterException` anywhere in the documentation or code, though, so I can't write a specific handler for when that occurs. Does anyone know what library module that exception lives in?
2017/01/25
[ "https://Stackoverflow.com/questions/41863595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442945/" ]
This is a misleading error by AWS, this error comes when the source image did not contain any detectable faces. Make sure your source image has a detectable face.
In Python3 with boto3 you can do: ``` from botocore.exceptions import ClientError catch ClientError as e: ```
41,863,595
I have some code that calls into AWS's Rekognition service. Sometimes it throws this exception: ``` An error occurred (InvalidParameterException) when calling the DetectLabels operation: Request has Invalid Parameters ``` I can't find the `InvalidParameterException` anywhere in the documentation or code, though, so I can't write a specific handler for when that occurs. Does anyone know what library module that exception lives in?
2017/01/25
[ "https://Stackoverflow.com/questions/41863595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442945/" ]
If you saw this exception in response to calling `search_faces_by_image` then it probably indicates that there were no detectable faces in the image that you provided. You can review a list of possible exceptions at [API\_SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/dg/API_SearchFacesByImage.html). To handle this exception, you could write code like this: ``` import boto3 rek = boto3.client('rekognition') def lookup_faces(image, collection_id): try: faces = rek.search_faces_by_image( CollectionId=collection_id, Image=image, FaceMatchThreshold=95 ) logger.info('faces detected: {}'.format(faces)) return faces except rek.exceptions.InvalidParameterException as e: logger.debug('no faces detected') return None ```
In Python3 with boto3 you can do: ``` from botocore.exceptions import ClientError catch ClientError as e: ```
41,863,595
I have some code that calls into AWS's Rekognition service. Sometimes it throws this exception: ``` An error occurred (InvalidParameterException) when calling the DetectLabels operation: Request has Invalid Parameters ``` I can't find the `InvalidParameterException` anywhere in the documentation or code, though, so I can't write a specific handler for when that occurs. Does anyone know what library module that exception lives in?
2017/01/25
[ "https://Stackoverflow.com/questions/41863595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442945/" ]
If you saw this exception in response to calling `search_faces_by_image` then it probably indicates that there were no detectable faces in the image that you provided. You can review a list of possible exceptions at [API\_SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/dg/API_SearchFacesByImage.html). To handle this exception, you could write code like this: ``` import boto3 rek = boto3.client('rekognition') def lookup_faces(image, collection_id): try: faces = rek.search_faces_by_image( CollectionId=collection_id, Image=image, FaceMatchThreshold=95 ) logger.info('faces detected: {}'.format(faces)) return faces except rek.exceptions.InvalidParameterException as e: logger.debug('no faces detected') return None ```
This is a misleading error by AWS, this error comes when the source image did not contain any detectable faces. Make sure your source image has a detectable face.
41,863,595
I have some code that calls into AWS's Rekognition service. Sometimes it throws this exception: ``` An error occurred (InvalidParameterException) when calling the DetectLabels operation: Request has Invalid Parameters ``` I can't find the `InvalidParameterException` anywhere in the documentation or code, though, so I can't write a specific handler for when that occurs. Does anyone know what library module that exception lives in?
2017/01/25
[ "https://Stackoverflow.com/questions/41863595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442945/" ]
This is a misleading error by AWS, this error comes when the source image did not contain any detectable faces. Make sure your source image has a detectable face.
jarmod's answer should work perfect, if you use boto3. To more explicitly answer the question regarding where the `InvalidParameterException` lives (in `boto3`): It can be acessed via a class instance of the `boto3` rekognition client: ``` import boto3 client = boto3.client('rekognition') ``` Now, the exception can be accessed via `client.exceptions.InvalidParameterException` (see jarmod's answer for a specific example). Stéphane Bruckert's suggestion of using an import from `boto` did not work for me as the exception does not appear to be caught by a specific handler using this import (but I did not tested it extensively).
41,863,595
I have some code that calls into AWS's Rekognition service. Sometimes it throws this exception: ``` An error occurred (InvalidParameterException) when calling the DetectLabels operation: Request has Invalid Parameters ``` I can't find the `InvalidParameterException` anywhere in the documentation or code, though, so I can't write a specific handler for when that occurs. Does anyone know what library module that exception lives in?
2017/01/25
[ "https://Stackoverflow.com/questions/41863595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442945/" ]
If you saw this exception in response to calling `search_faces_by_image` then it probably indicates that there were no detectable faces in the image that you provided. You can review a list of possible exceptions at [API\_SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/dg/API_SearchFacesByImage.html). To handle this exception, you could write code like this: ``` import boto3 rek = boto3.client('rekognition') def lookup_faces(image, collection_id): try: faces = rek.search_faces_by_image( CollectionId=collection_id, Image=image, FaceMatchThreshold=95 ) logger.info('faces detected: {}'.format(faces)) return faces except rek.exceptions.InvalidParameterException as e: logger.debug('no faces detected') return None ```
jarmod's answer should work perfect, if you use boto3. To more explicitly answer the question regarding where the `InvalidParameterException` lives (in `boto3`): It can be acessed via a class instance of the `boto3` rekognition client: ``` import boto3 client = boto3.client('rekognition') ``` Now, the exception can be accessed via `client.exceptions.InvalidParameterException` (see jarmod's answer for a specific example). Stéphane Bruckert's suggestion of using an import from `boto` did not work for me as the exception does not appear to be caught by a specific handler using this import (but I did not tested it extensively).
69,148,777
I was just wondering how this code works, I'm pretty new to coding and I was wondering how it works. ``` for (int x = 0; x < 53; x++) { int h = rand() % 52; int j = rand() % 52; // Randomize/shuffle deck Deck[52].face = Deck[h].face; Deck[52].suit = Deck[h].suit; Deck[52].value = Deck[h].value; Deck[h].face = Deck[j].face; Deck[h].suit = Deck[j].suit; Deck[h].value = Deck[j].value; Deck[j].face = Deck[52].face; Deck[j].suit = Deck[52].suit; Deck[j].value = Deck[52].value; } ```
2021/09/12
[ "https://Stackoverflow.com/questions/69148777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16889981/" ]
Indexing starts at 0, so the bottom of the deck is Deck[51]. They're using position 52 as an ancillary container to make the switch between Deck[e] and Deck[i].
D. Kupra has given an answer which is the technical core of how doublicating cards is avoided. I add an answer which tries to help you visualise "what's happening in the background", because it might help you seeing beyond array indexes and variable assignments. It works by doing 53 times a swap of two cards, in a spread deck, metaphorically using only one hand. By "spread deck" I mean that all cards are distributed on a wide table, if you take one card away, an empty place remains. (This is in contrast to the usual method of having a deck of cards in your hands, which would act like a linked list data structure; where if you take a card the two adjacent cards close the gap.) By "using only one hand" I mean that you cannot keep one card while moving another one. You can only move one card from one place to another. Luckily, at the end of the table (see answer by D. Kupra), there is one place more than there are cards. * pick two cards, by only memorising their position on the table ``` int e = rand() % 52; int i = rand() % 52; ``` * move the first selected card to the (currently free) end place ``` Deck[52].face = Deck[e].face; Deck[52].suit = Deck[e].suit; Deck[52].value = Deck[e].value; ``` * move the second selected card to the now free place where the first selected card was ``` Deck[e].face = Deck[i].face; Deck[e].suit = Deck[i].suit; Deck[e].value = Deck[i].value; ``` * move the first selected card, from its current place at the end of the table, to the place where the second selected card was until recently ``` Deck[i].face = Deck[52].face; Deck[i].suit = Deck[52].suit; Deck[i].value = Deck[52].value; ``` At this point, you can still "see the card" which temporarily was at the end of the table, the metaphor is limping a little here....
1,486,880
I need to open multiple files at one go on my linux shell and hence thought of passing the sequence value as the fd value as below: in my pwd i have files named as nile.300, nile.301,....nile.500 So I want to open nile.300 using fd 300, nile.301 as fd 301 and so on ``` #!/bin/bash for i in {300..500};do FILENAME=nile.$i # Opening file descriptors # 3 for reading and writing # i.e. /tmp/out.txt exec $i<>$FILENAME # Write to file echo "Today is $(date)" >&$i done sleep 10; for i in {300..500};do # close fd # 3 exec $i>&- done ``` However the script fails to run with ./fd.sh: line 5: exec: 300: not found
2019/09/27
[ "https://superuser.com/questions/1486880", "https://superuser.com", "https://superuser.com/users/1086623/" ]
Unless you are planning to work on all the open files at the same time, you might be better of processing one file at a time. This approach eliminate the need to have hundreds of open files at the same time, potentially running into the open file limit. ``` for i in {300..500};do FILENAME=nile.$i exec 3<>$FILENAME # Write to file echo "Today is $(date)" >&3 # Close exec 3>&- done ```
The correct syntax is `{variable}` if it's on the left-hand side: ``` exec {i}<>"$FILENAME" echo "Today is $(date)" >&$i exec {i}>&- ```
14,708,195
How I will convert this SQL query in Linq, sorry but I am not that much expert in LINQ ``` select ConnectionId from LearnerConnections where LearnerId = 1 union select LearnerId from LearnerConnections where ConnectionId = 1 ``` also can I write the DataTable methode to get the result (like DataTable.Select() method)? thanks in advance
2013/02/05
[ "https://Stackoverflow.com/questions/14708195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337033/" ]
something like that ``` LearnerConnections.Where(x => x.LearnerId == 1) .Select(m => m.ConnectionId) .Union(LearnerConnections.Where(l => l.ConnectionId ==1) .Select(lc => lc.LearnerId) ); ``` with a datatable, it should look like ``` dtLearnerConnections.AsEnumerable() .Where(m => m.Field<int>("LearnerId") == 1) .Select(m => m.Field<int>("ConnectionId")) .Union(dtLearnerConnections.AsEnumerable() .Where(x => x.Field<int>("ConnectionId") == 1) .Select(x => x.Field<int>("LearnerId")) ); ```
May this will helpful ``` var results = (from l in LearnerConnections where l.LearnerId == 1 select l.ConnectionId).Union(from a in LearnerConnections where a.ConnectionId == 1 select l.LeaenerId); ```
14,708,195
How I will convert this SQL query in Linq, sorry but I am not that much expert in LINQ ``` select ConnectionId from LearnerConnections where LearnerId = 1 union select LearnerId from LearnerConnections where ConnectionId = 1 ``` also can I write the DataTable methode to get the result (like DataTable.Select() method)? thanks in advance
2013/02/05
[ "https://Stackoverflow.com/questions/14708195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337033/" ]
something like that ``` LearnerConnections.Where(x => x.LearnerId == 1) .Select(m => m.ConnectionId) .Union(LearnerConnections.Where(l => l.ConnectionId ==1) .Select(lc => lc.LearnerId) ); ``` with a datatable, it should look like ``` dtLearnerConnections.AsEnumerable() .Where(m => m.Field<int>("LearnerId") == 1) .Select(m => m.Field<int>("ConnectionId")) .Union(dtLearnerConnections.AsEnumerable() .Where(x => x.Field<int>("ConnectionId") == 1) .Select(x => x.Field<int>("LearnerId")) ); ```
``` var result = (from lc in LearnerConnections where lc.LearnerId == 1 select lc.ConnectionId) .Union (from lc in LearnerConnections where lc.ConnectionId == 1 select lc.LearnerId); ``` If you are using DataTables, this involves the use of [LINQ to DataSet](http://blogs.msdn.com/b/adonet/archive/2007/01/26/querying-datasets-introduction-to-linq-to-dataset.aspx). This SO [question](https://stackoverflow.com/questions/10855/linq-query-on-a-datatable) might also help you.
20,052,591
Is there anyway I can hide a footer and/or header in a repeater? Basically I have two repeaters bound to different datasources one on top of the other: ``` <asp:Repeater runat="server" ID="rptAdditionalCosts"> <HeaderTemplate> <table id="optionalExtrasPriceBreakdown" cellpadding="0" cellspacing="0" border="0"> <thead> <tr> <th colspan="4"> Additional Costs </th> </tr> <tr> <th> Description </th> <th> Quantity </th> <th> Price </th> <th class="totalPrice"> Total Price </th> </tr> </thead> <tbody> </HeaderTemplate> <ItemTemplate> <tr> <td><%#DataBinder.Eval(Container.DataItem, "Description")%></td> <td><%#DataBinder.Eval(Container.DataItem, "Count")%></td> <td>£<%# DataBinder.Eval(Container.DataItem, "Gross", "{0:n2}")%></td> <td class="totalPrice">£<%#DataBinder.Eval(Container.DataItem, "Total", "{0:n2}")%></td> </tr> </ItemTemplate> <FooterTemplate> </tbody> </table> <hr class="spacer" /> </FooterTemplate> </asp:Repeater> <asp:Repeater runat="server" ID="rptOptionalExtras"> <HeaderTemplate> <table id="optionalExtrasPriceBreakdown" cellpadding="0" cellspacing="0" border="0"> <thead> <tr> <th colspan="4"> Additional Costs </th> </tr> <tr> <th> Description </th> <th> Quantity </th> <th> Price </th> <th class="totalPrice"> Total Price </th> </tr> </thead> <tbody> </HeaderTemplate> <ItemTemplate> <tr> <td><%#DataBinder.Eval(Container.DataItem, "Description")%></td> <td><%#DataBinder.Eval(Container.DataItem, "Number")%></td> <td>£<%# DataBinder.Eval(Container.DataItem, "UnitCost", "{0:n2}")%></td> <td class="totalPrice">£<%#DataBinder.Eval(Container.DataItem, "TotalCost", "{0:n2}")%></td> </tr> </ItemTemplate> <FooterTemplate> </tbody> </table> <hr class="spacer" /> </FooterTemplate> </asp:Repeater> ``` If they both contain data I want to hide the footer in the earlier and the header in the later, thus it makes one complete table in the HTML. I have bools that tells me if they contain data. ``` if (optionalVisible && additionalVisible) { //hide rptAdditionalCosts footer //and //hide rptPerBookingOptionalExtras header } ``` Problem is the repeater doesn't seem to contain any options to hide or display the footer or header templates? Am I missing something glaringly obvious?
2013/11/18
[ "https://Stackoverflow.com/questions/20052591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/542251/" ]
In the end I managed to get something working using the `ItemDataBound` event of the repeater: ``` void rptAdditionalCosts_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Footer) { if (optionalVisible && additionalVisible) e.Item.Visible = false; } } void rptOptionalExtras_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Header) { if (optionalVisible && additionalVisible) e.Item.Visible = false; } } ``` Thanks to @KarlAnderson for the answer, I never actually checked his solution it because I'd just got this running.
Try setting the header and footer templates, respectively, to `null` like this: ``` if (optionalVisible && additionalVisible) { //hide rptAdditionalCosts footer //and //hide rptPerBookingOptionalExtras header rptAdditionalCosts.FooterTemplate = null; rptPerBookingOptionalExtras.HeaderTemplate = null; } ```
20,052,591
Is there anyway I can hide a footer and/or header in a repeater? Basically I have two repeaters bound to different datasources one on top of the other: ``` <asp:Repeater runat="server" ID="rptAdditionalCosts"> <HeaderTemplate> <table id="optionalExtrasPriceBreakdown" cellpadding="0" cellspacing="0" border="0"> <thead> <tr> <th colspan="4"> Additional Costs </th> </tr> <tr> <th> Description </th> <th> Quantity </th> <th> Price </th> <th class="totalPrice"> Total Price </th> </tr> </thead> <tbody> </HeaderTemplate> <ItemTemplate> <tr> <td><%#DataBinder.Eval(Container.DataItem, "Description")%></td> <td><%#DataBinder.Eval(Container.DataItem, "Count")%></td> <td>£<%# DataBinder.Eval(Container.DataItem, "Gross", "{0:n2}")%></td> <td class="totalPrice">£<%#DataBinder.Eval(Container.DataItem, "Total", "{0:n2}")%></td> </tr> </ItemTemplate> <FooterTemplate> </tbody> </table> <hr class="spacer" /> </FooterTemplate> </asp:Repeater> <asp:Repeater runat="server" ID="rptOptionalExtras"> <HeaderTemplate> <table id="optionalExtrasPriceBreakdown" cellpadding="0" cellspacing="0" border="0"> <thead> <tr> <th colspan="4"> Additional Costs </th> </tr> <tr> <th> Description </th> <th> Quantity </th> <th> Price </th> <th class="totalPrice"> Total Price </th> </tr> </thead> <tbody> </HeaderTemplate> <ItemTemplate> <tr> <td><%#DataBinder.Eval(Container.DataItem, "Description")%></td> <td><%#DataBinder.Eval(Container.DataItem, "Number")%></td> <td>£<%# DataBinder.Eval(Container.DataItem, "UnitCost", "{0:n2}")%></td> <td class="totalPrice">£<%#DataBinder.Eval(Container.DataItem, "TotalCost", "{0:n2}")%></td> </tr> </ItemTemplate> <FooterTemplate> </tbody> </table> <hr class="spacer" /> </FooterTemplate> </asp:Repeater> ``` If they both contain data I want to hide the footer in the earlier and the header in the later, thus it makes one complete table in the HTML. I have bools that tells me if they contain data. ``` if (optionalVisible && additionalVisible) { //hide rptAdditionalCosts footer //and //hide rptPerBookingOptionalExtras header } ``` Problem is the repeater doesn't seem to contain any options to hide or display the footer or header templates? Am I missing something glaringly obvious?
2013/11/18
[ "https://Stackoverflow.com/questions/20052591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/542251/" ]
I have had issues with setting the templates to null interfering with repeater commands. I suggest setting to a new BindableTemplateBuilder instead. ``` if (optionalVisible && additionalVisible) { //hide rptAdditionalCosts footer //and //hide rptPerBookingOptionalExtras header rptAdditionalCosts.FooterTemplate = new BindableTemplateBuilder(); rptPerBookingOptionalExtras.HeaderTemplate = new BindableTemplateBuilder(); } ```
Try setting the header and footer templates, respectively, to `null` like this: ``` if (optionalVisible && additionalVisible) { //hide rptAdditionalCosts footer //and //hide rptPerBookingOptionalExtras header rptAdditionalCosts.FooterTemplate = null; rptPerBookingOptionalExtras.HeaderTemplate = null; } ```
20,052,591
Is there anyway I can hide a footer and/or header in a repeater? Basically I have two repeaters bound to different datasources one on top of the other: ``` <asp:Repeater runat="server" ID="rptAdditionalCosts"> <HeaderTemplate> <table id="optionalExtrasPriceBreakdown" cellpadding="0" cellspacing="0" border="0"> <thead> <tr> <th colspan="4"> Additional Costs </th> </tr> <tr> <th> Description </th> <th> Quantity </th> <th> Price </th> <th class="totalPrice"> Total Price </th> </tr> </thead> <tbody> </HeaderTemplate> <ItemTemplate> <tr> <td><%#DataBinder.Eval(Container.DataItem, "Description")%></td> <td><%#DataBinder.Eval(Container.DataItem, "Count")%></td> <td>£<%# DataBinder.Eval(Container.DataItem, "Gross", "{0:n2}")%></td> <td class="totalPrice">£<%#DataBinder.Eval(Container.DataItem, "Total", "{0:n2}")%></td> </tr> </ItemTemplate> <FooterTemplate> </tbody> </table> <hr class="spacer" /> </FooterTemplate> </asp:Repeater> <asp:Repeater runat="server" ID="rptOptionalExtras"> <HeaderTemplate> <table id="optionalExtrasPriceBreakdown" cellpadding="0" cellspacing="0" border="0"> <thead> <tr> <th colspan="4"> Additional Costs </th> </tr> <tr> <th> Description </th> <th> Quantity </th> <th> Price </th> <th class="totalPrice"> Total Price </th> </tr> </thead> <tbody> </HeaderTemplate> <ItemTemplate> <tr> <td><%#DataBinder.Eval(Container.DataItem, "Description")%></td> <td><%#DataBinder.Eval(Container.DataItem, "Number")%></td> <td>£<%# DataBinder.Eval(Container.DataItem, "UnitCost", "{0:n2}")%></td> <td class="totalPrice">£<%#DataBinder.Eval(Container.DataItem, "TotalCost", "{0:n2}")%></td> </tr> </ItemTemplate> <FooterTemplate> </tbody> </table> <hr class="spacer" /> </FooterTemplate> </asp:Repeater> ``` If they both contain data I want to hide the footer in the earlier and the header in the later, thus it makes one complete table in the HTML. I have bools that tells me if they contain data. ``` if (optionalVisible && additionalVisible) { //hide rptAdditionalCosts footer //and //hide rptPerBookingOptionalExtras header } ``` Problem is the repeater doesn't seem to contain any options to hide or display the footer or header templates? Am I missing something glaringly obvious?
2013/11/18
[ "https://Stackoverflow.com/questions/20052591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/542251/" ]
In the end I managed to get something working using the `ItemDataBound` event of the repeater: ``` void rptAdditionalCosts_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Footer) { if (optionalVisible && additionalVisible) e.Item.Visible = false; } } void rptOptionalExtras_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Header) { if (optionalVisible && additionalVisible) e.Item.Visible = false; } } ``` Thanks to @KarlAnderson for the answer, I never actually checked his solution it because I'd just got this running.
I have had issues with setting the templates to null interfering with repeater commands. I suggest setting to a new BindableTemplateBuilder instead. ``` if (optionalVisible && additionalVisible) { //hide rptAdditionalCosts footer //and //hide rptPerBookingOptionalExtras header rptAdditionalCosts.FooterTemplate = new BindableTemplateBuilder(); rptPerBookingOptionalExtras.HeaderTemplate = new BindableTemplateBuilder(); } ```
48,504,451
I have following scenario: 1. I have one data flow task with OLEDB source, taking data from source tables using query with inner join. One of the column is varchar(8) and few values are float, rest are int into this column. 2. The OLEDB destination is storing above data into a table where corresponding column is INT. 3. This package is deployed under SQL Server 2012 and SQL Job is executing this SSIS Package. 4. This SSIS Package is getting executed successfully in one of our environment and doing implicit conversion, but in other environments its failing with Conversion Error, which is obvious. So, my question is, why its not failing in one of our environment. could there be any environment specific, SSMS specific or SQL Job specific setting which is helping this job to be successful? Please help.
2018/01/29
[ "https://Stackoverflow.com/questions/48504451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5007906/" ]
You should use $builder->addEventListener. For multiple fields all you need to do is to have dynamic fields inside FormEvents::PRE\_SET\_DATA event handler. Also, use parent field data, as explained in the doc to fetch child field choices. I have used this approach, for generating Country, City and District Entities in hierarchical fields. Let me know if it helps or you need more information. ``` $builder->add(); // all other fields.. $builder->addEventSubscriber(new DynamicFieldsSubscriber()); ``` Create an eventSubscriber as defined in the doc, here the file name is DynamicFieldsSubscriber ``` public static function getSubscribedEvents() { return array( FormEvents::PRE_SET_DATA => 'preSetData', FormEvents::PRE_SUBMIT => 'preSubmitData', ); } /** * Handling form fields before form renders. * @param FormEvent $event */ public function preSetData(FormEvent $event) { $translator = $this->translator; $location = $event->getData(); // Location is the main entity which is obviously form's (data_class) $form = $event->getForm(); $country = ""; $city = ""; $district = ""; if ($location) { // collect preliminary values for 3 fields. $country = $location->getCountry(); $city = $location->getCity(); $district = $location->getDistrict(); } // Add country field as its static. $form->add('country', EntityType::class, array( 'class' => 'App\Entity\Countries', 'label' => $translator->trans('country'), 'placeholder' => $translator->trans('select'), 'required' => true, 'query_builder' => function (EntityRepository $er) { return $er->createQueryBuilder('c'); } )); // Now add all child fields. $this->addCityField($form, $country); $this->addDistrictField($form, $city); } /** * Handling Form fields before form submits. * @param FormEvent $event */ public function preSubmitData(FormEvent $event) { $form = $event->getForm(); $data = $event->getData(); // Here $data will be in array format. // Add property field if parent entity data is available. $country = isset($data['country']) ? $data['country'] : null; $city = isset($data['city']) ? $data['city'] : null; $district = isset($data['district']) ? $data['district'] : null; // Call methods to add child fields. $this->addCityField($form, $country); $this->addDistrictField($form, $city); } /** * Method to Add City Field. (first dynamic field.) * @param FormInterface $form * @param type $country */ private function addCityField(FormInterface $form, $country = null) { $translator = $this->translator; $countryCode = (is_object($country)) ? $country->getId() : $country; // $countryCode is dynamic here, collected from the event based data flow. $form->add('city', EntityType::class, array( 'class' => 'App\Entity\Cities', 'label' => $translator->trans('city'), 'placeholder' => $translator->trans('select'), 'required' => true, 'attr' => array( 'class' => 'col-md-12 validate-required', 'placeholder' => 'City *' ), 'query_builder' => function (EntityRepository $er) use($countryCode) { return $er->createQueryBuilder('p') ->where('p.country_id = :country') ->setParameter('country', $countryCode); } )); } /** * Method to Add District Field, (second dynamic field) * @param FormInterface $form * @param type $city */ private function addDistrictField(FormInterface $form, $city = null) { $translator = $this->translator; $cityCode = (is_object($city)) ? $city->getId() : $city; // $cityCode is dynamic in here collected from event based data flow. $form->add('district', EntityType::class, array( 'class' => 'App\Entity\Districts', 'label' => $translator->trans('district'), 'placeholder' => $translator->trans('select'), 'required' => true, 'attr' => array('class' => 'district'), 'query_builder' => function (EntityRepository $er) use($cityCode) { return $er->createQueryBuilder('s') ->where('s.city = :city') ->setParameter('city', $cityCode); } )); } ``` And your project JQuery should look like this ``` <script> var $sport = $('#new_address_form_country'); // When sport gets selected ... $sport.change(function() { // ... retrieve the corresponding form. var $form = $('#new_address_form').closest('form'); // Simulate form data, but only include the selected sport value. var data = {}; data[$sport.attr('name')] = $sport.val(); // Submit data via AJAX to the form's action path. $.ajax({ url : $form.attr('action'), type: $form.attr('method'), data : data, success: function(html) { // Replace current position field ... $('#new_address_form_city').replaceWith( // ... with the returned one from the AJAX response. $(html).find('#new_address_form_city') ); } }); }); $(document).on('change','#new_address_form_city',function () { // ... retrieve the corresponding form. var $form2 = $('#new_address_form').closest('form'); // Simulate form data, but only include the selected sport value. var data2 = {}; data2[$('#new_address_form_city').attr('name')] = $('#new_address_form_city').val(); // Submit data via AJAX to the form's action path. $.ajax({ url : $form2.attr('action'), type: $form2.attr('method'), data : data2, success: function(html) { console.log($(html).find('#new_address_form_district')); // Replace current position field ... $('#new_address_form_district').replaceWith( // ... with the returned one from the AJAX response. $(html).find('#new_address_form_district') ); } }); }); </script> ``` I hope this will help.
I believe that sometimes ajax call after ajax call doesn't work as it looses the contact with jquery event listeners. Create a function for `$sport2.change` event listener and name it something e.g. `sport2Change`. And try to call that function on an `onchange` event of the the element with id - `new_address_form_City`
52,744
Modular forms are defined here: <http://en.wikipedia.org/wiki/Modular_form#General_definitions> Maass forms are defined here: <http://en.wikipedia.org/wiki/Maass_wave_form> I wonder if modular forms can be transfered into Maass forms. Or they two are different categories of automorphic forms.
2011/01/21
[ "https://mathoverflow.net/questions/52744", "https://mathoverflow.net", "https://mathoverflow.net/users/2666/" ]
In the more common terminology modular forms on the upper half-plane fall into two categories: holomorphic forms and Maass forms. In fact there is a notion of Maass forms with weight and nebentypus, which includes holomorphic forms as follows: if $f(x+iy)$ is a weight $k$ holomorphic form, then $y^{k/2}f(x+iy)$ is a weight $k$ Maass form. There are so-called Maass lowering and raising operators that turn a weight $k$ Maass form into a weight $k-2$ or weight $k+2$ Maass form. Using these, the weight $k$ holomorphic forms can be understood as those that are "new" for weight $k$: for $k\geq 2$ the raising operator isometrically embeds the space of weight $k-2$ Maass forms into the space of weight $k$ Maass forms, and the orthogonal complement is the subspace coming from weight $k$ holomorphic forms as described in the previous paragraph; also, the lowering operator acts as an inverse on the image of the raising operator and annihilates the mentioned orthogonal component. All these connections can be better understood in the language of representation theory. I learned this material from Bump: Automorphic Forms and Representations, see especially Theorem 2.7.1 on page 241. Another good reference (from the classical perspective) is Duke-Friedlander-Iwaniec (Invent Math. 149 (2002), 489-577), see Section 4 there.
I'm not a specialist in the field, but recently it happened to me to read the beautiful paper by Ono "The last words of a genius" on the [Notices of the AMS, December 2010](http://www.ams.org/notices/201011/index.html), which seems related to your question. Let $M \colon \mathbb{H} \to \mathbb{C}$ be a *smooth* function that transforms like a weight $k$ modular form and such that $\Delta\_k(M)=0$. Then we say that $M$ is a *weight $k$ harmonic Maass form*. Any harmonic Maass form can be uniquely written as $M=M^{+} + M^{-}$, where $M^+$ is the *holomorphic part* and $M^-$ is the *non-holomorphic part*. Then the modular forms are exactly those harmonic Maass forms such that $M^-=0$. In the general case, the holomorphic part of a harmonic Maass form is *not* a modular form, but it is still a very interesting object. For instance, when $k=1/2$ it is a so-called *mock theta function*. Mock theta functions were first described by Ramanujan in a famous letter to Hardy, written on his deathbed, but only very recently their deep connections with real-analytic modular forms were discovered by S. Zwegers, in his Ph.D. thesis written under D. Zagier. For further detail you can look at Ono's paper or at the article "What is... a mock modular form?" by Amanda Folsom in the same issue of the Notices of the AMS.
52,744
Modular forms are defined here: <http://en.wikipedia.org/wiki/Modular_form#General_definitions> Maass forms are defined here: <http://en.wikipedia.org/wiki/Maass_wave_form> I wonder if modular forms can be transfered into Maass forms. Or they two are different categories of automorphic forms.
2011/01/21
[ "https://mathoverflow.net/questions/52744", "https://mathoverflow.net", "https://mathoverflow.net/users/2666/" ]
Automorphic forms correspond to representations that occur in $L^2(G/\Gamma)$. In the case when $G$ is $SL\_2$, holomorphic modular forms correspond to (highest weight vectors of) discrete series representations of $G$, while Maass wave forms correspond to (spherical vectors of) continuous series representations of $G$.
I'm not a specialist in the field, but recently it happened to me to read the beautiful paper by Ono "The last words of a genius" on the [Notices of the AMS, December 2010](http://www.ams.org/notices/201011/index.html), which seems related to your question. Let $M \colon \mathbb{H} \to \mathbb{C}$ be a *smooth* function that transforms like a weight $k$ modular form and such that $\Delta\_k(M)=0$. Then we say that $M$ is a *weight $k$ harmonic Maass form*. Any harmonic Maass form can be uniquely written as $M=M^{+} + M^{-}$, where $M^+$ is the *holomorphic part* and $M^-$ is the *non-holomorphic part*. Then the modular forms are exactly those harmonic Maass forms such that $M^-=0$. In the general case, the holomorphic part of a harmonic Maass form is *not* a modular form, but it is still a very interesting object. For instance, when $k=1/2$ it is a so-called *mock theta function*. Mock theta functions were first described by Ramanujan in a famous letter to Hardy, written on his deathbed, but only very recently their deep connections with real-analytic modular forms were discovered by S. Zwegers, in his Ph.D. thesis written under D. Zagier. For further detail you can look at Ono's paper or at the article "What is... a mock modular form?" by Amanda Folsom in the same issue of the Notices of the AMS.
52,744
Modular forms are defined here: <http://en.wikipedia.org/wiki/Modular_form#General_definitions> Maass forms are defined here: <http://en.wikipedia.org/wiki/Maass_wave_form> I wonder if modular forms can be transfered into Maass forms. Or they two are different categories of automorphic forms.
2011/01/21
[ "https://mathoverflow.net/questions/52744", "https://mathoverflow.net", "https://mathoverflow.net/users/2666/" ]
In the more common terminology modular forms on the upper half-plane fall into two categories: holomorphic forms and Maass forms. In fact there is a notion of Maass forms with weight and nebentypus, which includes holomorphic forms as follows: if $f(x+iy)$ is a weight $k$ holomorphic form, then $y^{k/2}f(x+iy)$ is a weight $k$ Maass form. There are so-called Maass lowering and raising operators that turn a weight $k$ Maass form into a weight $k-2$ or weight $k+2$ Maass form. Using these, the weight $k$ holomorphic forms can be understood as those that are "new" for weight $k$: for $k\geq 2$ the raising operator isometrically embeds the space of weight $k-2$ Maass forms into the space of weight $k$ Maass forms, and the orthogonal complement is the subspace coming from weight $k$ holomorphic forms as described in the previous paragraph; also, the lowering operator acts as an inverse on the image of the raising operator and annihilates the mentioned orthogonal component. All these connections can be better understood in the language of representation theory. I learned this material from Bump: Automorphic Forms and Representations, see especially Theorem 2.7.1 on page 241. Another good reference (from the classical perspective) is Duke-Friedlander-Iwaniec (Invent Math. 149 (2002), 489-577), see Section 4 there.
Automorphic forms correspond to representations that occur in $L^2(G/\Gamma)$. In the case when $G$ is $SL\_2$, holomorphic modular forms correspond to (highest weight vectors of) discrete series representations of $G$, while Maass wave forms correspond to (spherical vectors of) continuous series representations of $G$.
68,915,200
The data that I want to use has this structure: ``` { "1": { "id": 1, "name": "Bulbasaur" }, "2": { "id": 2, "name": "Ivysaur" }, "3": { "id": 3, "name": "Venusaur" } } ``` **Note:** The number labeling each object matches the id of the Pokémon, not the number of Pokémon My problem is that when I try to create data classes for this it ends up creating a data class for each object. Not one data class that fits each object. I believe this is due to the number labeling the object(Pokémon) being different for each object. Is there a way I can format this data in maybe one or two data classes and not over 800? Ideally I would like the data to be structured like this but it does not work when run. ``` data class ReleasedPokemonModel( val id: Int, val name: String ) ```
2021/08/24
[ "https://Stackoverflow.com/questions/68915200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11752124/" ]
When parsing Json to Object with this special case, you should custom Json Deserializer yourself. Here I use Gson library to parse Json to Object. First, create a custom Json Deserializer with Gson. As follows: *PokemonResponse.kt* ``` data class PokemonResponse( val pokemonMap: List<StringReleasedPokemonModel> ) data class ReleasedPokemonModel( val id: Int, val name: String ) ``` *GsonHelper.kt* ``` object GsonHelper { fun create(): Gson = GsonBuilder().apply { registerTypeAdapter(PokemonResponse::class.java, PokemonType()) setLenient() }.create() private class PokemonType : JsonDeserializer<PokemonResponse> { override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext? ): PokemonResponse { val list = mutableListOf<ReleasedPokemonModel>() // Get your all key val keys = json?.asJsonObject?.keySet() keys?.forEach { key -> // Get your item with key val item = Gson().fromJson<ReleasedPokemonModel>( json.asJsonObject[key], object : TypeToken<ReleasedPokemonModel>() {}.type ) list.add(item) } return PokemonResponse(list) } } } ``` Next I will create a `GsonConverterFactory` so that I can `addConvertFactory` to Retrofit. ``` val gsonConverterFactory = GsonConverterFactory.create(GsonHelper.create()) ``` And now I will add retrofit. ``` val retrofit = Retrofit.Builder() // Custom your Retrofit .addConverterFactory(gsonConverterFactory) // Add GsonConverterFactoty .build() ``` Finally in ApiService, your response will now return type `PokemonResponse`. ``` interface ApiService { @GET("your_link") suspend fun getGenres(): PokemonResponse } ```
The problem is that there's no JSON array there. it's literally one JSON object with each Pokemon listed as a property. I would recommend that you reformat the JSON beforehand to look like this: ``` [ { "id": 1, "name": "Bulbasaur" }, { "id": 2, "name": "Ivysaur" }, { "id": 3, "name": "Venusaur" } ] ``` And then you could model it like this: ``` data class ReleasedPokemonModel( val id: Int, val name: String ) data class Response( val items: List<ReleasedPokemonModel> ) ``` [See more here.](https://stackoverflow.com/a/45541563/7434090) [And see here for discussion about reformatting the data before handing it to Retrofit.](https://stackoverflow.com/questions/49490230/use-gson-retrofit-on-serializedname-which-is-unknown-beforehand/49501210)
68,915,200
The data that I want to use has this structure: ``` { "1": { "id": 1, "name": "Bulbasaur" }, "2": { "id": 2, "name": "Ivysaur" }, "3": { "id": 3, "name": "Venusaur" } } ``` **Note:** The number labeling each object matches the id of the Pokémon, not the number of Pokémon My problem is that when I try to create data classes for this it ends up creating a data class for each object. Not one data class that fits each object. I believe this is due to the number labeling the object(Pokémon) being different for each object. Is there a way I can format this data in maybe one or two data classes and not over 800? Ideally I would like the data to be structured like this but it does not work when run. ``` data class ReleasedPokemonModel( val id: Int, val name: String ) ```
2021/08/24
[ "https://Stackoverflow.com/questions/68915200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11752124/" ]
When parsing Json to Object with this special case, you should custom Json Deserializer yourself. Here I use Gson library to parse Json to Object. First, create a custom Json Deserializer with Gson. As follows: *PokemonResponse.kt* ``` data class PokemonResponse( val pokemonMap: List<StringReleasedPokemonModel> ) data class ReleasedPokemonModel( val id: Int, val name: String ) ``` *GsonHelper.kt* ``` object GsonHelper { fun create(): Gson = GsonBuilder().apply { registerTypeAdapter(PokemonResponse::class.java, PokemonType()) setLenient() }.create() private class PokemonType : JsonDeserializer<PokemonResponse> { override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext? ): PokemonResponse { val list = mutableListOf<ReleasedPokemonModel>() // Get your all key val keys = json?.asJsonObject?.keySet() keys?.forEach { key -> // Get your item with key val item = Gson().fromJson<ReleasedPokemonModel>( json.asJsonObject[key], object : TypeToken<ReleasedPokemonModel>() {}.type ) list.add(item) } return PokemonResponse(list) } } } ``` Next I will create a `GsonConverterFactory` so that I can `addConvertFactory` to Retrofit. ``` val gsonConverterFactory = GsonConverterFactory.create(GsonHelper.create()) ``` And now I will add retrofit. ``` val retrofit = Retrofit.Builder() // Custom your Retrofit .addConverterFactory(gsonConverterFactory) // Add GsonConverterFactoty .build() ``` Finally in ApiService, your response will now return type `PokemonResponse`. ``` interface ApiService { @GET("your_link") suspend fun getGenres(): PokemonResponse } ```
You can use Map to store the key like the following ``` data class PokemonResponse( val pokemonMap:Map<String,ReleasedPokemonModel> ) data class ReleasedPokemonModel( val id: Int, val name: String ) ```
47,082,847
I have my project in visual studio and i am using installshield as my windows installer. When I am installing new updated version of my application it will shows > > Another version of this product is automatically installed like this... > > > How can I install new version by overwriting my old version? Is there any way to configure in installshield or give me any other way ?
2017/11/02
[ "https://Stackoverflow.com/questions/47082847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8204957/" ]
The error that you're getting is because the ProductCode has not been changed. This code is what makes your product/installer unique. Generally to author the upgrade you'll need to change this code and make sure the UpgradeCode is the same so that it recognizes what is already installed. Authoring upgrades is a much wider topic and far too much information then can be covered here. I would suggest this [page](https://msdn.microsoft.com/en-us/library/windows/desktop/aa370579(v=vs.85).aspx) for learning about Windows installer upgrading.
Under The `Upgrade Paths`, create a new path. Leave the min version blank (unless you need it), include min version yes, Max version should be set to the version You are installing now. Include max version to yes. Each time you are installing an update, Increase the Product version(If u want to change) in the General Information section. Click on a new Product Code in the General Information Section `Do not change` the upgrade code. Go back to the `upgrade path`, and set the Max version to the same version you are deploying now. And make sure the `Upgrade code` in the "General Information" and "Upgrade path" are same. This process uninstalls previous version, and installs the latest. No duplicates in add/remove programs. If any doubt on this, comment your question...
47,082,847
I have my project in visual studio and i am using installshield as my windows installer. When I am installing new updated version of my application it will shows > > Another version of this product is automatically installed like this... > > > How can I install new version by overwriting my old version? Is there any way to configure in installshield or give me any other way ?
2017/11/02
[ "https://Stackoverflow.com/questions/47082847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8204957/" ]
The error that you're getting is because the ProductCode has not been changed. This code is what makes your product/installer unique. Generally to author the upgrade you'll need to change this code and make sure the UpgradeCode is the same so that it recognizes what is already installed. Authoring upgrades is a much wider topic and far too much information then can be covered here. I would suggest this [page](https://msdn.microsoft.com/en-us/library/windows/desktop/aa370579(v=vs.85).aspx) for learning about Windows installer upgrading.
Every upgraded version of install should have a different ProductCode. UpgradeCode is what tells the install package that this product has been installed. If ProductCode is also the same, install assumes you are installing the same product again. ProductCode needs to be different for each of the updated packages.
47,082,847
I have my project in visual studio and i am using installshield as my windows installer. When I am installing new updated version of my application it will shows > > Another version of this product is automatically installed like this... > > > How can I install new version by overwriting my old version? Is there any way to configure in installshield or give me any other way ?
2017/11/02
[ "https://Stackoverflow.com/questions/47082847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8204957/" ]
Under The `Upgrade Paths`, create a new path. Leave the min version blank (unless you need it), include min version yes, Max version should be set to the version You are installing now. Include max version to yes. Each time you are installing an update, Increase the Product version(If u want to change) in the General Information section. Click on a new Product Code in the General Information Section `Do not change` the upgrade code. Go back to the `upgrade path`, and set the Max version to the same version you are deploying now. And make sure the `Upgrade code` in the "General Information" and "Upgrade path" are same. This process uninstalls previous version, and installs the latest. No duplicates in add/remove programs. If any doubt on this, comment your question...
Every upgraded version of install should have a different ProductCode. UpgradeCode is what tells the install package that this product has been installed. If ProductCode is also the same, install assumes you are installing the same product again. ProductCode needs to be different for each of the updated packages.
1,214,216
I have a standard menu using ul and li tags. And in my database, I have a table Users with a field 'certificate' and depending the value of this 'certificate', the user will see or not some items of the menu. I was reading some texts and I think I will have to use `ActionFilters`. Is this right? So, how can I render different menus depending which user is accessing? thanks!!
2009/07/31
[ "https://Stackoverflow.com/questions/1214216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60286/" ]
.toFixed converts the object from a Number to a String. Leave the full values in place and only convert using .toFixed at the very end ``` $(".total").text(total.toFixed(2)); ``` Alternatively, convert the string back to a number. ``` total = total + + tmp; ```
Just FYI, there is an excellent mathematical aggregation plugin for jQuery: [jQuery Calculation](http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm) Using that plugin may also indirectly solve your issue. It's usage would reduce your script to: ``` $('.total').text($('.amount').sum()); ```
1,214,216
I have a standard menu using ul and li tags. And in my database, I have a table Users with a field 'certificate' and depending the value of this 'certificate', the user will see or not some items of the menu. I was reading some texts and I think I will have to use `ActionFilters`. Is this right? So, how can I render different menus depending which user is accessing? thanks!!
2009/07/31
[ "https://Stackoverflow.com/questions/1214216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60286/" ]
.toFixed converts the object from a Number to a String. Leave the full values in place and only convert using .toFixed at the very end ``` $(".total").text(total.toFixed(2)); ``` Alternatively, convert the string back to a number. ``` total = total + + tmp; ```
You are converting the parseFloat into a string, then adding it to total. Only add .toFixed(2) to the final line, once things have been added. ``` var total = 0; $(".amount").each(function() { var value = $(this).val(); value = (value.length < 1) ? 0 : value; var tmp = parseFloat(value); total += tmp; }); $(".total").text(total).toFixed(2); ```
1,214,216
I have a standard menu using ul and li tags. And in my database, I have a table Users with a field 'certificate' and depending the value of this 'certificate', the user will see or not some items of the menu. I was reading some texts and I think I will have to use `ActionFilters`. Is this right? So, how can I render different menus depending which user is accessing? thanks!!
2009/07/31
[ "https://Stackoverflow.com/questions/1214216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60286/" ]
Just FYI, there is an excellent mathematical aggregation plugin for jQuery: [jQuery Calculation](http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm) Using that plugin may also indirectly solve your issue. It's usage would reduce your script to: ``` $('.total').text($('.amount').sum()); ```
You are converting the parseFloat into a string, then adding it to total. Only add .toFixed(2) to the final line, once things have been added. ``` var total = 0; $(".amount").each(function() { var value = $(this).val(); value = (value.length < 1) ? 0 : value; var tmp = parseFloat(value); total += tmp; }); $(".total").text(total).toFixed(2); ```
36,902,209
i'm having problems with my page I created .the message i get is above.this is my articles controller.rb page code.learning ruby and the challenges it brings.i'm stuck in this section. And i've been having issues with section.once i post up my code.i don't know if i messed up my codes or something like that. class ArticlesController < ApplicationController ``` def index @articles = Article.all end def new @article =Article.new end def edit @article = Article.new(article_params[:id]) end def create @article =Article.new(article_params) [email protected] flash[:notice] = "Article was successfully created" redirect_to article_path(@article) else render 'new' end end def update @article =Article.find(params[:id]) [email protected] flash[:notice] = "Article was successfully updated" redirect_to article_path(@article) else render 'edit' end end def show @article =Article.find(params[:id]) end end ``` and this is the error page undefined local variable or method `article\_params' for # Extracted source (around line #12): 10 11 12 13 14 15 def edit @article = Article.new(article\_params[:id]) end ``` i get on ruby rails ```
2016/04/27
[ "https://Stackoverflow.com/questions/36902209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5931828/" ]
Yip, as Alfie said above, you're missing your article\_params. In rails 4 (which I assume is what you're using) there is the concept of strong paramaters, which is a way of only allowing the fields you're expecting through. Depending on what fields are in your "article" object, you need to add something like this: ``` def article_params params.require(:article).permit(:title, :body) end ``` Note, you'll need to adjust it to suit whatever your actual fields are. Also, might be a copy & paste error, but it's a good idea to get into the habit of indenting your code correctly! Good luck with getting the codes to work :)
You need to define your `article_params` in your controller
36,902,209
i'm having problems with my page I created .the message i get is above.this is my articles controller.rb page code.learning ruby and the challenges it brings.i'm stuck in this section. And i've been having issues with section.once i post up my code.i don't know if i messed up my codes or something like that. class ArticlesController < ApplicationController ``` def index @articles = Article.all end def new @article =Article.new end def edit @article = Article.new(article_params[:id]) end def create @article =Article.new(article_params) [email protected] flash[:notice] = "Article was successfully created" redirect_to article_path(@article) else render 'new' end end def update @article =Article.find(params[:id]) [email protected] flash[:notice] = "Article was successfully updated" redirect_to article_path(@article) else render 'edit' end end def show @article =Article.find(params[:id]) end end ``` and this is the error page undefined local variable or method `article\_params' for # Extracted source (around line #12): 10 11 12 13 14 15 def edit @article = Article.new(article\_params[:id]) end ``` i get on ruby rails ```
2016/04/27
[ "https://Stackoverflow.com/questions/36902209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5931828/" ]
Yip, as Alfie said above, you're missing your article\_params. In rails 4 (which I assume is what you're using) there is the concept of strong paramaters, which is a way of only allowing the fields you're expecting through. Depending on what fields are in your "article" object, you need to add something like this: ``` def article_params params.require(:article).permit(:title, :body) end ``` Note, you'll need to adjust it to suit whatever your actual fields are. Also, might be a copy & paste error, but it's a good idea to get into the habit of indenting your code correctly! Good luck with getting the codes to work :)
You forgot to pass article\_params to update. ``` def update @article = Article.find(params[:id]) if @article.update(article_params) flash[:notice] = 'Article was successfully updated' redirect_to article_path(@article) else redirect 'edit' end end ```
56,580,342
So I know how to get the sum of a single list so say, > > > > > > a=[1,2,3,4] > > > > > > sum(a) > > > > > > 10 > > > > > > > > > How would I go about trying to sum lists in a list of lists? So, from: > > > > > > [[1,2],[2,3],[3,42]] to > > > > > > [3,5,45]? > > > > > > > > >
2019/06/13
[ "https://Stackoverflow.com/questions/56580342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11138835/" ]
**Code:** ``` l = [[1,2],[2,3],[3,42]] print([sum(i) for i in l]) ``` **Output:** ``` [3, 5, 45] ```
You should use `sum()` in list comprehension for other lists ``` In [12]: a = [[1,2],[2,3],[3,42]] In [13]: [sum(i) for i in a] Out[13]: [3, 5, 45] ```
56,580,342
So I know how to get the sum of a single list so say, > > > > > > a=[1,2,3,4] > > > > > > sum(a) > > > > > > 10 > > > > > > > > > How would I go about trying to sum lists in a list of lists? So, from: > > > > > > [[1,2],[2,3],[3,42]] to > > > > > > [3,5,45]? > > > > > > > > >
2019/06/13
[ "https://Stackoverflow.com/questions/56580342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11138835/" ]
**Code:** ``` l = [[1,2],[2,3],[3,42]] print([sum(i) for i in l]) ``` **Output:** ``` [3, 5, 45] ```
``` intial_list = [[1,2],[2,3],[3,42]] res = list(map(sum, intial_list)) print(res) ``` output ``` [3,5,45] ```
56,580,342
So I know how to get the sum of a single list so say, > > > > > > a=[1,2,3,4] > > > > > > sum(a) > > > > > > 10 > > > > > > > > > How would I go about trying to sum lists in a list of lists? So, from: > > > > > > [[1,2],[2,3],[3,42]] to > > > > > > [3,5,45]? > > > > > > > > >
2019/06/13
[ "https://Stackoverflow.com/questions/56580342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11138835/" ]
You should use `sum()` in list comprehension for other lists ``` In [12]: a = [[1,2],[2,3],[3,42]] In [13]: [sum(i) for i in a] Out[13]: [3, 5, 45] ```
``` intial_list = [[1,2],[2,3],[3,42]] res = list(map(sum, intial_list)) print(res) ``` output ``` [3,5,45] ```
42,229,923
The admin returns this error when trying to add an instance to one of my models. The model itself has a correct **str**() method and contains no instances yet. Also tried replacing the **str**() method with a static method or removing it altogether. No luck. The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33. ``` Error during template rendering In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33 __str__ returned non-string (type NoneType) 23 {% endblock %} 24 {% endif %} 25 26 {% block content %}<div id="content-main"> 27 {% block object-tools %} 28 {% if change %}{% if not is_popup %} 29 <ul class="object-tools"> 30 {% block object-tools-items %} 31 <li> 32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} 33 <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> 34 </li> 35 {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} 36 {% endblock %} 37 </ul> 38 {% endif %}{% endif %} 39 {% endblock %} 40 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %} 41 <div> 42 {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %} 43 {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %} ``` These are the relevant parts of my `models.py` and `admin.py` ``` class UserContent(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='%(class)s_creator') updated_by = models.ForeignKey(User, related_name='%(class)s_updater') class Meta: abstract = True class Linetrans(UserContent): line = models.ForeignKey(Line) translation = models.ForeignKey(Translation) text = models.CharField(max_length=400) #def __str__(self): # return self.text class Meta: ordering = ['line'] ``` and ``` admin.site.register(Linetrans) ``` Other model classes are very similar and do not return an error. The error also occurs when the Linetrans is added as an inline to another admin class. edit / update: I commented out all other str() methods in my model and sure enough the error seems to go away. Now trying to pinpoint the issue.
2017/02/14
[ "https://Stackoverflow.com/questions/42229923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470917/" ]
I had a similar issue. The problem was that the primary key for one row was null ( I dont know how that happened). I couldnt delete the row because of cascade issues. so I had to change the **str** mmethod to somthing like this. ``` def __str__(self): if self.customerName==None: return "ERROR-CUSTOMER NAME IS NULL" return self.customerName ```
that's works for me: ``` def __str__(self): return f"{self.category}" ``` Just use "f" string
42,229,923
The admin returns this error when trying to add an instance to one of my models. The model itself has a correct **str**() method and contains no instances yet. Also tried replacing the **str**() method with a static method or removing it altogether. No luck. The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33. ``` Error during template rendering In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33 __str__ returned non-string (type NoneType) 23 {% endblock %} 24 {% endif %} 25 26 {% block content %}<div id="content-main"> 27 {% block object-tools %} 28 {% if change %}{% if not is_popup %} 29 <ul class="object-tools"> 30 {% block object-tools-items %} 31 <li> 32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} 33 <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> 34 </li> 35 {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} 36 {% endblock %} 37 </ul> 38 {% endif %}{% endif %} 39 {% endblock %} 40 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %} 41 <div> 42 {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %} 43 {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %} ``` These are the relevant parts of my `models.py` and `admin.py` ``` class UserContent(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='%(class)s_creator') updated_by = models.ForeignKey(User, related_name='%(class)s_updater') class Meta: abstract = True class Linetrans(UserContent): line = models.ForeignKey(Line) translation = models.ForeignKey(Translation) text = models.CharField(max_length=400) #def __str__(self): # return self.text class Meta: ordering = ['line'] ``` and ``` admin.site.register(Linetrans) ``` Other model classes are very similar and do not return an error. The error also occurs when the Linetrans is added as an inline to another admin class. edit / update: I commented out all other str() methods in my model and sure enough the error seems to go away. Now trying to pinpoint the issue.
2017/02/14
[ "https://Stackoverflow.com/questions/42229923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470917/" ]
There was one of the foreign reference which was returning non string field. I changed it to string field or you can change to str(foreign-key-return-element) name = models.CharField(max\_length=200, unique=True) # name of the article parent = models.ForeignKey('self',on\_delete=models.DO\_NOTHING,related\_name='category\_parent\_item', default=None, null=True) # Store child items created\_at = models.DateTimeField(auto\_now=True) # Creation date updated\_at = models.DateTimeField(auto\_now=True) # Updation Date user = models.ForeignKey(get\_user\_model(), on\_delete=models.DO\_NOTHING,related\_name='category\_update\_user', default=None, null=True) #User who updated the Article ``` def __str__(self): return self.name ----------> this was an integer field initially in foreign reference ```
In my case, I had a different model that was called by another one that had the default snippet from VSCode as: ``` def __str__(self): return ``` This was causing the error, even when it was showing in the log another place.
42,229,923
The admin returns this error when trying to add an instance to one of my models. The model itself has a correct **str**() method and contains no instances yet. Also tried replacing the **str**() method with a static method or removing it altogether. No luck. The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33. ``` Error during template rendering In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33 __str__ returned non-string (type NoneType) 23 {% endblock %} 24 {% endif %} 25 26 {% block content %}<div id="content-main"> 27 {% block object-tools %} 28 {% if change %}{% if not is_popup %} 29 <ul class="object-tools"> 30 {% block object-tools-items %} 31 <li> 32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} 33 <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> 34 </li> 35 {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} 36 {% endblock %} 37 </ul> 38 {% endif %}{% endif %} 39 {% endblock %} 40 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %} 41 <div> 42 {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %} 43 {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %} ``` These are the relevant parts of my `models.py` and `admin.py` ``` class UserContent(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='%(class)s_creator') updated_by = models.ForeignKey(User, related_name='%(class)s_updater') class Meta: abstract = True class Linetrans(UserContent): line = models.ForeignKey(Line) translation = models.ForeignKey(Translation) text = models.CharField(max_length=400) #def __str__(self): # return self.text class Meta: ordering = ['line'] ``` and ``` admin.site.register(Linetrans) ``` Other model classes are very similar and do not return an error. The error also occurs when the Linetrans is added as an inline to another admin class. edit / update: I commented out all other str() methods in my model and sure enough the error seems to go away. Now trying to pinpoint the issue.
2017/02/14
[ "https://Stackoverflow.com/questions/42229923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470917/" ]
If you are trying to use `__str__()` to return the value of a `ForeignKey` or a `OneToOneField` this would return error Example: ``` def __str__(): return self.user # where user is a key to other model class ``` It should be: ``` def __str__(): return self.user.__str__() # Or basically any other way that would explicitly unbox the value inside the related model class. ```
Toto\_tico is right, although the above error can also occur when you fail to return a str property of your django model within the **str**(self) method: ``` Class model and(models.Model): Class Meta: verbose_name = "something" title = models.CharField(max_length=100) email = models.CharField(max_length=100) #Error instance: def __str__(self): self.title #Right way def __str__(self): return self.title ``` So it is highly advised to return the str property within the > > def **str**(self) > > > method to avoid errors in the Django admin panel when trying to make changes to a particular data within a model table: ``` def __str__(self): return self.property ``` I hope this will help someone.
42,229,923
The admin returns this error when trying to add an instance to one of my models. The model itself has a correct **str**() method and contains no instances yet. Also tried replacing the **str**() method with a static method or removing it altogether. No luck. The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33. ``` Error during template rendering In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33 __str__ returned non-string (type NoneType) 23 {% endblock %} 24 {% endif %} 25 26 {% block content %}<div id="content-main"> 27 {% block object-tools %} 28 {% if change %}{% if not is_popup %} 29 <ul class="object-tools"> 30 {% block object-tools-items %} 31 <li> 32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} 33 <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> 34 </li> 35 {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} 36 {% endblock %} 37 </ul> 38 {% endif %}{% endif %} 39 {% endblock %} 40 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %} 41 <div> 42 {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %} 43 {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %} ``` These are the relevant parts of my `models.py` and `admin.py` ``` class UserContent(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='%(class)s_creator') updated_by = models.ForeignKey(User, related_name='%(class)s_updater') class Meta: abstract = True class Linetrans(UserContent): line = models.ForeignKey(Line) translation = models.ForeignKey(Translation) text = models.CharField(max_length=400) #def __str__(self): # return self.text class Meta: ordering = ['line'] ``` and ``` admin.site.register(Linetrans) ``` Other model classes are very similar and do not return an error. The error also occurs when the Linetrans is added as an inline to another admin class. edit / update: I commented out all other str() methods in my model and sure enough the error seems to go away. Now trying to pinpoint the issue.
2017/02/14
[ "https://Stackoverflow.com/questions/42229923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470917/" ]
I had a similar issue. The problem was that the primary key for one row was null ( I dont know how that happened). I couldnt delete the row because of cascade issues. so I had to change the **str** mmethod to somthing like this. ``` def __str__(self): if self.customerName==None: return "ERROR-CUSTOMER NAME IS NULL" return self.customerName ```
For this error you can use two solutions **first solution**: you can comment it out below code ``` def __str__(self): return self.id ``` to ``` #def __str__(self): # return self.id ``` **secound solution**: you can return the string from the object ``` def __str__(self): return str(self.id) ```
42,229,923
The admin returns this error when trying to add an instance to one of my models. The model itself has a correct **str**() method and contains no instances yet. Also tried replacing the **str**() method with a static method or removing it altogether. No luck. The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33. ``` Error during template rendering In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33 __str__ returned non-string (type NoneType) 23 {% endblock %} 24 {% endif %} 25 26 {% block content %}<div id="content-main"> 27 {% block object-tools %} 28 {% if change %}{% if not is_popup %} 29 <ul class="object-tools"> 30 {% block object-tools-items %} 31 <li> 32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} 33 <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> 34 </li> 35 {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} 36 {% endblock %} 37 </ul> 38 {% endif %}{% endif %} 39 {% endblock %} 40 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %} 41 <div> 42 {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %} 43 {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %} ``` These are the relevant parts of my `models.py` and `admin.py` ``` class UserContent(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='%(class)s_creator') updated_by = models.ForeignKey(User, related_name='%(class)s_updater') class Meta: abstract = True class Linetrans(UserContent): line = models.ForeignKey(Line) translation = models.ForeignKey(Translation) text = models.CharField(max_length=400) #def __str__(self): # return self.text class Meta: ordering = ['line'] ``` and ``` admin.site.register(Linetrans) ``` Other model classes are very similar and do not return an error. The error also occurs when the Linetrans is added as an inline to another admin class. edit / update: I commented out all other str() methods in my model and sure enough the error seems to go away. Now trying to pinpoint the issue.
2017/02/14
[ "https://Stackoverflow.com/questions/42229923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470917/" ]
Check out the class that you have referred to in ``` models.ForeignKey ``` The problem lies in the ``` __str__() ``` method of one of those classes. Then, add ``` or '' ``` in the return statement of that class like this. ``` def __str__(self): return self.title or '' ```
Toto\_tico is right, although the above error can also occur when you fail to return a str property of your django model within the **str**(self) method: ``` Class model and(models.Model): Class Meta: verbose_name = "something" title = models.CharField(max_length=100) email = models.CharField(max_length=100) #Error instance: def __str__(self): self.title #Right way def __str__(self): return self.title ``` So it is highly advised to return the str property within the > > def **str**(self) > > > method to avoid errors in the Django admin panel when trying to make changes to a particular data within a model table: ``` def __str__(self): return self.property ``` I hope this will help someone.
42,229,923
The admin returns this error when trying to add an instance to one of my models. The model itself has a correct **str**() method and contains no instances yet. Also tried replacing the **str**() method with a static method or removing it altogether. No luck. The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33. ``` Error during template rendering In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33 __str__ returned non-string (type NoneType) 23 {% endblock %} 24 {% endif %} 25 26 {% block content %}<div id="content-main"> 27 {% block object-tools %} 28 {% if change %}{% if not is_popup %} 29 <ul class="object-tools"> 30 {% block object-tools-items %} 31 <li> 32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} 33 <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> 34 </li> 35 {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} 36 {% endblock %} 37 </ul> 38 {% endif %}{% endif %} 39 {% endblock %} 40 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %} 41 <div> 42 {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %} 43 {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %} ``` These are the relevant parts of my `models.py` and `admin.py` ``` class UserContent(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='%(class)s_creator') updated_by = models.ForeignKey(User, related_name='%(class)s_updater') class Meta: abstract = True class Linetrans(UserContent): line = models.ForeignKey(Line) translation = models.ForeignKey(Translation) text = models.CharField(max_length=400) #def __str__(self): # return self.text class Meta: ordering = ['line'] ``` and ``` admin.site.register(Linetrans) ``` Other model classes are very similar and do not return an error. The error also occurs when the Linetrans is added as an inline to another admin class. edit / update: I commented out all other str() methods in my model and sure enough the error seems to go away. Now trying to pinpoint the issue.
2017/02/14
[ "https://Stackoverflow.com/questions/42229923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470917/" ]
There was one of the foreign reference which was returning non string field. I changed it to string field or you can change to str(foreign-key-return-element) name = models.CharField(max\_length=200, unique=True) # name of the article parent = models.ForeignKey('self',on\_delete=models.DO\_NOTHING,related\_name='category\_parent\_item', default=None, null=True) # Store child items created\_at = models.DateTimeField(auto\_now=True) # Creation date updated\_at = models.DateTimeField(auto\_now=True) # Updation Date user = models.ForeignKey(get\_user\_model(), on\_delete=models.DO\_NOTHING,related\_name='category\_update\_user', default=None, null=True) #User who updated the Article ``` def __str__(self): return self.name ----------> this was an integer field initially in foreign reference ```
Toto\_tico is right, although the above error can also occur when you fail to return a str property of your django model within the **str**(self) method: ``` Class model and(models.Model): Class Meta: verbose_name = "something" title = models.CharField(max_length=100) email = models.CharField(max_length=100) #Error instance: def __str__(self): self.title #Right way def __str__(self): return self.title ``` So it is highly advised to return the str property within the > > def **str**(self) > > > method to avoid errors in the Django admin panel when trying to make changes to a particular data within a model table: ``` def __str__(self): return self.property ``` I hope this will help someone.
42,229,923
The admin returns this error when trying to add an instance to one of my models. The model itself has a correct **str**() method and contains no instances yet. Also tried replacing the **str**() method with a static method or removing it altogether. No luck. The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33. ``` Error during template rendering In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33 __str__ returned non-string (type NoneType) 23 {% endblock %} 24 {% endif %} 25 26 {% block content %}<div id="content-main"> 27 {% block object-tools %} 28 {% if change %}{% if not is_popup %} 29 <ul class="object-tools"> 30 {% block object-tools-items %} 31 <li> 32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} 33 <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> 34 </li> 35 {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} 36 {% endblock %} 37 </ul> 38 {% endif %}{% endif %} 39 {% endblock %} 40 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %} 41 <div> 42 {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %} 43 {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %} ``` These are the relevant parts of my `models.py` and `admin.py` ``` class UserContent(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='%(class)s_creator') updated_by = models.ForeignKey(User, related_name='%(class)s_updater') class Meta: abstract = True class Linetrans(UserContent): line = models.ForeignKey(Line) translation = models.ForeignKey(Translation) text = models.CharField(max_length=400) #def __str__(self): # return self.text class Meta: ordering = ['line'] ``` and ``` admin.site.register(Linetrans) ``` Other model classes are very similar and do not return an error. The error also occurs when the Linetrans is added as an inline to another admin class. edit / update: I commented out all other str() methods in my model and sure enough the error seems to go away. Now trying to pinpoint the issue.
2017/02/14
[ "https://Stackoverflow.com/questions/42229923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470917/" ]
Turns out that there was an unexpected empty CharField in a related model. Leaving this an an answer, because it might help others. **Troubleshoot the issue** by systematically commenting out the `__str__()` methods of your models until you find the offending model. Work from there to identify the offending record(s).
that's works for me: ``` def __str__(self): return f"{self.category}" ``` Just use "f" string
42,229,923
The admin returns this error when trying to add an instance to one of my models. The model itself has a correct **str**() method and contains no instances yet. Also tried replacing the **str**() method with a static method or removing it altogether. No luck. The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33. ``` Error during template rendering In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33 __str__ returned non-string (type NoneType) 23 {% endblock %} 24 {% endif %} 25 26 {% block content %}<div id="content-main"> 27 {% block object-tools %} 28 {% if change %}{% if not is_popup %} 29 <ul class="object-tools"> 30 {% block object-tools-items %} 31 <li> 32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} 33 <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> 34 </li> 35 {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} 36 {% endblock %} 37 </ul> 38 {% endif %}{% endif %} 39 {% endblock %} 40 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %} 41 <div> 42 {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %} 43 {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %} ``` These are the relevant parts of my `models.py` and `admin.py` ``` class UserContent(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='%(class)s_creator') updated_by = models.ForeignKey(User, related_name='%(class)s_updater') class Meta: abstract = True class Linetrans(UserContent): line = models.ForeignKey(Line) translation = models.ForeignKey(Translation) text = models.CharField(max_length=400) #def __str__(self): # return self.text class Meta: ordering = ['line'] ``` and ``` admin.site.register(Linetrans) ``` Other model classes are very similar and do not return an error. The error also occurs when the Linetrans is added as an inline to another admin class. edit / update: I commented out all other str() methods in my model and sure enough the error seems to go away. Now trying to pinpoint the issue.
2017/02/14
[ "https://Stackoverflow.com/questions/42229923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470917/" ]
Check out the class that you have referred to in ``` models.ForeignKey ``` The problem lies in the ``` __str__() ``` method of one of those classes. Then, add ``` or '' ``` in the return statement of that class like this. ``` def __str__(self): return self.title or '' ```
that's works for me: ``` def __str__(self): return f"{self.category}" ``` Just use "f" string
42,229,923
The admin returns this error when trying to add an instance to one of my models. The model itself has a correct **str**() method and contains no instances yet. Also tried replacing the **str**() method with a static method or removing it altogether. No luck. The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33. ``` Error during template rendering In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33 __str__ returned non-string (type NoneType) 23 {% endblock %} 24 {% endif %} 25 26 {% block content %}<div id="content-main"> 27 {% block object-tools %} 28 {% if change %}{% if not is_popup %} 29 <ul class="object-tools"> 30 {% block object-tools-items %} 31 <li> 32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} 33 <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> 34 </li> 35 {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} 36 {% endblock %} 37 </ul> 38 {% endif %}{% endif %} 39 {% endblock %} 40 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %} 41 <div> 42 {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %} 43 {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %} ``` These are the relevant parts of my `models.py` and `admin.py` ``` class UserContent(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='%(class)s_creator') updated_by = models.ForeignKey(User, related_name='%(class)s_updater') class Meta: abstract = True class Linetrans(UserContent): line = models.ForeignKey(Line) translation = models.ForeignKey(Translation) text = models.CharField(max_length=400) #def __str__(self): # return self.text class Meta: ordering = ['line'] ``` and ``` admin.site.register(Linetrans) ``` Other model classes are very similar and do not return an error. The error also occurs when the Linetrans is added as an inline to another admin class. edit / update: I commented out all other str() methods in my model and sure enough the error seems to go away. Now trying to pinpoint the issue.
2017/02/14
[ "https://Stackoverflow.com/questions/42229923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470917/" ]
``` def __str__(self): return str(self.topic) ``` Use str to make it type string. Then it's not not-string type.
There was one of the foreign reference which was returning non string field. I changed it to string field or you can change to str(foreign-key-return-element) name = models.CharField(max\_length=200, unique=True) # name of the article parent = models.ForeignKey('self',on\_delete=models.DO\_NOTHING,related\_name='category\_parent\_item', default=None, null=True) # Store child items created\_at = models.DateTimeField(auto\_now=True) # Creation date updated\_at = models.DateTimeField(auto\_now=True) # Updation Date user = models.ForeignKey(get\_user\_model(), on\_delete=models.DO\_NOTHING,related\_name='category\_update\_user', default=None, null=True) #User who updated the Article ``` def __str__(self): return self.name ----------> this was an integer field initially in foreign reference ```
42,229,923
The admin returns this error when trying to add an instance to one of my models. The model itself has a correct **str**() method and contains no instances yet. Also tried replacing the **str**() method with a static method or removing it altogether. No luck. The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33. ``` Error during template rendering In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33 __str__ returned non-string (type NoneType) 23 {% endblock %} 24 {% endif %} 25 26 {% block content %}<div id="content-main"> 27 {% block object-tools %} 28 {% if change %}{% if not is_popup %} 29 <ul class="object-tools"> 30 {% block object-tools-items %} 31 <li> 32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} 33 <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> 34 </li> 35 {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} 36 {% endblock %} 37 </ul> 38 {% endif %}{% endif %} 39 {% endblock %} 40 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %} 41 <div> 42 {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %} 43 {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %} ``` These are the relevant parts of my `models.py` and `admin.py` ``` class UserContent(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='%(class)s_creator') updated_by = models.ForeignKey(User, related_name='%(class)s_updater') class Meta: abstract = True class Linetrans(UserContent): line = models.ForeignKey(Line) translation = models.ForeignKey(Translation) text = models.CharField(max_length=400) #def __str__(self): # return self.text class Meta: ordering = ['line'] ``` and ``` admin.site.register(Linetrans) ``` Other model classes are very similar and do not return an error. The error also occurs when the Linetrans is added as an inline to another admin class. edit / update: I commented out all other str() methods in my model and sure enough the error seems to go away. Now trying to pinpoint the issue.
2017/02/14
[ "https://Stackoverflow.com/questions/42229923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470917/" ]
``` def __str__(self): return str(self.topic) ``` Use str to make it type string. Then it's not not-string type.
You can also delete the instances in the model causing this problem from the django shell `python manage.py shell` . This helps when you are dealing with a model with lots of related models like mine. > > Typically this problem is caused by altering model fields and > migrating, such that the instances are incompatible with each other > and related fields > > >
24,201,932
So I have a text field where the user can type in anything. I use the following code to assign the input an NSString value: ``` NSString *input = _inputTextField.text; ``` If the user has the word "smart" anywhere in the input, than it will replace it with "clever". Likewise, if they have "smarter" it will replace it with "cleverer". I have the following code to achieve this: ``` input = [input stringByReplacingOccurrencesOfString:@"smart" withString:@"clever"]; input = [input stringByReplacingOccurrencesOfString:@"smarter" withString:@"cleverer"]; ``` Now this works perfect, BUT I ran into a problem while running the app. If the user has ANY word that contains "smart", for example, "smartweed", than it will make it into "cleverweed", which is not even a word. In order to bypass this, I added the following code: ``` input = [input stringByReplacingOccurrencesOfString:@"cleverweed" withString:@"smartweed"]; ``` Now, I know I don't have to do that to EVERY word that exists that has "smart" into it, so I changed the code to say this: ``` input = [input stringByReplacingOccurrencesOfString:@" smart " withString:@" clever "]; ``` Hey, that fixed it. But then I ran into a problem... it won't fix it if the word " smart " is the beginning of a sentence, or the last one of a sentence! I can fix it by adding this: ``` input = [input stringByReplacingOccurrencesOfString:@"Smart " withString:@"Clever "]; input = [input stringByReplacingOccurrencesOfString:@" smart." withString:@" clever."]; ``` And so on with whatever the sentence ended. Now, my official question is, is there a way where the code will just replace "smart" into "clever" without it changing the word "smart" that appears inside other words? I've looked at NSRange, but I'm confused how to properly use it here since it can depend on whatever the user inputs. Also, I've tried searching for this and couldn't find it.
2014/06/13
[ "https://Stackoverflow.com/questions/24201932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705492/" ]
We can iterate over the list with `enumerate` and replace the old value with new value, like this ``` myl = [1, 2, 3, 4, 5, 4, 4, 4, 6] for idx, item in enumerate(myl): if item == 4: myl[idx] = 44 print myl # [1, 2, 3, 44, 5, 44, 44, 44, 6] ```
``` for item in myl: if item ==4: myl[myl.index(item)]=44 ```
24,201,932
So I have a text field where the user can type in anything. I use the following code to assign the input an NSString value: ``` NSString *input = _inputTextField.text; ``` If the user has the word "smart" anywhere in the input, than it will replace it with "clever". Likewise, if they have "smarter" it will replace it with "cleverer". I have the following code to achieve this: ``` input = [input stringByReplacingOccurrencesOfString:@"smart" withString:@"clever"]; input = [input stringByReplacingOccurrencesOfString:@"smarter" withString:@"cleverer"]; ``` Now this works perfect, BUT I ran into a problem while running the app. If the user has ANY word that contains "smart", for example, "smartweed", than it will make it into "cleverweed", which is not even a word. In order to bypass this, I added the following code: ``` input = [input stringByReplacingOccurrencesOfString:@"cleverweed" withString:@"smartweed"]; ``` Now, I know I don't have to do that to EVERY word that exists that has "smart" into it, so I changed the code to say this: ``` input = [input stringByReplacingOccurrencesOfString:@" smart " withString:@" clever "]; ``` Hey, that fixed it. But then I ran into a problem... it won't fix it if the word " smart " is the beginning of a sentence, or the last one of a sentence! I can fix it by adding this: ``` input = [input stringByReplacingOccurrencesOfString:@"Smart " withString:@"Clever "]; input = [input stringByReplacingOccurrencesOfString:@" smart." withString:@" clever."]; ``` And so on with whatever the sentence ended. Now, my official question is, is there a way where the code will just replace "smart" into "clever" without it changing the word "smart" that appears inside other words? I've looked at NSRange, but I'm confused how to properly use it here since it can depend on whatever the user inputs. Also, I've tried searching for this and couldn't find it.
2014/06/13
[ "https://Stackoverflow.com/questions/24201932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705492/" ]
We can iterate over the list with `enumerate` and replace the old value with new value, like this ``` myl = [1, 2, 3, 4, 5, 4, 4, 4, 6] for idx, item in enumerate(myl): if item == 4: myl[idx] = 44 print myl # [1, 2, 3, 44, 5, 44, 44, 44, 6] ```
``` while True: try: myl[myl.index(4)] = 44 except: break ``` The `try-except` approach, although more **pythonic**, is less efficient. This [timeit program on ideone](http://ideone.com/fC6oA5) compares at least two of the answers provided herein.
24,201,932
So I have a text field where the user can type in anything. I use the following code to assign the input an NSString value: ``` NSString *input = _inputTextField.text; ``` If the user has the word "smart" anywhere in the input, than it will replace it with "clever". Likewise, if they have "smarter" it will replace it with "cleverer". I have the following code to achieve this: ``` input = [input stringByReplacingOccurrencesOfString:@"smart" withString:@"clever"]; input = [input stringByReplacingOccurrencesOfString:@"smarter" withString:@"cleverer"]; ``` Now this works perfect, BUT I ran into a problem while running the app. If the user has ANY word that contains "smart", for example, "smartweed", than it will make it into "cleverweed", which is not even a word. In order to bypass this, I added the following code: ``` input = [input stringByReplacingOccurrencesOfString:@"cleverweed" withString:@"smartweed"]; ``` Now, I know I don't have to do that to EVERY word that exists that has "smart" into it, so I changed the code to say this: ``` input = [input stringByReplacingOccurrencesOfString:@" smart " withString:@" clever "]; ``` Hey, that fixed it. But then I ran into a problem... it won't fix it if the word " smart " is the beginning of a sentence, or the last one of a sentence! I can fix it by adding this: ``` input = [input stringByReplacingOccurrencesOfString:@"Smart " withString:@"Clever "]; input = [input stringByReplacingOccurrencesOfString:@" smart." withString:@" clever."]; ``` And so on with whatever the sentence ended. Now, my official question is, is there a way where the code will just replace "smart" into "clever" without it changing the word "smart" that appears inside other words? I've looked at NSRange, but I'm confused how to properly use it here since it can depend on whatever the user inputs. Also, I've tried searching for this and couldn't find it.
2014/06/13
[ "https://Stackoverflow.com/questions/24201932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705492/" ]
``` myl[:] = [x if x != 4 else 44 for x in myl] ``` Perform the replacement not-in-place with a list comprehension, then slice-assign the new values into the original list if you really want to change the original.
``` for item in myl: if item ==4: myl[myl.index(item)]=44 ```
24,201,932
So I have a text field where the user can type in anything. I use the following code to assign the input an NSString value: ``` NSString *input = _inputTextField.text; ``` If the user has the word "smart" anywhere in the input, than it will replace it with "clever". Likewise, if they have "smarter" it will replace it with "cleverer". I have the following code to achieve this: ``` input = [input stringByReplacingOccurrencesOfString:@"smart" withString:@"clever"]; input = [input stringByReplacingOccurrencesOfString:@"smarter" withString:@"cleverer"]; ``` Now this works perfect, BUT I ran into a problem while running the app. If the user has ANY word that contains "smart", for example, "smartweed", than it will make it into "cleverweed", which is not even a word. In order to bypass this, I added the following code: ``` input = [input stringByReplacingOccurrencesOfString:@"cleverweed" withString:@"smartweed"]; ``` Now, I know I don't have to do that to EVERY word that exists that has "smart" into it, so I changed the code to say this: ``` input = [input stringByReplacingOccurrencesOfString:@" smart " withString:@" clever "]; ``` Hey, that fixed it. But then I ran into a problem... it won't fix it if the word " smart " is the beginning of a sentence, or the last one of a sentence! I can fix it by adding this: ``` input = [input stringByReplacingOccurrencesOfString:@"Smart " withString:@"Clever "]; input = [input stringByReplacingOccurrencesOfString:@" smart." withString:@" clever."]; ``` And so on with whatever the sentence ended. Now, my official question is, is there a way where the code will just replace "smart" into "clever" without it changing the word "smart" that appears inside other words? I've looked at NSRange, but I'm confused how to properly use it here since it can depend on whatever the user inputs. Also, I've tried searching for this and couldn't find it.
2014/06/13
[ "https://Stackoverflow.com/questions/24201932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705492/" ]
``` myl[:] = [x if x != 4 else 44 for x in myl] ``` Perform the replacement not-in-place with a list comprehension, then slice-assign the new values into the original list if you really want to change the original.
``` while True: try: myl[myl.index(4)] = 44 except: break ``` The `try-except` approach, although more **pythonic**, is less efficient. This [timeit program on ideone](http://ideone.com/fC6oA5) compares at least two of the answers provided herein.
1,387,239
> > Prove that $2730$ divides $n^{13} - n$ for all integers $n$. > > > What I attempted is breaking $2730$ into $2, 3, 5$, and $7, 13$. Thus if I prove each prime factor divides by $n^{13} - n$ for all integers $n$, it will prove the original problem. I already proved $2, 3$, and $5$ work. Struggling with how to do $91$? Other solutions are welcome, but they should be associated with mod and solutions of this kind, because my answer should pertain to what was learned in class. (Edit: Fixed the 91 problem, being slow today...In any case, I've got this problem now, so no answers are *necessary*. Posting my own soon.)
2015/08/06
[ "https://math.stackexchange.com/questions/1387239", "https://math.stackexchange.com", "https://math.stackexchange.com/users/257731/" ]
As pointed out in a comment $91$ is not prime but the product of $7$ and $13$. You can then deal with these two as you likely dealt with the other factors, via using Fermat's Little Theorem.
> > Let $k>1$ be an integer. Write $D(k)$ for the set of all prime natural numbers $p$ such that $p-1$ divides $k-1$. Then, $\displaystyle\underset{n\in\mathbb{N}}{\gcd}\left(n^k-n\right)$ is the product $\prod\_{p \in D(k)}\,p$. > > > Let $d\_k$ be the number $\displaystyle\underset{n\in\mathbb{N}}{\gcd}\left(n^k-n\right)$. Clearly, $d\_k$ is squarefree (otherwise, if a prime $q$ satisfies $q^2\mid d\_k$, then $q^2\mid d\_k\mid q^k-q$, which is a contradiction). Now, we shall find which prime numbers can divide $d\_k$. Suppose a prime $p\mid d\_k$. Then, $n^k\equiv n\pmod{p}$ for all $n\in\mathbb{N}$. Hence, $p-1$ must divide $k-1$ (otherwise, we can take $n$ to be a primitive element modulo $p$). That is, $p\in D(k)$. On the other hand, if a prime $p$ is such that $p-1$ divides $k-1$, then we have $n^k=n\cdot n^{k-1}\equiv n\cdot 1=n\pmod{p}$ if $p\nmid n$, and $n^k\equiv 0\equiv n\pmod{p}$ if $p\mid n$. Hence, if $p\in D(k)$, then $p\mid d\_k$. --- This problem is only a particular case where $k=13$. Note that $$\prod\_{p\in D(13)}\,p=2\cdot 3\cdot 5\cdot 7\cdot 13=2730\,.$$
1,387,239
> > Prove that $2730$ divides $n^{13} - n$ for all integers $n$. > > > What I attempted is breaking $2730$ into $2, 3, 5$, and $7, 13$. Thus if I prove each prime factor divides by $n^{13} - n$ for all integers $n$, it will prove the original problem. I already proved $2, 3$, and $5$ work. Struggling with how to do $91$? Other solutions are welcome, but they should be associated with mod and solutions of this kind, because my answer should pertain to what was learned in class. (Edit: Fixed the 91 problem, being slow today...In any case, I've got this problem now, so no answers are *necessary*. Posting my own soon.)
2015/08/06
[ "https://math.stackexchange.com/questions/1387239", "https://math.stackexchange.com", "https://math.stackexchange.com/users/257731/" ]
$2730 = 2\times 3\times 5\times 7\times 13$ Let's consider two cases: First case: if n is divisible by 2730 then $n\equiv 0[2730]$ so ${ n }^{ 13 }\equiv 0[2730]$ which means ${ n }^{ 13 }\equiv n[2730]$. Second case $\gcd(2730,n)=1$: Then all the prime divisors of $2730$ will be coprime with n. Using Fermat little's theorem for $2, 3,5, 7, 13$: $$ { n }\equiv 1[2]\longrightarrow { n }^{ 12 }\equiv 1[2]\\ { { n }^{ 2 } }\equiv 1[3]\longrightarrow { n }^{ 12 }\equiv 1[3]\\ { { n }^{ 4 } }\equiv 1[5]\longrightarrow { n }^{ 12 }\equiv 1[5]\\ { { n }^{ 6 } }\equiv 1[7]\longrightarrow { n }^{ 12 }\equiv 1[7]\\ { { n }^{ 12 } }\equiv 1[13]\longrightarrow { n }^{ 12 }\equiv 1[13]\\ $$ Which yields: $2730|{ n }^{ 12 }-1$ so: $$ { n }^{ 12 }\equiv 1[2730]\longrightarrow { n }^{ 13 }\equiv n[2730]\\ \qquad \qquad \qquad \longrightarrow \quad 2730|{ n }^{ 13 }-n $$ Third case $d = \gcd(n,2730)\quad \neq 1$: In this case $n = d\alpha$ and $2730 = dq$ So: $$ n\equiv n[2730]\\ d\alpha \equiv d\alpha [dq]\\ \alpha \equiv \alpha [q] $$ And you apply the same method I did in the previous cases. Hence proved for all n ^^. Note: For all primes ${ p }\_{ 1 },{ p }\_{ 2 },{ p }\_{ 3 },...{ p }\_{ m }$: ${ p }\_{ 1 }|n,\quad { p }\_{ 2 }|n,\quad { p }\_{ 3 }|n,\quad ...{ p }\_{ m }|n\Longleftrightarrow { p }\_{ 1 }{ p }\_{ 2 }...{ p }\_{ m }|n$
As pointed out in a comment $91$ is not prime but the product of $7$ and $13$. You can then deal with these two as you likely dealt with the other factors, via using Fermat's Little Theorem.
1,387,239
> > Prove that $2730$ divides $n^{13} - n$ for all integers $n$. > > > What I attempted is breaking $2730$ into $2, 3, 5$, and $7, 13$. Thus if I prove each prime factor divides by $n^{13} - n$ for all integers $n$, it will prove the original problem. I already proved $2, 3$, and $5$ work. Struggling with how to do $91$? Other solutions are welcome, but they should be associated with mod and solutions of this kind, because my answer should pertain to what was learned in class. (Edit: Fixed the 91 problem, being slow today...In any case, I've got this problem now, so no answers are *necessary*. Posting my own soon.)
2015/08/06
[ "https://math.stackexchange.com/questions/1387239", "https://math.stackexchange.com", "https://math.stackexchange.com/users/257731/" ]
$2730 = 2\times 3\times 5\times 7\times 13$ Let's consider two cases: First case: if n is divisible by 2730 then $n\equiv 0[2730]$ so ${ n }^{ 13 }\equiv 0[2730]$ which means ${ n }^{ 13 }\equiv n[2730]$. Second case $\gcd(2730,n)=1$: Then all the prime divisors of $2730$ will be coprime with n. Using Fermat little's theorem for $2, 3,5, 7, 13$: $$ { n }\equiv 1[2]\longrightarrow { n }^{ 12 }\equiv 1[2]\\ { { n }^{ 2 } }\equiv 1[3]\longrightarrow { n }^{ 12 }\equiv 1[3]\\ { { n }^{ 4 } }\equiv 1[5]\longrightarrow { n }^{ 12 }\equiv 1[5]\\ { { n }^{ 6 } }\equiv 1[7]\longrightarrow { n }^{ 12 }\equiv 1[7]\\ { { n }^{ 12 } }\equiv 1[13]\longrightarrow { n }^{ 12 }\equiv 1[13]\\ $$ Which yields: $2730|{ n }^{ 12 }-1$ so: $$ { n }^{ 12 }\equiv 1[2730]\longrightarrow { n }^{ 13 }\equiv n[2730]\\ \qquad \qquad \qquad \longrightarrow \quad 2730|{ n }^{ 13 }-n $$ Third case $d = \gcd(n,2730)\quad \neq 1$: In this case $n = d\alpha$ and $2730 = dq$ So: $$ n\equiv n[2730]\\ d\alpha \equiv d\alpha [dq]\\ \alpha \equiv \alpha [q] $$ And you apply the same method I did in the previous cases. Hence proved for all n ^^. Note: For all primes ${ p }\_{ 1 },{ p }\_{ 2 },{ p }\_{ 3 },...{ p }\_{ m }$: ${ p }\_{ 1 }|n,\quad { p }\_{ 2 }|n,\quad { p }\_{ 3 }|n,\quad ...{ p }\_{ m }|n\Longleftrightarrow { p }\_{ 1 }{ p }\_{ 2 }...{ p }\_{ m }|n$
> > Let $k>1$ be an integer. Write $D(k)$ for the set of all prime natural numbers $p$ such that $p-1$ divides $k-1$. Then, $\displaystyle\underset{n\in\mathbb{N}}{\gcd}\left(n^k-n\right)$ is the product $\prod\_{p \in D(k)}\,p$. > > > Let $d\_k$ be the number $\displaystyle\underset{n\in\mathbb{N}}{\gcd}\left(n^k-n\right)$. Clearly, $d\_k$ is squarefree (otherwise, if a prime $q$ satisfies $q^2\mid d\_k$, then $q^2\mid d\_k\mid q^k-q$, which is a contradiction). Now, we shall find which prime numbers can divide $d\_k$. Suppose a prime $p\mid d\_k$. Then, $n^k\equiv n\pmod{p}$ for all $n\in\mathbb{N}$. Hence, $p-1$ must divide $k-1$ (otherwise, we can take $n$ to be a primitive element modulo $p$). That is, $p\in D(k)$. On the other hand, if a prime $p$ is such that $p-1$ divides $k-1$, then we have $n^k=n\cdot n^{k-1}\equiv n\cdot 1=n\pmod{p}$ if $p\nmid n$, and $n^k\equiv 0\equiv n\pmod{p}$ if $p\mid n$. Hence, if $p\in D(k)$, then $p\mid d\_k$. --- This problem is only a particular case where $k=13$. Note that $$\prod\_{p\in D(13)}\,p=2\cdot 3\cdot 5\cdot 7\cdot 13=2730\,.$$
1,387,239
> > Prove that $2730$ divides $n^{13} - n$ for all integers $n$. > > > What I attempted is breaking $2730$ into $2, 3, 5$, and $7, 13$. Thus if I prove each prime factor divides by $n^{13} - n$ for all integers $n$, it will prove the original problem. I already proved $2, 3$, and $5$ work. Struggling with how to do $91$? Other solutions are welcome, but they should be associated with mod and solutions of this kind, because my answer should pertain to what was learned in class. (Edit: Fixed the 91 problem, being slow today...In any case, I've got this problem now, so no answers are *necessary*. Posting my own soon.)
2015/08/06
[ "https://math.stackexchange.com/questions/1387239", "https://math.stackexchange.com", "https://math.stackexchange.com/users/257731/" ]
$\phi(2),\phi(3),\phi(5),\phi(7)$ and $\phi(13)$ all divide $\phi(13)=12$, hence for any prime $p\in\{2,3,5,7,13\}$ we have: $$ n^{13}\equiv n\pmod{p} $$ and that implies $2\cdot 3\cdot 5\cdot 7\cdot 13\mid (n^{13}-n)$.
> > Let $k>1$ be an integer. Write $D(k)$ for the set of all prime natural numbers $p$ such that $p-1$ divides $k-1$. Then, $\displaystyle\underset{n\in\mathbb{N}}{\gcd}\left(n^k-n\right)$ is the product $\prod\_{p \in D(k)}\,p$. > > > Let $d\_k$ be the number $\displaystyle\underset{n\in\mathbb{N}}{\gcd}\left(n^k-n\right)$. Clearly, $d\_k$ is squarefree (otherwise, if a prime $q$ satisfies $q^2\mid d\_k$, then $q^2\mid d\_k\mid q^k-q$, which is a contradiction). Now, we shall find which prime numbers can divide $d\_k$. Suppose a prime $p\mid d\_k$. Then, $n^k\equiv n\pmod{p}$ for all $n\in\mathbb{N}$. Hence, $p-1$ must divide $k-1$ (otherwise, we can take $n$ to be a primitive element modulo $p$). That is, $p\in D(k)$. On the other hand, if a prime $p$ is such that $p-1$ divides $k-1$, then we have $n^k=n\cdot n^{k-1}\equiv n\cdot 1=n\pmod{p}$ if $p\nmid n$, and $n^k\equiv 0\equiv n\pmod{p}$ if $p\mid n$. Hence, if $p\in D(k)$, then $p\mid d\_k$. --- This problem is only a particular case where $k=13$. Note that $$\prod\_{p\in D(13)}\,p=2\cdot 3\cdot 5\cdot 7\cdot 13=2730\,.$$
1,387,239
> > Prove that $2730$ divides $n^{13} - n$ for all integers $n$. > > > What I attempted is breaking $2730$ into $2, 3, 5$, and $7, 13$. Thus if I prove each prime factor divides by $n^{13} - n$ for all integers $n$, it will prove the original problem. I already proved $2, 3$, and $5$ work. Struggling with how to do $91$? Other solutions are welcome, but they should be associated with mod and solutions of this kind, because my answer should pertain to what was learned in class. (Edit: Fixed the 91 problem, being slow today...In any case, I've got this problem now, so no answers are *necessary*. Posting my own soon.)
2015/08/06
[ "https://math.stackexchange.com/questions/1387239", "https://math.stackexchange.com", "https://math.stackexchange.com/users/257731/" ]
$2730 = 2\times 3\times 5\times 7\times 13$ Let's consider two cases: First case: if n is divisible by 2730 then $n\equiv 0[2730]$ so ${ n }^{ 13 }\equiv 0[2730]$ which means ${ n }^{ 13 }\equiv n[2730]$. Second case $\gcd(2730,n)=1$: Then all the prime divisors of $2730$ will be coprime with n. Using Fermat little's theorem for $2, 3,5, 7, 13$: $$ { n }\equiv 1[2]\longrightarrow { n }^{ 12 }\equiv 1[2]\\ { { n }^{ 2 } }\equiv 1[3]\longrightarrow { n }^{ 12 }\equiv 1[3]\\ { { n }^{ 4 } }\equiv 1[5]\longrightarrow { n }^{ 12 }\equiv 1[5]\\ { { n }^{ 6 } }\equiv 1[7]\longrightarrow { n }^{ 12 }\equiv 1[7]\\ { { n }^{ 12 } }\equiv 1[13]\longrightarrow { n }^{ 12 }\equiv 1[13]\\ $$ Which yields: $2730|{ n }^{ 12 }-1$ so: $$ { n }^{ 12 }\equiv 1[2730]\longrightarrow { n }^{ 13 }\equiv n[2730]\\ \qquad \qquad \qquad \longrightarrow \quad 2730|{ n }^{ 13 }-n $$ Third case $d = \gcd(n,2730)\quad \neq 1$: In this case $n = d\alpha$ and $2730 = dq$ So: $$ n\equiv n[2730]\\ d\alpha \equiv d\alpha [dq]\\ \alpha \equiv \alpha [q] $$ And you apply the same method I did in the previous cases. Hence proved for all n ^^. Note: For all primes ${ p }\_{ 1 },{ p }\_{ 2 },{ p }\_{ 3 },...{ p }\_{ m }$: ${ p }\_{ 1 }|n,\quad { p }\_{ 2 }|n,\quad { p }\_{ 3 }|n,\quad ...{ p }\_{ m }|n\Longleftrightarrow { p }\_{ 1 }{ p }\_{ 2 }...{ p }\_{ m }|n$
$\phi(2),\phi(3),\phi(5),\phi(7)$ and $\phi(13)$ all divide $\phi(13)=12$, hence for any prime $p\in\{2,3,5,7,13\}$ we have: $$ n^{13}\equiv n\pmod{p} $$ and that implies $2\cdot 3\cdot 5\cdot 7\cdot 13\mid (n^{13}-n)$.
52,486,797
I am trying to produce JSON from an SQLSRV query. I believe the best way to do this is retrieve the data and build a valid array which can then be run through json\_endode(). I am having problems building the array. I have the following SQL Statement. It is a classic one to many SELECT. ``` SELECT OrderHeader.SiteId, OrderHeader.OrderRef, OrderDetail.JobRef, OrderDetail.Qty, OrderDetail.ActionDate, OrderDetail.ContractorId FROM OrderHeader INNER JOIN OrderDetail ON OrderHeader.OrderHeaderId = OrderDetail.OrderHeaderId WHERE OrderHeader.OrderRef = '0001008' ``` It SELECTS the following data: ``` SiteId OrderRef JobRef Qty ActionDate ContractorId 1 0001008 1000001021 1 2010-04-21 1 1 0001008 1000001034 1 2010-05-07 1 1 0001008 1000001035 1 2010-05-12 1 1 0001008 1000001172 1 2010-06-09 1 1 0001008 1000001276 1 2010-06-24 1 ``` The PHP that retrieves the rows and produces my current array looks like this: ``` $RS_Result01 = sqlsrv_query($conn,$sql); $result1 = array(); $row = sqlsrv_fetch_array($RS_Result01,SQLSRV_FETCH_ASSOC); while ($row = sqlsrv_fetch_array($RS_Result01,SQLSRV_FETCH_ASSOC)) { $result[] = $row; } print_r($result); ``` Which produces the following array output. ``` Array ( [0] => Array ( [SiteId] => 1 [OrderRef] => ORD0001008 [JobRef] => 1000001034 [Qty] => 1 [ActionDate] => 2010-05-07 00:00:00.000 [ContractorId] => 1 ) [1] => Array ( [SiteId] => 1 [OrderRef] => ORD0001008 [JobRef] => 1000001035 [Qty] => 1 [ActionDate] => 2010-05-12 00:00:00.000 [ContractorId] => 1 ) [2] => Array ( [SiteId] => 1 [OrderRef] => ORD0001008 [JobRef] => 1000001172 [Qty] => 1 [ActionDate] => 2010-06-09 00:00:00.000 [ContractorId] => 1 ) [3] => Array ( [SiteId] => 1 [OrderRef] => ORD0001008 [JobRef] => 1000001276 [Qty] => 1 [ActionDate] => 2010-06-24 00:00:00.000 [ContractorId] => 1 ) [4] => Array ( [SiteId] => 1 [OrderRef] => ORD0001008 [JobRef] => 1000001027 [Qty] => 1 [ActionDate] => 2010-04-28 00:00:00.000 [ContractorId] => 1 ) ) ``` This is relativly standard output. What I would like to produce is something like this that I can use for a cleaner JSON conversion. ``` Array ( [0] => Array ( [SiteId] => 1 [OrderRef] => ORD0001008 [JobRef] => Array ( [0] => Array ( [JobRef] => 1000001034 [Qty] => 1 [ActionDate] => 2010-05-07 00:00:00.000 [ContractorId] => 1 ) [1] => Array ( [JobRef] => 1000001035 [Qty] => 1 [ActionDate] => 2010-05-12 00:00:00.000 [ContractorId] => 1 ) [2] => Array ( [JobRef] => 1000001172 [Qty] => 1 [ActionDate] => 2010-06-09 00:00:00.000 [ContractorId] => 1 ) [3] => Array ( [JobRef] => 1000001276 [Qty] => 1 [ActionDate] => 2010-06-24 00:00:00.000 [ContractorId] => 1 ) [4] => Array ( [JobRef] => 1000001027 [Qty] => 1 [ActionDate] => 2010-04-28 00:00:00.000 [ContractorId] => 1 ) ) ) ) ``` I have tried multiple ways of doing this but I have spent hours going round in circles. I could really use some assistance and an explanation to help me understand a solution. Kind regards
2018/09/24
[ "https://Stackoverflow.com/questions/52486797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Neo4j has a limited [property type](https://neo4j.com/docs/developer-manual/current/cypher/syntax/values/) set. You should store the values as properties of the node, instead of craming them into one property. ``` // You need the `` around the property name to escape the period CREATE (c1:Config) set c1.`properties.name`="CiPipelineConfig1" set c1.`properties.type`="test" ``` If this is not good enough for you, you will need to reformat your data to something that is compatible with the Neo4j Types.
One way to create nested properties is using `JSON` property as string property, you can dump and encode data in write and load and decode when read. One example of this is [neomodel](https://neomodel.readthedocs.io/en/latest/module_documentation.html#neomodel.properties.JSONProperty) json property in python. This is code of neomodel json property: ``` class JSONProperty(Property): """ Store a data structure as a JSON string. The structure will be inflated when a node is retrieved. """ def __init__(self, *args, **kwargs): super(JSONProperty, self).__init__(*args, **kwargs) @validator def inflate(self, value): return json.loads(value) @validator def deflate(self, value): return json.dumps(value) ```
30,968,679
I would like to access a variable from my rootViewController from within a different viewController (it‘s a CollectionViewCell). ``` window!.rootViewController = ViewController() ``` I declare the var like so: ``` import UIKit class ViewController: UIViewController { var testString : String = "Test"; override func viewDidLoad() { […] ``` And try to access it this way: ``` import UIKit class MainCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { […] super.init(frame: frame) let mainView = self.window!.rootViewController var testStringFromMainView = mainView.test […] ``` But all I keep getting is: ``` Type of expression is ambiguous without more context ``` Strange thing is, when I try for example ``` mainView.view.backgroundColor = UIColor.redColor() ``` it works. I can’t figure out what I am doing wrong. Any help is appreciated!
2015/06/21
[ "https://Stackoverflow.com/questions/30968679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3808543/" ]
ViewPostImeInputStage ACTION\_DOWN is a bug that occurs stemming from the rare instance where your layout is rejected and you are no longer able to click on any clickable items, and what occurs instead is a ViewPostImeInputStage ACTION\_DOWN with every button press (and no action). The solution for this is simple, wrap your layout content with a parent. So if you xml format was ``` <LinearLayout <---root layout ... <!-- your content --> </LinearLayout> <-- root layout end ``` change to ``` <FrameLayout <---root layout <LinearLayout <-- parent wrap start ... <!-- your content --> </LinearLayout> <-- parent wrap end </FrameLayout> <-- root layout end ``` This solution should resolve that conflict. Atleast this is what has worked for me. Cheers!
I got the same problem as yours,and I tried portfoliobuilder's way but it didn't work. And then I just make some changes on my code,then it worked. I just set every instance of my button an OnlickListener interface instead of letting my Class inplements the View.OnClickListener~ ``` button.setOnclickListener(new View.OnClickListener){ public void onClick(View v){//... } } ``` INSTEAD OF ``` public YourClass implements View.OnClickListener{... public void OnClick(View v){ switch(v.getId()){ case://... break;}}} ```
30,968,679
I would like to access a variable from my rootViewController from within a different viewController (it‘s a CollectionViewCell). ``` window!.rootViewController = ViewController() ``` I declare the var like so: ``` import UIKit class ViewController: UIViewController { var testString : String = "Test"; override func viewDidLoad() { […] ``` And try to access it this way: ``` import UIKit class MainCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { […] super.init(frame: frame) let mainView = self.window!.rootViewController var testStringFromMainView = mainView.test […] ``` But all I keep getting is: ``` Type of expression is ambiguous without more context ``` Strange thing is, when I try for example ``` mainView.view.backgroundColor = UIColor.redColor() ``` it works. I can’t figure out what I am doing wrong. Any help is appreciated!
2015/06/21
[ "https://Stackoverflow.com/questions/30968679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3808543/" ]
ViewPostImeInputStage ACTION\_DOWN is a bug that occurs stemming from the rare instance where your layout is rejected and you are no longer able to click on any clickable items, and what occurs instead is a ViewPostImeInputStage ACTION\_DOWN with every button press (and no action). The solution for this is simple, wrap your layout content with a parent. So if you xml format was ``` <LinearLayout <---root layout ... <!-- your content --> </LinearLayout> <-- root layout end ``` change to ``` <FrameLayout <---root layout <LinearLayout <-- parent wrap start ... <!-- your content --> </LinearLayout> <-- parent wrap end </FrameLayout> <-- root layout end ``` This solution should resolve that conflict. Atleast this is what has worked for me. Cheers!
I have faced the same issue which was corrected when I made the relative layout clickable(in properties). cheers
30,968,679
I would like to access a variable from my rootViewController from within a different viewController (it‘s a CollectionViewCell). ``` window!.rootViewController = ViewController() ``` I declare the var like so: ``` import UIKit class ViewController: UIViewController { var testString : String = "Test"; override func viewDidLoad() { […] ``` And try to access it this way: ``` import UIKit class MainCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { […] super.init(frame: frame) let mainView = self.window!.rootViewController var testStringFromMainView = mainView.test […] ``` But all I keep getting is: ``` Type of expression is ambiguous without more context ``` Strange thing is, when I try for example ``` mainView.view.backgroundColor = UIColor.redColor() ``` it works. I can’t figure out what I am doing wrong. Any help is appreciated!
2015/06/21
[ "https://Stackoverflow.com/questions/30968679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3808543/" ]
ViewPostImeInputStage ACTION\_DOWN is a bug that occurs stemming from the rare instance where your layout is rejected and you are no longer able to click on any clickable items, and what occurs instead is a ViewPostImeInputStage ACTION\_DOWN with every button press (and no action). The solution for this is simple, wrap your layout content with a parent. So if you xml format was ``` <LinearLayout <---root layout ... <!-- your content --> </LinearLayout> <-- root layout end ``` change to ``` <FrameLayout <---root layout <LinearLayout <-- parent wrap start ... <!-- your content --> </LinearLayout> <-- parent wrap end </FrameLayout> <-- root layout end ``` This solution should resolve that conflict. Atleast this is what has worked for me. Cheers!
I had this happen to me on the first click of a CardView inside a RecyclerView. It turns out the CardView XML set: ``` android:focusable="true" android:focusableInTouchMode="true" ``` Once I removed that, the first click (and subsequent clicks) worked fine, and I no longer had the error with ACTION\_DOWN.
30,968,679
I would like to access a variable from my rootViewController from within a different viewController (it‘s a CollectionViewCell). ``` window!.rootViewController = ViewController() ``` I declare the var like so: ``` import UIKit class ViewController: UIViewController { var testString : String = "Test"; override func viewDidLoad() { […] ``` And try to access it this way: ``` import UIKit class MainCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { […] super.init(frame: frame) let mainView = self.window!.rootViewController var testStringFromMainView = mainView.test […] ``` But all I keep getting is: ``` Type of expression is ambiguous without more context ``` Strange thing is, when I try for example ``` mainView.view.backgroundColor = UIColor.redColor() ``` it works. I can’t figure out what I am doing wrong. Any help is appreciated!
2015/06/21
[ "https://Stackoverflow.com/questions/30968679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3808543/" ]
ViewPostImeInputStage ACTION\_DOWN is a bug that occurs stemming from the rare instance where your layout is rejected and you are no longer able to click on any clickable items, and what occurs instead is a ViewPostImeInputStage ACTION\_DOWN with every button press (and no action). The solution for this is simple, wrap your layout content with a parent. So if you xml format was ``` <LinearLayout <---root layout ... <!-- your content --> </LinearLayout> <-- root layout end ``` change to ``` <FrameLayout <---root layout <LinearLayout <-- parent wrap start ... <!-- your content --> </LinearLayout> <-- parent wrap end </FrameLayout> <-- root layout end ``` This solution should resolve that conflict. Atleast this is what has worked for me. Cheers!
I was getting `ViewPostImeInputStage ACTION_DOWN` message when a line of my code had --> ``` if(button.getText().equals("word")) ``` I got the desired output after correcting the if statement to --> ``` if(button.getText().toString().equals("word")) ``` Hope it helps someone.
30,968,679
I would like to access a variable from my rootViewController from within a different viewController (it‘s a CollectionViewCell). ``` window!.rootViewController = ViewController() ``` I declare the var like so: ``` import UIKit class ViewController: UIViewController { var testString : String = "Test"; override func viewDidLoad() { […] ``` And try to access it this way: ``` import UIKit class MainCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { […] super.init(frame: frame) let mainView = self.window!.rootViewController var testStringFromMainView = mainView.test […] ``` But all I keep getting is: ``` Type of expression is ambiguous without more context ``` Strange thing is, when I try for example ``` mainView.view.backgroundColor = UIColor.redColor() ``` it works. I can’t figure out what I am doing wrong. Any help is appreciated!
2015/06/21
[ "https://Stackoverflow.com/questions/30968679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3808543/" ]
ViewPostImeInputStage ACTION\_DOWN is a bug that occurs stemming from the rare instance where your layout is rejected and you are no longer able to click on any clickable items, and what occurs instead is a ViewPostImeInputStage ACTION\_DOWN with every button press (and no action). The solution for this is simple, wrap your layout content with a parent. So if you xml format was ``` <LinearLayout <---root layout ... <!-- your content --> </LinearLayout> <-- root layout end ``` change to ``` <FrameLayout <---root layout <LinearLayout <-- parent wrap start ... <!-- your content --> </LinearLayout> <-- parent wrap end </FrameLayout> <-- root layout end ``` This solution should resolve that conflict. Atleast this is what has worked for me. Cheers!
None of the solutions above worked to me. Pretty strange bug, wondering if some view is intercepting the touch events and broking it, maybe some appcompat stuff, there is a lot of touch intercepts over there… Anyway, I workarounded the problem adding a transparent `View` over my real broken button and adding the click listener on this view, pretty ugly but it worked `¯\_(ツ)_/¯` e.g. imagine the error happened in this layout: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp"> <Button android:id="@+id/broken_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="0dp" android:layout_marginTop="0dp" android:text="Hello world" /> </RelativeLayout> ``` I added the transparent view and I set the click on it. ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp"> <Button android:id="@+id/broken_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="0dp" android:layout_marginTop="0dp" android:text="Hello world" /> <View android:id="@+id/workaround_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignStart="@+id/broken_button" android:layout_alignTop="@+id/broken_button" android:layout_alignEnd="@+id/broken_button" android:layout_alignBottom="@+id/broken_button" /> </RelativeLayout> ``` Again, it is an ugly solution, but still a solution.
30,968,679
I would like to access a variable from my rootViewController from within a different viewController (it‘s a CollectionViewCell). ``` window!.rootViewController = ViewController() ``` I declare the var like so: ``` import UIKit class ViewController: UIViewController { var testString : String = "Test"; override func viewDidLoad() { […] ``` And try to access it this way: ``` import UIKit class MainCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { […] super.init(frame: frame) let mainView = self.window!.rootViewController var testStringFromMainView = mainView.test […] ``` But all I keep getting is: ``` Type of expression is ambiguous without more context ``` Strange thing is, when I try for example ``` mainView.view.backgroundColor = UIColor.redColor() ``` it works. I can’t figure out what I am doing wrong. Any help is appreciated!
2015/06/21
[ "https://Stackoverflow.com/questions/30968679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3808543/" ]
I got the same problem as yours,and I tried portfoliobuilder's way but it didn't work. And then I just make some changes on my code,then it worked. I just set every instance of my button an OnlickListener interface instead of letting my Class inplements the View.OnClickListener~ ``` button.setOnclickListener(new View.OnClickListener){ public void onClick(View v){//... } } ``` INSTEAD OF ``` public YourClass implements View.OnClickListener{... public void OnClick(View v){ switch(v.getId()){ case://... break;}}} ```
I have faced the same issue which was corrected when I made the relative layout clickable(in properties). cheers
30,968,679
I would like to access a variable from my rootViewController from within a different viewController (it‘s a CollectionViewCell). ``` window!.rootViewController = ViewController() ``` I declare the var like so: ``` import UIKit class ViewController: UIViewController { var testString : String = "Test"; override func viewDidLoad() { […] ``` And try to access it this way: ``` import UIKit class MainCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { […] super.init(frame: frame) let mainView = self.window!.rootViewController var testStringFromMainView = mainView.test […] ``` But all I keep getting is: ``` Type of expression is ambiguous without more context ``` Strange thing is, when I try for example ``` mainView.view.backgroundColor = UIColor.redColor() ``` it works. I can’t figure out what I am doing wrong. Any help is appreciated!
2015/06/21
[ "https://Stackoverflow.com/questions/30968679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3808543/" ]
I got the same problem as yours,and I tried portfoliobuilder's way but it didn't work. And then I just make some changes on my code,then it worked. I just set every instance of my button an OnlickListener interface instead of letting my Class inplements the View.OnClickListener~ ``` button.setOnclickListener(new View.OnClickListener){ public void onClick(View v){//... } } ``` INSTEAD OF ``` public YourClass implements View.OnClickListener{... public void OnClick(View v){ switch(v.getId()){ case://... break;}}} ```
I had this happen to me on the first click of a CardView inside a RecyclerView. It turns out the CardView XML set: ``` android:focusable="true" android:focusableInTouchMode="true" ``` Once I removed that, the first click (and subsequent clicks) worked fine, and I no longer had the error with ACTION\_DOWN.
30,968,679
I would like to access a variable from my rootViewController from within a different viewController (it‘s a CollectionViewCell). ``` window!.rootViewController = ViewController() ``` I declare the var like so: ``` import UIKit class ViewController: UIViewController { var testString : String = "Test"; override func viewDidLoad() { […] ``` And try to access it this way: ``` import UIKit class MainCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { […] super.init(frame: frame) let mainView = self.window!.rootViewController var testStringFromMainView = mainView.test […] ``` But all I keep getting is: ``` Type of expression is ambiguous without more context ``` Strange thing is, when I try for example ``` mainView.view.backgroundColor = UIColor.redColor() ``` it works. I can’t figure out what I am doing wrong. Any help is appreciated!
2015/06/21
[ "https://Stackoverflow.com/questions/30968679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3808543/" ]
I got the same problem as yours,and I tried portfoliobuilder's way but it didn't work. And then I just make some changes on my code,then it worked. I just set every instance of my button an OnlickListener interface instead of letting my Class inplements the View.OnClickListener~ ``` button.setOnclickListener(new View.OnClickListener){ public void onClick(View v){//... } } ``` INSTEAD OF ``` public YourClass implements View.OnClickListener{... public void OnClick(View v){ switch(v.getId()){ case://... break;}}} ```
I was getting `ViewPostImeInputStage ACTION_DOWN` message when a line of my code had --> ``` if(button.getText().equals("word")) ``` I got the desired output after correcting the if statement to --> ``` if(button.getText().toString().equals("word")) ``` Hope it helps someone.
30,968,679
I would like to access a variable from my rootViewController from within a different viewController (it‘s a CollectionViewCell). ``` window!.rootViewController = ViewController() ``` I declare the var like so: ``` import UIKit class ViewController: UIViewController { var testString : String = "Test"; override func viewDidLoad() { […] ``` And try to access it this way: ``` import UIKit class MainCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { […] super.init(frame: frame) let mainView = self.window!.rootViewController var testStringFromMainView = mainView.test […] ``` But all I keep getting is: ``` Type of expression is ambiguous without more context ``` Strange thing is, when I try for example ``` mainView.view.backgroundColor = UIColor.redColor() ``` it works. I can’t figure out what I am doing wrong. Any help is appreciated!
2015/06/21
[ "https://Stackoverflow.com/questions/30968679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3808543/" ]
I got the same problem as yours,and I tried portfoliobuilder's way but it didn't work. And then I just make some changes on my code,then it worked. I just set every instance of my button an OnlickListener interface instead of letting my Class inplements the View.OnClickListener~ ``` button.setOnclickListener(new View.OnClickListener){ public void onClick(View v){//... } } ``` INSTEAD OF ``` public YourClass implements View.OnClickListener{... public void OnClick(View v){ switch(v.getId()){ case://... break;}}} ```
None of the solutions above worked to me. Pretty strange bug, wondering if some view is intercepting the touch events and broking it, maybe some appcompat stuff, there is a lot of touch intercepts over there… Anyway, I workarounded the problem adding a transparent `View` over my real broken button and adding the click listener on this view, pretty ugly but it worked `¯\_(ツ)_/¯` e.g. imagine the error happened in this layout: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp"> <Button android:id="@+id/broken_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="0dp" android:layout_marginTop="0dp" android:text="Hello world" /> </RelativeLayout> ``` I added the transparent view and I set the click on it. ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp"> <Button android:id="@+id/broken_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="0dp" android:layout_marginTop="0dp" android:text="Hello world" /> <View android:id="@+id/workaround_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignStart="@+id/broken_button" android:layout_alignTop="@+id/broken_button" android:layout_alignEnd="@+id/broken_button" android:layout_alignBottom="@+id/broken_button" /> </RelativeLayout> ``` Again, it is an ugly solution, but still a solution.
15,779,826
Below I have a snippet of code that I won't work. I get input in my main method then pass that input into another method to check for validation. But it doesn't really check correctly. If I input `99` for `month` and `day` I expect it to give me the message `Check Month`. Instead I get: `THIS THIS` If I input `02` for month and `99` for day, I expect it to give me the message: `Check day`. Instead I get `THIS THIS` If I input `02` for both, I expect it to run and continue running other methods. Instead I get `THIS THIS`. ``` public class Date { private Calendar parsedDate; public static void main(String[] args) { Date main = new Date(); System.out.println("Enter a date (use the format -> (MM/DD/YYYY)"); //declare Scanner Scanner in = new Scanner (System.in); System.out.println("Enter a month (MM): "); String month = in.nextLine(); System.out.println("Enter a day (DD): "); String day = in.nextLine(); System.out.println("Enter a year (YYYY): "); String year = in.nextLine(); if (main.isValidDate(month, day, year) == true) { main.newFormat(month, day, year); main.isLeapYear(year); main.dayNumber(month, day); } else if (main.isValidDate(month, day, year) == false) { System.out.println("Invalid Input"); } }//end of main private boolean isValidDate(String month, String day, String year) { //check month if(month == "01" || month == "03" || month == "04" || month == "05" || month == "06" || month == "07" || month == "08" || month == "09" || month == "10" || month == "11" || month == "12") { //check day if(day == "01" || day == "02" || day == "03" || day == "04" || day == "05" || day == "06" || day == "07" || day == "08" || day == "09" || day == "10" || day == "11" || day == "12" || day == "13" || day == "14" || day == "15" || day == "16" || day == "17" || day == "18" || day == "19" || day == "20" || day == "21" || day == "22" || day == "23" || day == "24" || day == "25" || day == "26" || day == "27" || day == "28" || day == "29" || day == "30" || day == "31") { return true; } else { System.out.println("Check Day"); return false; } }//end of check month else if (month == "02") { if (day == "28" || day == "29") { return true; } }//end of month 2 else { System.out.println("THIS"); return false; } parsedDate = null;// if it's valid set the parsed Calendar object up. return true; }//end of isValidDate ```
2013/04/03
[ "https://Stackoverflow.com/questions/15779826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2094247/" ]
You should use the equals method for comparing Strings. When using the `==` operator, you compare the Strings' addresses, and not their content.
This `month == "01"` is not the correct way to compare `String`s in Java. You are trying to compare memory locations of the two variables, which aren't likely to be equal. Instead you should be using `month.equals("01")`.
15,779,826
Below I have a snippet of code that I won't work. I get input in my main method then pass that input into another method to check for validation. But it doesn't really check correctly. If I input `99` for `month` and `day` I expect it to give me the message `Check Month`. Instead I get: `THIS THIS` If I input `02` for month and `99` for day, I expect it to give me the message: `Check day`. Instead I get `THIS THIS` If I input `02` for both, I expect it to run and continue running other methods. Instead I get `THIS THIS`. ``` public class Date { private Calendar parsedDate; public static void main(String[] args) { Date main = new Date(); System.out.println("Enter a date (use the format -> (MM/DD/YYYY)"); //declare Scanner Scanner in = new Scanner (System.in); System.out.println("Enter a month (MM): "); String month = in.nextLine(); System.out.println("Enter a day (DD): "); String day = in.nextLine(); System.out.println("Enter a year (YYYY): "); String year = in.nextLine(); if (main.isValidDate(month, day, year) == true) { main.newFormat(month, day, year); main.isLeapYear(year); main.dayNumber(month, day); } else if (main.isValidDate(month, day, year) == false) { System.out.println("Invalid Input"); } }//end of main private boolean isValidDate(String month, String day, String year) { //check month if(month == "01" || month == "03" || month == "04" || month == "05" || month == "06" || month == "07" || month == "08" || month == "09" || month == "10" || month == "11" || month == "12") { //check day if(day == "01" || day == "02" || day == "03" || day == "04" || day == "05" || day == "06" || day == "07" || day == "08" || day == "09" || day == "10" || day == "11" || day == "12" || day == "13" || day == "14" || day == "15" || day == "16" || day == "17" || day == "18" || day == "19" || day == "20" || day == "21" || day == "22" || day == "23" || day == "24" || day == "25" || day == "26" || day == "27" || day == "28" || day == "29" || day == "30" || day == "31") { return true; } else { System.out.println("Check Day"); return false; } }//end of check month else if (month == "02") { if (day == "28" || day == "29") { return true; } }//end of month 2 else { System.out.println("THIS"); return false; } parsedDate = null;// if it's valid set the parsed Calendar object up. return true; }//end of isValidDate ```
2013/04/03
[ "https://Stackoverflow.com/questions/15779826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2094247/" ]
While the answers explaining the reason it's *currently* not working - using `==` rather than `equals` - I would suggest you *don't* just start using `equals`. Instead, parse the user input into numbers first, and then validate those... it's much easier to perform numeric comparisons with *numbers* rather than strings. Something like: ``` private boolean isValidDate(int year, int month, int day) { // Adjust for whatever bounds you want if (year < 1900 || year > 2100) { System.out.println("Check year"); return false; } if (month < 1 || month > 12) { System.out.println("Check month"); return false; } Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(year, month - 1, 1); if (day < 1 || day > calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) { System.out.println("Check day"); return false; } calendar.set(Calendar.DAY_OF_MONTH, day); // Store calendar somewhere if you want... return true; } ``` Additionally, I'd strongly recommend the use of [Joda Time](http://joda-time.sf.net) as a much nicer date/time API if you can. EDIT: Your next problem seems to be this block: ``` if (main.isValidDate(month, day, year) == true) { main.newFormat(month, day, year); main.isLeapYear(year); main.dayNumber(month, day); } else if (main.isValidDate(month, day, year) == false) { System.out.println("Invalid Input"); } ``` Now the code I've presented already checks everything *and* constructs a `Calendar` - it's not clear what the methods in the `if` block are meant to do. But you don't need to call `isValidDate` a second time. You just need: ``` // Assuming you're using my new method... if (isValidDate(year, month, day)) { // Do whatever you need to do } else { System.out.println("Invalid input"); } ```
This `month == "01"` is not the correct way to compare `String`s in Java. You are trying to compare memory locations of the two variables, which aren't likely to be equal. Instead you should be using `month.equals("01")`.
15,779,826
Below I have a snippet of code that I won't work. I get input in my main method then pass that input into another method to check for validation. But it doesn't really check correctly. If I input `99` for `month` and `day` I expect it to give me the message `Check Month`. Instead I get: `THIS THIS` If I input `02` for month and `99` for day, I expect it to give me the message: `Check day`. Instead I get `THIS THIS` If I input `02` for both, I expect it to run and continue running other methods. Instead I get `THIS THIS`. ``` public class Date { private Calendar parsedDate; public static void main(String[] args) { Date main = new Date(); System.out.println("Enter a date (use the format -> (MM/DD/YYYY)"); //declare Scanner Scanner in = new Scanner (System.in); System.out.println("Enter a month (MM): "); String month = in.nextLine(); System.out.println("Enter a day (DD): "); String day = in.nextLine(); System.out.println("Enter a year (YYYY): "); String year = in.nextLine(); if (main.isValidDate(month, day, year) == true) { main.newFormat(month, day, year); main.isLeapYear(year); main.dayNumber(month, day); } else if (main.isValidDate(month, day, year) == false) { System.out.println("Invalid Input"); } }//end of main private boolean isValidDate(String month, String day, String year) { //check month if(month == "01" || month == "03" || month == "04" || month == "05" || month == "06" || month == "07" || month == "08" || month == "09" || month == "10" || month == "11" || month == "12") { //check day if(day == "01" || day == "02" || day == "03" || day == "04" || day == "05" || day == "06" || day == "07" || day == "08" || day == "09" || day == "10" || day == "11" || day == "12" || day == "13" || day == "14" || day == "15" || day == "16" || day == "17" || day == "18" || day == "19" || day == "20" || day == "21" || day == "22" || day == "23" || day == "24" || day == "25" || day == "26" || day == "27" || day == "28" || day == "29" || day == "30" || day == "31") { return true; } else { System.out.println("Check Day"); return false; } }//end of check month else if (month == "02") { if (day == "28" || day == "29") { return true; } }//end of month 2 else { System.out.println("THIS"); return false; } parsedDate = null;// if it's valid set the parsed Calendar object up. return true; }//end of isValidDate ```
2013/04/03
[ "https://Stackoverflow.com/questions/15779826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2094247/" ]
This `month == "01"` is not the correct way to compare `String`s in Java. You are trying to compare memory locations of the two variables, which aren't likely to be equal. Instead you should be using `month.equals("01")`.
It would be MUCH more efficient and easier to read/write/test to convert your string to integer and then check that (e.g.use `int monthVal = Integer.parseInt(month);` thenyou can check if (a) it parsed properly,with a try/catch around it and (b) test the value with `if (monthVal > 0 && monthVal< 13) { /* month is good */}`
15,779,826
Below I have a snippet of code that I won't work. I get input in my main method then pass that input into another method to check for validation. But it doesn't really check correctly. If I input `99` for `month` and `day` I expect it to give me the message `Check Month`. Instead I get: `THIS THIS` If I input `02` for month and `99` for day, I expect it to give me the message: `Check day`. Instead I get `THIS THIS` If I input `02` for both, I expect it to run and continue running other methods. Instead I get `THIS THIS`. ``` public class Date { private Calendar parsedDate; public static void main(String[] args) { Date main = new Date(); System.out.println("Enter a date (use the format -> (MM/DD/YYYY)"); //declare Scanner Scanner in = new Scanner (System.in); System.out.println("Enter a month (MM): "); String month = in.nextLine(); System.out.println("Enter a day (DD): "); String day = in.nextLine(); System.out.println("Enter a year (YYYY): "); String year = in.nextLine(); if (main.isValidDate(month, day, year) == true) { main.newFormat(month, day, year); main.isLeapYear(year); main.dayNumber(month, day); } else if (main.isValidDate(month, day, year) == false) { System.out.println("Invalid Input"); } }//end of main private boolean isValidDate(String month, String day, String year) { //check month if(month == "01" || month == "03" || month == "04" || month == "05" || month == "06" || month == "07" || month == "08" || month == "09" || month == "10" || month == "11" || month == "12") { //check day if(day == "01" || day == "02" || day == "03" || day == "04" || day == "05" || day == "06" || day == "07" || day == "08" || day == "09" || day == "10" || day == "11" || day == "12" || day == "13" || day == "14" || day == "15" || day == "16" || day == "17" || day == "18" || day == "19" || day == "20" || day == "21" || day == "22" || day == "23" || day == "24" || day == "25" || day == "26" || day == "27" || day == "28" || day == "29" || day == "30" || day == "31") { return true; } else { System.out.println("Check Day"); return false; } }//end of check month else if (month == "02") { if (day == "28" || day == "29") { return true; } }//end of month 2 else { System.out.println("THIS"); return false; } parsedDate = null;// if it's valid set the parsed Calendar object up. return true; }//end of isValidDate ```
2013/04/03
[ "https://Stackoverflow.com/questions/15779826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2094247/" ]
You should use the equals method for comparing Strings. When using the `==` operator, you compare the Strings' addresses, and not their content.
It would be MUCH more efficient and easier to read/write/test to convert your string to integer and then check that (e.g.use `int monthVal = Integer.parseInt(month);` thenyou can check if (a) it parsed properly,with a try/catch around it and (b) test the value with `if (monthVal > 0 && monthVal< 13) { /* month is good */}`
15,779,826
Below I have a snippet of code that I won't work. I get input in my main method then pass that input into another method to check for validation. But it doesn't really check correctly. If I input `99` for `month` and `day` I expect it to give me the message `Check Month`. Instead I get: `THIS THIS` If I input `02` for month and `99` for day, I expect it to give me the message: `Check day`. Instead I get `THIS THIS` If I input `02` for both, I expect it to run and continue running other methods. Instead I get `THIS THIS`. ``` public class Date { private Calendar parsedDate; public static void main(String[] args) { Date main = new Date(); System.out.println("Enter a date (use the format -> (MM/DD/YYYY)"); //declare Scanner Scanner in = new Scanner (System.in); System.out.println("Enter a month (MM): "); String month = in.nextLine(); System.out.println("Enter a day (DD): "); String day = in.nextLine(); System.out.println("Enter a year (YYYY): "); String year = in.nextLine(); if (main.isValidDate(month, day, year) == true) { main.newFormat(month, day, year); main.isLeapYear(year); main.dayNumber(month, day); } else if (main.isValidDate(month, day, year) == false) { System.out.println("Invalid Input"); } }//end of main private boolean isValidDate(String month, String day, String year) { //check month if(month == "01" || month == "03" || month == "04" || month == "05" || month == "06" || month == "07" || month == "08" || month == "09" || month == "10" || month == "11" || month == "12") { //check day if(day == "01" || day == "02" || day == "03" || day == "04" || day == "05" || day == "06" || day == "07" || day == "08" || day == "09" || day == "10" || day == "11" || day == "12" || day == "13" || day == "14" || day == "15" || day == "16" || day == "17" || day == "18" || day == "19" || day == "20" || day == "21" || day == "22" || day == "23" || day == "24" || day == "25" || day == "26" || day == "27" || day == "28" || day == "29" || day == "30" || day == "31") { return true; } else { System.out.println("Check Day"); return false; } }//end of check month else if (month == "02") { if (day == "28" || day == "29") { return true; } }//end of month 2 else { System.out.println("THIS"); return false; } parsedDate = null;// if it's valid set the parsed Calendar object up. return true; }//end of isValidDate ```
2013/04/03
[ "https://Stackoverflow.com/questions/15779826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2094247/" ]
You should use the equals method for comparing Strings. When using the `==` operator, you compare the Strings' addresses, and not their content.
There are two big mistakes 1. you are comparing string with equals equals which will compare memory not content so the line `if(month == "01")` should be `if("01".equals(month))` 2. The condition for checking valid date `if (main.isValidDate(month, day, year) == true)` should be like `if (main.isValidDate(month, day, year))`
15,779,826
Below I have a snippet of code that I won't work. I get input in my main method then pass that input into another method to check for validation. But it doesn't really check correctly. If I input `99` for `month` and `day` I expect it to give me the message `Check Month`. Instead I get: `THIS THIS` If I input `02` for month and `99` for day, I expect it to give me the message: `Check day`. Instead I get `THIS THIS` If I input `02` for both, I expect it to run and continue running other methods. Instead I get `THIS THIS`. ``` public class Date { private Calendar parsedDate; public static void main(String[] args) { Date main = new Date(); System.out.println("Enter a date (use the format -> (MM/DD/YYYY)"); //declare Scanner Scanner in = new Scanner (System.in); System.out.println("Enter a month (MM): "); String month = in.nextLine(); System.out.println("Enter a day (DD): "); String day = in.nextLine(); System.out.println("Enter a year (YYYY): "); String year = in.nextLine(); if (main.isValidDate(month, day, year) == true) { main.newFormat(month, day, year); main.isLeapYear(year); main.dayNumber(month, day); } else if (main.isValidDate(month, day, year) == false) { System.out.println("Invalid Input"); } }//end of main private boolean isValidDate(String month, String day, String year) { //check month if(month == "01" || month == "03" || month == "04" || month == "05" || month == "06" || month == "07" || month == "08" || month == "09" || month == "10" || month == "11" || month == "12") { //check day if(day == "01" || day == "02" || day == "03" || day == "04" || day == "05" || day == "06" || day == "07" || day == "08" || day == "09" || day == "10" || day == "11" || day == "12" || day == "13" || day == "14" || day == "15" || day == "16" || day == "17" || day == "18" || day == "19" || day == "20" || day == "21" || day == "22" || day == "23" || day == "24" || day == "25" || day == "26" || day == "27" || day == "28" || day == "29" || day == "30" || day == "31") { return true; } else { System.out.println("Check Day"); return false; } }//end of check month else if (month == "02") { if (day == "28" || day == "29") { return true; } }//end of month 2 else { System.out.println("THIS"); return false; } parsedDate = null;// if it's valid set the parsed Calendar object up. return true; }//end of isValidDate ```
2013/04/03
[ "https://Stackoverflow.com/questions/15779826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2094247/" ]
While the answers explaining the reason it's *currently* not working - using `==` rather than `equals` - I would suggest you *don't* just start using `equals`. Instead, parse the user input into numbers first, and then validate those... it's much easier to perform numeric comparisons with *numbers* rather than strings. Something like: ``` private boolean isValidDate(int year, int month, int day) { // Adjust for whatever bounds you want if (year < 1900 || year > 2100) { System.out.println("Check year"); return false; } if (month < 1 || month > 12) { System.out.println("Check month"); return false; } Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(year, month - 1, 1); if (day < 1 || day > calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) { System.out.println("Check day"); return false; } calendar.set(Calendar.DAY_OF_MONTH, day); // Store calendar somewhere if you want... return true; } ``` Additionally, I'd strongly recommend the use of [Joda Time](http://joda-time.sf.net) as a much nicer date/time API if you can. EDIT: Your next problem seems to be this block: ``` if (main.isValidDate(month, day, year) == true) { main.newFormat(month, day, year); main.isLeapYear(year); main.dayNumber(month, day); } else if (main.isValidDate(month, day, year) == false) { System.out.println("Invalid Input"); } ``` Now the code I've presented already checks everything *and* constructs a `Calendar` - it's not clear what the methods in the `if` block are meant to do. But you don't need to call `isValidDate` a second time. You just need: ``` // Assuming you're using my new method... if (isValidDate(year, month, day)) { // Do whatever you need to do } else { System.out.println("Invalid input"); } ```
It would be MUCH more efficient and easier to read/write/test to convert your string to integer and then check that (e.g.use `int monthVal = Integer.parseInt(month);` thenyou can check if (a) it parsed properly,with a try/catch around it and (b) test the value with `if (monthVal > 0 && monthVal< 13) { /* month is good */}`
15,779,826
Below I have a snippet of code that I won't work. I get input in my main method then pass that input into another method to check for validation. But it doesn't really check correctly. If I input `99` for `month` and `day` I expect it to give me the message `Check Month`. Instead I get: `THIS THIS` If I input `02` for month and `99` for day, I expect it to give me the message: `Check day`. Instead I get `THIS THIS` If I input `02` for both, I expect it to run and continue running other methods. Instead I get `THIS THIS`. ``` public class Date { private Calendar parsedDate; public static void main(String[] args) { Date main = new Date(); System.out.println("Enter a date (use the format -> (MM/DD/YYYY)"); //declare Scanner Scanner in = new Scanner (System.in); System.out.println("Enter a month (MM): "); String month = in.nextLine(); System.out.println("Enter a day (DD): "); String day = in.nextLine(); System.out.println("Enter a year (YYYY): "); String year = in.nextLine(); if (main.isValidDate(month, day, year) == true) { main.newFormat(month, day, year); main.isLeapYear(year); main.dayNumber(month, day); } else if (main.isValidDate(month, day, year) == false) { System.out.println("Invalid Input"); } }//end of main private boolean isValidDate(String month, String day, String year) { //check month if(month == "01" || month == "03" || month == "04" || month == "05" || month == "06" || month == "07" || month == "08" || month == "09" || month == "10" || month == "11" || month == "12") { //check day if(day == "01" || day == "02" || day == "03" || day == "04" || day == "05" || day == "06" || day == "07" || day == "08" || day == "09" || day == "10" || day == "11" || day == "12" || day == "13" || day == "14" || day == "15" || day == "16" || day == "17" || day == "18" || day == "19" || day == "20" || day == "21" || day == "22" || day == "23" || day == "24" || day == "25" || day == "26" || day == "27" || day == "28" || day == "29" || day == "30" || day == "31") { return true; } else { System.out.println("Check Day"); return false; } }//end of check month else if (month == "02") { if (day == "28" || day == "29") { return true; } }//end of month 2 else { System.out.println("THIS"); return false; } parsedDate = null;// if it's valid set the parsed Calendar object up. return true; }//end of isValidDate ```
2013/04/03
[ "https://Stackoverflow.com/questions/15779826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2094247/" ]
While the answers explaining the reason it's *currently* not working - using `==` rather than `equals` - I would suggest you *don't* just start using `equals`. Instead, parse the user input into numbers first, and then validate those... it's much easier to perform numeric comparisons with *numbers* rather than strings. Something like: ``` private boolean isValidDate(int year, int month, int day) { // Adjust for whatever bounds you want if (year < 1900 || year > 2100) { System.out.println("Check year"); return false; } if (month < 1 || month > 12) { System.out.println("Check month"); return false; } Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(year, month - 1, 1); if (day < 1 || day > calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) { System.out.println("Check day"); return false; } calendar.set(Calendar.DAY_OF_MONTH, day); // Store calendar somewhere if you want... return true; } ``` Additionally, I'd strongly recommend the use of [Joda Time](http://joda-time.sf.net) as a much nicer date/time API if you can. EDIT: Your next problem seems to be this block: ``` if (main.isValidDate(month, day, year) == true) { main.newFormat(month, day, year); main.isLeapYear(year); main.dayNumber(month, day); } else if (main.isValidDate(month, day, year) == false) { System.out.println("Invalid Input"); } ``` Now the code I've presented already checks everything *and* constructs a `Calendar` - it's not clear what the methods in the `if` block are meant to do. But you don't need to call `isValidDate` a second time. You just need: ``` // Assuming you're using my new method... if (isValidDate(year, month, day)) { // Do whatever you need to do } else { System.out.println("Invalid input"); } ```
There are two big mistakes 1. you are comparing string with equals equals which will compare memory not content so the line `if(month == "01")` should be `if("01".equals(month))` 2. The condition for checking valid date `if (main.isValidDate(month, day, year) == true)` should be like `if (main.isValidDate(month, day, year))`
15,779,826
Below I have a snippet of code that I won't work. I get input in my main method then pass that input into another method to check for validation. But it doesn't really check correctly. If I input `99` for `month` and `day` I expect it to give me the message `Check Month`. Instead I get: `THIS THIS` If I input `02` for month and `99` for day, I expect it to give me the message: `Check day`. Instead I get `THIS THIS` If I input `02` for both, I expect it to run and continue running other methods. Instead I get `THIS THIS`. ``` public class Date { private Calendar parsedDate; public static void main(String[] args) { Date main = new Date(); System.out.println("Enter a date (use the format -> (MM/DD/YYYY)"); //declare Scanner Scanner in = new Scanner (System.in); System.out.println("Enter a month (MM): "); String month = in.nextLine(); System.out.println("Enter a day (DD): "); String day = in.nextLine(); System.out.println("Enter a year (YYYY): "); String year = in.nextLine(); if (main.isValidDate(month, day, year) == true) { main.newFormat(month, day, year); main.isLeapYear(year); main.dayNumber(month, day); } else if (main.isValidDate(month, day, year) == false) { System.out.println("Invalid Input"); } }//end of main private boolean isValidDate(String month, String day, String year) { //check month if(month == "01" || month == "03" || month == "04" || month == "05" || month == "06" || month == "07" || month == "08" || month == "09" || month == "10" || month == "11" || month == "12") { //check day if(day == "01" || day == "02" || day == "03" || day == "04" || day == "05" || day == "06" || day == "07" || day == "08" || day == "09" || day == "10" || day == "11" || day == "12" || day == "13" || day == "14" || day == "15" || day == "16" || day == "17" || day == "18" || day == "19" || day == "20" || day == "21" || day == "22" || day == "23" || day == "24" || day == "25" || day == "26" || day == "27" || day == "28" || day == "29" || day == "30" || day == "31") { return true; } else { System.out.println("Check Day"); return false; } }//end of check month else if (month == "02") { if (day == "28" || day == "29") { return true; } }//end of month 2 else { System.out.println("THIS"); return false; } parsedDate = null;// if it's valid set the parsed Calendar object up. return true; }//end of isValidDate ```
2013/04/03
[ "https://Stackoverflow.com/questions/15779826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2094247/" ]
There are two big mistakes 1. you are comparing string with equals equals which will compare memory not content so the line `if(month == "01")` should be `if("01".equals(month))` 2. The condition for checking valid date `if (main.isValidDate(month, day, year) == true)` should be like `if (main.isValidDate(month, day, year))`
It would be MUCH more efficient and easier to read/write/test to convert your string to integer and then check that (e.g.use `int monthVal = Integer.parseInt(month);` thenyou can check if (a) it parsed properly,with a try/catch around it and (b) test the value with `if (monthVal > 0 && monthVal< 13) { /* month is good */}`
70,829,973
I want to say > > for f in x: do certain thing. > > > but i dont want to connect them to each other. first do a work for x[0] then for x[1] then etc. ``` x = ['ABCED', 'BACF', 'BCD'] ``` for exmple, it cant seprate them by the index, it just repeate print part for all q in x. how can i fix it? ``` for f in x: for q in f: print('hi') ``` the output that i except that is: > > [[A,B,C,E,D],[B,A,C,F],[B,C,D]] > > >
2022/01/24
[ "https://Stackoverflow.com/questions/70829973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14676981/" ]
Use `list` on `str` create a list of each character: ``` out = [list(i) for i in x] print(out) # Output [['A', 'B', 'C', 'E', 'D'], ['B', 'A', 'C', 'F'], ['B', 'C', 'D']] ```
``` x = ['ABCED', 'BACF', 'BCD'] new_list= [list(i) for i in x] ``` or: ``` list(map(list, x)) ``` output: ``` [['A', 'B', 'C', 'E', 'D'], ['B', 'A', 'C', 'F'], ['B', 'C', 'D']] ```
26,559,840
I'm using Visual Studio 2010 and SQL Server 2012. When I try to connect to SQL Server through Visual Studio, I don't get my server name on Add connection drop down menu.
2014/10/25
[ "https://Stackoverflow.com/questions/26559840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3786234/" ]
Go to SQL Server Management Studio to look for the correct `Server Name` and copy the value. Make all the configurations by yourself at the end just click `Test connection` button. If the connection is test successfully proceed with your work.
If the database is in your local machine, Just put a . (Dot) in Server Name and select the database. ![Add connection dialogue](https://i.stack.imgur.com/BXixw.png)
26,559,840
I'm using Visual Studio 2010 and SQL Server 2012. When I try to connect to SQL Server through Visual Studio, I don't get my server name on Add connection drop down menu.
2014/10/25
[ "https://Stackoverflow.com/questions/26559840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3786234/" ]
If the database is in your local machine, Just put a . (Dot) in Server Name and select the database. ![Add connection dialogue](https://i.stack.imgur.com/BXixw.png)
Insert machine\_name/SqlServerName
26,559,840
I'm using Visual Studio 2010 and SQL Server 2012. When I try to connect to SQL Server through Visual Studio, I don't get my server name on Add connection drop down menu.
2014/10/25
[ "https://Stackoverflow.com/questions/26559840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3786234/" ]
If the database is in your local machine, Just put a . (Dot) in Server Name and select the database. ![Add connection dialogue](https://i.stack.imgur.com/BXixw.png)
run services.msc find " SQL server browser " , it might be disabled , start that service and set it to automatic.
26,559,840
I'm using Visual Studio 2010 and SQL Server 2012. When I try to connect to SQL Server through Visual Studio, I don't get my server name on Add connection drop down menu.
2014/10/25
[ "https://Stackoverflow.com/questions/26559840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3786234/" ]
If the database is in your local machine, Just put a . (Dot) in Server Name and select the database. ![Add connection dialogue](https://i.stack.imgur.com/BXixw.png)
For people using sql server 2014+ and using the local db on your pc. simply set the server name to be (localdb)\ name of your database. It worked for me.
26,559,840
I'm using Visual Studio 2010 and SQL Server 2012. When I try to connect to SQL Server through Visual Studio, I don't get my server name on Add connection drop down menu.
2014/10/25
[ "https://Stackoverflow.com/questions/26559840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3786234/" ]
Go to SQL Server Management Studio to look for the correct `Server Name` and copy the value. Make all the configurations by yourself at the end just click `Test connection` button. If the connection is test successfully proceed with your work.
Insert machine\_name/SqlServerName
26,559,840
I'm using Visual Studio 2010 and SQL Server 2012. When I try to connect to SQL Server through Visual Studio, I don't get my server name on Add connection drop down menu.
2014/10/25
[ "https://Stackoverflow.com/questions/26559840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3786234/" ]
Go to SQL Server Management Studio to look for the correct `Server Name` and copy the value. Make all the configurations by yourself at the end just click `Test connection` button. If the connection is test successfully proceed with your work.
run services.msc find " SQL server browser " , it might be disabled , start that service and set it to automatic.
26,559,840
I'm using Visual Studio 2010 and SQL Server 2012. When I try to connect to SQL Server through Visual Studio, I don't get my server name on Add connection drop down menu.
2014/10/25
[ "https://Stackoverflow.com/questions/26559840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3786234/" ]
Go to SQL Server Management Studio to look for the correct `Server Name` and copy the value. Make all the configurations by yourself at the end just click `Test connection` button. If the connection is test successfully proceed with your work.
For people using sql server 2014+ and using the local db on your pc. simply set the server name to be (localdb)\ name of your database. It worked for me.
26,559,840
I'm using Visual Studio 2010 and SQL Server 2012. When I try to connect to SQL Server through Visual Studio, I don't get my server name on Add connection drop down menu.
2014/10/25
[ "https://Stackoverflow.com/questions/26559840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3786234/" ]
run services.msc find " SQL server browser " , it might be disabled , start that service and set it to automatic.
Insert machine\_name/SqlServerName