qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
31,004,962
I have a json schema defining several properties. I've moved 2 of the properties to definitions and I make references to them. I did this because I wanted to group them together and do some testing for these properties in a generic way. This works fine and all the json data is handled as before. But, I noticed that when I read the json schema file into my javascript file, I only see the last $ref. I don't know what the cause of this is. I'd really need to know all of the properties that are referenced. Here's an snippet of my json schema (in file schemas/schema1.json): ``` { "type": "object", "properties": { "$ref": "#/definitions/groupedProperties/property1", "$ref": "#/definitions/groupedProperties/property2" }, "definitions": { "groupedProperties": { "type": "object", "properties": { "property1": { "type": "string" }, "property2": { "type": "string" } } } } } ``` Then I'm reading it into my js file like this (in file test.js): ``` var schemas = requireDir('./schemas') for (var prop in schemas['schema1'].properties) { console.log(prop) } ``` When I iterate over the properties in the schema from my js file, all I can see is one $ref. I imagine this is because it thinks the property name is '$ref' and there can be only unique names. Is there a certain way I need to require this file so that the first $ref doesn't get clobbered? EDIT: My syntax wasn't passing the json schema validators, although I'm not sure why, so instead of struggling with that, I decided to do it a bit differently. All I wanted was a way to group certain properties, so I put the properties back in the main schema, and changed the definition to be just an enum of the property names comprising the group. So now my schema looks like: ``` { "type": "object", "properties": { "property1": { "type": "string" }, "property2": { "type": "string" } }, "definitions": { "groupedProperties": { "enum": ["property1", "property2"] } } } ``` And then in my js file: ``` var myGroup = (schema.definitions ? schema.definitions.groupedProperties : []) console.log(myGroup.enum) // [ 'property1', 'property2' ] ```
2015/06/23
[ "https://Stackoverflow.com/questions/31004962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3884280/" ]
There are a lot of problems with how you reference your definitions. ###JSON objects can not have duplicate properties All properties in a JSON or JavaScript object are unique. The second one will overwrite the first. Consider the syntax for accessing a property to understand why. When you read your JSON into a JavaScript object, you could try accessing the `$ref` property using `schema.properties['$ref']`. If there were two, which one (or both) would you get? JavaScript has no mechanism to distinguish because it is not allowed. ###`$ref` must stand alone When `$ref` is used in an object, it must be the only property in that object. All other properties will be ignored. This is just one more reason why having two `$ref`s doesn't work. > > Any members other than "$ref" in a JSON Reference object SHALL be > ignored. > > > * <https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03#section-3> > > > ###`$ref` should not be used in `properties` `$ref` should only be used to reference schemas. In this case, the `properties` keyword is using `$ref` which is an object with schema values. Using `$ref` in this way is not explicitly forbidden in the documentation for JSON Schema or JSON Reference, but it is not idiomatic JSON Schema and is consequently not supported by most validators. Even if the validator you are using does support references like this, it should be avoid because it is never necessary and can make the schema confusing and difficult to maintain. ###Your JSON-Pointers are wrong Your JSON-Pointers do not actually point to the schemas you have defined. The correct pointer would be `#/definitions/groupedProperties/properties/property1`. ###Posible Solutions This is what you were trying to do. ``` { "type": "object", "properties": { "property1": { "$ref": "#/definitions/groupedProperties/properties/property1" }, "property2": { "$ref": "#/definitions/groupedProperties/properties/property2" } }, "definitions": { "groupedProperties": { "type": "object", "properties": { "property1": { "type": "string" }, "property2": { "type": "string" } } } } } ``` Here is a cleaner way to include all of your `groupedProperties` at once. ``` { "type": "object", "allOf": [ { "$ref": "#/definitions/groupedProperties" } ], "definitions": { "groupedProperties": { "type": "object", "properties": { "property1": { "type": "string" }, "property2": { "type": "string" } } } } } ``` Or, since you are only using it for testing purposes, you can flip it around so the definition references the schema. You can use the definition in your tests without it affecting your schema. ``` { "type": "object", "properties": { "property1": { "type": "string" }, "property2": { "type": "string" } }, "definitions": { "groupedProperties": { "type": "object", "properties": { "property1": { "$ref": "#/properties/property1" }, "property2": { "$ref": "#/properties/property2" } } } } } ```
This has nothing to do with `require`, object keys are not unique (in that you may declare them several times in one object), but they are overwritable (in the same way that a variable declared twice is overwritable). You will only receive the last value declared on two keys with the same name. I'd suggesting giving the refs a distinguishing ID, this will also aid clarity when your code expands
56,887,520
I'm fetching github repositories from api.github.com/users/ncesar/repos and i wanna get only 10 items, then after scrolling, load more items. I have tried to implement myself but i dont know how to adapt it to array slice(that is limiting my array length to 2, just for testings). This is my current code ``` class SearchResult extends Component { constructor() { super(); this.state = { githubRepo: [], loaded: false, error: false, }; } componentDidMount() { this.loadItems(this.props.location.state.userName); } componentWillReceiveProps(nextProps) { if ( nextProps.location.state.userName !== this.props.location.state.userName ) { this.loadItems(nextProps.location.state.userName); } } loadItems(userName) { axios .get(`${api.baseUrl}/users/${userName}/repos`) .then((repo) => { console.log('repo', repo); if (repo.data.length <= 0) { this.setState({ githubRepo: '' }); } else { this.setState({ githubRepo: repo.data }); } }) .catch((err) => { if (err.response.status === 404) { this.setState({ error: true, loaded: true }); } }); } render() { const { githubRepo, loaded, error, } = this.state; return ( <div className="search-result"> {error === true ? ( <h1 style={style}>User not found :(</h1> ) : ( <section id="user-infos"> <div className="row"> <div className="col-md-8"> {githubRepo .sort((a, b) => { if (a.stargazers_count < b.stargazers_count) return 1; if (a.stargazers_count > b.stargazers_count) return -1; return 0; }).slice(0, 2) .map(name => ( <UserRepositories key={name.id} repoName={name.name} repoDescription={name.description} starNumber={name.stargazers_count} /> ))} </div> </div> </section> )} </div> ); } } export default SearchResult; ``` Just to clarify, the sort is ordening repos by stars count. What i have tried: ``` //setting theses states and calling this function page: 1, totalPages: null, scrolling: false, componentDidMount() { this.loadContacts(); //carrega os contatos iniciais this.scrollListener = window.addEventListener('scroll', (event) => {//escuta o scroll this.handleScroll(event); }); } handleScroll = () => { const { scrolling, totalPages, page } = this.state; //pega os 3 pra fora do state if(scrolling) return; //se ja está scrollando, retorna true if(totalPages <= page) return; //se o total de páginas é menor ou igual a page const lastLi = document.querySelector('ul.contacts > li:last-child');//pegando o último li const lastLiOffset = lastLi.offsetTop + lastLi.clientHeight; const pageOffset = window.pageYOffset + window.innerHeight; var bottomOffSet = 20; if(pageOffset > lastLiOffset - bottomOffSet) this.loadMore(); } loadMore = () => { // event.preventDefault(); this.setState(prevState => ({ page: prevState.page + 1, scrolling: true, }), this.loadContacts); } ``` But i dont know where i can pass the page parameter. The explanation of this code: it was used on a API with page number and per page parameters. The problem is that Github API does not offer this in repositories list, so, this is why i'm using slice.
2019/07/04
[ "https://Stackoverflow.com/questions/56887520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8402168/" ]
You could use the empty line as a loop-breaker: ``` while (s.hasNextLine()){ //no need for "== true" String read = s.nextLine(); if(read == null || read.isEmpty()){ //if the line is empty break; //exit the loop } in.add(read); [...] } ```
You could end the loop with something like below. Here, the String "END" (case-insenstive) is used to signify end of the multi-line content: ``` public static void main(String[] args) { ArrayList<String> in = new ArrayList<String>(); Scanner s = new Scanner(System.in); while (s.hasNextLine()) { String line = s.nextLine(); in.add(line); if (line != null && line.equalsIgnoreCase("END")) { System.out.println("Output list : " + in); break; } } } ```
56,887,520
I'm fetching github repositories from api.github.com/users/ncesar/repos and i wanna get only 10 items, then after scrolling, load more items. I have tried to implement myself but i dont know how to adapt it to array slice(that is limiting my array length to 2, just for testings). This is my current code ``` class SearchResult extends Component { constructor() { super(); this.state = { githubRepo: [], loaded: false, error: false, }; } componentDidMount() { this.loadItems(this.props.location.state.userName); } componentWillReceiveProps(nextProps) { if ( nextProps.location.state.userName !== this.props.location.state.userName ) { this.loadItems(nextProps.location.state.userName); } } loadItems(userName) { axios .get(`${api.baseUrl}/users/${userName}/repos`) .then((repo) => { console.log('repo', repo); if (repo.data.length <= 0) { this.setState({ githubRepo: '' }); } else { this.setState({ githubRepo: repo.data }); } }) .catch((err) => { if (err.response.status === 404) { this.setState({ error: true, loaded: true }); } }); } render() { const { githubRepo, loaded, error, } = this.state; return ( <div className="search-result"> {error === true ? ( <h1 style={style}>User not found :(</h1> ) : ( <section id="user-infos"> <div className="row"> <div className="col-md-8"> {githubRepo .sort((a, b) => { if (a.stargazers_count < b.stargazers_count) return 1; if (a.stargazers_count > b.stargazers_count) return -1; return 0; }).slice(0, 2) .map(name => ( <UserRepositories key={name.id} repoName={name.name} repoDescription={name.description} starNumber={name.stargazers_count} /> ))} </div> </div> </section> )} </div> ); } } export default SearchResult; ``` Just to clarify, the sort is ordening repos by stars count. What i have tried: ``` //setting theses states and calling this function page: 1, totalPages: null, scrolling: false, componentDidMount() { this.loadContacts(); //carrega os contatos iniciais this.scrollListener = window.addEventListener('scroll', (event) => {//escuta o scroll this.handleScroll(event); }); } handleScroll = () => { const { scrolling, totalPages, page } = this.state; //pega os 3 pra fora do state if(scrolling) return; //se ja está scrollando, retorna true if(totalPages <= page) return; //se o total de páginas é menor ou igual a page const lastLi = document.querySelector('ul.contacts > li:last-child');//pegando o último li const lastLiOffset = lastLi.offsetTop + lastLi.clientHeight; const pageOffset = window.pageYOffset + window.innerHeight; var bottomOffSet = 20; if(pageOffset > lastLiOffset - bottomOffSet) this.loadMore(); } loadMore = () => { // event.preventDefault(); this.setState(prevState => ({ page: prevState.page + 1, scrolling: true, }), this.loadContacts); } ``` But i dont know where i can pass the page parameter. The explanation of this code: it was used on a API with page number and per page parameters. The problem is that Github API does not offer this in repositories list, so, this is why i'm using slice.
2019/07/04
[ "https://Stackoverflow.com/questions/56887520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8402168/" ]
You could use the empty line as a loop-breaker: ``` while (s.hasNextLine()){ //no need for "== true" String read = s.nextLine(); if(read == null || read.isEmpty()){ //if the line is empty break; //exit the loop } in.add(read); [...] } ```
You can use this code. It returns when the user press `Enter` on an empty line. ``` import java.util.Scanner; import java.util.ArrayList; public class Main { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); ArrayList<String> arrayLines = new ArrayList<>(); String line; while(true){ line = scanner.nextLine(); if(line.equals("")){ break; } else { System.out.println(line); arrayLines.add(line); } } System.out.println(arrayLines); } } ``` Best
56,887,520
I'm fetching github repositories from api.github.com/users/ncesar/repos and i wanna get only 10 items, then after scrolling, load more items. I have tried to implement myself but i dont know how to adapt it to array slice(that is limiting my array length to 2, just for testings). This is my current code ``` class SearchResult extends Component { constructor() { super(); this.state = { githubRepo: [], loaded: false, error: false, }; } componentDidMount() { this.loadItems(this.props.location.state.userName); } componentWillReceiveProps(nextProps) { if ( nextProps.location.state.userName !== this.props.location.state.userName ) { this.loadItems(nextProps.location.state.userName); } } loadItems(userName) { axios .get(`${api.baseUrl}/users/${userName}/repos`) .then((repo) => { console.log('repo', repo); if (repo.data.length <= 0) { this.setState({ githubRepo: '' }); } else { this.setState({ githubRepo: repo.data }); } }) .catch((err) => { if (err.response.status === 404) { this.setState({ error: true, loaded: true }); } }); } render() { const { githubRepo, loaded, error, } = this.state; return ( <div className="search-result"> {error === true ? ( <h1 style={style}>User not found :(</h1> ) : ( <section id="user-infos"> <div className="row"> <div className="col-md-8"> {githubRepo .sort((a, b) => { if (a.stargazers_count < b.stargazers_count) return 1; if (a.stargazers_count > b.stargazers_count) return -1; return 0; }).slice(0, 2) .map(name => ( <UserRepositories key={name.id} repoName={name.name} repoDescription={name.description} starNumber={name.stargazers_count} /> ))} </div> </div> </section> )} </div> ); } } export default SearchResult; ``` Just to clarify, the sort is ordening repos by stars count. What i have tried: ``` //setting theses states and calling this function page: 1, totalPages: null, scrolling: false, componentDidMount() { this.loadContacts(); //carrega os contatos iniciais this.scrollListener = window.addEventListener('scroll', (event) => {//escuta o scroll this.handleScroll(event); }); } handleScroll = () => { const { scrolling, totalPages, page } = this.state; //pega os 3 pra fora do state if(scrolling) return; //se ja está scrollando, retorna true if(totalPages <= page) return; //se o total de páginas é menor ou igual a page const lastLi = document.querySelector('ul.contacts > li:last-child');//pegando o último li const lastLiOffset = lastLi.offsetTop + lastLi.clientHeight; const pageOffset = window.pageYOffset + window.innerHeight; var bottomOffSet = 20; if(pageOffset > lastLiOffset - bottomOffSet) this.loadMore(); } loadMore = () => { // event.preventDefault(); this.setState(prevState => ({ page: prevState.page + 1, scrolling: true, }), this.loadContacts); } ``` But i dont know where i can pass the page parameter. The explanation of this code: it was used on a API with page number and per page parameters. The problem is that Github API does not offer this in repositories list, so, this is why i'm using slice.
2019/07/04
[ "https://Stackoverflow.com/questions/56887520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8402168/" ]
You could use the empty line as a loop-breaker: ``` while (s.hasNextLine()){ //no need for "== true" String read = s.nextLine(); if(read == null || read.isEmpty()){ //if the line is empty break; //exit the loop } in.add(read); [...] } ```
You can do somthing like this: ``` while (s.hasNextLine() == true){ String line = s.nextLine(); if ("".equals(line)) { break; } in.add(line); //infinite loop } ```
201,138
Wrote a long story about me moving my mothers washing machine but decided to keep it short: Machine 8 years old, aesthetically in perfect condition other than some exposed sheet metal on the side due to a scratch. Reportedly a few of its programs don't work. The room where I installed it was (according to the previous owner) intended for a washing machine but he never got around to it. It had water but no electrical sockets, only an improvised lamp attached to a heavy gauge 3 core electrical cable sticking out the wall. I removed the lamp and attached a grounded outlet instead. Plugged the machine in, all the lights came on as normal. Reached over to adjust the drain hose and got a mild shock from the scratch of exposed metal on the side. Didn't try if any other parts of it would shock me too, just unplugged it. Searched around the internet, some claim that its normal if the machine isn't grounded properly. I have no clue if the ground on that wire I connected the outlet to actually serves any purpose. The other end of the cable is connected to the electricity of the bathroom next to it but I have no clue where. The bathroom has no sockets either, only lamps. I looked under the housing of a few of the bathroom lamps, they get their electricity via a 2 core cable. In the electrical panel, the switch that controls the bathroom and the washing machine room has a 3 core medium gauge cable leaving and disappearing into a wall. Its not the same kind of cable as either the washing machine room or the bathroom have. So now I'm suspecting that the grounding in that room might be fake and as such would justify the shock that the machine gave me. Is that a plausible scenario? Or should I just be looking for a new washing machine? This took place in europe, 230V is the standard. Blue and brown wires make zap, yellow/green stripe wire is supposed to be ground. EDIT: Looked up how to test for grounding, turns out all I needed was a multimeter, I got one of those. Surely enough, the cable in the washing machine room is not grounded. Also tested other outlets around the house, the grounding works in most places, other than the washing machine room, all the basement outlets save for one, the outlets behind the house on the patio don't work at all.
2020/08/15
[ "https://diy.stackexchange.com/questions/201138", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/51018/" ]
Well, don't be confused by what happens in North America. There, some very silly things were done to dryers regarding bootlegging ground off neutral, and so dryers are a holy terror. Not Your Problem. Your washer hooks up just like a normal appliance - Hot, Neutral and Earth. I suspect the root of your problem is this "improvised" electrical connection. The first thing you did - that is a cardinal sin in Britain and European influenced areas - is **you attached an appliance to a lighting circuit**. Many lighting circuits are some piddly small ampacity like 3 or 6 amps. They are simply not intended for a large appliance. Only lighting can be on those circuits. It's possible that light was herky-jerked off an appliance circuit, but you should have investigated that. Further, it's likely the lighting cord that was run for it, was "lighting-sized". So too small to run a large appliance like a washer. Again, in Europe, never convert a lighting outlet to an appliance outlet! Generally anytime you find hork-a-dork wiring like that, you need to go through it "with a fine-tooth comb". Think about it -- when you're *looking right at* several Code violations, it would be insane to assume the rest of it was done safely to Code. What you really need to do is find out whether DIY is allowed in your country, and either *properly* install a receptacle outlet in the room off an appliance circuit, or wire a dedicated circuit (that's Code in *El NEC* countries like Panama and the USA), or have a professional do it if local Code requires that.
I would verify the polarization is correct. When I was a kid all of my grand mothers house outlets were non polarized. I remember getting the tingle touching the metal toaster. My grandma pulled the cord out flipped it over and plugged it back in. I remember trying that as I got older with socks on then with shoes until I finally rewired that house in my 2nd year as an apprentice. She was so proud. But I think with no ground and the polarity being swapped may be your issue since the washer is working. My example is 120v but the same thing would happen with shoes on on a higher voltage.
11,420,224
According to this quirksmode article, <http://www.quirksmode.org/css/display.html> > > A block has some whitespace above and below it and tolerates no HTML > elements next to it, except when ordered > > > Are the whitespace above or below stated in pixels or is it just 'whitespace'?.
2012/07/10
[ "https://Stackoverflow.com/questions/11420224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492293/" ]
In the given context, "whitespace" is a gross misnomer. Whitespace in terms of text should *never* directly interfere with the layout of non-inline block boxes; what you should see between block boxes are *margins* (usually of said boxes), which are completely different. Margins are indeed stated in pixels. In fact, they may be stated with any CSS length unit; see the [`margin` properties](http://www.w3.org/TR/CSS21/box.html#margin-properties) in the spec. You don't specify a pixel length for whitespace directly for elements that flow inline; that is usually controlled by `font-size` instead, but when working with block boxes that should be entirely irrelevant.
The 'whitespace' is the element's margin and can be controlled via any standard CSS unit (e.g. px, em, %, etc.)
11,420,224
According to this quirksmode article, <http://www.quirksmode.org/css/display.html> > > A block has some whitespace above and below it and tolerates no HTML > elements next to it, except when ordered > > > Are the whitespace above or below stated in pixels or is it just 'whitespace'?.
2012/07/10
[ "https://Stackoverflow.com/questions/11420224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492293/" ]
The 'whitespace' is the element's margin and can be controlled via any standard CSS unit (e.g. px, em, %, etc.)
You can use the padding or margin properties of a CSS element to specify such a thing (in any CSS unit, including pixels). You many specify something like: ``` .class { padding-left: 4px; padding-top: 3px; } ``` The difference between padding and margin has to do with display. The padding property puts some 'whitespace' (rather clear space, whatever is behind the element will show there) between the element and its neighbor. A margin increases the size of your element around its content; the extra space will show up as whatever background the current element has.
11,420,224
According to this quirksmode article, <http://www.quirksmode.org/css/display.html> > > A block has some whitespace above and below it and tolerates no HTML > elements next to it, except when ordered > > > Are the whitespace above or below stated in pixels or is it just 'whitespace'?.
2012/07/10
[ "https://Stackoverflow.com/questions/11420224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492293/" ]
In the given context, "whitespace" is a gross misnomer. Whitespace in terms of text should *never* directly interfere with the layout of non-inline block boxes; what you should see between block boxes are *margins* (usually of said boxes), which are completely different. Margins are indeed stated in pixels. In fact, they may be stated with any CSS length unit; see the [`margin` properties](http://www.w3.org/TR/CSS21/box.html#margin-properties) in the spec. You don't specify a pixel length for whitespace directly for elements that flow inline; that is usually controlled by `font-size` instead, but when working with block boxes that should be entirely irrelevant.
You can use the padding or margin properties of a CSS element to specify such a thing (in any CSS unit, including pixels). You many specify something like: ``` .class { padding-left: 4px; padding-top: 3px; } ``` The difference between padding and margin has to do with display. The padding property puts some 'whitespace' (rather clear space, whatever is behind the element will show there) between the element and its neighbor. A margin increases the size of your element around its content; the extra space will show up as whatever background the current element has.
8,029,871
I am working on a webapp in WinXP, Eclipse Indigo and Google web plugin. I have a simple form that takes a value from user (e.g email) , passes it to a servlet named `SignIn.java` that processes it and saves the email value to the session. The `SignIn` code is very simple , here is what its `doGet` mostly does: ``` String email = req.getParameter("email"); //getting the parameter from html form ... ... HttpSession session = req.getSession(); //create a new session session.setAttribute("email", email); ``` So far so good, I've verified that the values aren't `null` at this point. Now comes the problem, I want to redirect to another servlet (`ShowOnline.java`) that needs to do some more processing. When I write ``` resp.sendRedirect(resp.encodeRedirectURL("/ShowOnlineServlet")); ``` `ShowOnline` gets `null` session values (the same email attribute I saved a second before is now `null`) When I write ``` getServletConfig().getServletContext().getRequestDispatcher("/ShowOnlineServlet"); ``` everything is OK, the email attribute from before isn't `null`! What is going on? `sendRedirect()` just makes your browser send a new request, it shouldn't affect the session scope. I have checked the cookies and they are fine (it is the same session from before for sure since it is the first and only session my webapp creates and furthermore I even bothered and checked the sesison ID's and they're the same on both requests). Why would there be a difference between `sendRedirect()` and `forward()`? The easy solution would be to use `forward()` but I want to get to the bottom of this before I just let go , I think it is important for me to understand what happened. I'm not sure I like the idea of not knowing what's going on on such basic concepts (my whole webapp is very simple and basic at this point since I'm a beginner). Any thoughts ideas or suggestions would be warmly welcome !
2011/11/06
[ "https://Stackoverflow.com/questions/8029871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1032663/" ]
If your `SignIn` servlet is only saving a request parameter (email), then you could also replace the servlet with a [filter](https://stackoverflow.com/tags/servlet-filters/info), e.g. `SignInFilter`. `SignInFilter` would contain the same logic as your `SignIn` servlet (copying the email from the request parameters to the session), but would call the next item in the chain (which will be your `ShowOnline` servlet) instead of doing any redirect/forward. ``` public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(); String email = req.getParameter("email"); session.setAttribute("email", email); chain.doFilter(req, res); // continue to 'ShowOnline' } ``` Set up your form to POST to the `ShowOnline` servlet instead, and configure your new SignInFilter to execute before `ShowOnline` (servlet mapping omitted below for brevity). ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <filter> <filter-name>SignInFilter</filter-name> <filter-class>com.example.SignInFilter</filter-class> </filter> <filter-mapping> <filter-name>SignInFilter</filter-name> <url-pattern>/ShowOnline</url-pattern> </filter-mapping> </web-app> ```
As far as my knowledge, sendRedirect() just redirects the control to another page without transfering the associated request & response object of parent page, but RequestDispatcher(object) will dispatch the ServletRequest and ServletResponse to the page mentioned in path argument { getServletContext().getRequestDispatcher("path")} after that you can either forward the objects to that page or include the objects. So by this container becomes assured that he has to use the previous request and response object from of the parent page instead of creating new one. Specially if you are using session management the best option is RequestDispatcher. Hope that answers the question. To All :- Please correct me if i am wrong. @rs
7,483,233
My question is a continuation of [How to serialize a TimeSpan to XML](https://stackoverflow.com/questions/637933/net-how-to-serialize-a-timespan-to-xml) I have many DTO objects which pass `TimeSpan` instances around. Using the hack described in the original post works, but it requires me to repeat the same bulk of code in each and every DTO for each and every `TimeSpan` property. So, I came with the following wrapper class, which is XML serializable just fine: ``` #if !SILVERLIGHT [Serializable] #endif [DataContract] public class TimeSpanWrapper { [DataMember(Order = 1)] [XmlIgnore] public TimeSpan Value { get; set; } public static implicit operator TimeSpan?(TimeSpanWrapper o) { return o == null ? default(TimeSpan?) : o.Value; } public static implicit operator TimeSpanWrapper(TimeSpan? o) { return o == null ? null : new TimeSpanWrapper { Value = o.Value }; } public static implicit operator TimeSpan(TimeSpanWrapper o) { return o == null ? default(TimeSpan) : o.Value; } public static implicit operator TimeSpanWrapper(TimeSpan o) { return o == default(TimeSpan) ? null : new TimeSpanWrapper { Value = o }; } [JsonIgnore] [XmlElement("Value")] [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public long ValueMilliSeconds { get { return Value.Ticks / 10000; } set { Value = new TimeSpan(value * 10000); } } } ``` The problem is that the XML it produces looks like so: ``` <Duration> <Value>20000</Value> </Duration> ``` instead of the natural ``` <Duration>20000</Duration> ``` My question is can I both "eat the cake and have it whole"? Meaning, enjoy the described hack without cluttering all the DTOs with the same repetitive code and yet have a natural looking XML? Thanks.
2011/09/20
[ "https://Stackoverflow.com/questions/7483233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/80002/" ]
Change `[XmlElement("Value")]` to `[XmlText]`. Then, if you serialize something like this: ``` [Serializable] public class TestEntity { public string Name { get; set; } public TimeSpanWrapper Time { get; set; } } ``` You will get XML like this: ``` <TestEntity> <Name>Hello</Name> <Time>3723000</Time> </TestEntity> ```
You will need to implement IXmlSerializable: ``` [Serializable,XmlSchemaProvider("TimeSpanSchema")] public class TimeSpanWrapper : IXmlSerializable { private TimeSpan _value; public TimeSpanWrapper() { _value = TimeSpan.Zero; } public TimeSpanWrapper(TimeSpan value) { _value = value; } public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { _value = XmlConvert.ToTimeSpan(reader.ReadElementContentAsString()); } public void WriteXml(XmlWriter writer) { writer.WriteValue(XmlConvert.ToString(_value)); } public static XmlQualifiedName TimeSpanSchema(XmlSchemaSet xs) { return new XmlQualifiedName("duration", "http://www.w3.org/2001/XMLSchema"); } public static implicit operator TimeSpan?(TimeSpanWrapper o) { return o == null ? default(TimeSpan?) : o._value; } public static implicit operator TimeSpanWrapper(TimeSpan? o) { return o == null ? null : new TimeSpanWrapper { _value = o.Value }; } public static implicit operator TimeSpan(TimeSpanWrapper o) { return o == null ? default(TimeSpan) : o._value; } public static implicit operator TimeSpanWrapper(TimeSpan o) { return o == default(TimeSpan) ? null : new TimeSpanWrapper { _value = o }; } } ```
44,210,547
I've got a static-hosting enable S3 bucket. There's also a cloudfront distribution that is being powered by that bucket. I've added a CNAME entry to the cloudfront distribution for "mywebsite.com" and when I go to load "mywebsite.com" in my browser, it redirects to `http://my-bucket.s3-us-west-2.amazonaws.com/index.html` Why is this redirect happening? how do I stop that hostname from being rewritten? **Edit: here's the setup details after some suggested changes:** * **cloudfront** - ***alternate domain***: mysite.com * **cloudfront** - ***alternate domain***: www.mysite.com * **cloudfront** - ***origin***: my-bucket.s3-website-us-west-2.amazonaws.com * **route53** - ***hosted zone***: mysite.com * **route53** - ***A record***: 12345.cloudfront.net * **route53** - ***CNAME***: www.mysite.com --> mysite.com **and the effects of this setup:** * Loading: `mysite.com` --> 301 redirects to `my-bucket.s3-website-us-west-2.amazonaws.com` * Loading: `www.mysite.com` --> 301 redirects to `my-bucket.s3-website-us-west-2.amazonaws.com` * Loading: `my-bucket.s3-website-us-west-2.amazonaws.com` --> 200 Success * Loading: `d1h3yk3zemxpnb.cloudfront.net` --> 301 redirects to `my-bucket.s3-website-us-west-2.amazonaws.com` * Loading: `http://my-bucket.s3.amazonaws.com/` --> permissions error
2017/05/26
[ "https://Stackoverflow.com/questions/44210547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680578/" ]
The issue here is a side effect of a misconfiguration. This specific behavior may go away within a few minutes or hours of bucket creation, but the underlying issue won't be resolved. When configuring a static website hosting enabled bucket behind CloudFront, you don't want to select the bucket name from the list of buckets. > > On the Create Distribution page, in the Origin Settings section, for Origin Domain Name, type the Amazon S3 static website hosting endpoint for your bucket. For example, `example.com.s3-website-us-east-1.amazonaws.com`. > > > **Note** > > > Be sure to specify the static website hosting endpoint, not the name of the bucket. > > > <http://docs.aws.amazon.com/AmazonS3/latest/dev/website-hosting-cloudfront-walkthrough.html#create-distribution> > > > Selecting the `example.com.s3.amazonaws.com` entry from the list, rather than typing in the bucket's website hosting endpoint, would be the most likely explanation of this behavior. S3 updates the DNS for the global REST endpoint hierarchy `*.s3.amazonaws.com` with a record sending requests to the right region for the bucket within a short time after bucket creation, and CloudFront appears rely on this for sending the requests to the right place. Before that initial update is complete, S3 will return a redirect and CloudFront returns that redirect to the browser... but all of this indicates that you didn't use the static website hosting endpoint as the origin domain name.
From AWS support <https://forums.aws.amazon.com/thread.jspa?threadID=216814> --- > > This is an expected behavior when you create a new bucket. The > following pages explains the concept: > <http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html> > > > "Amazon S3 routes any virtual hosted–style requests to the US East (N. > Virginia) region by default if you use the US East (N. Virginia) > endpoint (s3.amazonaws.com), instead of the region-specific endpoint > (for example, s3-eu-west-1.amazonaws.com). When you create a bucket, > in any region, Amazon S3 updates DNS to reroute the request to the > correct location, which might take time. In the meantime, the default > rule applies and your virtual hosted–style request goes to the US East > (N. Virginia) region, and Amazon S3 redirects it with HTTP 307 > redirect to the correct region." > > > Please give some time to S3 until the domain name becomes ready > (normally an hour or so). Also, please note, errors are cached in > CloudFront by default. This means "307 Temporary Redirect" is cached > for 300 seconds unless you change it: > <http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html> > > > In order to test your cloudfront again, please make sure the cache has > been invalidated: > <http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html> > > > Hope that helps. > > > --- The default cache policy has ``` Default TTL 86400 ``` That is, 24h, so you may want to invalidate it rather than wait. From <https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html> --- > > If you use the AWS command line interface (CLI) for invalidating files > and you specify a path that includes the \* wildcard, you must use > quotes (") around the path. > > > For example: aws cloudfront create-invalidation --distribution-id > distribution\_ID --paths "/\*" > > > --- Another thing you can do if nothing of the above works and you are in development and just want to get something accessible is to change the reference or your bucket from ``` global — {bucket-name}.s3.amazonaws.com ``` to ``` regional — {bucket-name}.s3.{region}.amazonaws.com ``` As explained on the forum this will bypass the attempt to use the replicated buckets by going just to one, which will not fail and therefore you won't get a redirect. You will see that easily with `curl` ``` $ curl -I http://blah.cloudfront.net/x.svg HTTP/1.1 307 Temporary Redirect Content-Type: application/xml Connection: keep-alive x-amz-bucket-region: eu-west-1 $ curl -I http://blah.cloudfront.net/x.svg HTTP/1.1 200 OK Content-Type: image/svg+xml Content-Length: 657 Connection: keep-alive ```
11,077,426
I've got a ruby hash like this ``` [{user_id: 3, purchase: {amount: 2, type_id:3, name:"chocolate"}, {user_id: 4, purchase: {amount: 1, type_id:3, name: "chocolate"}, {user_id: 5, purchase: {amount: 10, type_id:4, name: "penny-candy"}] ``` I want to take the array and merge by the type\_id, sum the amounts, connect the user to the amounts, so the end result would be ``` [{type_id: 3, name: "chocolate", total_amounts:3, user_purchases[{user_id:3, amount:2},user_id:4,amount:1}], {type_id:4, name: "penny-candy", total_amounts: 10, [{user_id:5,amount:2}]}] ``` how would I go from one type of output to the other?
2012/06/18
[ "https://Stackoverflow.com/questions/11077426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48067/" ]
It's a group\_by problem. I'll give you 2: ``` new_array = old_array.group_by{|x| x[:purchase][:type_id]}.values.map do |group| {:type_id => group[0][:purchase][:type_id], :total_amounts => group.map{|g| g[:purchase][:amount]}.reduce(&:+)} end ``` and leave the other 2 as an exercise
I would first simplify it: ``` old_arr = [ {user_id: 3, purchase: {amount: 2, type_id:3, name:"chocolate"}}, {user_id: 4, purchase: {amount: 1, type_id:3, name: "chocolate"}}, {user_id: 5, purchase: {amount: 10, type_id:4, name: "penny-candy"}}] intermediate_arr = old_arr.map{ |h| [h[:user_id], h[:purchase][:amount], h[:purchase][:type_id], h[:purchase][:name]]} ``` This creates the following array: ``` [[3, 2, 3, "chocolate"], [4, 1, 3, "chocolate"], [5, 10, 4, "penny-candy"]] ``` Now you can format it any way you want. I chose to format it like this: ``` new_hash = {} intermediate_arr.each do |arr| if new_hash[arr[2]] new_hash[arr[2]][:purchase] += [{user_id: arr[0], amount: arr[1]}] else new_hash[arr[2]] = {name: arr[3], purchase: [{user_id: arr[0], amount: arr[1]}]} end end ``` Giving: ``` {3=>{:name=>"chocolate", :purchase=>[{:user_id=>3, :amount=>2}, {:user_id=>4, :amount=>1}]}, 4=>{:name=>"penny-candy", :purchase=>[{:user_id=>5, :amount=>10}]}} ```
664,955
I know it's not perhaps in the true spirit of MVC, but I just want to have a single global controller that always gets called no matter *what* the url looks like. For example, it could be: <http://myserver.com/anything/at/all/here.fun?happy=yes&sad=no#yippie> ...and I want that to be passed to my single controller. I intend to obtain the path programmatically and handle it myself--so in other words, I don't really want any routing at all. I've opened up the global.asax file and found where routes are registered, but I just don't know what to put for the 'url' parameter in MapRoute: ``` routes.MapRoute( "Global", "", new { controller = "Global", action = "Index" } ); ``` This (with the blank 'url') works fine for the default path of '/', but if I change it to anything I get a file not found, when I want it to handle *any* url. I also tried "\*", etc. but that didn't work. I couldn't find any definitive reference to the format that the url parameter takes.
2009/03/20
[ "https://Stackoverflow.com/questions/664955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238948/" ]
How about: ``` routes.MapRoute("Global", "{*url}", new { controller = "Global", action = "Index" } ); ``` from [this](https://stackoverflow.com/questions/19941/aspnet-mvc-catch-exception-when-non-existant-controller-is-requested) question
You have not removed the default have you? You need to keep that one. Maybe try: ``` routes.MapRoute("Global", "/", new { controller = "Global", action = "Index" }); ```
62,988,547
How can one get the AWS::StackName without the random generate part? I create a stack: `aws cloudformation create-stack --stack-name test` The stack name returned when evaluated using `AWS:StackName` will included a random generated part, e.g. `test-KB0IKRIHP9PH` What I really want returned is the parameter without the generated part, in this case `test`, omitting `-KB0IKRIHP9PH` --- My use case for this is, when my containers startup, they need to get database credential from a pre created named secret. With the random part in place the service all fail to start initially until the secrets are created. In the code below I assign the StackName to an environment variable. ``` TaskDefinition: Type: AWS::ECS::TaskDefinition Properties: ContainerDefinitions: - Name: website-service Environment: - Name: ENVIRONMENT_VAR Value: !Join ["", ["CF_", {"Ref": "AWS::StackName"}]] ``` --- Here is an update as requested, to show how I create the stack. I am using a MakeFile... ``` create-test: s3 @ip_address=$$(dig @resolver1.opendns.com ANY myip.opendns.com +short); \ read -s -p "Enter DB Root Password: " pswd; \ [[ -z $$pswd ]] && exit 1 || \ aws cloudformation create-stack \ --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM \ --stack-name test \ --template-body file://master.yaml \ --parameters ParameterKey=DBRootPassword,ParameterValue=$$pswd \ ParameterKey=DBHostAccessCidr,ParameterValue=$$ip_address/32 ```
2020/07/20
[ "https://Stackoverflow.com/questions/62988547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/919918/" ]
I test this with a simple template: ```yaml AWSTemplateFormatVersion: 2010-09-09 Resources: Bucket: Type: AWS::S3::Bucket Outputs: Stack: Value: !Sub ${AWS::StackName} ``` The **Stack** output variable exactly matched the name of the stack that I created. There were *no* random characters. I launched the stack via the console.
If `AWS::StackName` is in the form of `test-KB0IKRIHP9PH`, then you can get `test` and perform the Join as follows: ``` Environment: - Name: ENVIRONMENT_VAR Value: !Join ["", ["CD_", !Select [0, !Split ['-', !Ref "AWS::StackName"] ] ] ] ```
62,988,547
How can one get the AWS::StackName without the random generate part? I create a stack: `aws cloudformation create-stack --stack-name test` The stack name returned when evaluated using `AWS:StackName` will included a random generated part, e.g. `test-KB0IKRIHP9PH` What I really want returned is the parameter without the generated part, in this case `test`, omitting `-KB0IKRIHP9PH` --- My use case for this is, when my containers startup, they need to get database credential from a pre created named secret. With the random part in place the service all fail to start initially until the secrets are created. In the code below I assign the StackName to an environment variable. ``` TaskDefinition: Type: AWS::ECS::TaskDefinition Properties: ContainerDefinitions: - Name: website-service Environment: - Name: ENVIRONMENT_VAR Value: !Join ["", ["CF_", {"Ref": "AWS::StackName"}]] ``` --- Here is an update as requested, to show how I create the stack. I am using a MakeFile... ``` create-test: s3 @ip_address=$$(dig @resolver1.opendns.com ANY myip.opendns.com +short); \ read -s -p "Enter DB Root Password: " pswd; \ [[ -z $$pswd ]] && exit 1 || \ aws cloudformation create-stack \ --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM \ --stack-name test \ --template-body file://master.yaml \ --parameters ParameterKey=DBRootPassword,ParameterValue=$$pswd \ ParameterKey=DBHostAccessCidr,ParameterValue=$$ip_address/32 ```
2020/07/20
[ "https://Stackoverflow.com/questions/62988547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/919918/" ]
**Nested Stack Names** contain a random hash. To overcome the problem, pass the `AWS::StackName` as a parameter to the nested stack, from the root/master stack. --- In the example below, the `AWS::StackName` is passed as a parameter. **master.yaml** ``` Resources: S3: Type: AWS::CloudFormation::Stack Properties: TemplateURL: https://s3-ap-southeast-2.amazonaws.com/...s3.yaml Parameters: ParamStackName: !Ref AWS::StackName ``` --- **s3.yaml** Notice: `!Ref AWS::StackName` while **nested**, will include a random hash. ``` Parameters: ParamStackName: Type: String Resources: MyS3: Type: AWS::S3::Bucket Properties: # Using !Ref AWS::StackName will include the random hash BucketName: !Ref ParamStackName ```
If `AWS::StackName` is in the form of `test-KB0IKRIHP9PH`, then you can get `test` and perform the Join as follows: ``` Environment: - Name: ENVIRONMENT_VAR Value: !Join ["", ["CD_", !Select [0, !Split ['-', !Ref "AWS::StackName"] ] ] ] ```
78,354
From time to time (quite randomly), Nemo on my Linux Mint 14 Cinnamon starts looking like this ![enter image description here](https://i.stack.imgur.com/w578e.png) When usually it looks like this: ![enter image description here](https://i.stack.imgur.com/dSNt7.png) Restarting Cinnamon (`Alt`+`F2`, `r`, `Enter`) doesn't help, I need to log out, and then log on. Can someone tell me, * (I guess, that something with [X Window System](http://en.wikipedia.org/wiki/X_Window_System) had crashed. `dmesg` doesn't show anything.) how to diagnose, what really happened? (*update: it seems it is `gnome-settings-daemon` crash*) * how to restore the normal theme without logging off (which requires closing all programs)? * how to minimize frequency of such things? --- Suspicious entries in `xsession-errors.lob` ``` [0x7f9590006068] main input error: ES_OUT_SET_(GROUP_)PCR is called too late (pts_delay increased to 300 ms) [0x7f9590006068] main input error: ES_OUT_RESET_PCR called [0x7f9590006068] main input error: ES_OUT_SET_(GROUP_)PCR is called too late (pts_delay increased to 1108 ms) [0x7f9590006068] main input error: ES_OUT_RESET_PCR called ``` (...) ``` [h264 @ 0x7f95790fc160] Missing reference picture [h264 @ 0x7f95790fc160] decode_slice_header error [h264 @ 0x7f95790fc160] mmco: unref short failure [h264 @ 0x7f95790fc160] concealing 1620 DC, 1620 AC, 1620 MV errors [h264 @ 0x7f95790fc160] Missing reference picture [h264 @ 0x7f95790fc160] Missing reference picture [h264 @ 0x7f95790fc160] Missing reference picture ``` (...) ``` No such schema 'com.canonical.unity-greeter' ``` Suspicious entries in syslog: ``` Jun 13 01:03:45 adam-N56VZ kernel: [49764.694213] gnome-settings-[4198]: segfault at 188b2 ip 00007f2e46acf0a6 sp 00007fff8acb45d0 error 4 in libgdk-3.so.0.600.0[7f2e46a8c000+7c000] Jun 13 01:03:52 adam-N56VZ gnome-session[4098]: WARNING: Application 'gnome-settings-daemon.desktop' killed by signal 11 ``` (...) ``` Jun 13 01:40:59 adam-N56VZ laptop-mode: Warning: Configuration file /etc/laptop-mode/conf.d/board-specific/*.conf is not readable, skipping. ``` --- Update: It seems, that the this behavior can be reproduced by killing `gnome-settings-daemon`. The question remains on how to restore it? Simply running it as user or root doesn't change anything, even with restarting cinnamon (`Alt`+`F2`, `r`, `Enter`). And the hardest question: how to prevent it from happening? Since it is a crash I guess I'll need to follow the procedure with filing bug report. But who's fault it is? Gnome's or Cinnamon's? Or maybe some other component is at fault here?
2013/06/05
[ "https://unix.stackexchange.com/questions/78354", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/17765/" ]
It seems that `cinnamon-settings-daemon`/`gnome-settings-daemon` is not running. You can put it in startup aplications to make sure it starts when you log in.
finally i got solution. Simply open **Startup Applications** from *Control Center*, check the option **MATE Settings Daemon** or **Cinnamon Settings Daemon** (according to your Desktop Environment) and that’s it. Now login again and problem solved.
10,772,686
to be able to add annotations to a pdf file in linux, i have to reset the "Commenting" security setting in the pdf document. `qpdf --decrypt input.pdf output.pdf` should remove any passwords or "encryption" ([according to this post](https://superuser.com/questions/216616/does-pdftk-respect-pdf-security-flags)) `pdftk input input.pdf output output.pdf allow AllFeatures` should set all document securities (including "Commenting") to be allowed After applying both commands, in acroread i can still see (file -> document -> security tab) that commenting is not allowed. How can I reset this security property?
2012/05/27
[ "https://Stackoverflow.com/questions/10772686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989762/" ]
The command `qpdf --decrypt input.pdf output.pdf` removes the 'owner' password. But it only works if there is no 'user' password set. Once the owner password is removed, the `output.pdf` should already have unset *all* security protection and have allowed commenting. Needless to run your extra `pdftk ...` command then... BTW, your `allow` parameter in your `pdftk` call will not work the way you quoted your command. The `allow` permissions will only be applied if you also... * ...either specify an encryption strength * ...or give a user or an owner password Try the following to find out the detailed security settings of the file(s): ``` qpdf --show-encryption input.pdf qpdf --show-encryption output.pdf ```
The question is a common one and the answer is simple. Do not use acroread to check a document's security settings. qpdf is correctly removing the restrictions, but acroread does not know that. Acroread is purposefully limited by Adobe so that it will not compete with Acrobat. (For example, you can type in forms, but you can't save the document).
35,181,472
I faced the problem that I dont understand how itertools.takewhile() code works. ``` import itertools z = [3,3,9,4,1] zcycle = itertools.cycle(z) next_symbol = zcycle.next() y = list(itertools.takewhile(lambda symbol: symbol == next_symbol or symbol == 9, zcycle)) print y ``` my code suppose to give me elements of the list from the beginning if they are the same or if element is equal to 9. So once we hit element that differs from previous one we should stop. I expected that the outcome would be `[3, 3]` but instead I got `[3, 9]`. Why we miss the very first element of the list? and is it possible somehow to get output equal to `[3, 3, 9]`?
2016/02/03
[ "https://Stackoverflow.com/questions/35181472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5366684/" ]
You removed the first `3` from the sequence here: ``` next_symbol = zcycle.next() ``` That advances `zcycle` to the next element, so it'll yield one more `3`, not two. Don't call `next()` on the `zcycle` object; perhaps use `z[0]` instead: ``` next_symbol = z[0] ``` Now `zcycle` will yield `3`, then another `3`, then `9`, after which the `takewhile()` condition will be `False` and all iteration will stop.
it is possible to do it with tee an groupby if you had an actul iterator: ``` from itertools import tee, groupby, cycle z = [3, 3, 9, 4, 1] zcycle = cycle(z) a, b = tee(zcycle) next_symbol = next(b) grps = groupby(a, key=lambda symbol: symbol in {9, next(b), next_symbol}) g = next(grps) if g[0]: print(list(g[1])) ```
55,022,363
I making a ASP.NET CORE 2.1 website. The database in Visual studio works fine, but when i deployed to the IIS which on another computer, the database not work. In log, the error: ``` fail: Microsoft.EntityFrameworkCore.Query[10100] An exception occurred in the database while iterating the results of a query for context type 'WebApplication3.Data.ApplicationDbContext'. System.ArgumentException: Keyword not supported: 'id'. ................. ``` The connectionstring in the web.config: ``` "ConnectionStrings": { "DefaultConnection": "Server=.\\SQLEXPRESS;Database=XXXX;Trusted_Connection=True;ID=XXXXXXX;pwd=XXXXXXXXX;MultipleActiveResultSets=true " ``` }, I read lot of articles for this, but i cant add any plus tags for the connection string, wil be error, the connection string is bad? When i run the project the in Visual Studio i can use database and i see the database in the SQL Server Managment Studio. For the database i use the "stock database" when created a the project in visual studio. Because i use Entity Framework i need another format connection string? [Stock Databse](https://i.stack.imgur.com/r6B46.png)
2019/03/06
[ "https://Stackoverflow.com/questions/55022363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850219/" ]
Oh my jesus... I figured out the answer.. Just one f\*... word... In connenction strig DONT USE *database*, the correct word is **Initial Catalog** and maybe use user id instead of id. Correct string: ``` "DefaultConnection": "Server=.\\SQLEXPRESS;Initial Catalog=XXX;Trusted_Connection=False;user id=XXX;pwd=XXX;MultipleActiveResultSets=true " ```
Based on my research if the server have morethan one databases .net core suffers to identify if the dabtase is mentioned in connection string. This is not a problem if you use .Net framework, instead of .Net Core.
59,164
Um hervorzuheben, dass ein Wort euphemistisch gebraucht wird oder, dass es eigentlich nicht ganz seinen normalerweise zugedachten Inhalt widerspiegelt, kann man Anführungszeichen nutzen: > > Hans "arbeitet" schwer im Home-Office. (Hans schaut eigentlich eine Serie auf Netflix) > > > > > Hans hat gestern seine Wohnung "aufgeräumt". (Hans hat einen Teller in den Geschirrspüler geräumt). > > > Wie verhält es sich denn, wenn das Verb geteilt ist? > > Hans räumt morgen seine Wohnung auf. > > > > > a) Hans "räumt" morgen "auf" > > b) Hans "räumt" morgen auf > > c) Hans räumt morgen "auf" > > >
2020/06/30
[ "https://german.stackexchange.com/questions/59164", "https://german.stackexchange.com", "https://german.stackexchange.com/users/30455/" ]
Ignoriere die pedantischen Angriffe gegen die Vorstellung von Ironie in der Sprache. Wenn man ein Verb durch Anführungszeichen hervorhebt, egal zu welchem Zweck, und das Verb geteilt wird, dann stehen die Anführungszeichen natürlich um beide Teile, also ist a) richtig. (Am Rande: Davon unabhängig muß man natürlich darauf achten, daß *eine* der Verwendungen von "" ist, ein wörtliches Zitat zu kennzeichnen, und wörtliche Zitate dürfen nicht verändert werden. Wenn also das Originalzitat das Verb ungetrennt verwendete, z.B. im Nebensatz, dann darf man es nicht so umformulieren, daß das Verb getrennt wird.)
Weder, noch und schon gar nicht. > > Hans räumt morgen seine Wohnung auf. > > > Wenn es Ironie sein soll, und man will diese unbedingt mit Anführungszeichen ausdrücken, dann kommt der ganze Satzteil in solche: > > Hans "räumt morgen seine Wohnung auf". > > > Es ist für den Leser natürlich nicht ersichtlich, worauf sich die Ironie bezieht. Behauptet Hans selbst, dass sein Tellerrücken aufräumen sei? Wem gegenüber? Dass es nur ein Teller war kann der Leser natürlich nicht erraten. Verrät man es, dann braucht man die Anführungszeichen nicht.
16,966,812
I use this layout : ``` <?xml version="1.0" encoding="UTF-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" android:background="#00868B"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_alignParentTop="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_below="@+id/title" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" android:text="@string/getloc" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" /> <Button .. android:layout_width="match_parent" .. android:layout_alignParentBottom="true" /> </RelativeLayout> </ScrollView> ``` There is no scrollview. I want when the user enters sth in second textview to "go down" because else the textview gets bigger but the first button is steady and blocks the view.
2013/06/06
[ "https://Stackoverflow.com/questions/16966812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/583464/" ]
I just had problem getting SASS source maps getting to work on my host.... I had completely no idea what could be the solution because the map-file was generated, the sourceMappingURL-tag was present and everything was fine, Chrome was configured and I even used the canary-version..... but then I got it: I used a development Webserver with a self signed SSL-certificate which I need to test my authentication etc.. When I switched to plain HTTP without encryption my sourcemaps got working instantly.
For anyone who has tried everything and can't get css source maps to work, make sure the source map is actually accessible via URL. In my case, rewrite rules were not exposing the source map. Once I changed that, it worked immediately.
16,966,812
I use this layout : ``` <?xml version="1.0" encoding="UTF-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" android:background="#00868B"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_alignParentTop="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_below="@+id/title" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" android:text="@string/getloc" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" /> <Button .. android:layout_width="match_parent" .. android:layout_alignParentBottom="true" /> </RelativeLayout> </ScrollView> ``` There is no scrollview. I want when the user enters sth in second textview to "go down" because else the textview gets bigger but the first button is steady and blocks the view.
2013/06/06
[ "https://Stackoverflow.com/questions/16966812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/583464/" ]
Try following the tutorial in [this link](http://net.tutsplus.com/tutorials/html-css-techniques/developing-with-sass-and-chrome-devtools/). I just set this up this morning and it's working fine for me. This will let you inspect an element and then find what the corresponding SCSS declaration is.
As @gerryster said, Chrome now supports `source maps proposal v 3`. I wrote blog post about [Debugging Rails 4 CoffeeScript and Sass source files in Google Chrome](http://blog.vhyza.eu/blog/2013/09/22/debugging-rails-4-coffeescript-and-sass-source-files-in-google-chrome/).
16,966,812
I use this layout : ``` <?xml version="1.0" encoding="UTF-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" android:background="#00868B"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_alignParentTop="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_below="@+id/title" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" android:text="@string/getloc" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" /> <Button .. android:layout_width="match_parent" .. android:layout_alignParentBottom="true" /> </RelativeLayout> </ScrollView> ``` There is no scrollview. I want when the user enters sth in second textview to "go down" because else the textview gets bigger but the first button is steady and blocks the view.
2013/06/06
[ "https://Stackoverflow.com/questions/16966812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/583464/" ]
For anyone who has tried everything and can't get css source maps to work, make sure the source map is actually accessible via URL. In my case, rewrite rules were not exposing the source map. Once I changed that, it worked immediately.
In case anyone else ends up here after struggling to make Chrome work with Sass, you need to run a different command to generate source maps via command line: `sass --watch --sourcemap sass/styles.scss:styles.css` instead of `--debug-info`. The newer versions of Chrome now support source maps instead of the in-css debug info. More info: <https://developers.google.com/chrome-developer-tools/docs/tips-and-tricks#debugging-sass>
16,966,812
I use this layout : ``` <?xml version="1.0" encoding="UTF-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" android:background="#00868B"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_alignParentTop="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_below="@+id/title" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" android:text="@string/getloc" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" /> <Button .. android:layout_width="match_parent" .. android:layout_alignParentBottom="true" /> </RelativeLayout> </ScrollView> ``` There is no scrollview. I want when the user enters sth in second textview to "go down" because else the textview gets bigger but the first button is steady and blocks the view.
2013/06/06
[ "https://Stackoverflow.com/questions/16966812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/583464/" ]
As @gerryster said, Chrome now supports `source maps proposal v 3`. I wrote blog post about [Debugging Rails 4 CoffeeScript and Sass source files in Google Chrome](http://blog.vhyza.eu/blog/2013/09/22/debugging-rails-4-coffeescript-and-sass-source-files-in-google-chrome/).
In case anyone else ends up here after struggling to make Chrome work with Sass, you need to run a different command to generate source maps via command line: `sass --watch --sourcemap sass/styles.scss:styles.css` instead of `--debug-info`. The newer versions of Chrome now support source maps instead of the in-css debug info. More info: <https://developers.google.com/chrome-developer-tools/docs/tips-and-tricks#debugging-sass>
16,966,812
I use this layout : ``` <?xml version="1.0" encoding="UTF-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" android:background="#00868B"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_alignParentTop="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_below="@+id/title" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" android:text="@string/getloc" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" /> <Button .. android:layout_width="match_parent" .. android:layout_alignParentBottom="true" /> </RelativeLayout> </ScrollView> ``` There is no scrollview. I want when the user enters sth in second textview to "go down" because else the textview gets bigger but the first button is steady and blocks the view.
2013/06/06
[ "https://Stackoverflow.com/questions/16966812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/583464/" ]
The problem is that Chrome developer tools recently changed what version of source maps it supports. The article you mention details how to set up an older style of CSS source maps. However, Chrome now supports [version 3 source maps](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.75yo6yoyk7x5). The new source maps puts the mapping in a separate \*.css.map file instead of inline in the compiled CSS file. The benefits of the new format is that it is much smaller and does not break styles for older Internet Explorers. The [link](http://net.tutsplus.com/tutorials/html-css-techniques/developing-with-sass-and-chrome-devtools/) that @justin-smith provided should point you in the right direction. However, from my findings, even though the pre-released version 3.3 of the SASS gem knows how to generate the .map files, there still needs to be support from the sass-rails gem to correctly serve these files from the Rails asset pipeline. I created a [repo](https://github.com/gerryster/rails4-v3-sourcemaps) in order to figure out the current state of support for v3 sass source maps in Rails. There may be a way to short circuit the asset pipeline and have the sass gem precompile files and put them in a directory which comes early in the asset path. However, I have not figured out how to to this.
For anyone who has tried everything and can't get css source maps to work, make sure the source map is actually accessible via URL. In my case, rewrite rules were not exposing the source map. Once I changed that, it worked immediately.
16,966,812
I use this layout : ``` <?xml version="1.0" encoding="UTF-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" android:background="#00868B"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_alignParentTop="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_below="@+id/title" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" android:text="@string/getloc" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" /> <Button .. android:layout_width="match_parent" .. android:layout_alignParentBottom="true" /> </RelativeLayout> </ScrollView> ``` There is no scrollview. I want when the user enters sth in second textview to "go down" because else the textview gets bigger but the first button is steady and blocks the view.
2013/06/06
[ "https://Stackoverflow.com/questions/16966812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/583464/" ]
Try following the tutorial in [this link](http://net.tutsplus.com/tutorials/html-css-techniques/developing-with-sass-and-chrome-devtools/). I just set this up this morning and it's working fine for me. This will let you inspect an element and then find what the corresponding SCSS declaration is.
For anyone who has tried everything and can't get css source maps to work, make sure the source map is actually accessible via URL. In my case, rewrite rules were not exposing the source map. Once I changed that, it worked immediately.
16,966,812
I use this layout : ``` <?xml version="1.0" encoding="UTF-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" android:background="#00868B"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_alignParentTop="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_below="@+id/title" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" android:text="@string/getloc" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" /> <Button .. android:layout_width="match_parent" .. android:layout_alignParentBottom="true" /> </RelativeLayout> </ScrollView> ``` There is no scrollview. I want when the user enters sth in second textview to "go down" because else the textview gets bigger but the first button is steady and blocks the view.
2013/06/06
[ "https://Stackoverflow.com/questions/16966812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/583464/" ]
I just had problem getting SASS source maps getting to work on my host.... I had completely no idea what could be the solution because the map-file was generated, the sourceMappingURL-tag was present and everything was fine, Chrome was configured and I even used the canary-version..... but then I got it: I used a development Webserver with a self signed SSL-certificate which I need to test my authentication etc.. When I switched to plain HTTP without encryption my sourcemaps got working instantly.
As @gerryster said, Chrome now supports `source maps proposal v 3`. I wrote blog post about [Debugging Rails 4 CoffeeScript and Sass source files in Google Chrome](http://blog.vhyza.eu/blog/2013/09/22/debugging-rails-4-coffeescript-and-sass-source-files-in-google-chrome/).
16,966,812
I use this layout : ``` <?xml version="1.0" encoding="UTF-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" android:background="#00868B"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_alignParentTop="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_below="@+id/title" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" android:text="@string/getloc" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" /> <Button .. android:layout_width="match_parent" .. android:layout_alignParentBottom="true" /> </RelativeLayout> </ScrollView> ``` There is no scrollview. I want when the user enters sth in second textview to "go down" because else the textview gets bigger but the first button is steady and blocks the view.
2013/06/06
[ "https://Stackoverflow.com/questions/16966812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/583464/" ]
The problem is that Chrome developer tools recently changed what version of source maps it supports. The article you mention details how to set up an older style of CSS source maps. However, Chrome now supports [version 3 source maps](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.75yo6yoyk7x5). The new source maps puts the mapping in a separate \*.css.map file instead of inline in the compiled CSS file. The benefits of the new format is that it is much smaller and does not break styles for older Internet Explorers. The [link](http://net.tutsplus.com/tutorials/html-css-techniques/developing-with-sass-and-chrome-devtools/) that @justin-smith provided should point you in the right direction. However, from my findings, even though the pre-released version 3.3 of the SASS gem knows how to generate the .map files, there still needs to be support from the sass-rails gem to correctly serve these files from the Rails asset pipeline. I created a [repo](https://github.com/gerryster/rails4-v3-sourcemaps) in order to figure out the current state of support for v3 sass source maps in Rails. There may be a way to short circuit the asset pipeline and have the sass gem precompile files and put them in a directory which comes early in the asset path. However, I have not figured out how to to this.
In case anyone else ends up here after struggling to make Chrome work with Sass, you need to run a different command to generate source maps via command line: `sass --watch --sourcemap sass/styles.scss:styles.css` instead of `--debug-info`. The newer versions of Chrome now support source maps instead of the in-css debug info. More info: <https://developers.google.com/chrome-developer-tools/docs/tips-and-tricks#debugging-sass>
16,966,812
I use this layout : ``` <?xml version="1.0" encoding="UTF-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" android:background="#00868B"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_alignParentTop="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_below="@+id/title" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" android:text="@string/getloc" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" /> <Button .. android:layout_width="match_parent" .. android:layout_alignParentBottom="true" /> </RelativeLayout> </ScrollView> ``` There is no scrollview. I want when the user enters sth in second textview to "go down" because else the textview gets bigger but the first button is steady and blocks the view.
2013/06/06
[ "https://Stackoverflow.com/questions/16966812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/583464/" ]
Try following the tutorial in [this link](http://net.tutsplus.com/tutorials/html-css-techniques/developing-with-sass-and-chrome-devtools/). I just set this up this morning and it's working fine for me. This will let you inspect an element and then find what the corresponding SCSS declaration is.
I just had problem getting SASS source maps getting to work on my host.... I had completely no idea what could be the solution because the map-file was generated, the sourceMappingURL-tag was present and everything was fine, Chrome was configured and I even used the canary-version..... but then I got it: I used a development Webserver with a self signed SSL-certificate which I need to test my authentication etc.. When I switched to plain HTTP without encryption my sourcemaps got working instantly.
16,966,812
I use this layout : ``` <?xml version="1.0" encoding="UTF-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" android:background="#00868B"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_alignParentTop="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_below="@+id/title" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" android:text="@string/getloc" /> <Button .. android:layout_width="match_parent" android:layout_height="50dp" /> <Button .. android:layout_width="match_parent" .. android:layout_alignParentBottom="true" /> </RelativeLayout> </ScrollView> ``` There is no scrollview. I want when the user enters sth in second textview to "go down" because else the textview gets bigger but the first button is steady and blocks the view.
2013/06/06
[ "https://Stackoverflow.com/questions/16966812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/583464/" ]
The problem is that Chrome developer tools recently changed what version of source maps it supports. The article you mention details how to set up an older style of CSS source maps. However, Chrome now supports [version 3 source maps](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.75yo6yoyk7x5). The new source maps puts the mapping in a separate \*.css.map file instead of inline in the compiled CSS file. The benefits of the new format is that it is much smaller and does not break styles for older Internet Explorers. The [link](http://net.tutsplus.com/tutorials/html-css-techniques/developing-with-sass-and-chrome-devtools/) that @justin-smith provided should point you in the right direction. However, from my findings, even though the pre-released version 3.3 of the SASS gem knows how to generate the .map files, there still needs to be support from the sass-rails gem to correctly serve these files from the Rails asset pipeline. I created a [repo](https://github.com/gerryster/rails4-v3-sourcemaps) in order to figure out the current state of support for v3 sass source maps in Rails. There may be a way to short circuit the asset pipeline and have the sass gem precompile files and put them in a directory which comes early in the asset path. However, I have not figured out how to to this.
As @gerryster said, Chrome now supports `source maps proposal v 3`. I wrote blog post about [Debugging Rails 4 CoffeeScript and Sass source files in Google Chrome](http://blog.vhyza.eu/blog/2013/09/22/debugging-rails-4-coffeescript-and-sass-source-files-in-google-chrome/).
24,472,223
Consider HTML code below. In that code I am dynamically adding a DIV with a class "dynamic" and I am expecting that it would pick up the CSS attributes defined for that class which in turn would show a black square. The black square, however, never appears. Am I doing anything wrong here? If not, then is there a way to define CSS attributes upfront and dynamically add elements or should I always add css attributes to the element after it was added (which seems inconvenient). Thanks. ``` <!DOCTYPE html> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script> $(function() { $("body").append( $("<div/>").attr("class", "dynamic") ) }); </script> <html> <head> <style> .dynamic { backgorund-color: black; width: 100px; height: 130px; left: 10px; top: 10px; } </style> </head> <body> </body> </html> ```
2014/06/29
[ "https://Stackoverflow.com/questions/24472223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128461/" ]
In your class, you spelled background incorrectly: ``` .dynamic { background-color: black; width: 100px; height: 130px; left: 10px; top: 10px; } ``` I also recommend jQuery's `.addClass()` instead of `.attr()` ``` $("<div/>").addClass("dynamic") ``` <http://jsbin.com/qufeq/1/>
You have misspelled `background-color`. You might want to double-check your spelling in the future, because it is much easier to fix these trivial bugs than to wait for answers.
56,769,100
I am using officeGen to generate word documents. > > generateDocumentService.js > > > ``` var generateReportFromTableData = function (tableData) { console.log('tableData: ', tableData); var docx = officegen({ type: 'docx', orientation: 'portrait', pageMargins: { top: 1000, left: 1000, bottom: 1000, right: 1000 } }) docx.on('error', function (err) { console.log(err) }) pObj = docx.createP({ align: 'center' }) pObj.addText('Business Process General Information', { border: 'dotted', borderSize: 12, borderColor: '88CCFF', bold: true }) var table = [ [ { val: 'Ref', opts: { cellColWidth: 2000, b: true, sz: '10', shd: { fill: '7F7F7F', themeFill: 'Arial', themeFillTint: '20' }, fontFamily: 'Arial' } }, { val: 'Risk Statements', opts: { cellColWidth: 2000, b: true, sz: '10', shd: { fill: '7F7F7F', themeFill: 'Arial', themeFillTint: '20' }, fontFamily: 'Arial' } }, { val: 'Max Impact', opts: { cellColWidth: 2000, b: true, sz: '10', shd: { fill: '7F7F7F', themeFill: 'Arial', themeFillTint: '20' }, fontFamily: 'Arial' } }, { val: 'Control effectiveness', opts: { cellColWidth: 2000, b: true, sz: '10', shd: { fill: '7F7F7F', themeFill: 'Arial', themeFillTint: '20' }, fontFamily: 'Arial' } }, { val: 'Recommended Risk Rating', opts: { cellColWidth: 2000, b: true, sz: '10', shd: { fill: '7F7F7F', themeFill: 'Arial', themeFillTint: '20' }, fontFamily: 'Arial' } }, { val: 'Frequency', opts: { cellColWidth: 2000, b: true, sz: '10', shd: { fill: '7F7F7F', themeFill: 'Arial', themeFillTint: '20' }, fontFamily: 'Arial' } }, { val: 'Impact', opts: { cellColWidth: 2000, b: true, sz: '10', shd: { fill: '7F7F7F', themeFill: 'Arial', themeFillTint: '20' }, fontFamily: 'Arial' } }, { val: 'Validated Review Risk Rating', opts: { cellColWidth: 2000, b: true, sz: '10', shd: { fill: '7F7F7F', themeFill: 'Arial', themeFillTint: '20' }, fontFamily: 'Arial' } }, { val: 'Rational For Risk Adjustment', opts: { cellColWidth: 2000, b: true, sz: '20', shd: { fill: '7F7F7F', themeFill: 'Arial', themeFillTint: '20' }, fontFamily: 'Arial' } }, ], ['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'], ['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'], ['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'], ['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'], ['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'], ['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'], ] var tableStyle = { tableColWidth: 4261, tableSize: 72, tableColor: 'ada', tableAlign: 'left', tableFontFamily: 'Comic Sans MS', borders: true } pObj = docx.createTable(table, tableStyle) var out = fs.createWriteStream(path.join('./docs/Table Data Report.docx')) out.on('error', function (err) { console.log(err) }) async.parallel( [ function (done) { out.on('close', function () { console.log('Finish to create a DOCX file.') done(null) }) docx.generate(out) } ], function (err) { if (err) { console.log('error: ' + err) } // Endif. } ) } ``` Here's the result : [![enter image description here](https://i.stack.imgur.com/VtcJv.png)](https://i.stack.imgur.com/VtcJv.png) Although I really love the OfficeGen framework, I couldn't find a way to choose a size for the text inside the table. It seems that either they have missed it or I couldn't find how. For the table column headers it was possible with this property sz inside their definition: ``` {val: 'Ref', opts: { cellColWidth: 2000, b: true, sz: '10', shd: { fill: '7F7F7F', themeFill: 'Arial', themeFillTint: '20' }, fontFamily: 'Arial' } } ``` But for the data inside the table, for days I couldn't find a way. Nothing inside the tableStyle definition hints to a way to do that: ``` var tableStyle = { tableColWidth: 4261, tableSize: 72, tableColor: 'ada', tableAlign: 'left', tableFontFamily: 'Comic Sans MS', borders: true } ``` Any help?? Thanks! [Generating word document with OfficeGen documentation](https://github.com/Ziv-Barber/officegen/blob/2c482ea3e83c45b4cde7ddfc6a3fe01c24b0f393/manual/README-docx.md)
2019/06/26
[ "https://Stackoverflow.com/questions/56769100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11379139/" ]
You can try out with below code in your configuration ``` var tableStyle = { sz: 20 tableColWidth: 4261, tableSize: 72, tableColor: 'ada', tableAlign: 'left', tableFontFamily: 'Comic Sans MS', borders: true } ``` **sz: 20** - this value will divide by 2 and it sets the font size ie. if you want to set size as 10 you have to set configuration as 20) Mark this as answer . Thumps up if this works for you !!!!
I have done this using only 'column headers' for multiple rows in the table
35,134,394
Let's say that I have six different classes and three of them should use the same constant value. What can we do? We either: * Define as global variable ``` A = 1 class B: def __init__(self): self.a = A class C: def __init__(self): self.a = A class D: def __init__(self): self.a = A ``` * Define as class level for 1 class and give it to another class: ``` class B: A = 1 def __init__(self): self.b = 2 class C: def __init__(self, a): self.a = a self.b = 3 b = B() c = B(a=b.A) ``` The second way I just made up and as for me it's dirty and not convenient. Is there any way to avoid using a global variable?
2016/02/01
[ "https://Stackoverflow.com/questions/35134394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434076/" ]
Use class inheritance: ``` class Holder: a = 4 class A(Holder): pass print A().a ```
You could use inheritance, using `B` as the base class ``` class B: A = 1 def __init__(self): self.b = 2 class C(B): def __init__(self): B.__init__(self) self.a = B.A self.b = 3 b = B() c = C() print c.a ```
72,859,168
I have a pandas data frame from which I'm trying to create a dictionary based on a users age, where age is the key and the data associated with it is the value. So lets say users with age 10 will be in a dictionary {Age:10, Data:[Pole, Carl]} [Table Image](https://i.stack.imgur.com/utCnQ.png)
2022/07/04
[ "https://Stackoverflow.com/questions/72859168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19480593/" ]
Did you try explicitly deleting the l-value overload? ``` template <typename T> auto f(T &&) {} template <typename T> auto f(T &) = delete; ```
You can use `static_assert` if you don't need SFINAE: ``` template<typename T> auto f(T&&) { static_assert(std::is_rvalue_reference_v<T&&>); } ```
72,859,168
I have a pandas data frame from which I'm trying to create a dictionary based on a users age, where age is the key and the data associated with it is the value. So lets say users with age 10 will be in a dictionary {Age:10, Data:[Pole, Carl]} [Table Image](https://i.stack.imgur.com/utCnQ.png)
2022/07/04
[ "https://Stackoverflow.com/questions/72859168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19480593/" ]
As @HolyBlackCat commented, you can use concepts to simplify the function signature ``` #include <type_traits> template<typename T> requires (!std::is_lvalue_reference_v<T>) auto f(T&&) {} ``` Or detect lvalue or rvalue by checking the validity of a lambda expression that accepts an lvalue reference ``` #include <utility> template<typename T> requires (!requires (T&& x) { [](auto&){}(std::forward<T>(x)); }) auto f(T&&) {} ```
You can use `static_assert` if you don't need SFINAE: ``` template<typename T> auto f(T&&) { static_assert(std::is_rvalue_reference_v<T&&>); } ```
13,055
I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations welcome.
2008/08/16
[ "https://Stackoverflow.com/questions/13055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
Boxing & unboxing is the process of converting a primitive value into an object oriented wrapper class (boxing), or converting a value from an object oriented wrapper class back to the primitive value (unboxing). For example, in java, you may need to convert an `int` value into an `Integer` (boxing) if you want to store it in a `Collection` because primitives can't be stored in a `Collection`, only objects. But when you want to get it back out of the `Collection` you may want to get the value as an `int` and not an `Integer` so you would unbox it. Boxing and unboxing is not inherently *bad*, but it is a tradeoff. Depending on the language implementation, it can be slower and more memory intensive than just using primitives. However, it may also allow you to use higher level data structures and achieve greater flexibility in your code. These days, it is most commonly discussed in the context of Java's (and other language's) "autoboxing/autounboxing" feature. Here is a [java centric explanation of autoboxing](http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html).
The language-agnostic meaning of a box is just "an object contains some other value". Literally, *boxing* is an operation to put some value into the box. More specifically, it is an operation to *create* a new box containing the value. After boxing, the boxed value can be accessed from the box object, by *unboxing*. Note that objects (not OOP-specific) in many programming languages are about *identities*, but values are not. Two objects are same iff. they have identities not distinguishable in the program semantics. Values can also be the same (usually under some equality operators), but we do not distinguish them as "one" or "two" *unique* values. Providing boxes is mainly about the effort to distinguish side effects (typically, mutation) from the states on the objects otherwise probably invisible to the users. A language may limit the allowed ways to access an object and hide the identity of the object by default. For example, typical Lisp dialects has no explicit distinctions between objects and values. As a result, the implementation has the freedom to share the underlying storage of the objects until some mutation operations occurs on the object (so the object must be "detached" after the operation from the shared instance to make the effect visible, i.e. the mutated value stored in the object could be different than the other objects having the old value). This technique is sometimes called *object interning*. Interning makes the program more memory efficient at runtime if the objects are shared without frequent needs of mutation, at the cost that: * The users cannot distinguish the identity of the objects. + There are no way to identify an object and to ensure it has states explicitly independent to other objects *in the program* before some side effects have actually occur (and the implementation does not aggressively to do the interning concurrently; this should be the rare case, though). * There may be more problems on interoperations which require to identify different objects for different operations. * There are risks that such assumptions can be false, so the performance is actually made worse by applying the interning. + This depends on the programming paradigm. Imperative programming which mutates objects frequently certainly would not work well with interning. * Implementations depending on COW (copy-on-write) to ensure interning can incur serious performance degradation in concurrent environments. + Even local sharing specifically for a few internal data structures can be bad. For example, ISO C++ 11 did not allow sharing of the internal elements of `std::basic_string` for this reason exactly, even at the cost of breaking the ABI on at least one mainstream implementation (libstdc++). * Boxing and unboxing incur performance penalties. This is obvious especially when these operations can be naively avoided by hand but actually not easy for the optimizer. The concrete measurement of the cost depends (on per-implementation or even per-program basis), though. Mutable cells, i.e. boxes, are well-established facilities exactly to resolve the problems of the 1st and 2nd bullets listed above. Additionally, there can be immutable boxes for implementation of assignment in a functional language. See [SRFI-111](https://srfi.schemers.org/srfi-111/srfi-111.html) for a practical instance. Using mutable cells as function arguments with call-by-value strategy implements the visible effects of mutation being shared between the caller and the callee. The object contained by an box is effectively "called by shared" in this sense. Sometimes, the boxes are referred as references (which is technically false), so the shared semantics are named "reference semantics". This is not correct, because not all references can propagate the visible side effects (e.g. immutable references). References are more about exposing the access *by indirection*, while boxes are the efforts to expose *minimal* details of the accesses like whether indirection or not (which is uninterested and better avoided by the implementation). Moreover, "value semantic" is irrelevant here. Values are not against to references, nor to boxes. All the discussions above are based on call-by-value strategy. For others (like call-by-name or call-by-need), no boxes are needed to shared object contents in this way. Java is probably the first programming language to make these features popular in the industry. Unfortunately, there seem many bad consequences concerned in this topic: * The overall programming paradigm does not fit the design. * Practically, the interning are limited to specific objects like immutable strings, and the cost of (auto-)boxing and unboxing are often blamed. * Fundamental PL knowledge like the definition of the term "object" (as "instance of a class") in the language specification, as well as the descriptions of parameter passing, are biased compared to the the [original](https://classes.cs.uoregon.edu/14S/cis607pl/Papers/fundamental-1967.pdf), [well-known](https://en.wikipedia.org/wiki/Fundamental_Concepts_in_Programming_Languages) meaning, during the adoption of Java by programmers. + At least CLR languages are following the similar parlance. Some more tips on implementations (and comments to [this answer](https://stackoverflow.com/a/25324/2307646)): * Whether to put the objects on the call stacks or the heap is an implementation details, and irrelevant to the implementation of boxes. + Some language implementations do not maintain a contiguous storage as the call stack. + Some language implementations do not even make the (per thread) activation records a linear stack. + Some language implementations do allocate stacks on the free store ("the heap") and transfer slices of frames between the stacks and the heap back and forth. + These strategies has nothing to do boxes. For instance, many Scheme implementations have boxes, with different activation records layouts, including all the ways listed above. * Besides the technical inaccuracy, the statement "everything is an object" is irrelevant to boxing. + Python, Ruby, and JavaScript all use latent typing (by default), so all identifiers referring to some objects will evaluate to values having the same static type. So does Scheme. + Some JavaScript and Ruby implementations use the so-called [NaN-boxing](https://softwareengineering.stackexchange.com/questions/185406/what-is-the-purpose-of-nan-boxing) to allow inlining allocation of some objects. Some others (including [CPython](https://softwareengineering.stackexchange.com/a/185431/154697)) do not. With NaN boxing, a normal `double` object needs no unboxing to access its value, while a value of some other types can be boxed in a host `double` object, and there is no reference for `double` or the boxed value. With the naive pointer approach, a value of host object pointer like `PyObject*` is an object reference holding a box whose boxed value is stored in the dynamically allocated space. + [At least in Python](https://stackoverflow.com/questions/865911/is-everything-an-object-in-python-like-ruby), objects are not "everything". They are also not known as "boxed values" unless you are talking about interoperability with specific implementations.
13,055
I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations welcome.
2008/08/16
[ "https://Stackoverflow.com/questions/13055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
from [C# 3.0 In a Nutshell](http://books.google.com/books?id=_Y0rWd-Q2xkC&pg=PA81&vq=boxing&source=gbs_search_r&cad=1_1&sig=ACfU3U0SIw4v8UZzMH3f5xImIyHZHD90sA#PPA82,M1): > > Boxing is the act of casting a value > type into a reference type: > > > ``` int x = 9; object o = x; // boxing the int ``` > > unboxing is... the reverse: > > > ``` // unboxing o object o = 9; int x = (int)o; ```
The language-agnostic meaning of a box is just "an object contains some other value". Literally, *boxing* is an operation to put some value into the box. More specifically, it is an operation to *create* a new box containing the value. After boxing, the boxed value can be accessed from the box object, by *unboxing*. Note that objects (not OOP-specific) in many programming languages are about *identities*, but values are not. Two objects are same iff. they have identities not distinguishable in the program semantics. Values can also be the same (usually under some equality operators), but we do not distinguish them as "one" or "two" *unique* values. Providing boxes is mainly about the effort to distinguish side effects (typically, mutation) from the states on the objects otherwise probably invisible to the users. A language may limit the allowed ways to access an object and hide the identity of the object by default. For example, typical Lisp dialects has no explicit distinctions between objects and values. As a result, the implementation has the freedom to share the underlying storage of the objects until some mutation operations occurs on the object (so the object must be "detached" after the operation from the shared instance to make the effect visible, i.e. the mutated value stored in the object could be different than the other objects having the old value). This technique is sometimes called *object interning*. Interning makes the program more memory efficient at runtime if the objects are shared without frequent needs of mutation, at the cost that: * The users cannot distinguish the identity of the objects. + There are no way to identify an object and to ensure it has states explicitly independent to other objects *in the program* before some side effects have actually occur (and the implementation does not aggressively to do the interning concurrently; this should be the rare case, though). * There may be more problems on interoperations which require to identify different objects for different operations. * There are risks that such assumptions can be false, so the performance is actually made worse by applying the interning. + This depends on the programming paradigm. Imperative programming which mutates objects frequently certainly would not work well with interning. * Implementations depending on COW (copy-on-write) to ensure interning can incur serious performance degradation in concurrent environments. + Even local sharing specifically for a few internal data structures can be bad. For example, ISO C++ 11 did not allow sharing of the internal elements of `std::basic_string` for this reason exactly, even at the cost of breaking the ABI on at least one mainstream implementation (libstdc++). * Boxing and unboxing incur performance penalties. This is obvious especially when these operations can be naively avoided by hand but actually not easy for the optimizer. The concrete measurement of the cost depends (on per-implementation or even per-program basis), though. Mutable cells, i.e. boxes, are well-established facilities exactly to resolve the problems of the 1st and 2nd bullets listed above. Additionally, there can be immutable boxes for implementation of assignment in a functional language. See [SRFI-111](https://srfi.schemers.org/srfi-111/srfi-111.html) for a practical instance. Using mutable cells as function arguments with call-by-value strategy implements the visible effects of mutation being shared between the caller and the callee. The object contained by an box is effectively "called by shared" in this sense. Sometimes, the boxes are referred as references (which is technically false), so the shared semantics are named "reference semantics". This is not correct, because not all references can propagate the visible side effects (e.g. immutable references). References are more about exposing the access *by indirection*, while boxes are the efforts to expose *minimal* details of the accesses like whether indirection or not (which is uninterested and better avoided by the implementation). Moreover, "value semantic" is irrelevant here. Values are not against to references, nor to boxes. All the discussions above are based on call-by-value strategy. For others (like call-by-name or call-by-need), no boxes are needed to shared object contents in this way. Java is probably the first programming language to make these features popular in the industry. Unfortunately, there seem many bad consequences concerned in this topic: * The overall programming paradigm does not fit the design. * Practically, the interning are limited to specific objects like immutable strings, and the cost of (auto-)boxing and unboxing are often blamed. * Fundamental PL knowledge like the definition of the term "object" (as "instance of a class") in the language specification, as well as the descriptions of parameter passing, are biased compared to the the [original](https://classes.cs.uoregon.edu/14S/cis607pl/Papers/fundamental-1967.pdf), [well-known](https://en.wikipedia.org/wiki/Fundamental_Concepts_in_Programming_Languages) meaning, during the adoption of Java by programmers. + At least CLR languages are following the similar parlance. Some more tips on implementations (and comments to [this answer](https://stackoverflow.com/a/25324/2307646)): * Whether to put the objects on the call stacks or the heap is an implementation details, and irrelevant to the implementation of boxes. + Some language implementations do not maintain a contiguous storage as the call stack. + Some language implementations do not even make the (per thread) activation records a linear stack. + Some language implementations do allocate stacks on the free store ("the heap") and transfer slices of frames between the stacks and the heap back and forth. + These strategies has nothing to do boxes. For instance, many Scheme implementations have boxes, with different activation records layouts, including all the ways listed above. * Besides the technical inaccuracy, the statement "everything is an object" is irrelevant to boxing. + Python, Ruby, and JavaScript all use latent typing (by default), so all identifiers referring to some objects will evaluate to values having the same static type. So does Scheme. + Some JavaScript and Ruby implementations use the so-called [NaN-boxing](https://softwareengineering.stackexchange.com/questions/185406/what-is-the-purpose-of-nan-boxing) to allow inlining allocation of some objects. Some others (including [CPython](https://softwareengineering.stackexchange.com/a/185431/154697)) do not. With NaN boxing, a normal `double` object needs no unboxing to access its value, while a value of some other types can be boxed in a host `double` object, and there is no reference for `double` or the boxed value. With the naive pointer approach, a value of host object pointer like `PyObject*` is an object reference holding a box whose boxed value is stored in the dynamically allocated space. + [At least in Python](https://stackoverflow.com/questions/865911/is-everything-an-object-in-python-like-ruby), objects are not "everything". They are also not known as "boxed values" unless you are talking about interoperability with specific implementations.
13,055
I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations welcome.
2008/08/16
[ "https://Stackoverflow.com/questions/13055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
In .Net: Often you can't rely on what the type of variable a function will consume, so you need to use an object variable which extends from the lowest common denominator - in .Net this is `object`. However `object` is a class and stores its contents as a reference. ``` List<int> notBoxed = new List<int> { 1, 2, 3 }; int i = notBoxed[1]; // this is the actual value List<object> boxed = new List<object> { 1, 2, 3 }; int j = (int) boxed[1]; // this is an object that can be 'unboxed' to an int ``` While both these hold the same information the second list is larger and slower. Each value in the second list is actually a reference to an `object` that holds the `int`. This is called boxed because the `int` is wrapped by the `object`. When its cast back the `int` is unboxed - converted back to it's value. For value types (i.e. all `structs`) this is slow, and potentially uses a lot more space. For reference types (i.e. all `classes`) this is far less of a problem, as they are stored as a reference anyway. A further problem with a boxed value type is that it's not obvious that you're dealing with the box, rather than the value. When you compare two `structs` then you're comparing values, but when you compare two `classes` then (by default) you're comparing the reference - i.e. are these the same instance? This can be confusing when dealing with boxed value types: ``` int a = 7; int b = 7; if(a == b) // Evaluates to true, because a and b have the same value object c = (object) 7; object d = (object) 7; if(c == d) // Evaluates to false, because c and d are different instances ``` It's easy to work around: ``` if(c.Equals(d)) // Evaluates to true because it calls the underlying int's equals if(((int) c) == ((int) d)) // Evaluates to true once the values are cast ``` However it is another thing to be careful of when dealing with boxed values.
The language-agnostic meaning of a box is just "an object contains some other value". Literally, *boxing* is an operation to put some value into the box. More specifically, it is an operation to *create* a new box containing the value. After boxing, the boxed value can be accessed from the box object, by *unboxing*. Note that objects (not OOP-specific) in many programming languages are about *identities*, but values are not. Two objects are same iff. they have identities not distinguishable in the program semantics. Values can also be the same (usually under some equality operators), but we do not distinguish them as "one" or "two" *unique* values. Providing boxes is mainly about the effort to distinguish side effects (typically, mutation) from the states on the objects otherwise probably invisible to the users. A language may limit the allowed ways to access an object and hide the identity of the object by default. For example, typical Lisp dialects has no explicit distinctions between objects and values. As a result, the implementation has the freedom to share the underlying storage of the objects until some mutation operations occurs on the object (so the object must be "detached" after the operation from the shared instance to make the effect visible, i.e. the mutated value stored in the object could be different than the other objects having the old value). This technique is sometimes called *object interning*. Interning makes the program more memory efficient at runtime if the objects are shared without frequent needs of mutation, at the cost that: * The users cannot distinguish the identity of the objects. + There are no way to identify an object and to ensure it has states explicitly independent to other objects *in the program* before some side effects have actually occur (and the implementation does not aggressively to do the interning concurrently; this should be the rare case, though). * There may be more problems on interoperations which require to identify different objects for different operations. * There are risks that such assumptions can be false, so the performance is actually made worse by applying the interning. + This depends on the programming paradigm. Imperative programming which mutates objects frequently certainly would not work well with interning. * Implementations depending on COW (copy-on-write) to ensure interning can incur serious performance degradation in concurrent environments. + Even local sharing specifically for a few internal data structures can be bad. For example, ISO C++ 11 did not allow sharing of the internal elements of `std::basic_string` for this reason exactly, even at the cost of breaking the ABI on at least one mainstream implementation (libstdc++). * Boxing and unboxing incur performance penalties. This is obvious especially when these operations can be naively avoided by hand but actually not easy for the optimizer. The concrete measurement of the cost depends (on per-implementation or even per-program basis), though. Mutable cells, i.e. boxes, are well-established facilities exactly to resolve the problems of the 1st and 2nd bullets listed above. Additionally, there can be immutable boxes for implementation of assignment in a functional language. See [SRFI-111](https://srfi.schemers.org/srfi-111/srfi-111.html) for a practical instance. Using mutable cells as function arguments with call-by-value strategy implements the visible effects of mutation being shared between the caller and the callee. The object contained by an box is effectively "called by shared" in this sense. Sometimes, the boxes are referred as references (which is technically false), so the shared semantics are named "reference semantics". This is not correct, because not all references can propagate the visible side effects (e.g. immutable references). References are more about exposing the access *by indirection*, while boxes are the efforts to expose *minimal* details of the accesses like whether indirection or not (which is uninterested and better avoided by the implementation). Moreover, "value semantic" is irrelevant here. Values are not against to references, nor to boxes. All the discussions above are based on call-by-value strategy. For others (like call-by-name or call-by-need), no boxes are needed to shared object contents in this way. Java is probably the first programming language to make these features popular in the industry. Unfortunately, there seem many bad consequences concerned in this topic: * The overall programming paradigm does not fit the design. * Practically, the interning are limited to specific objects like immutable strings, and the cost of (auto-)boxing and unboxing are often blamed. * Fundamental PL knowledge like the definition of the term "object" (as "instance of a class") in the language specification, as well as the descriptions of parameter passing, are biased compared to the the [original](https://classes.cs.uoregon.edu/14S/cis607pl/Papers/fundamental-1967.pdf), [well-known](https://en.wikipedia.org/wiki/Fundamental_Concepts_in_Programming_Languages) meaning, during the adoption of Java by programmers. + At least CLR languages are following the similar parlance. Some more tips on implementations (and comments to [this answer](https://stackoverflow.com/a/25324/2307646)): * Whether to put the objects on the call stacks or the heap is an implementation details, and irrelevant to the implementation of boxes. + Some language implementations do not maintain a contiguous storage as the call stack. + Some language implementations do not even make the (per thread) activation records a linear stack. + Some language implementations do allocate stacks on the free store ("the heap") and transfer slices of frames between the stacks and the heap back and forth. + These strategies has nothing to do boxes. For instance, many Scheme implementations have boxes, with different activation records layouts, including all the ways listed above. * Besides the technical inaccuracy, the statement "everything is an object" is irrelevant to boxing. + Python, Ruby, and JavaScript all use latent typing (by default), so all identifiers referring to some objects will evaluate to values having the same static type. So does Scheme. + Some JavaScript and Ruby implementations use the so-called [NaN-boxing](https://softwareengineering.stackexchange.com/questions/185406/what-is-the-purpose-of-nan-boxing) to allow inlining allocation of some objects. Some others (including [CPython](https://softwareengineering.stackexchange.com/a/185431/154697)) do not. With NaN boxing, a normal `double` object needs no unboxing to access its value, while a value of some other types can be boxed in a host `double` object, and there is no reference for `double` or the boxed value. With the naive pointer approach, a value of host object pointer like `PyObject*` is an object reference holding a box whose boxed value is stored in the dynamically allocated space. + [At least in Python](https://stackoverflow.com/questions/865911/is-everything-an-object-in-python-like-ruby), objects are not "everything". They are also not known as "boxed values" unless you are talking about interoperability with specific implementations.
13,055
I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations welcome.
2008/08/16
[ "https://Stackoverflow.com/questions/13055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
The .NET FCL generic collections: ``` List<T> Dictionary<TKey, UValue> SortedDictionary<TKey, UValue> Stack<T> Queue<T> LinkedList<T> ``` were all designed to overcome the performance issues of boxing and unboxing in previous collection implementations. For more, see chapter 16, [*CLR via C# (2nd Edition)*](http://books.google.com/books?id=C-V_AAAACAAJ&dq=clr+via+c%23&ei=tyKnSPqSI5T2iQHzwJTECQ).
Boxing and unboxing facilitates value types to be treated as objects. Boxing means converting a value to an instance of the object reference type. For example, `Int` is a class and `int` is a data type. Converting `int` to `Int` is an exemplification of boxing, whereas converting `Int` to `int` is unboxing. The concept helps in garbage collection, Unboxing, on the other hand, converts object type to value type. ``` int i=123; object o=(object)i; //Boxing o=123; i=(int)o; //Unboxing. ```
13,055
I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations welcome.
2008/08/16
[ "https://Stackoverflow.com/questions/13055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
from [C# 3.0 In a Nutshell](http://books.google.com/books?id=_Y0rWd-Q2xkC&pg=PA81&vq=boxing&source=gbs_search_r&cad=1_1&sig=ACfU3U0SIw4v8UZzMH3f5xImIyHZHD90sA#PPA82,M1): > > Boxing is the act of casting a value > type into a reference type: > > > ``` int x = 9; object o = x; // boxing the int ``` > > unboxing is... the reverse: > > > ``` // unboxing o object o = 9; int x = (int)o; ```
Boxing and unboxing facilitates value types to be treated as objects. Boxing means converting a value to an instance of the object reference type. For example, `Int` is a class and `int` is a data type. Converting `int` to `Int` is an exemplification of boxing, whereas converting `Int` to `int` is unboxing. The concept helps in garbage collection, Unboxing, on the other hand, converts object type to value type. ``` int i=123; object o=(object)i; //Boxing o=123; i=(int)o; //Unboxing. ```
13,055
I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations welcome.
2008/08/16
[ "https://Stackoverflow.com/questions/13055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
Boxing & unboxing is the process of converting a primitive value into an object oriented wrapper class (boxing), or converting a value from an object oriented wrapper class back to the primitive value (unboxing). For example, in java, you may need to convert an `int` value into an `Integer` (boxing) if you want to store it in a `Collection` because primitives can't be stored in a `Collection`, only objects. But when you want to get it back out of the `Collection` you may want to get the value as an `int` and not an `Integer` so you would unbox it. Boxing and unboxing is not inherently *bad*, but it is a tradeoff. Depending on the language implementation, it can be slower and more memory intensive than just using primitives. However, it may also allow you to use higher level data structures and achieve greater flexibility in your code. These days, it is most commonly discussed in the context of Java's (and other language's) "autoboxing/autounboxing" feature. Here is a [java centric explanation of autoboxing](http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html).
In .Net: Often you can't rely on what the type of variable a function will consume, so you need to use an object variable which extends from the lowest common denominator - in .Net this is `object`. However `object` is a class and stores its contents as a reference. ``` List<int> notBoxed = new List<int> { 1, 2, 3 }; int i = notBoxed[1]; // this is the actual value List<object> boxed = new List<object> { 1, 2, 3 }; int j = (int) boxed[1]; // this is an object that can be 'unboxed' to an int ``` While both these hold the same information the second list is larger and slower. Each value in the second list is actually a reference to an `object` that holds the `int`. This is called boxed because the `int` is wrapped by the `object`. When its cast back the `int` is unboxed - converted back to it's value. For value types (i.e. all `structs`) this is slow, and potentially uses a lot more space. For reference types (i.e. all `classes`) this is far less of a problem, as they are stored as a reference anyway. A further problem with a boxed value type is that it's not obvious that you're dealing with the box, rather than the value. When you compare two `structs` then you're comparing values, but when you compare two `classes` then (by default) you're comparing the reference - i.e. are these the same instance? This can be confusing when dealing with boxed value types: ``` int a = 7; int b = 7; if(a == b) // Evaluates to true, because a and b have the same value object c = (object) 7; object d = (object) 7; if(c == d) // Evaluates to false, because c and d are different instances ``` It's easy to work around: ``` if(c.Equals(d)) // Evaluates to true because it calls the underlying int's equals if(((int) c) == ((int) d)) // Evaluates to true once the values are cast ``` However it is another thing to be careful of when dealing with boxed values.
13,055
I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations welcome.
2008/08/16
[ "https://Stackoverflow.com/questions/13055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
Boxed values are [data structures](http://en.wikipedia.org/wiki/Data_structure) that are minimal wrappers around [primitive types](http://en.wikipedia.org/wiki/Primitive_type)\*. Boxed values are typically stored as pointers to objects on [the heap](http://en.wikipedia.org/wiki/Dynamic_memory_allocation). Thus, boxed values use more memory and take at minimum two memory lookups to access: once to get the pointer, and another to follow that pointer to the primitive. Obviously this isn't the kind of thing you want in your inner loops. On the other hand, boxed values typically play better with other types in the system. Since they are first-class data structures in the language, they have the expected metadata and structure that other data structures have. In Java and Haskell generic collections can't contain unboxed values. Generic collections in .NET can hold unboxed values with no penalties. Where Java's generics are only used for compile-time type checking, .NET will [generate specific classes for each generic type instantiated at run time](http://msdn.microsoft.com/en-us/library/f4a6ta2h.aspx). Java and Haskell have unboxed arrays, but they're distinctly less convenient than the other collections. However, when peak performance is needed it's worth a little inconvenience to avoid the overhead of boxing and unboxing. \* For this discussion, a primitive value is any that can be stored on [the call stack](http://en.wikipedia.org/wiki/Call_stack), rather than stored as a pointer to a value on the heap. Frequently that's just the machine types (ints, floats, etc), structs, and sometimes static sized arrays. .NET-land calls them value types (as opposed to reference types). Java folks call them primitive types. Haskellions just call them unboxed. \*\* I'm also focusing on Java, Haskell, and C# in this answer, because that's what I know. For what it's worth, Python, Ruby, and Javascript all have exclusively boxed values. This is also known as the "Everything is an object" approach\*\*\*. \*\*\* Caveat: A sufficiently advanced compiler / JIT can in some cases actually detect that a value which is semantically boxed when looking at the source, can safely be an unboxed value at runtime. In essence, thanks to brilliant language implementors your boxes are sometimes free.
`Boxing` is the process of conversion of a value type into a reference type. Whereas `Unboxing` is the conversion of a reference type into a value type. ``` EX: int i = 123; object o = i;// Boxing int j = (int)o;// UnBoxing ``` Value Types are: `int`, `char` and `structures`, `enumerations`. Reference Types are: `Classes`,`interfaces`,`arrays`,`strings` and `objects`
13,055
I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations welcome.
2008/08/16
[ "https://Stackoverflow.com/questions/13055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
Boxing & unboxing is the process of converting a primitive value into an object oriented wrapper class (boxing), or converting a value from an object oriented wrapper class back to the primitive value (unboxing). For example, in java, you may need to convert an `int` value into an `Integer` (boxing) if you want to store it in a `Collection` because primitives can't be stored in a `Collection`, only objects. But when you want to get it back out of the `Collection` you may want to get the value as an `int` and not an `Integer` so you would unbox it. Boxing and unboxing is not inherently *bad*, but it is a tradeoff. Depending on the language implementation, it can be slower and more memory intensive than just using primitives. However, it may also allow you to use higher level data structures and achieve greater flexibility in your code. These days, it is most commonly discussed in the context of Java's (and other language's) "autoboxing/autounboxing" feature. Here is a [java centric explanation of autoboxing](http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html).
Boxing and unboxing facilitates value types to be treated as objects. Boxing means converting a value to an instance of the object reference type. For example, `Int` is a class and `int` is a data type. Converting `int` to `Int` is an exemplification of boxing, whereas converting `Int` to `int` is unboxing. The concept helps in garbage collection, Unboxing, on the other hand, converts object type to value type. ``` int i=123; object o=(object)i; //Boxing o=123; i=(int)o; //Unboxing. ```
13,055
I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations welcome.
2008/08/16
[ "https://Stackoverflow.com/questions/13055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
Boxed values are [data structures](http://en.wikipedia.org/wiki/Data_structure) that are minimal wrappers around [primitive types](http://en.wikipedia.org/wiki/Primitive_type)\*. Boxed values are typically stored as pointers to objects on [the heap](http://en.wikipedia.org/wiki/Dynamic_memory_allocation). Thus, boxed values use more memory and take at minimum two memory lookups to access: once to get the pointer, and another to follow that pointer to the primitive. Obviously this isn't the kind of thing you want in your inner loops. On the other hand, boxed values typically play better with other types in the system. Since they are first-class data structures in the language, they have the expected metadata and structure that other data structures have. In Java and Haskell generic collections can't contain unboxed values. Generic collections in .NET can hold unboxed values with no penalties. Where Java's generics are only used for compile-time type checking, .NET will [generate specific classes for each generic type instantiated at run time](http://msdn.microsoft.com/en-us/library/f4a6ta2h.aspx). Java and Haskell have unboxed arrays, but they're distinctly less convenient than the other collections. However, when peak performance is needed it's worth a little inconvenience to avoid the overhead of boxing and unboxing. \* For this discussion, a primitive value is any that can be stored on [the call stack](http://en.wikipedia.org/wiki/Call_stack), rather than stored as a pointer to a value on the heap. Frequently that's just the machine types (ints, floats, etc), structs, and sometimes static sized arrays. .NET-land calls them value types (as opposed to reference types). Java folks call them primitive types. Haskellions just call them unboxed. \*\* I'm also focusing on Java, Haskell, and C# in this answer, because that's what I know. For what it's worth, Python, Ruby, and Javascript all have exclusively boxed values. This is also known as the "Everything is an object" approach\*\*\*. \*\*\* Caveat: A sufficiently advanced compiler / JIT can in some cases actually detect that a value which is semantically boxed when looking at the source, can safely be an unboxed value at runtime. In essence, thanks to brilliant language implementors your boxes are sometimes free.
The .NET FCL generic collections: ``` List<T> Dictionary<TKey, UValue> SortedDictionary<TKey, UValue> Stack<T> Queue<T> LinkedList<T> ``` were all designed to overcome the performance issues of boxing and unboxing in previous collection implementations. For more, see chapter 16, [*CLR via C# (2nd Edition)*](http://books.google.com/books?id=C-V_AAAACAAJ&dq=clr+via+c%23&ei=tyKnSPqSI5T2iQHzwJTECQ).
13,055
I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations welcome.
2008/08/16
[ "https://Stackoverflow.com/questions/13055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
Boxing & unboxing is the process of converting a primitive value into an object oriented wrapper class (boxing), or converting a value from an object oriented wrapper class back to the primitive value (unboxing). For example, in java, you may need to convert an `int` value into an `Integer` (boxing) if you want to store it in a `Collection` because primitives can't be stored in a `Collection`, only objects. But when you want to get it back out of the `Collection` you may want to get the value as an `int` and not an `Integer` so you would unbox it. Boxing and unboxing is not inherently *bad*, but it is a tradeoff. Depending on the language implementation, it can be slower and more memory intensive than just using primitives. However, it may also allow you to use higher level data structures and achieve greater flexibility in your code. These days, it is most commonly discussed in the context of Java's (and other language's) "autoboxing/autounboxing" feature. Here is a [java centric explanation of autoboxing](http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html).
Like anything else, autoboxing can be problematic if not used carefully. The classic is to end up with a NullPointerException and not be able to track it down. Even with a debugger. Try this: ``` public class TestAutoboxNPE { public static void main(String[] args) { Integer i = null; // .. do some other stuff and forget to initialise i i = addOne(i); // Whoa! NPE! } public static int addOne(int i) { return i + 1; } } ```
17,314,513
I want to create a software: - Input as a video stream H264 ( from another software) - Output as a webcam for my friends can watch in skype, yahoo, or something like that. I knows I need to create directshow filter to do that, but I dont know what type filter I must to create. And when I have a filter, I dont know how to import it to my application? I need a example or a tutorial, please help me
2013/06/26
[ "https://Stackoverflow.com/questions/17314513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376873/" ]
You need to create a virtual video source/camera filter. There have been a dozen of questions like this on SO, so I will just link to some of them: * [How to write an own capture filter?](https://stackoverflow.com/questions/10086897/how-to-write-an-own-capture-filter/10087276#10087276) * [Set byte stream as live source in Expression Encoder 4](https://stackoverflow.com/questions/8488073/set-byte-stream-as-live-source-in-expression-encoder-4) * ["Fake" DirectShow video capture device](https://stackoverflow.com/questions/1376734/fake-directshow-video-capture-device) Windows SDK has `PushSource` sample which shows how to generate video off a filter. `VCam` sample [you can find online](http://tmhare.mvps.org/downloads.htm) shows what it takes to make a virtual device from video source. See also: [How to implement a "source filter" for splitting camera video based on Vivek's vcam?](http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/ce717600-750b-46c0-8a63-31d65659740b/how-to-implement-a-source-filter-for-splitting-camera-video-based-on-viveks-vcam). NOTE: Latest versions of Skype [are picky as for video devices and ignore virtual devices for no apparent reason](http://webcache.googleusercontent.com/search?q=cache:mjhhnU-9uEUJ:https://jira.skype.com/browse/SCW-3881%3FfocusedCommentId%3D58828%26page%3Dcom.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel+&cd=1&hl=en&ct=clnk&client=firefox-beta).
You should start here : [Writing DirectShow Filters](http://msdn.microsoft.com/en-us/library/windows/desktop/dd391013%28v=vs.85%29.aspx) or here : [Introduction to DirectShow Filter Development](http://msdn.microsoft.com/en-us/library/windows/desktop/dd390354%28v=vs.85%29.aspx) I assume you already have Windows SDK for such develpment, if not check [this](http://msdn.microsoft.com/en-us/library/windows/desktop/dd375454%28v=vs.85%29.aspx)
22,830,387
I don't know why and how, but my jQuery code appears to be firing twice on any event. Here's a part of my code: `commmon.js`: ``` $(document).ready(function() { $(".fpbtn-one").click(function() { console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); $(window).load(function() { console.log("Setting up slides"); // Gets logged 2 on page load // These get initialized twice $("#div-1").responsiveSlides({ auto: true, pager: true, pause:true, nav: false, timeout: 3000, speed: 500, maxwidth: 482, namespace: "transparent-btns" }); $("#div-2").responsiveSlides({ auto: true, pager: false, pause:true, nav: false, speed: 2000, maxwidth: 320, }); }); ``` --- HTML: ``` <!doctype html> <html lang="en"> <head><link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/> <link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script> <script type="text/javascript" src="/assets/script/jquery/jquery.qtip.js"></script> <script type="text/javascript" src="/assets/script/jquery/plugin.efiling.full.js"></script> <meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function a(b,c,d){function e(f){if(!c[f]){var g=c[f]={exports:{}};b[f][0].call(g.exports,function(a){var c=b[f][1][a];return e(c?c:a)},g,g.exports,a,b,c,d)}return c[f].exports}for(var f=0;f<d.length;f++)e(d[f]);return e}({"4O2Y62":[function(a,b){function c(a,b){var c=d[a];return c?c.apply(this,b):(e[a]||(e[a]=[]),void e[a].push(b))}var d={},e={};b.exports=c,c.queues=e,c.handlers=d},{}],handle:[function(a,b){b.exports=a("4O2Y62")},{}],YLUGVp:[function(a,b){function c(){var a=m.info=NREUM.info;if(a&&a.agent&&a.licenseKey&&a.applicationID){m.proto="https"===l.split(":")[0]||a.sslForHttp?"https://":"http://",g("mark",["onload",f()]);var b=i.createElement("script");b.src=m.proto+a.agent,i.body.appendChild(b)}}function d(){"complete"===i.readyState&&e()}function e(){g("mark",["domContent",f()])}function f(){return(new Date).getTime()}var g=a("handle"),h=window,i=h.document,j="addEventListener",k="attachEvent",l=(""+location).split("?")[0],m=b.exports={offset:f(),origin:l,features:[]};i[j]?(i[j]("DOMContentLoaded",e,!1),h[j]("load",c,!1)):(i[k]("onreadystatechange",d),h[k]("onload",c)),g("mark",["firstbyte",f()])},{handle:"4O2Y62"}],loader:[function(a,b){b.exports=a("YLUGVp")},{}]},{},["YLUGVp"]);</script> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <link href="/assets/custom/files/favicon.ico" rel="shortcut icon" /> <link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" /> <link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" /> <link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" /> <meta content="" name="description" /> <meta content="" name="keywords" /> <meta content="NOINDEX, NOFOLLOW" name="ROBOTS" /> <title>Some title</title> <link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" /> <!--[if IE 7]> <link rel="stylesheet" href="/assets/custom/files/css/font-awesome-ie7_min.css"> <![endif]--> <script type="text/javascript" src="/assets/custom/files/js/adobe-type.js"></script> </head> <body> <!-- BODY STUFF IN HERE (REMOVED) --> <script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery-anystretch-stand-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/common.js"></script> <script type="text/javascript" src="/assets/custom/files/js/modernizr.js"></script> <script type="text/javascript" src="/assets/custom/files/js/responsiveslides_min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/socialmedia.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery_atooltip_min.js"></script></div> <script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-4.newrelic.com","licenseKey":"204ccc8db2","applicationID":"1825150","transactionName":"YVNVYBACWxFTWxFcWVgZYkYLTFwMVl0dG0ZeRg==","queueTime":0,"applicationTime":187,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-361.min.js"}</script></body> </html> ``` What could be the reason?
2014/04/03
[ "https://Stackoverflow.com/questions/22830387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999681/" ]
be careful for beginning use good practice when calling jquery : ``` !function( $ ) { your code }( jQuery ) ``` like that you avoid conflict... Then be careful when adding js script in html, you can add it twice, for example you call one js in a html file, ok but in the js you load in callback for example another page with the js inside, it will call twice your code.... i had the same probleme before with a recursive call, the js never stop to call it !! in the main page it is better if your js will be called in several files otherwise you have to debug it.... moreover you don't paste all your code we can't help you, we can just tell in my opinion.... not a good advices often...
Your relevant code is required, but from the snippets above; try putting all the codes in the document ready method.
22,830,387
I don't know why and how, but my jQuery code appears to be firing twice on any event. Here's a part of my code: `commmon.js`: ``` $(document).ready(function() { $(".fpbtn-one").click(function() { console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); $(window).load(function() { console.log("Setting up slides"); // Gets logged 2 on page load // These get initialized twice $("#div-1").responsiveSlides({ auto: true, pager: true, pause:true, nav: false, timeout: 3000, speed: 500, maxwidth: 482, namespace: "transparent-btns" }); $("#div-2").responsiveSlides({ auto: true, pager: false, pause:true, nav: false, speed: 2000, maxwidth: 320, }); }); ``` --- HTML: ``` <!doctype html> <html lang="en"> <head><link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/> <link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script> <script type="text/javascript" src="/assets/script/jquery/jquery.qtip.js"></script> <script type="text/javascript" src="/assets/script/jquery/plugin.efiling.full.js"></script> <meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function a(b,c,d){function e(f){if(!c[f]){var g=c[f]={exports:{}};b[f][0].call(g.exports,function(a){var c=b[f][1][a];return e(c?c:a)},g,g.exports,a,b,c,d)}return c[f].exports}for(var f=0;f<d.length;f++)e(d[f]);return e}({"4O2Y62":[function(a,b){function c(a,b){var c=d[a];return c?c.apply(this,b):(e[a]||(e[a]=[]),void e[a].push(b))}var d={},e={};b.exports=c,c.queues=e,c.handlers=d},{}],handle:[function(a,b){b.exports=a("4O2Y62")},{}],YLUGVp:[function(a,b){function c(){var a=m.info=NREUM.info;if(a&&a.agent&&a.licenseKey&&a.applicationID){m.proto="https"===l.split(":")[0]||a.sslForHttp?"https://":"http://",g("mark",["onload",f()]);var b=i.createElement("script");b.src=m.proto+a.agent,i.body.appendChild(b)}}function d(){"complete"===i.readyState&&e()}function e(){g("mark",["domContent",f()])}function f(){return(new Date).getTime()}var g=a("handle"),h=window,i=h.document,j="addEventListener",k="attachEvent",l=(""+location).split("?")[0],m=b.exports={offset:f(),origin:l,features:[]};i[j]?(i[j]("DOMContentLoaded",e,!1),h[j]("load",c,!1)):(i[k]("onreadystatechange",d),h[k]("onload",c)),g("mark",["firstbyte",f()])},{handle:"4O2Y62"}],loader:[function(a,b){b.exports=a("YLUGVp")},{}]},{},["YLUGVp"]);</script> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <link href="/assets/custom/files/favicon.ico" rel="shortcut icon" /> <link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" /> <link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" /> <link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" /> <meta content="" name="description" /> <meta content="" name="keywords" /> <meta content="NOINDEX, NOFOLLOW" name="ROBOTS" /> <title>Some title</title> <link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" /> <!--[if IE 7]> <link rel="stylesheet" href="/assets/custom/files/css/font-awesome-ie7_min.css"> <![endif]--> <script type="text/javascript" src="/assets/custom/files/js/adobe-type.js"></script> </head> <body> <!-- BODY STUFF IN HERE (REMOVED) --> <script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery-anystretch-stand-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/common.js"></script> <script type="text/javascript" src="/assets/custom/files/js/modernizr.js"></script> <script type="text/javascript" src="/assets/custom/files/js/responsiveslides_min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/socialmedia.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery_atooltip_min.js"></script></div> <script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-4.newrelic.com","licenseKey":"204ccc8db2","applicationID":"1825150","transactionName":"YVNVYBACWxFTWxFcWVgZYkYLTFwMVl0dG0ZeRg==","queueTime":0,"applicationTime":187,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-361.min.js"}</script></body> </html> ``` What could be the reason?
2014/04/03
[ "https://Stackoverflow.com/questions/22830387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999681/" ]
Try putting the stuff in the body inside divs. example. `<div id = "menu"><script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> </div>` I hope that works. :)
It might be event bubbling. Use `event.preventDefault()`, it will prevent the default event from occuring or `event.stopPropagation()` will prevent the event from bubbling up. ``` $(document).ready(function() { $(".fpbtn-one").click(function(event) { event.stopPropagation(); console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); ```
22,830,387
I don't know why and how, but my jQuery code appears to be firing twice on any event. Here's a part of my code: `commmon.js`: ``` $(document).ready(function() { $(".fpbtn-one").click(function() { console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); $(window).load(function() { console.log("Setting up slides"); // Gets logged 2 on page load // These get initialized twice $("#div-1").responsiveSlides({ auto: true, pager: true, pause:true, nav: false, timeout: 3000, speed: 500, maxwidth: 482, namespace: "transparent-btns" }); $("#div-2").responsiveSlides({ auto: true, pager: false, pause:true, nav: false, speed: 2000, maxwidth: 320, }); }); ``` --- HTML: ``` <!doctype html> <html lang="en"> <head><link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/> <link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script> <script type="text/javascript" src="/assets/script/jquery/jquery.qtip.js"></script> <script type="text/javascript" src="/assets/script/jquery/plugin.efiling.full.js"></script> <meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function a(b,c,d){function e(f){if(!c[f]){var g=c[f]={exports:{}};b[f][0].call(g.exports,function(a){var c=b[f][1][a];return e(c?c:a)},g,g.exports,a,b,c,d)}return c[f].exports}for(var f=0;f<d.length;f++)e(d[f]);return e}({"4O2Y62":[function(a,b){function c(a,b){var c=d[a];return c?c.apply(this,b):(e[a]||(e[a]=[]),void e[a].push(b))}var d={},e={};b.exports=c,c.queues=e,c.handlers=d},{}],handle:[function(a,b){b.exports=a("4O2Y62")},{}],YLUGVp:[function(a,b){function c(){var a=m.info=NREUM.info;if(a&&a.agent&&a.licenseKey&&a.applicationID){m.proto="https"===l.split(":")[0]||a.sslForHttp?"https://":"http://",g("mark",["onload",f()]);var b=i.createElement("script");b.src=m.proto+a.agent,i.body.appendChild(b)}}function d(){"complete"===i.readyState&&e()}function e(){g("mark",["domContent",f()])}function f(){return(new Date).getTime()}var g=a("handle"),h=window,i=h.document,j="addEventListener",k="attachEvent",l=(""+location).split("?")[0],m=b.exports={offset:f(),origin:l,features:[]};i[j]?(i[j]("DOMContentLoaded",e,!1),h[j]("load",c,!1)):(i[k]("onreadystatechange",d),h[k]("onload",c)),g("mark",["firstbyte",f()])},{handle:"4O2Y62"}],loader:[function(a,b){b.exports=a("YLUGVp")},{}]},{},["YLUGVp"]);</script> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <link href="/assets/custom/files/favicon.ico" rel="shortcut icon" /> <link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" /> <link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" /> <link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" /> <meta content="" name="description" /> <meta content="" name="keywords" /> <meta content="NOINDEX, NOFOLLOW" name="ROBOTS" /> <title>Some title</title> <link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" /> <!--[if IE 7]> <link rel="stylesheet" href="/assets/custom/files/css/font-awesome-ie7_min.css"> <![endif]--> <script type="text/javascript" src="/assets/custom/files/js/adobe-type.js"></script> </head> <body> <!-- BODY STUFF IN HERE (REMOVED) --> <script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery-anystretch-stand-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/common.js"></script> <script type="text/javascript" src="/assets/custom/files/js/modernizr.js"></script> <script type="text/javascript" src="/assets/custom/files/js/responsiveslides_min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/socialmedia.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery_atooltip_min.js"></script></div> <script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-4.newrelic.com","licenseKey":"204ccc8db2","applicationID":"1825150","transactionName":"YVNVYBACWxFTWxFcWVgZYkYLTFwMVl0dG0ZeRg==","queueTime":0,"applicationTime":187,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-361.min.js"}</script></body> </html> ``` What could be the reason?
2014/04/03
[ "https://Stackoverflow.com/questions/22830387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999681/" ]
May be you have included your script file `commmon.js` twice. Check your references to it in your code.
Your relevant code is required, but from the snippets above; try putting all the codes in the document ready method.
22,830,387
I don't know why and how, but my jQuery code appears to be firing twice on any event. Here's a part of my code: `commmon.js`: ``` $(document).ready(function() { $(".fpbtn-one").click(function() { console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); $(window).load(function() { console.log("Setting up slides"); // Gets logged 2 on page load // These get initialized twice $("#div-1").responsiveSlides({ auto: true, pager: true, pause:true, nav: false, timeout: 3000, speed: 500, maxwidth: 482, namespace: "transparent-btns" }); $("#div-2").responsiveSlides({ auto: true, pager: false, pause:true, nav: false, speed: 2000, maxwidth: 320, }); }); ``` --- HTML: ``` <!doctype html> <html lang="en"> <head><link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/> <link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script> <script type="text/javascript" src="/assets/script/jquery/jquery.qtip.js"></script> <script type="text/javascript" src="/assets/script/jquery/plugin.efiling.full.js"></script> <meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function a(b,c,d){function e(f){if(!c[f]){var g=c[f]={exports:{}};b[f][0].call(g.exports,function(a){var c=b[f][1][a];return e(c?c:a)},g,g.exports,a,b,c,d)}return c[f].exports}for(var f=0;f<d.length;f++)e(d[f]);return e}({"4O2Y62":[function(a,b){function c(a,b){var c=d[a];return c?c.apply(this,b):(e[a]||(e[a]=[]),void e[a].push(b))}var d={},e={};b.exports=c,c.queues=e,c.handlers=d},{}],handle:[function(a,b){b.exports=a("4O2Y62")},{}],YLUGVp:[function(a,b){function c(){var a=m.info=NREUM.info;if(a&&a.agent&&a.licenseKey&&a.applicationID){m.proto="https"===l.split(":")[0]||a.sslForHttp?"https://":"http://",g("mark",["onload",f()]);var b=i.createElement("script");b.src=m.proto+a.agent,i.body.appendChild(b)}}function d(){"complete"===i.readyState&&e()}function e(){g("mark",["domContent",f()])}function f(){return(new Date).getTime()}var g=a("handle"),h=window,i=h.document,j="addEventListener",k="attachEvent",l=(""+location).split("?")[0],m=b.exports={offset:f(),origin:l,features:[]};i[j]?(i[j]("DOMContentLoaded",e,!1),h[j]("load",c,!1)):(i[k]("onreadystatechange",d),h[k]("onload",c)),g("mark",["firstbyte",f()])},{handle:"4O2Y62"}],loader:[function(a,b){b.exports=a("YLUGVp")},{}]},{},["YLUGVp"]);</script> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <link href="/assets/custom/files/favicon.ico" rel="shortcut icon" /> <link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" /> <link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" /> <link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" /> <meta content="" name="description" /> <meta content="" name="keywords" /> <meta content="NOINDEX, NOFOLLOW" name="ROBOTS" /> <title>Some title</title> <link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" /> <!--[if IE 7]> <link rel="stylesheet" href="/assets/custom/files/css/font-awesome-ie7_min.css"> <![endif]--> <script type="text/javascript" src="/assets/custom/files/js/adobe-type.js"></script> </head> <body> <!-- BODY STUFF IN HERE (REMOVED) --> <script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery-anystretch-stand-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/common.js"></script> <script type="text/javascript" src="/assets/custom/files/js/modernizr.js"></script> <script type="text/javascript" src="/assets/custom/files/js/responsiveslides_min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/socialmedia.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery_atooltip_min.js"></script></div> <script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-4.newrelic.com","licenseKey":"204ccc8db2","applicationID":"1825150","transactionName":"YVNVYBACWxFTWxFcWVgZYkYLTFwMVl0dG0ZeRg==","queueTime":0,"applicationTime":187,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-361.min.js"}</script></body> </html> ``` What could be the reason?
2014/04/03
[ "https://Stackoverflow.com/questions/22830387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999681/" ]
Could it be that your code was manipulating the element that the code was loading into? This answer may be the reason why it was happening: [jQuery $(document).ready () fires twice](https://stackoverflow.com/questions/10727002/jquery-document-ready-fires-twice)
It might be event bubbling. Use `event.preventDefault()`, it will prevent the default event from occuring or `event.stopPropagation()` will prevent the event from bubbling up. ``` $(document).ready(function() { $(".fpbtn-one").click(function(event) { event.stopPropagation(); console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); ```
22,830,387
I don't know why and how, but my jQuery code appears to be firing twice on any event. Here's a part of my code: `commmon.js`: ``` $(document).ready(function() { $(".fpbtn-one").click(function() { console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); $(window).load(function() { console.log("Setting up slides"); // Gets logged 2 on page load // These get initialized twice $("#div-1").responsiveSlides({ auto: true, pager: true, pause:true, nav: false, timeout: 3000, speed: 500, maxwidth: 482, namespace: "transparent-btns" }); $("#div-2").responsiveSlides({ auto: true, pager: false, pause:true, nav: false, speed: 2000, maxwidth: 320, }); }); ``` --- HTML: ``` <!doctype html> <html lang="en"> <head><link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/> <link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script> <script type="text/javascript" src="/assets/script/jquery/jquery.qtip.js"></script> <script type="text/javascript" src="/assets/script/jquery/plugin.efiling.full.js"></script> <meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function a(b,c,d){function e(f){if(!c[f]){var g=c[f]={exports:{}};b[f][0].call(g.exports,function(a){var c=b[f][1][a];return e(c?c:a)},g,g.exports,a,b,c,d)}return c[f].exports}for(var f=0;f<d.length;f++)e(d[f]);return e}({"4O2Y62":[function(a,b){function c(a,b){var c=d[a];return c?c.apply(this,b):(e[a]||(e[a]=[]),void e[a].push(b))}var d={},e={};b.exports=c,c.queues=e,c.handlers=d},{}],handle:[function(a,b){b.exports=a("4O2Y62")},{}],YLUGVp:[function(a,b){function c(){var a=m.info=NREUM.info;if(a&&a.agent&&a.licenseKey&&a.applicationID){m.proto="https"===l.split(":")[0]||a.sslForHttp?"https://":"http://",g("mark",["onload",f()]);var b=i.createElement("script");b.src=m.proto+a.agent,i.body.appendChild(b)}}function d(){"complete"===i.readyState&&e()}function e(){g("mark",["domContent",f()])}function f(){return(new Date).getTime()}var g=a("handle"),h=window,i=h.document,j="addEventListener",k="attachEvent",l=(""+location).split("?")[0],m=b.exports={offset:f(),origin:l,features:[]};i[j]?(i[j]("DOMContentLoaded",e,!1),h[j]("load",c,!1)):(i[k]("onreadystatechange",d),h[k]("onload",c)),g("mark",["firstbyte",f()])},{handle:"4O2Y62"}],loader:[function(a,b){b.exports=a("YLUGVp")},{}]},{},["YLUGVp"]);</script> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <link href="/assets/custom/files/favicon.ico" rel="shortcut icon" /> <link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" /> <link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" /> <link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" /> <meta content="" name="description" /> <meta content="" name="keywords" /> <meta content="NOINDEX, NOFOLLOW" name="ROBOTS" /> <title>Some title</title> <link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" /> <!--[if IE 7]> <link rel="stylesheet" href="/assets/custom/files/css/font-awesome-ie7_min.css"> <![endif]--> <script type="text/javascript" src="/assets/custom/files/js/adobe-type.js"></script> </head> <body> <!-- BODY STUFF IN HERE (REMOVED) --> <script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery-anystretch-stand-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/common.js"></script> <script type="text/javascript" src="/assets/custom/files/js/modernizr.js"></script> <script type="text/javascript" src="/assets/custom/files/js/responsiveslides_min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/socialmedia.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery_atooltip_min.js"></script></div> <script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-4.newrelic.com","licenseKey":"204ccc8db2","applicationID":"1825150","transactionName":"YVNVYBACWxFTWxFcWVgZYkYLTFwMVl0dG0ZeRg==","queueTime":0,"applicationTime":187,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-361.min.js"}</script></body> </html> ``` What could be the reason?
2014/04/03
[ "https://Stackoverflow.com/questions/22830387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999681/" ]
be careful for beginning use good practice when calling jquery : ``` !function( $ ) { your code }( jQuery ) ``` like that you avoid conflict... Then be careful when adding js script in html, you can add it twice, for example you call one js in a html file, ok but in the js you load in callback for example another page with the js inside, it will call twice your code.... i had the same probleme before with a recursive call, the js never stop to call it !! in the main page it is better if your js will be called in several files otherwise you have to debug it.... moreover you don't paste all your code we can't help you, we can just tell in my opinion.... not a good advices often...
It might be event bubbling. Use `event.preventDefault()`, it will prevent the default event from occuring or `event.stopPropagation()` will prevent the event from bubbling up. ``` $(document).ready(function() { $(".fpbtn-one").click(function(event) { event.stopPropagation(); console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); ```
22,830,387
I don't know why and how, but my jQuery code appears to be firing twice on any event. Here's a part of my code: `commmon.js`: ``` $(document).ready(function() { $(".fpbtn-one").click(function() { console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); $(window).load(function() { console.log("Setting up slides"); // Gets logged 2 on page load // These get initialized twice $("#div-1").responsiveSlides({ auto: true, pager: true, pause:true, nav: false, timeout: 3000, speed: 500, maxwidth: 482, namespace: "transparent-btns" }); $("#div-2").responsiveSlides({ auto: true, pager: false, pause:true, nav: false, speed: 2000, maxwidth: 320, }); }); ``` --- HTML: ``` <!doctype html> <html lang="en"> <head><link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/> <link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script> <script type="text/javascript" src="/assets/script/jquery/jquery.qtip.js"></script> <script type="text/javascript" src="/assets/script/jquery/plugin.efiling.full.js"></script> <meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function a(b,c,d){function e(f){if(!c[f]){var g=c[f]={exports:{}};b[f][0].call(g.exports,function(a){var c=b[f][1][a];return e(c?c:a)},g,g.exports,a,b,c,d)}return c[f].exports}for(var f=0;f<d.length;f++)e(d[f]);return e}({"4O2Y62":[function(a,b){function c(a,b){var c=d[a];return c?c.apply(this,b):(e[a]||(e[a]=[]),void e[a].push(b))}var d={},e={};b.exports=c,c.queues=e,c.handlers=d},{}],handle:[function(a,b){b.exports=a("4O2Y62")},{}],YLUGVp:[function(a,b){function c(){var a=m.info=NREUM.info;if(a&&a.agent&&a.licenseKey&&a.applicationID){m.proto="https"===l.split(":")[0]||a.sslForHttp?"https://":"http://",g("mark",["onload",f()]);var b=i.createElement("script");b.src=m.proto+a.agent,i.body.appendChild(b)}}function d(){"complete"===i.readyState&&e()}function e(){g("mark",["domContent",f()])}function f(){return(new Date).getTime()}var g=a("handle"),h=window,i=h.document,j="addEventListener",k="attachEvent",l=(""+location).split("?")[0],m=b.exports={offset:f(),origin:l,features:[]};i[j]?(i[j]("DOMContentLoaded",e,!1),h[j]("load",c,!1)):(i[k]("onreadystatechange",d),h[k]("onload",c)),g("mark",["firstbyte",f()])},{handle:"4O2Y62"}],loader:[function(a,b){b.exports=a("YLUGVp")},{}]},{},["YLUGVp"]);</script> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <link href="/assets/custom/files/favicon.ico" rel="shortcut icon" /> <link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" /> <link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" /> <link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" /> <meta content="" name="description" /> <meta content="" name="keywords" /> <meta content="NOINDEX, NOFOLLOW" name="ROBOTS" /> <title>Some title</title> <link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" /> <!--[if IE 7]> <link rel="stylesheet" href="/assets/custom/files/css/font-awesome-ie7_min.css"> <![endif]--> <script type="text/javascript" src="/assets/custom/files/js/adobe-type.js"></script> </head> <body> <!-- BODY STUFF IN HERE (REMOVED) --> <script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery-anystretch-stand-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/common.js"></script> <script type="text/javascript" src="/assets/custom/files/js/modernizr.js"></script> <script type="text/javascript" src="/assets/custom/files/js/responsiveslides_min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/socialmedia.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery_atooltip_min.js"></script></div> <script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-4.newrelic.com","licenseKey":"204ccc8db2","applicationID":"1825150","transactionName":"YVNVYBACWxFTWxFcWVgZYkYLTFwMVl0dG0ZeRg==","queueTime":0,"applicationTime":187,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-361.min.js"}</script></body> </html> ``` What could be the reason?
2014/04/03
[ "https://Stackoverflow.com/questions/22830387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999681/" ]
Try putting the stuff in the body inside divs. example. `<div id = "menu"><script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> </div>` I hope that works. :)
Your relevant code is required, but from the snippets above; try putting all the codes in the document ready method.
22,830,387
I don't know why and how, but my jQuery code appears to be firing twice on any event. Here's a part of my code: `commmon.js`: ``` $(document).ready(function() { $(".fpbtn-one").click(function() { console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); $(window).load(function() { console.log("Setting up slides"); // Gets logged 2 on page load // These get initialized twice $("#div-1").responsiveSlides({ auto: true, pager: true, pause:true, nav: false, timeout: 3000, speed: 500, maxwidth: 482, namespace: "transparent-btns" }); $("#div-2").responsiveSlides({ auto: true, pager: false, pause:true, nav: false, speed: 2000, maxwidth: 320, }); }); ``` --- HTML: ``` <!doctype html> <html lang="en"> <head><link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/> <link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script> <script type="text/javascript" src="/assets/script/jquery/jquery.qtip.js"></script> <script type="text/javascript" src="/assets/script/jquery/plugin.efiling.full.js"></script> <meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function a(b,c,d){function e(f){if(!c[f]){var g=c[f]={exports:{}};b[f][0].call(g.exports,function(a){var c=b[f][1][a];return e(c?c:a)},g,g.exports,a,b,c,d)}return c[f].exports}for(var f=0;f<d.length;f++)e(d[f]);return e}({"4O2Y62":[function(a,b){function c(a,b){var c=d[a];return c?c.apply(this,b):(e[a]||(e[a]=[]),void e[a].push(b))}var d={},e={};b.exports=c,c.queues=e,c.handlers=d},{}],handle:[function(a,b){b.exports=a("4O2Y62")},{}],YLUGVp:[function(a,b){function c(){var a=m.info=NREUM.info;if(a&&a.agent&&a.licenseKey&&a.applicationID){m.proto="https"===l.split(":")[0]||a.sslForHttp?"https://":"http://",g("mark",["onload",f()]);var b=i.createElement("script");b.src=m.proto+a.agent,i.body.appendChild(b)}}function d(){"complete"===i.readyState&&e()}function e(){g("mark",["domContent",f()])}function f(){return(new Date).getTime()}var g=a("handle"),h=window,i=h.document,j="addEventListener",k="attachEvent",l=(""+location).split("?")[0],m=b.exports={offset:f(),origin:l,features:[]};i[j]?(i[j]("DOMContentLoaded",e,!1),h[j]("load",c,!1)):(i[k]("onreadystatechange",d),h[k]("onload",c)),g("mark",["firstbyte",f()])},{handle:"4O2Y62"}],loader:[function(a,b){b.exports=a("YLUGVp")},{}]},{},["YLUGVp"]);</script> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <link href="/assets/custom/files/favicon.ico" rel="shortcut icon" /> <link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" /> <link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" /> <link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" /> <meta content="" name="description" /> <meta content="" name="keywords" /> <meta content="NOINDEX, NOFOLLOW" name="ROBOTS" /> <title>Some title</title> <link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" /> <!--[if IE 7]> <link rel="stylesheet" href="/assets/custom/files/css/font-awesome-ie7_min.css"> <![endif]--> <script type="text/javascript" src="/assets/custom/files/js/adobe-type.js"></script> </head> <body> <!-- BODY STUFF IN HERE (REMOVED) --> <script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery-anystretch-stand-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/common.js"></script> <script type="text/javascript" src="/assets/custom/files/js/modernizr.js"></script> <script type="text/javascript" src="/assets/custom/files/js/responsiveslides_min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/socialmedia.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery_atooltip_min.js"></script></div> <script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-4.newrelic.com","licenseKey":"204ccc8db2","applicationID":"1825150","transactionName":"YVNVYBACWxFTWxFcWVgZYkYLTFwMVl0dG0ZeRg==","queueTime":0,"applicationTime":187,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-361.min.js"}</script></body> </html> ``` What could be the reason?
2014/04/03
[ "https://Stackoverflow.com/questions/22830387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999681/" ]
May be you have included your script file `commmon.js` twice. Check your references to it in your code.
It might be event bubbling. Use `event.preventDefault()`, it will prevent the default event from occuring or `event.stopPropagation()` will prevent the event from bubbling up. ``` $(document).ready(function() { $(".fpbtn-one").click(function(event) { event.stopPropagation(); console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); ```
22,830,387
I don't know why and how, but my jQuery code appears to be firing twice on any event. Here's a part of my code: `commmon.js`: ``` $(document).ready(function() { $(".fpbtn-one").click(function() { console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); $(window).load(function() { console.log("Setting up slides"); // Gets logged 2 on page load // These get initialized twice $("#div-1").responsiveSlides({ auto: true, pager: true, pause:true, nav: false, timeout: 3000, speed: 500, maxwidth: 482, namespace: "transparent-btns" }); $("#div-2").responsiveSlides({ auto: true, pager: false, pause:true, nav: false, speed: 2000, maxwidth: 320, }); }); ``` --- HTML: ``` <!doctype html> <html lang="en"> <head><link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/> <link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script> <script type="text/javascript" src="/assets/script/jquery/jquery.qtip.js"></script> <script type="text/javascript" src="/assets/script/jquery/plugin.efiling.full.js"></script> <meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function a(b,c,d){function e(f){if(!c[f]){var g=c[f]={exports:{}};b[f][0].call(g.exports,function(a){var c=b[f][1][a];return e(c?c:a)},g,g.exports,a,b,c,d)}return c[f].exports}for(var f=0;f<d.length;f++)e(d[f]);return e}({"4O2Y62":[function(a,b){function c(a,b){var c=d[a];return c?c.apply(this,b):(e[a]||(e[a]=[]),void e[a].push(b))}var d={},e={};b.exports=c,c.queues=e,c.handlers=d},{}],handle:[function(a,b){b.exports=a("4O2Y62")},{}],YLUGVp:[function(a,b){function c(){var a=m.info=NREUM.info;if(a&&a.agent&&a.licenseKey&&a.applicationID){m.proto="https"===l.split(":")[0]||a.sslForHttp?"https://":"http://",g("mark",["onload",f()]);var b=i.createElement("script");b.src=m.proto+a.agent,i.body.appendChild(b)}}function d(){"complete"===i.readyState&&e()}function e(){g("mark",["domContent",f()])}function f(){return(new Date).getTime()}var g=a("handle"),h=window,i=h.document,j="addEventListener",k="attachEvent",l=(""+location).split("?")[0],m=b.exports={offset:f(),origin:l,features:[]};i[j]?(i[j]("DOMContentLoaded",e,!1),h[j]("load",c,!1)):(i[k]("onreadystatechange",d),h[k]("onload",c)),g("mark",["firstbyte",f()])},{handle:"4O2Y62"}],loader:[function(a,b){b.exports=a("YLUGVp")},{}]},{},["YLUGVp"]);</script> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <link href="/assets/custom/files/favicon.ico" rel="shortcut icon" /> <link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" /> <link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" /> <link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" /> <meta content="" name="description" /> <meta content="" name="keywords" /> <meta content="NOINDEX, NOFOLLOW" name="ROBOTS" /> <title>Some title</title> <link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" /> <!--[if IE 7]> <link rel="stylesheet" href="/assets/custom/files/css/font-awesome-ie7_min.css"> <![endif]--> <script type="text/javascript" src="/assets/custom/files/js/adobe-type.js"></script> </head> <body> <!-- BODY STUFF IN HERE (REMOVED) --> <script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery-anystretch-stand-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/common.js"></script> <script type="text/javascript" src="/assets/custom/files/js/modernizr.js"></script> <script type="text/javascript" src="/assets/custom/files/js/responsiveslides_min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/socialmedia.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery_atooltip_min.js"></script></div> <script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-4.newrelic.com","licenseKey":"204ccc8db2","applicationID":"1825150","transactionName":"YVNVYBACWxFTWxFcWVgZYkYLTFwMVl0dG0ZeRg==","queueTime":0,"applicationTime":187,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-361.min.js"}</script></body> </html> ``` What could be the reason?
2014/04/03
[ "https://Stackoverflow.com/questions/22830387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999681/" ]
Try putting the stuff in the body inside divs. example. `<div id = "menu"><script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> </div>` I hope that works. :)
The simplest explanation is that you have included the common.js twice by mistake. Look into individual scripts and see if you have referenced common.js on top of your main file.
22,830,387
I don't know why and how, but my jQuery code appears to be firing twice on any event. Here's a part of my code: `commmon.js`: ``` $(document).ready(function() { $(".fpbtn-one").click(function() { console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); $(window).load(function() { console.log("Setting up slides"); // Gets logged 2 on page load // These get initialized twice $("#div-1").responsiveSlides({ auto: true, pager: true, pause:true, nav: false, timeout: 3000, speed: 500, maxwidth: 482, namespace: "transparent-btns" }); $("#div-2").responsiveSlides({ auto: true, pager: false, pause:true, nav: false, speed: 2000, maxwidth: 320, }); }); ``` --- HTML: ``` <!doctype html> <html lang="en"> <head><link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/> <link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script> <script type="text/javascript" src="/assets/script/jquery/jquery.qtip.js"></script> <script type="text/javascript" src="/assets/script/jquery/plugin.efiling.full.js"></script> <meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function a(b,c,d){function e(f){if(!c[f]){var g=c[f]={exports:{}};b[f][0].call(g.exports,function(a){var c=b[f][1][a];return e(c?c:a)},g,g.exports,a,b,c,d)}return c[f].exports}for(var f=0;f<d.length;f++)e(d[f]);return e}({"4O2Y62":[function(a,b){function c(a,b){var c=d[a];return c?c.apply(this,b):(e[a]||(e[a]=[]),void e[a].push(b))}var d={},e={};b.exports=c,c.queues=e,c.handlers=d},{}],handle:[function(a,b){b.exports=a("4O2Y62")},{}],YLUGVp:[function(a,b){function c(){var a=m.info=NREUM.info;if(a&&a.agent&&a.licenseKey&&a.applicationID){m.proto="https"===l.split(":")[0]||a.sslForHttp?"https://":"http://",g("mark",["onload",f()]);var b=i.createElement("script");b.src=m.proto+a.agent,i.body.appendChild(b)}}function d(){"complete"===i.readyState&&e()}function e(){g("mark",["domContent",f()])}function f(){return(new Date).getTime()}var g=a("handle"),h=window,i=h.document,j="addEventListener",k="attachEvent",l=(""+location).split("?")[0],m=b.exports={offset:f(),origin:l,features:[]};i[j]?(i[j]("DOMContentLoaded",e,!1),h[j]("load",c,!1)):(i[k]("onreadystatechange",d),h[k]("onload",c)),g("mark",["firstbyte",f()])},{handle:"4O2Y62"}],loader:[function(a,b){b.exports=a("YLUGVp")},{}]},{},["YLUGVp"]);</script> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <link href="/assets/custom/files/favicon.ico" rel="shortcut icon" /> <link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" /> <link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" /> <link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" /> <meta content="" name="description" /> <meta content="" name="keywords" /> <meta content="NOINDEX, NOFOLLOW" name="ROBOTS" /> <title>Some title</title> <link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" /> <!--[if IE 7]> <link rel="stylesheet" href="/assets/custom/files/css/font-awesome-ie7_min.css"> <![endif]--> <script type="text/javascript" src="/assets/custom/files/js/adobe-type.js"></script> </head> <body> <!-- BODY STUFF IN HERE (REMOVED) --> <script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery-anystretch-stand-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/common.js"></script> <script type="text/javascript" src="/assets/custom/files/js/modernizr.js"></script> <script type="text/javascript" src="/assets/custom/files/js/responsiveslides_min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/socialmedia.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery_atooltip_min.js"></script></div> <script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-4.newrelic.com","licenseKey":"204ccc8db2","applicationID":"1825150","transactionName":"YVNVYBACWxFTWxFcWVgZYkYLTFwMVl0dG0ZeRg==","queueTime":0,"applicationTime":187,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-361.min.js"}</script></body> </html> ``` What could be the reason?
2014/04/03
[ "https://Stackoverflow.com/questions/22830387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999681/" ]
Could it be that your code was manipulating the element that the code was loading into? This answer may be the reason why it was happening: [jQuery $(document).ready () fires twice](https://stackoverflow.com/questions/10727002/jquery-document-ready-fires-twice)
Your relevant code is required, but from the snippets above; try putting all the codes in the document ready method.
22,830,387
I don't know why and how, but my jQuery code appears to be firing twice on any event. Here's a part of my code: `commmon.js`: ``` $(document).ready(function() { $(".fpbtn-one").click(function() { console.log("Click recorded!"); // Gets logged twice on click $(this).parent().next().slideToggle(); }); // The rest of the code... }); $(window).load(function() { console.log("Setting up slides"); // Gets logged 2 on page load // These get initialized twice $("#div-1").responsiveSlides({ auto: true, pager: true, pause:true, nav: false, timeout: 3000, speed: 500, maxwidth: 482, namespace: "transparent-btns" }); $("#div-2").responsiveSlides({ auto: true, pager: false, pause:true, nav: false, speed: 2000, maxwidth: 320, }); }); ``` --- HTML: ``` <!doctype html> <html lang="en"> <head><link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/> <link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script> <script type="text/javascript" src="/assets/script/jquery/jquery.qtip.js"></script> <script type="text/javascript" src="/assets/script/jquery/plugin.efiling.full.js"></script> <meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function a(b,c,d){function e(f){if(!c[f]){var g=c[f]={exports:{}};b[f][0].call(g.exports,function(a){var c=b[f][1][a];return e(c?c:a)},g,g.exports,a,b,c,d)}return c[f].exports}for(var f=0;f<d.length;f++)e(d[f]);return e}({"4O2Y62":[function(a,b){function c(a,b){var c=d[a];return c?c.apply(this,b):(e[a]||(e[a]=[]),void e[a].push(b))}var d={},e={};b.exports=c,c.queues=e,c.handlers=d},{}],handle:[function(a,b){b.exports=a("4O2Y62")},{}],YLUGVp:[function(a,b){function c(){var a=m.info=NREUM.info;if(a&&a.agent&&a.licenseKey&&a.applicationID){m.proto="https"===l.split(":")[0]||a.sslForHttp?"https://":"http://",g("mark",["onload",f()]);var b=i.createElement("script");b.src=m.proto+a.agent,i.body.appendChild(b)}}function d(){"complete"===i.readyState&&e()}function e(){g("mark",["domContent",f()])}function f(){return(new Date).getTime()}var g=a("handle"),h=window,i=h.document,j="addEventListener",k="attachEvent",l=(""+location).split("?")[0],m=b.exports={offset:f(),origin:l,features:[]};i[j]?(i[j]("DOMContentLoaded",e,!1),h[j]("load",c,!1)):(i[k]("onreadystatechange",d),h[k]("onload",c)),g("mark",["firstbyte",f()])},{handle:"4O2Y62"}],loader:[function(a,b){b.exports=a("YLUGVp")},{}]},{},["YLUGVp"]);</script> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <link href="/assets/custom/files/favicon.ico" rel="shortcut icon" /> <link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" /> <link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" /> <link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" /> <meta content="" name="description" /> <meta content="" name="keywords" /> <meta content="NOINDEX, NOFOLLOW" name="ROBOTS" /> <title>Some title</title> <link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" /> <link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" /> <!--[if IE 7]> <link rel="stylesheet" href="/assets/custom/files/css/font-awesome-ie7_min.css"> <![endif]--> <script type="text/javascript" src="/assets/custom/files/js/adobe-type.js"></script> </head> <body> <!-- BODY STUFF IN HERE (REMOVED) --> <script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery-anystretch-stand-min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/common.js"></script> <script type="text/javascript" src="/assets/custom/files/js/modernizr.js"></script> <script type="text/javascript" src="/assets/custom/files/js/responsiveslides_min.js"></script> <script type="text/javascript" src="/assets/custom/files/js/socialmedia.js"></script> <script type="text/javascript" src="/assets/custom/files/js/jquery_atooltip_min.js"></script></div> <script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-4.newrelic.com","licenseKey":"204ccc8db2","applicationID":"1825150","transactionName":"YVNVYBACWxFTWxFcWVgZYkYLTFwMVl0dG0ZeRg==","queueTime":0,"applicationTime":187,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-361.min.js"}</script></body> </html> ``` What could be the reason?
2014/04/03
[ "https://Stackoverflow.com/questions/22830387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999681/" ]
Could it be that your code was manipulating the element that the code was loading into? This answer may be the reason why it was happening: [jQuery $(document).ready () fires twice](https://stackoverflow.com/questions/10727002/jquery-document-ready-fires-twice)
The simplest explanation is that you have included the common.js twice by mistake. Look into individual scripts and see if you have referenced common.js on top of your main file.
31,646,520
Here is my code: ``` private void textBox1_TextChanged(object sender, EventArgs e) { DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s", System.Globalization.CultureInfo.InvariantCulture); TimeChangedHandler(myDate); } ``` If I delete 1 number from hours then it works fine, but if I delete both numbers e.x. I want to change from 11 to 22 then it crashes. So how do I make the form `"yyyy-MM-dd H:m:s"` work for all cases? Thanks!
2015/07/27
[ "https://Stackoverflow.com/questions/31646520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4551943/" ]
If you want to indicate that the date/time is invalid, use `DateTime.TryParseExact` to *check* whether or not it's valid, without throwing an exception. Use the return value (true/false) to determine the validity. Basically, you shouldn't expect that the value is always valid while the user is editing - just like while I'm editing code, it won't always be syntactically correct. You need to check that it's valid when you actually *use* the value - and until then, probably just add a visual marker to indicate that it's invalid. You may want to think about whether your `TimeChangedHandler` (whatever that is) should implicitly fire whenever the date/time provided is valid, or whether your UI should provide a more explicit "use this value" action (e.g. a button). Also, consider using a `DateTimePicker` as a friendlier way of selecting a date and time. Finally, I'd personally avoid using a pattern of `H:m:s`... the date part looks like ISO-8601-like, so I'd suggest using `HH:mm:ss` for complete validity - it would be odd (IMO) to see a value of `2015-07-27 7:55:5` for example.
Since it is on `TextChanged` event handler, you may wanna try to add, a `try...catch` handling during real time edits. ``` try { DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s", System.Globalization.CultureInfo.InvariantCulture); TimeChangedHandler(myDate); }catch( Exception ex ) { //Catch exception } ``` Although a better solution would be placing it on a different event. Does the flexible edit means real time editing? If it is, changing the text from 11 to 22 during that time may cause the format to change, so the `ParseExact` would be better be placed on different event.
31,646,520
Here is my code: ``` private void textBox1_TextChanged(object sender, EventArgs e) { DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s", System.Globalization.CultureInfo.InvariantCulture); TimeChangedHandler(myDate); } ``` If I delete 1 number from hours then it works fine, but if I delete both numbers e.x. I want to change from 11 to 22 then it crashes. So how do I make the form `"yyyy-MM-dd H:m:s"` work for all cases? Thanks!
2015/07/27
[ "https://Stackoverflow.com/questions/31646520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4551943/" ]
You may benefit from using DateTime.TryParse method to check what of two formats your date is : ``` private void textBox1_TextChanged(object sender, EventArgs e) { DateTime myDate = default(DateTime); if(!DateTime.TryParseExact(textBox1.Text, "yyyy-MM-dd H:m:s", System.Globalization.CultureInfo.InvariantCulture, out myDate)) DateTime.TryParseExact(textBox1.Text, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, out myDate) if(myDate == default(DateTime)) return; // or // throw new ArgumentException("your text here"); TimeChangedHandler(myDate); } ```
Since it is on `TextChanged` event handler, you may wanna try to add, a `try...catch` handling during real time edits. ``` try { DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s", System.Globalization.CultureInfo.InvariantCulture); TimeChangedHandler(myDate); }catch( Exception ex ) { //Catch exception } ``` Although a better solution would be placing it on a different event. Does the flexible edit means real time editing? If it is, changing the text from 11 to 22 during that time may cause the format to change, so the `ParseExact` would be better be placed on different event.
31,646,520
Here is my code: ``` private void textBox1_TextChanged(object sender, EventArgs e) { DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s", System.Globalization.CultureInfo.InvariantCulture); TimeChangedHandler(myDate); } ``` If I delete 1 number from hours then it works fine, but if I delete both numbers e.x. I want to change from 11 to 22 then it crashes. So how do I make the form `"yyyy-MM-dd H:m:s"` work for all cases? Thanks!
2015/07/27
[ "https://Stackoverflow.com/questions/31646520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4551943/" ]
you shouldn't expect that the value is always valid while the user is editing - just like while I'm editing code, it won't always be syntactically correct. this code need to be placed inside try catch as you want flexible values something like this ``` private void textBox1_TextChanged(object sender, EventArgs e) { try { DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s",System.Globalization.CultureInfo.InvariantCulture); TimeChangedHandler(myDate); } catch (Exception ex) {} } ``` so, it will not explode if user enters incorrect values and consider using a DateTimePicker as a friendlier way of selecting a date and time.
Since it is on `TextChanged` event handler, you may wanna try to add, a `try...catch` handling during real time edits. ``` try { DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s", System.Globalization.CultureInfo.InvariantCulture); TimeChangedHandler(myDate); }catch( Exception ex ) { //Catch exception } ``` Although a better solution would be placing it on a different event. Does the flexible edit means real time editing? If it is, changing the text from 11 to 22 during that time may cause the format to change, so the `ParseExact` would be better be placed on different event.
31,646,520
Here is my code: ``` private void textBox1_TextChanged(object sender, EventArgs e) { DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s", System.Globalization.CultureInfo.InvariantCulture); TimeChangedHandler(myDate); } ``` If I delete 1 number from hours then it works fine, but if I delete both numbers e.x. I want to change from 11 to 22 then it crashes. So how do I make the form `"yyyy-MM-dd H:m:s"` work for all cases? Thanks!
2015/07/27
[ "https://Stackoverflow.com/questions/31646520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4551943/" ]
If you want to indicate that the date/time is invalid, use `DateTime.TryParseExact` to *check* whether or not it's valid, without throwing an exception. Use the return value (true/false) to determine the validity. Basically, you shouldn't expect that the value is always valid while the user is editing - just like while I'm editing code, it won't always be syntactically correct. You need to check that it's valid when you actually *use* the value - and until then, probably just add a visual marker to indicate that it's invalid. You may want to think about whether your `TimeChangedHandler` (whatever that is) should implicitly fire whenever the date/time provided is valid, or whether your UI should provide a more explicit "use this value" action (e.g. a button). Also, consider using a `DateTimePicker` as a friendlier way of selecting a date and time. Finally, I'd personally avoid using a pattern of `H:m:s`... the date part looks like ISO-8601-like, so I'd suggest using `HH:mm:ss` for complete validity - it would be odd (IMO) to see a value of `2015-07-27 7:55:5` for example.
You may benefit from using DateTime.TryParse method to check what of two formats your date is : ``` private void textBox1_TextChanged(object sender, EventArgs e) { DateTime myDate = default(DateTime); if(!DateTime.TryParseExact(textBox1.Text, "yyyy-MM-dd H:m:s", System.Globalization.CultureInfo.InvariantCulture, out myDate)) DateTime.TryParseExact(textBox1.Text, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, out myDate) if(myDate == default(DateTime)) return; // or // throw new ArgumentException("your text here"); TimeChangedHandler(myDate); } ```
31,646,520
Here is my code: ``` private void textBox1_TextChanged(object sender, EventArgs e) { DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s", System.Globalization.CultureInfo.InvariantCulture); TimeChangedHandler(myDate); } ``` If I delete 1 number from hours then it works fine, but if I delete both numbers e.x. I want to change from 11 to 22 then it crashes. So how do I make the form `"yyyy-MM-dd H:m:s"` work for all cases? Thanks!
2015/07/27
[ "https://Stackoverflow.com/questions/31646520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4551943/" ]
If you want to indicate that the date/time is invalid, use `DateTime.TryParseExact` to *check* whether or not it's valid, without throwing an exception. Use the return value (true/false) to determine the validity. Basically, you shouldn't expect that the value is always valid while the user is editing - just like while I'm editing code, it won't always be syntactically correct. You need to check that it's valid when you actually *use* the value - and until then, probably just add a visual marker to indicate that it's invalid. You may want to think about whether your `TimeChangedHandler` (whatever that is) should implicitly fire whenever the date/time provided is valid, or whether your UI should provide a more explicit "use this value" action (e.g. a button). Also, consider using a `DateTimePicker` as a friendlier way of selecting a date and time. Finally, I'd personally avoid using a pattern of `H:m:s`... the date part looks like ISO-8601-like, so I'd suggest using `HH:mm:ss` for complete validity - it would be odd (IMO) to see a value of `2015-07-27 7:55:5` for example.
you shouldn't expect that the value is always valid while the user is editing - just like while I'm editing code, it won't always be syntactically correct. this code need to be placed inside try catch as you want flexible values something like this ``` private void textBox1_TextChanged(object sender, EventArgs e) { try { DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s",System.Globalization.CultureInfo.InvariantCulture); TimeChangedHandler(myDate); } catch (Exception ex) {} } ``` so, it will not explode if user enters incorrect values and consider using a DateTimePicker as a friendlier way of selecting a date and time.
40,798,676
I'm using a table layout for my website. It's working in IE and Chrome, even IE 8 perfectly. My entire website is in one table with three cells. The top navbar, the content, and the bottom footer navbar. The table's width and min-height is set to 100%, and the middle cell is set to height: auto. This makes the footer get pushed to at least the bottom of the window, and if there is enough content the footer is painlessly pushed farther along with the content. But Firefox won't make the middle cell's height fill to reach the table's min-height of 100%. Here is what it looks like in Internet Explorer and Chrome (working): [![Internet Explorer is working](https://i.stack.imgur.com/3gY9Z.png)](https://i.stack.imgur.com/3gY9Z.png) [![Chrome is working](https://i.stack.imgur.com/dgaAJ.png)](https://i.stack.imgur.com/dgaAJ.png) but in Firefox the middle cell's height isn't filling (not working): [![Firefox Table's Middle Cell won't Fill](https://i.stack.imgur.com/ignog.png)](https://i.stack.imgur.com/ignog.png) Here is my CSS: ``` <style> #tablecontainer{ width: 100%; min-height: 100%; } .table-panel { display: table; } .table-panel > div { display: table-row; } .table-panel > div.fill { height: auto; } /* Unimportant styles just to make the demo looks better */ #top-cell { height: 50px; background-color:aqua; } #middle-cell { /* nothing here yet */ background-color:purple; } #bottom-cell { height:50px; background-color:red; } body { height: 100%; margin: 0; } html { height: 100%; } ``` Here is my HTML: ``` <body> <div id="tablecontainer" class="table-panel"> <div id="top-cell"> <nav> </nav> </div> <div id="middle-cell" class="fill"> <div class="section"> <div class="container"> <p>{{ content }}</p> </div> </div> </div> <div id="bottom-cell"> <nav> <p>I'm the footer!</p> </nav> </div> </body> ``` Here's a fiddle. <https://jsfiddle.net/mmgftmyr/> It is completely accurate, the fiddle will work in Chrome and Internet Explorer but not Firefox.
2016/11/25
[ "https://Stackoverflow.com/questions/40798676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6283055/" ]
Problem exists in the following styles: ``` #tablecontainer { min-height: 100%; /* change min-height to height */ width: 100%; } .table-panel { display: table; } ``` `min-height: 100%` property doesn't work properly with `min-height` always. Change `min-height` to `height` and it will work. ***Note***: `HTML` tables have special behavior with height. If you specify `height` for a `table` or and element having `display: table` and its content doesn't fit in then its height will be increased automatically according to the content. So we can always use `height` instead of `min-height` with tables. ```css #tablecontainer{ width: 100%; height: 100%; } .table-panel { display: table; } .table-panel > div { display: table-row; } .table-panel > div.fill { height: auto; } /* Unimportant styles just to make the demo looks better */ #top-cell { height: 50px; background-color:aqua; } #middle-cell { /* nothing here yet */ background-color:purple; } #bottom-cell { height:50px; background-color:red; } body { height: 100%; margin: 0; } html { height: 100%; } ``` ```html <div id="tablecontainer" class="table-panel"> <div id="top-cell"> <nav> </nav> </div> <div id="middle-cell" class="fill"> <div class="section"> <div class="container"> <p>{{ content }}</p> </div> </div> </div> <div id="bottom-cell"> <nav> <p>I'm the footer!</p> </nav> </div> </div> ```
On Firefox, `min-height` is not interpreted on `display: table;` instead of using `min-height` use `height:100%;` ``` #tablecontainer{ width: 100%; height:100%; } ``` [updated fiddle](https://jsfiddle.net/4Lr0esn4/3/)
58,919,766
I registered Moment.js as a plugin, like this: ``` import Vue from 'vue' import moment from 'moment' moment.locale('pt_BR') Vue.use({ install (Vue) { Vue.prototype.$moment = moment } }) ``` Now, I need to use this in my `main.js` filters ``` import './plugins/moment' Vue.filter('formatDate', value => { return this.$moment(value, 'YYYY-MM-DD').format('DD/MM/YYYY') }) ``` Buth this return an error: > > Error in render: "TypeError: Cannot read property '$moment' of > undefined" > > >
2019/11/18
[ "https://Stackoverflow.com/questions/58919766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3691686/" ]
Looks like you can not access `this` like in the `vue` components for filter methods. [By Evan You](https://github.com/vuejs/vue/issues/5998#issuecomment-311965292) > > This is intentional in 2.x. Filters should be pure functions and should not be dependent on this context. If you need this you should use a computed property or just a method e.g. $translate(foo) > > > I guess the best way is importing the `moment` on `main.js` like this: ``` import moment from 'moment' Vue.filter('formatDate', value => { return moment(value, 'YYYY-MM-DD').format('DD/MM/YYYY') }) ```
Vue.filter() creates a global filter before the Vue instance is created, a global filter does not have access to the Vue instance therefore you can not access this.$moment. If you need to access the vue instance, you'll need to register a local filter on components. However, you could rectify this by directly referencing the module: ``` import moment from 'moment'; Vue.filter('formatDate', value => { moment(value, 'YYYY-MM-DD').format('DD/MM/YYYY') }); ```
172,288
Multiple times I've found myself in a situation in a meeting where I'm laying out my plans for a project I've been assigned and either my manager or a co-worker identify something to be impossible and therefore I should do something else (taking the time to explain how to do it). Instead of trying to convince them that my plan is possible in the meeting (which I've learned the hard way is a very bad thing to do), I instead after the meeting go and create a proof of concept to show that it is possible and present it the next time we have a meeting about my project with pros and cons compared to the solution they presented. Is this bad etiquette on my part and should I just go with the group and implement the suggested solution just to keep a good rapport with my coworkers (not making them look bad).   Normally if the meeting is about my co-worker's project, I won't do anything after the meeting if they choose a different path than what I would have done and if my boss or co-worker states that they don't want something implemented a particular way and they don't specify that its because they think it's impossible I respect their viewpoint and adjust my project accordingly. If this is bad etiquette, what should I do when someone is trying to guide my project using known incorrect reasoning?
2021/05/08
[ "https://workplace.stackexchange.com/questions/172288", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/81043/" ]
> > If this is bad etiquette, what should I do when someone is trying to > guide my project using known incorrect reasoning? > > > Make your case. If they reject your suggestions, ideas, and opinions then do what your boss tells you to do. It isn't your company. It isn't your decision. At the end of the day, they pay you to perform work. You may sometimes disagree with that work. That's OK.
In the future, present your ideas privately one-on-one to the usual meeting participants before you bring them up to the entire group in the larger meeting. Group dynamics are weird, and it's much easier to correct your idea or convince someone of your idea when you're dealing with them one-on-one. Do the same with your manager as well. If your manager has any hesitation, then you can ask them for permission to build a quick proof-of-concept. With that said, the situation is a little bit different now since the group has already shot down your idea. If you'd be willing to work on this idea during your own personal time, and assuming you have a good relationship with your manager, I don't see anything wrong with trying to build a proof-of-concept that specifically addresses the features that are supposedly "impossible". But if you do this, and if you've used your own time, and assuming it actually works, present your proof-of-concept privately to your manager and see what he says. Do not surprise him with this during a meeting with others.
172,288
Multiple times I've found myself in a situation in a meeting where I'm laying out my plans for a project I've been assigned and either my manager or a co-worker identify something to be impossible and therefore I should do something else (taking the time to explain how to do it). Instead of trying to convince them that my plan is possible in the meeting (which I've learned the hard way is a very bad thing to do), I instead after the meeting go and create a proof of concept to show that it is possible and present it the next time we have a meeting about my project with pros and cons compared to the solution they presented. Is this bad etiquette on my part and should I just go with the group and implement the suggested solution just to keep a good rapport with my coworkers (not making them look bad).   Normally if the meeting is about my co-worker's project, I won't do anything after the meeting if they choose a different path than what I would have done and if my boss or co-worker states that they don't want something implemented a particular way and they don't specify that its because they think it's impossible I respect their viewpoint and adjust my project accordingly. If this is bad etiquette, what should I do when someone is trying to guide my project using known incorrect reasoning?
2021/05/08
[ "https://workplace.stackexchange.com/questions/172288", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/81043/" ]
> > If this is bad etiquette, what should I do when someone is trying to > guide my project using known incorrect reasoning? > > > Make your case. If they reject your suggestions, ideas, and opinions then do what your boss tells you to do. It isn't your company. It isn't your decision. At the end of the day, they pay you to perform work. You may sometimes disagree with that work. That's OK.
> > I instead after the meeting go and create a proof of concept to show that it is possible and present it the next time > > > Do this before the first meeting. Meeting dynamics are things to learn from. If you want something to happen a certain way you prepare for the meeting and have your strategies in place before it starts to accomplish what you want. Make this a normal part of your meeting preparations. Anticipate objections and overwhelm them, you have the huge advantage of being prepared and ready while others are raising issues on the fly.
172,288
Multiple times I've found myself in a situation in a meeting where I'm laying out my plans for a project I've been assigned and either my manager or a co-worker identify something to be impossible and therefore I should do something else (taking the time to explain how to do it). Instead of trying to convince them that my plan is possible in the meeting (which I've learned the hard way is a very bad thing to do), I instead after the meeting go and create a proof of concept to show that it is possible and present it the next time we have a meeting about my project with pros and cons compared to the solution they presented. Is this bad etiquette on my part and should I just go with the group and implement the suggested solution just to keep a good rapport with my coworkers (not making them look bad).   Normally if the meeting is about my co-worker's project, I won't do anything after the meeting if they choose a different path than what I would have done and if my boss or co-worker states that they don't want something implemented a particular way and they don't specify that its because they think it's impossible I respect their viewpoint and adjust my project accordingly. If this is bad etiquette, what should I do when someone is trying to guide my project using known incorrect reasoning?
2021/05/08
[ "https://workplace.stackexchange.com/questions/172288", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/81043/" ]
> > I instead after the meeting go and create a proof of concept to show that it is possible and present it the next time > > > Do this before the first meeting. Meeting dynamics are things to learn from. If you want something to happen a certain way you prepare for the meeting and have your strategies in place before it starts to accomplish what you want. Make this a normal part of your meeting preparations. Anticipate objections and overwhelm them, you have the huge advantage of being prepared and ready while others are raising issues on the fly.
In the future, present your ideas privately one-on-one to the usual meeting participants before you bring them up to the entire group in the larger meeting. Group dynamics are weird, and it's much easier to correct your idea or convince someone of your idea when you're dealing with them one-on-one. Do the same with your manager as well. If your manager has any hesitation, then you can ask them for permission to build a quick proof-of-concept. With that said, the situation is a little bit different now since the group has already shot down your idea. If you'd be willing to work on this idea during your own personal time, and assuming you have a good relationship with your manager, I don't see anything wrong with trying to build a proof-of-concept that specifically addresses the features that are supposedly "impossible". But if you do this, and if you've used your own time, and assuming it actually works, present your proof-of-concept privately to your manager and see what he says. Do not surprise him with this during a meeting with others.
65,891,422
I want to retrieve the original index of the column with the largest sum at each iteration after the previous column with the largest sum is removed. Meanwhile, the row of the same index of the deleted column is also deleted from the matrix at each iteration. For example, in a 10 by 10 matrix, the 5th column has the largest sum, hence the 5th column and row are removed. Now the matrix is 9 by 9 and the sum of columns is recalculated. Suppose the 6th column has the largest sum, hence the 6th column and row of the current matrix are removed, which is the 7th in the original matrix. Do this iteratively until the desired number of columns index is preserved. My code in Julia that **does not work** is pasted below. **Step two in the for loop is not correct because a row is removed at each iteration, thus the sum of columns are different.** Thanks! ``` # a matrix of random numbers mat = rand(10, 10); # column sum of the original matrix matColSum = sum(mat, dims=1); # iteratively remove columns with the largest sum idxColRemoveList = []; matTemp = mat; for i in 1:4 # Suppose 4 columns need to be removed # 1. find the index of the column with the largest column sum at current iteration sumTemp = sum(matTemp, dims=1); maxSumTemp = maximum(sumTemp); idxColRemoveTemp = argmax(sumTemp)[2]; # 2. record the orignial index of the removed scenario idxColRemoveOrig = findall(x->x==maxSumTemp, matColSum)[1][2]; push!(idxColRemoveList, idxColRemoveOrig); # 3. update the matrix. Note that the corresponding row is also removed. matTemp = matTemp[Not(idxColRemoveTemp), Not(idxColRemoveTemp)]; end ```
2021/01/25
[ "https://Stackoverflow.com/questions/65891422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10865571/" ]
python solution: ```py import numpy as np mat = np.random.rand(5, 5) n_remove = 3 original = np.arange(len(mat)).tolist() removed = [] for i in range(n_remove): col_sum = np.sum(mat, axis=0) col_rm = np.argsort(col_sum)[-1] removed.append(original.pop(col_rm)) mat = np.delete(np.delete(mat, col_rm, 0), col_rm, 1) print(removed) print(original) print(mat) ``` I'm guessing the problem you had was keeping track with information what was the index of current columns/rows in original array. I've just used a list `[0, 1, 2, ...]` and then pop one value in each iteration.
A simpler way to code the problem would be to replace elements in the selected column with a significantly small number instead of deleting the column. This approach avoids the use of "sort" and "pop" to improve code efficiency. ``` import numpy as np n = 1000 mat = np.random.rand(n, n) n_remove = 500 removed = [] for i in range(n_remove): # get sum of each column col_sum = np.sum(mat, axis=0) col_rm = np.argmax(col_sum) # record the column ID removed.append(col_rm) # replace elements in the col_rm-th column and row with the zeros mat[:, col_rm] = 1e-10 mat[col_rm, :] = 1e-10 print(removed) ```
24,235,183
I feel like I have a pretty good grasp on using decorators when dealing with regular functions, but between using methods of base classes for decorators in derived classes, and passing parameters to said decorators, I cannot figure out what to do next. Here is a snippet of code. ``` class ValidatedObject: ... def apply_validation(self, field_name, code): def wrap(self, f): self._validations.append(Validation(field_name, code, f)) return f return wrap class test(ValidatedObject): .... @apply_validation("_name", "oh no!") def name_validation(self, name): return name == "jacob" ``` If I try this as is, I get an "apply\_validation" is not found. If I try it with `@self.apply_validation` I get a "self" isn't found. I've also been messing around with making `apply_validation` a class method without success. Would someone please explain what I'm doing wrong, and the best way to fix this? Thank you.
2014/06/16
[ "https://Stackoverflow.com/questions/24235183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431333/" ]
In case someone stumbled on this later. To extract the data you can use regex, while for the custom median filter you can have a look [here](https://gist.github.com/bhawkins/3535131). I will leave a copy down here in case it is removed: ``` def medfilt (x, k): """Apply a length-k median filter to a 1D array x. Boundaries are extended by repeating endpoints. """ assert k % 2 == 1, "Median filter length must be odd." assert x.ndim == 1, "Input must be one-dimensional." k2 = (k - 1) // 2 y = np.zeros ((len (x), k), dtype=x.dtype) y[:,k2] = x for i in range (k2): j = k2 - i y[j:,i] = x[:-j] y[:j,i] = x[0] y[:-j,-(i+1)] = x[j:] y[-j:,-(i+1)] = x[-1] return np.median (y, axis=1) ```
*scipy.signal.medfilt* accepts 1D kernels: ``` import pandas as pd import scipy.signal def median_filter(file_name, new_file_name, kernel_size): with open(file_name, 'r') as f: df = pd.read_csv(f, header=None) signal = df.iloc[:, 1].values median = scipy.signal.medfilt(signal, kernel_size) df = df.drop(df.columns[1], 1) df[1] = median df.to_csv(new_file_name, sep=',', index=None, header=None) if __name__=='__main__': median_filter('old_signal.csv', 'new_signal.csv', 23) ```
49,481,364
I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned. Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array? ``` function removeFromEnd(arr) { t = [...arr].reverse().findIndex(e => e !== ''); if (t === 0) { return arr; } else if (t === -1) { return []; } else { return arr.slice(0, -1 * t); } } ``` Test cases ---------- ``` console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ``` [ 'a', 'b', '', 'c' ] [ 'a' ] [ '', '', '', '', 'c' ] [] ```
2018/03/25
[ "https://Stackoverflow.com/questions/49481364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552063/" ]
I'd use reduce and only add an element if it isn't an empty string or the array already has entries in it ```js console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); function removeFromEnd(arr) { return arr.reduceRight((a, b) => { if (b !== '' || a.length) a.push(b); return a; }, []).reverse(); } ```
> > is there a way that does not require all these ifs? Can I do it without creating in-memory copy of array? > > > Probably not very functional, but a very straight forward implementation: ```js function removeFromEnd(arr) { let i = arr.length - 1; while (arr[i] === "") i--; return arr.slice(0, i + 1); } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` It's hard to find the balance here... You tagged `functional-programming`, and the answer by @naomik shows you a beautiful functional solution that matches both the tag and the concern in the quote. If you're just looking to simplify and optimize, my snippet here might just be enough...
49,481,364
I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned. Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array? ``` function removeFromEnd(arr) { t = [...arr].reverse().findIndex(e => e !== ''); if (t === 0) { return arr; } else if (t === -1) { return []; } else { return arr.slice(0, -1 * t); } } ``` Test cases ---------- ``` console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ``` [ 'a', 'b', '', 'c' ] [ 'a' ] [ '', '', '', '', 'c' ] [] ```
2018/03/25
[ "https://Stackoverflow.com/questions/49481364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552063/" ]
An alternative is using the function **[`reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight)** along with the **[`Spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)**. ```js let removeFromEnd = (arr) => arr.reduceRight((a, b) => ((b !== '' || a.length) ? [b, ...a] : a), []); console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
You can reverse the array and remove elements until you reach a non empty string. Here is an example: ```js function removeFromEnd(arr){ return arr.reverse().filter(function(v){ if(v !== ""){ this.stopRemoving = true; } return this.stopRemoving; }, {stopRemoving: false}).reverse(); } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` And here is an example using a classic loop ```js function removeFromEnd(arr){ for(var i = arr.length - 1; i >= 0; i--){ if(arr[i] !== ""){ break; } arr.pop(); } return arr; } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ```
49,481,364
I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned. Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array? ``` function removeFromEnd(arr) { t = [...arr].reverse().findIndex(e => e !== ''); if (t === 0) { return arr; } else if (t === -1) { return []; } else { return arr.slice(0, -1 * t); } } ``` Test cases ---------- ``` console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ``` [ 'a', 'b', '', 'c' ] [ 'a' ] [ '', '', '', '', 'c' ] [] ```
2018/03/25
[ "https://Stackoverflow.com/questions/49481364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552063/" ]
An alternative is using the function **[`reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight)** along with the **[`Spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)**. ```js let removeFromEnd = (arr) => arr.reduceRight((a, b) => ((b !== '' || a.length) ? [b, ...a] : a), []); console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
> > is there a way that does not require all these ifs? Can I do it without creating in-memory copy of array? > > > Probably not very functional, but a very straight forward implementation: ```js function removeFromEnd(arr) { let i = arr.length - 1; while (arr[i] === "") i--; return arr.slice(0, i + 1); } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` It's hard to find the balance here... You tagged `functional-programming`, and the answer by @naomik shows you a beautiful functional solution that matches both the tag and the concern in the quote. If you're just looking to simplify and optimize, my snippet here might just be enough...
49,481,364
I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned. Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array? ``` function removeFromEnd(arr) { t = [...arr].reverse().findIndex(e => e !== ''); if (t === 0) { return arr; } else if (t === -1) { return []; } else { return arr.slice(0, -1 * t); } } ``` Test cases ---------- ``` console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ``` [ 'a', 'b', '', 'c' ] [ 'a' ] [ '', '', '', '', 'c' ] [] ```
2018/03/25
[ "https://Stackoverflow.com/questions/49481364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552063/" ]
Here's a tail recursive implementation of `removeFromEnd`. Our implementation: * does not mutate its input * does not unnecessarily calculate the `reverse` of the input * does not unnecessarily search the input using `find` or `findIndex` * does not iterate thru the input more than once * does not require `Array.prototype.reduce` or `Array.prototype.reduceRight` * accepts *any* [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) input – not only Arrays ```js const identity = x => x const Empty = Symbol () const removeFromEnd = ([ x = Empty, ...xs ], cont = identity) => x === Empty ? cont ([]) : removeFromEnd (xs, end => end.length === 0 && x === '' ? cont ([]) : cont ([ x, ...end ])) console.log (removeFromEnd ([ 'a', 'b', '', 'c', '', '' ])) // [ 'a', 'b', '', 'c' ] console.log (removeFromEnd ([ 'a', '', '' ])) // [ 'a' ] console.log (removeFromEnd ([ '', '', '', '', 'c' ])) // [ '', '', '', '', 'c' ] console.log (removeFromEnd ([ '', '', '', '' ])) // [] ``` I think `removeFromEnd` can be improved as a higher-order function, much like `Array.prototype.filter` ```js const identity = x => x const Empty = Symbol () const removeFromEnd = (f = Boolean, [ x = Empty, ...xs ], cont = identity) => x === Empty ? cont ([]) : removeFromEnd (f, xs, end => end.length === 0 && f (x) ? cont ([]) : cont ([ x, ...end ])) console.log (removeFromEnd (x => x === '', [ 'a', 'b', '', 'c', '', '', false, 0 ])) // [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => !x, [ 'a', 'b', '', 'c', '', '', false, 0 ])) // [ 'a', 'b', '', 'c' ] ``` For beginners, here is `removeFromEnd` expressed without fanciful ES6 destructuring syntaxes or arrow functions ```js const identity = function (x) { return x } const removeFromEnd = function (f = Boolean, xs = [], i = 0, cont = identity) { if (i > xs.length) return cont ([]) else return removeFromEnd (f, xs, i + 1, function (end) { if (end.length === 0 && f (xs [i])) return cont ([]) else return cont ([ xs [i] ].concat (end)) }) } const data = [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => x === '', data)) // [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => !x, data)) // [ 'a', 'b', '', 'c' ] ``` The continuation-passing style used above might seem foreign to you, but it's essential if you want to write `removeFromEnd`: 1. with a proper [tail call](https://en.wikipedia.org/wiki/Tail_call) 2. with functional style using a pure expression Reverting to imperative style, JavaScript allows us to write the program without the continuation complexity – however, the recursive call is no longer in tail position I share this version of the program because most people that are new to functional thinking are coming from writing programs like this. Seeing the same program expressed in many different styles is something that always helped me tremendously. Maybe it can help you the same way ^^ ```js const removeFromEnd = function (f = Boolean, xs = [], i = 0) { if (i > xs.length) return [] const end = removeFromEnd (f, xs, i + 1) if (end.length === 0 && f (xs [i])) return [] return [ xs [i] ] .concat (end) } const data = [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => x === '', data)) // [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => !x, data)) // [ 'a', 'b', '', 'c' ] ```
I'd use reduce and only add an element if it isn't an empty string or the array already has entries in it ```js console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); function removeFromEnd(arr) { return arr.reduceRight((a, b) => { if (b !== '' || a.length) a.push(b); return a; }, []).reverse(); } ```
49,481,364
I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned. Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array? ``` function removeFromEnd(arr) { t = [...arr].reverse().findIndex(e => e !== ''); if (t === 0) { return arr; } else if (t === -1) { return []; } else { return arr.slice(0, -1 * t); } } ``` Test cases ---------- ``` console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ``` [ 'a', 'b', '', 'c' ] [ 'a' ] [ '', '', '', '', 'c' ] [] ```
2018/03/25
[ "https://Stackoverflow.com/questions/49481364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552063/" ]
Here's a tail recursive implementation of `removeFromEnd`. Our implementation: * does not mutate its input * does not unnecessarily calculate the `reverse` of the input * does not unnecessarily search the input using `find` or `findIndex` * does not iterate thru the input more than once * does not require `Array.prototype.reduce` or `Array.prototype.reduceRight` * accepts *any* [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) input – not only Arrays ```js const identity = x => x const Empty = Symbol () const removeFromEnd = ([ x = Empty, ...xs ], cont = identity) => x === Empty ? cont ([]) : removeFromEnd (xs, end => end.length === 0 && x === '' ? cont ([]) : cont ([ x, ...end ])) console.log (removeFromEnd ([ 'a', 'b', '', 'c', '', '' ])) // [ 'a', 'b', '', 'c' ] console.log (removeFromEnd ([ 'a', '', '' ])) // [ 'a' ] console.log (removeFromEnd ([ '', '', '', '', 'c' ])) // [ '', '', '', '', 'c' ] console.log (removeFromEnd ([ '', '', '', '' ])) // [] ``` I think `removeFromEnd` can be improved as a higher-order function, much like `Array.prototype.filter` ```js const identity = x => x const Empty = Symbol () const removeFromEnd = (f = Boolean, [ x = Empty, ...xs ], cont = identity) => x === Empty ? cont ([]) : removeFromEnd (f, xs, end => end.length === 0 && f (x) ? cont ([]) : cont ([ x, ...end ])) console.log (removeFromEnd (x => x === '', [ 'a', 'b', '', 'c', '', '', false, 0 ])) // [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => !x, [ 'a', 'b', '', 'c', '', '', false, 0 ])) // [ 'a', 'b', '', 'c' ] ``` For beginners, here is `removeFromEnd` expressed without fanciful ES6 destructuring syntaxes or arrow functions ```js const identity = function (x) { return x } const removeFromEnd = function (f = Boolean, xs = [], i = 0, cont = identity) { if (i > xs.length) return cont ([]) else return removeFromEnd (f, xs, i + 1, function (end) { if (end.length === 0 && f (xs [i])) return cont ([]) else return cont ([ xs [i] ].concat (end)) }) } const data = [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => x === '', data)) // [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => !x, data)) // [ 'a', 'b', '', 'c' ] ``` The continuation-passing style used above might seem foreign to you, but it's essential if you want to write `removeFromEnd`: 1. with a proper [tail call](https://en.wikipedia.org/wiki/Tail_call) 2. with functional style using a pure expression Reverting to imperative style, JavaScript allows us to write the program without the continuation complexity – however, the recursive call is no longer in tail position I share this version of the program because most people that are new to functional thinking are coming from writing programs like this. Seeing the same program expressed in many different styles is something that always helped me tremendously. Maybe it can help you the same way ^^ ```js const removeFromEnd = function (f = Boolean, xs = [], i = 0) { if (i > xs.length) return [] const end = removeFromEnd (f, xs, i + 1) if (end.length === 0 && f (xs [i])) return [] return [ xs [i] ] .concat (end) } const data = [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => x === '', data)) // [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => !x, data)) // [ 'a', 'b', '', 'c' ] ```
You could do this with `reduceRight` and change one value when you find first elements that is not empty string. ```js function removeFromEnd(arr) { return arr.reduceRight((r, e) => { if (e) r.match = true; if (r.match) r.arr.unshift(e) return r; }, {arr: []}).arr } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ```
49,481,364
I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned. Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array? ``` function removeFromEnd(arr) { t = [...arr].reverse().findIndex(e => e !== ''); if (t === 0) { return arr; } else if (t === -1) { return []; } else { return arr.slice(0, -1 * t); } } ``` Test cases ---------- ``` console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ``` [ 'a', 'b', '', 'c' ] [ 'a' ] [ '', '', '', '', 'c' ] [] ```
2018/03/25
[ "https://Stackoverflow.com/questions/49481364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552063/" ]
Here's a tail recursive implementation of `removeFromEnd`. Our implementation: * does not mutate its input * does not unnecessarily calculate the `reverse` of the input * does not unnecessarily search the input using `find` or `findIndex` * does not iterate thru the input more than once * does not require `Array.prototype.reduce` or `Array.prototype.reduceRight` * accepts *any* [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) input – not only Arrays ```js const identity = x => x const Empty = Symbol () const removeFromEnd = ([ x = Empty, ...xs ], cont = identity) => x === Empty ? cont ([]) : removeFromEnd (xs, end => end.length === 0 && x === '' ? cont ([]) : cont ([ x, ...end ])) console.log (removeFromEnd ([ 'a', 'b', '', 'c', '', '' ])) // [ 'a', 'b', '', 'c' ] console.log (removeFromEnd ([ 'a', '', '' ])) // [ 'a' ] console.log (removeFromEnd ([ '', '', '', '', 'c' ])) // [ '', '', '', '', 'c' ] console.log (removeFromEnd ([ '', '', '', '' ])) // [] ``` I think `removeFromEnd` can be improved as a higher-order function, much like `Array.prototype.filter` ```js const identity = x => x const Empty = Symbol () const removeFromEnd = (f = Boolean, [ x = Empty, ...xs ], cont = identity) => x === Empty ? cont ([]) : removeFromEnd (f, xs, end => end.length === 0 && f (x) ? cont ([]) : cont ([ x, ...end ])) console.log (removeFromEnd (x => x === '', [ 'a', 'b', '', 'c', '', '', false, 0 ])) // [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => !x, [ 'a', 'b', '', 'c', '', '', false, 0 ])) // [ 'a', 'b', '', 'c' ] ``` For beginners, here is `removeFromEnd` expressed without fanciful ES6 destructuring syntaxes or arrow functions ```js const identity = function (x) { return x } const removeFromEnd = function (f = Boolean, xs = [], i = 0, cont = identity) { if (i > xs.length) return cont ([]) else return removeFromEnd (f, xs, i + 1, function (end) { if (end.length === 0 && f (xs [i])) return cont ([]) else return cont ([ xs [i] ].concat (end)) }) } const data = [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => x === '', data)) // [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => !x, data)) // [ 'a', 'b', '', 'c' ] ``` The continuation-passing style used above might seem foreign to you, but it's essential if you want to write `removeFromEnd`: 1. with a proper [tail call](https://en.wikipedia.org/wiki/Tail_call) 2. with functional style using a pure expression Reverting to imperative style, JavaScript allows us to write the program without the continuation complexity – however, the recursive call is no longer in tail position I share this version of the program because most people that are new to functional thinking are coming from writing programs like this. Seeing the same program expressed in many different styles is something that always helped me tremendously. Maybe it can help you the same way ^^ ```js const removeFromEnd = function (f = Boolean, xs = [], i = 0) { if (i > xs.length) return [] const end = removeFromEnd (f, xs, i + 1) if (end.length === 0 && f (xs [i])) return [] return [ xs [i] ] .concat (end) } const data = [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => x === '', data)) // [ 'a', 'b', '', 'c', '', '', false, 0 ] console.log (removeFromEnd (x => !x, data)) // [ 'a', 'b', '', 'c' ] ```
> > is there a way that does not require all these ifs? Can I do it without creating in-memory copy of array? > > > Probably not very functional, but a very straight forward implementation: ```js function removeFromEnd(arr) { let i = arr.length - 1; while (arr[i] === "") i--; return arr.slice(0, i + 1); } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` It's hard to find the balance here... You tagged `functional-programming`, and the answer by @naomik shows you a beautiful functional solution that matches both the tag and the concern in the quote. If you're just looking to simplify and optimize, my snippet here might just be enough...
49,481,364
I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned. Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array? ``` function removeFromEnd(arr) { t = [...arr].reverse().findIndex(e => e !== ''); if (t === 0) { return arr; } else if (t === -1) { return []; } else { return arr.slice(0, -1 * t); } } ``` Test cases ---------- ``` console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ``` [ 'a', 'b', '', 'c' ] [ 'a' ] [ '', '', '', '', 'c' ] [] ```
2018/03/25
[ "https://Stackoverflow.com/questions/49481364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552063/" ]
You could do this with `reduceRight` and change one value when you find first elements that is not empty string. ```js function removeFromEnd(arr) { return arr.reduceRight((r, e) => { if (e) r.match = true; if (r.match) r.arr.unshift(e) return r; }, {arr: []}).arr } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ```
> > is there a way that does not require all these ifs? Can I do it without creating in-memory copy of array? > > > Probably not very functional, but a very straight forward implementation: ```js function removeFromEnd(arr) { let i = arr.length - 1; while (arr[i] === "") i--; return arr.slice(0, i + 1); } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` It's hard to find the balance here... You tagged `functional-programming`, and the answer by @naomik shows you a beautiful functional solution that matches both the tag and the concern in the quote. If you're just looking to simplify and optimize, my snippet here might just be enough...
49,481,364
I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned. Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array? ``` function removeFromEnd(arr) { t = [...arr].reverse().findIndex(e => e !== ''); if (t === 0) { return arr; } else if (t === -1) { return []; } else { return arr.slice(0, -1 * t); } } ``` Test cases ---------- ``` console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ``` [ 'a', 'b', '', 'c' ] [ 'a' ] [ '', '', '', '', 'c' ] [] ```
2018/03/25
[ "https://Stackoverflow.com/questions/49481364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552063/" ]
An alternative is using the function **[`reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight)** along with the **[`Spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)**. ```js let removeFromEnd = (arr) => arr.reduceRight((a, b) => ((b !== '' || a.length) ? [b, ...a] : a), []); console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
You could do this with `reduceRight` and change one value when you find first elements that is not empty string. ```js function removeFromEnd(arr) { return arr.reduceRight((r, e) => { if (e) r.match = true; if (r.match) r.arr.unshift(e) return r; }, {arr: []}).arr } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ```
49,481,364
I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned. Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array? ``` function removeFromEnd(arr) { t = [...arr].reverse().findIndex(e => e !== ''); if (t === 0) { return arr; } else if (t === -1) { return []; } else { return arr.slice(0, -1 * t); } } ``` Test cases ---------- ``` console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ``` [ 'a', 'b', '', 'c' ] [ 'a' ] [ '', '', '', '', 'c' ] [] ```
2018/03/25
[ "https://Stackoverflow.com/questions/49481364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552063/" ]
You could do this with `reduceRight` and change one value when you find first elements that is not empty string. ```js function removeFromEnd(arr) { return arr.reduceRight((r, e) => { if (e) r.match = true; if (r.match) r.arr.unshift(e) return r; }, {arr: []}).arr } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ```
You can reverse the array and remove elements until you reach a non empty string. Here is an example: ```js function removeFromEnd(arr){ return arr.reverse().filter(function(v){ if(v !== ""){ this.stopRemoving = true; } return this.stopRemoving; }, {stopRemoving: false}).reverse(); } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` And here is an example using a classic loop ```js function removeFromEnd(arr){ for(var i = arr.length - 1; i >= 0; i--){ if(arr[i] !== ""){ break; } arr.pop(); } return arr; } console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ```
49,481,364
I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned. Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array? ``` function removeFromEnd(arr) { t = [...arr].reverse().findIndex(e => e !== ''); if (t === 0) { return arr; } else if (t === -1) { return []; } else { return arr.slice(0, -1 * t); } } ``` Test cases ---------- ``` console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ``` [ 'a', 'b', '', 'c' ] [ 'a' ] [ '', '', '', '', 'c' ] [] ```
2018/03/25
[ "https://Stackoverflow.com/questions/49481364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552063/" ]
An alternative is using the function **[`reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight)** along with the **[`Spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)**. ```js let removeFromEnd = (arr) => arr.reduceRight((a, b) => ((b !== '' || a.length) ? [b, ...a] : a), []); console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
I'd use reduce and only add an element if it isn't an empty string or the array already has entries in it ```js console.log(removeFromEnd(['a', 'b', '', 'c', '', ''])); console.log(removeFromEnd(['a', '', ''])); console.log(removeFromEnd(['', '', '', '', 'c'])); console.log(removeFromEnd(['', '', '', ''])); function removeFromEnd(arr) { return arr.reduceRight((a, b) => { if (b !== '' || a.length) a.push(b); return a; }, []).reverse(); } ```
62,069,673
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]? Thanks in advance for your help! ``` int main (int argc, char **argv) { if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", argv[1]); printf("file 2: "); scanf("%s ", argv[2]); } printf("%s\n", argv[1]); printf("%s\n", argv[2]); FILE *file1 = fopen(argv[1], "r"); FILE *file2 = fopen(argv[2], "r"); } ```
2020/05/28
[ "https://Stackoverflow.com/questions/62069673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You don't. As the popular phrase goes, every problem in computer science can be solved by an extra layer of indirection. In this case the indirection is that you define a clean interface for opening a file and pass it a `char const*`. But this pointer doesn't have to be `argv[1]`. You have to malloc your own buffer (because **none** exists) and write to it. Using `scanf("%s",...)` for this purpose will likely create a buffer overrun as you cannot know in advance how large your buffer needs to be. *Edit*: Every single answer given to you suggesting to use `char buffer[NUMBER]` as the buffer for `scanf` **will blow up in your face**.
`Argv` is passed from console and you pass it while executing your program. First, you have to compile it with, for example: `gcc program.c -o program` And then execute it with arguments, for example: `./program arg1 arg2` If you wish to wait for a user to enter parameters for your program through the console you should use regular variables.
62,069,673
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]? Thanks in advance for your help! ``` int main (int argc, char **argv) { if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", argv[1]); printf("file 2: "); scanf("%s ", argv[2]); } printf("%s\n", argv[1]); printf("%s\n", argv[2]); FILE *file1 = fopen(argv[1], "r"); FILE *file2 = fopen(argv[2], "r"); } ```
2020/05/28
[ "https://Stackoverflow.com/questions/62069673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A segmentation fault occurs because length of the argv array is determined when the user runs the program. If you run a program like this: ``` ./programName ``` argv is only 1 element long. It's impossible to access argv[1] or argv[2] after that. Still, You can get the necessary data and save them in regular variables.
`Argv` is passed from console and you pass it while executing your program. First, you have to compile it with, for example: `gcc program.c -o program` And then execute it with arguments, for example: `./program arg1 arg2` If you wish to wait for a user to enter parameters for your program through the console you should use regular variables.
62,069,673
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]? Thanks in advance for your help! ``` int main (int argc, char **argv) { if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", argv[1]); printf("file 2: "); scanf("%s ", argv[2]); } printf("%s\n", argv[1]); printf("%s\n", argv[2]); FILE *file1 = fopen(argv[1], "r"); FILE *file2 = fopen(argv[2], "r"); } ```
2020/05/28
[ "https://Stackoverflow.com/questions/62069673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You don't. As the popular phrase goes, every problem in computer science can be solved by an extra layer of indirection. In this case the indirection is that you define a clean interface for opening a file and pass it a `char const*`. But this pointer doesn't have to be `argv[1]`. You have to malloc your own buffer (because **none** exists) and write to it. Using `scanf("%s",...)` for this purpose will likely create a buffer overrun as you cannot know in advance how large your buffer needs to be. *Edit*: Every single answer given to you suggesting to use `char buffer[NUMBER]` as the buffer for `scanf` **will blow up in your face**.
Note that `argv[1]` and `argv[2]` are only valid if `argc >= 3`. Thus accessing them is of course wrong. Then if you want to read the arguments from stdin, you must make sure that you have memory where those strings are kept. You might use something like ``` char filename1[20], filename2[20]; char *f1, *f2; if (argc == 3) { f1 = argv[1]; f2 = argv[2]; } else { f1 = filename1; f2 = filename2; /* add code to read into filename1 and filename2 */ } /* use f1 and f2 */ ``` You can see that I only reserved 20 bytes for each filename, which was arbitrary chosen by me. It is critical here to not write more than 20 bytes into those arrays (including the terminating NUL char), so you should not use scanf like this. You can see that this is not really straight-forward in C so there is also not an answer that suites all purposes. Edit: also be sure to never write into any `argc[...]` memory, as it is supplied from the system. Although not marked `const` I would rather consider it as such.
62,069,673
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]? Thanks in advance for your help! ``` int main (int argc, char **argv) { if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", argv[1]); printf("file 2: "); scanf("%s ", argv[2]); } printf("%s\n", argv[1]); printf("%s\n", argv[2]); FILE *file1 = fopen(argv[1], "r"); FILE *file2 = fopen(argv[2], "r"); } ```
2020/05/28
[ "https://Stackoverflow.com/questions/62069673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You don't. As the popular phrase goes, every problem in computer science can be solved by an extra layer of indirection. In this case the indirection is that you define a clean interface for opening a file and pass it a `char const*`. But this pointer doesn't have to be `argv[1]`. You have to malloc your own buffer (because **none** exists) and write to it. Using `scanf("%s",...)` for this purpose will likely create a buffer overrun as you cannot know in advance how large your buffer needs to be. *Edit*: Every single answer given to you suggesting to use `char buffer[NUMBER]` as the buffer for `scanf` **will blow up in your face**.
You can't do this because `argv[1]` and `argv[2]` are NULL pointers (if they even exist in the array), so you can't access them. You need to approach the problem from a different way. Instead of trying to change members of `argv`, assign them to other variables that hold the file names. ``` int main (int argc, char **argv) { char file1[100], file2[100]; if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", file1); printf("file 2: "); scanf("%s ", file2); } else { strcpy(file1, argv[1]); strcpy(file2, argv[2]); } printf("%s\n", file1); printf("%s\n", file2); FILE *file1 = fopen(file1, "r"); FILE *file2 = fopen(file2, "r"); } ``` Note that I made some assumptions about the length of a filename. Adjust as necessary.
62,069,673
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]? Thanks in advance for your help! ``` int main (int argc, char **argv) { if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", argv[1]); printf("file 2: "); scanf("%s ", argv[2]); } printf("%s\n", argv[1]); printf("%s\n", argv[2]); FILE *file1 = fopen(argv[1], "r"); FILE *file2 = fopen(argv[2], "r"); } ```
2020/05/28
[ "https://Stackoverflow.com/questions/62069673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You don't. As the popular phrase goes, every problem in computer science can be solved by an extra layer of indirection. In this case the indirection is that you define a clean interface for opening a file and pass it a `char const*`. But this pointer doesn't have to be `argv[1]`. You have to malloc your own buffer (because **none** exists) and write to it. Using `scanf("%s",...)` for this purpose will likely create a buffer overrun as you cannot know in advance how large your buffer needs to be. *Edit*: Every single answer given to you suggesting to use `char buffer[NUMBER]` as the buffer for `scanf` **will blow up in your face**.
Placing them in `argv` is the wrong approach. Much better to do something like this: ``` int main (int argc, char **argv) { char f1[255]; char f2[255]; if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", f1); printf("file 2: "); scanf("%s ", f2); } else { strcpy(f1, argv[1]); strcpy(f2, argv[2]); } FILE *file1 = fopen(f1, "r"); FILE *file2 = fopen(f2, "r"); } ``` You should avoid writing to `argv`. That's in general a bad idea.
62,069,673
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]? Thanks in advance for your help! ``` int main (int argc, char **argv) { if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", argv[1]); printf("file 2: "); scanf("%s ", argv[2]); } printf("%s\n", argv[1]); printf("%s\n", argv[2]); FILE *file1 = fopen(argv[1], "r"); FILE *file2 = fopen(argv[2], "r"); } ```
2020/05/28
[ "https://Stackoverflow.com/questions/62069673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You don't. As the popular phrase goes, every problem in computer science can be solved by an extra layer of indirection. In this case the indirection is that you define a clean interface for opening a file and pass it a `char const*`. But this pointer doesn't have to be `argv[1]`. You have to malloc your own buffer (because **none** exists) and write to it. Using `scanf("%s",...)` for this purpose will likely create a buffer overrun as you cannot know in advance how large your buffer needs to be. *Edit*: Every single answer given to you suggesting to use `char buffer[NUMBER]` as the buffer for `scanf` **will blow up in your face**.
A segmentation fault occurs because length of the argv array is determined when the user runs the program. If you run a program like this: ``` ./programName ``` argv is only 1 element long. It's impossible to access argv[1] or argv[2] after that. Still, You can get the necessary data and save them in regular variables.
62,069,673
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]? Thanks in advance for your help! ``` int main (int argc, char **argv) { if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", argv[1]); printf("file 2: "); scanf("%s ", argv[2]); } printf("%s\n", argv[1]); printf("%s\n", argv[2]); FILE *file1 = fopen(argv[1], "r"); FILE *file2 = fopen(argv[2], "r"); } ```
2020/05/28
[ "https://Stackoverflow.com/questions/62069673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A segmentation fault occurs because length of the argv array is determined when the user runs the program. If you run a program like this: ``` ./programName ``` argv is only 1 element long. It's impossible to access argv[1] or argv[2] after that. Still, You can get the necessary data and save them in regular variables.
Note that `argv[1]` and `argv[2]` are only valid if `argc >= 3`. Thus accessing them is of course wrong. Then if you want to read the arguments from stdin, you must make sure that you have memory where those strings are kept. You might use something like ``` char filename1[20], filename2[20]; char *f1, *f2; if (argc == 3) { f1 = argv[1]; f2 = argv[2]; } else { f1 = filename1; f2 = filename2; /* add code to read into filename1 and filename2 */ } /* use f1 and f2 */ ``` You can see that I only reserved 20 bytes for each filename, which was arbitrary chosen by me. It is critical here to not write more than 20 bytes into those arrays (including the terminating NUL char), so you should not use scanf like this. You can see that this is not really straight-forward in C so there is also not an answer that suites all purposes. Edit: also be sure to never write into any `argc[...]` memory, as it is supplied from the system. Although not marked `const` I would rather consider it as such.
62,069,673
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]? Thanks in advance for your help! ``` int main (int argc, char **argv) { if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", argv[1]); printf("file 2: "); scanf("%s ", argv[2]); } printf("%s\n", argv[1]); printf("%s\n", argv[2]); FILE *file1 = fopen(argv[1], "r"); FILE *file2 = fopen(argv[2], "r"); } ```
2020/05/28
[ "https://Stackoverflow.com/questions/62069673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A segmentation fault occurs because length of the argv array is determined when the user runs the program. If you run a program like this: ``` ./programName ``` argv is only 1 element long. It's impossible to access argv[1] or argv[2] after that. Still, You can get the necessary data and save them in regular variables.
You can't do this because `argv[1]` and `argv[2]` are NULL pointers (if they even exist in the array), so you can't access them. You need to approach the problem from a different way. Instead of trying to change members of `argv`, assign them to other variables that hold the file names. ``` int main (int argc, char **argv) { char file1[100], file2[100]; if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", file1); printf("file 2: "); scanf("%s ", file2); } else { strcpy(file1, argv[1]); strcpy(file2, argv[2]); } printf("%s\n", file1); printf("%s\n", file2); FILE *file1 = fopen(file1, "r"); FILE *file2 = fopen(file2, "r"); } ``` Note that I made some assumptions about the length of a filename. Adjust as necessary.
62,069,673
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]? Thanks in advance for your help! ``` int main (int argc, char **argv) { if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", argv[1]); printf("file 2: "); scanf("%s ", argv[2]); } printf("%s\n", argv[1]); printf("%s\n", argv[2]); FILE *file1 = fopen(argv[1], "r"); FILE *file2 = fopen(argv[2], "r"); } ```
2020/05/28
[ "https://Stackoverflow.com/questions/62069673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A segmentation fault occurs because length of the argv array is determined when the user runs the program. If you run a program like this: ``` ./programName ``` argv is only 1 element long. It's impossible to access argv[1] or argv[2] after that. Still, You can get the necessary data and save them in regular variables.
Placing them in `argv` is the wrong approach. Much better to do something like this: ``` int main (int argc, char **argv) { char f1[255]; char f2[255]; if (argc != 3) { printf("You did not enter two files.\n"); printf("You can now enter those two files.\n"); printf("file 1: "); scanf("%s", f1); printf("file 2: "); scanf("%s ", f2); } else { strcpy(f1, argv[1]); strcpy(f2, argv[2]); } FILE *file1 = fopen(f1, "r"); FILE *file2 = fopen(f2, "r"); } ``` You should avoid writing to `argv`. That's in general a bad idea.
42,372,532
I need to open an existing \*.xlsx Excel file, make some modifications, and then save it as a new file (or stream it to the frontend without saving). The original file must remain unchanged. For Memory reasons, I avoid using FileInputStream (as described here: <http://poi.apache.org/spreadsheet/quick-guide.html#FileInputStream> ) ``` // XSSFWorkbook, File OPCPackage pkg = OPCPackage.open(new File("file.xlsx")); XSSFWorkbook wb = new XSSFWorkbook(pkg); .... pkg.close(); ```
2017/02/21
[ "https://Stackoverflow.com/questions/42372532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6426882/" ]
X and y labels are bound to an axes in matplotlib. So it makes little sense to use `xlabel` or `ylabel` commands for the purpose of labeling several subplots. What is possible though, is to create a simple text and place it at the desired position. `fig.text(x,y, text)` places some text at coordinates `x` and `y` in figure coordinates, i.e. the lower left corner of the figure has coordinates `(0,0)` the upper right one `(1,1)`. ``` import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd')) axes = df.plot(kind="bar", subplots=True, layout=(2,2), sharey=True, sharex=True) fig=axes[0,0].figure fig.text(0.5,0.04, "Some very long and even longer xlabel", ha="center", va="center") fig.text(0.05,0.5, "Some quite extensive ylabel", ha="center", va="center", rotation=90) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/8A97k.png)](https://i.stack.imgur.com/8A97k.png) The drawback of this solution is that the coordinates of where to place the text need to be set manually and may depend on the figure size.
This will create an invisible 111 axis where you can set the general x and y labels: ``` import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd')) ax = df.plot(kind="bar", subplots=True, layout=(2, 2), sharey=True, sharex=True, rot=0, fontsize=12) fig = ax[0][0].get_figure() # getting the figure ax0 = fig.add_subplot(111, frame_on=False) # creating a single axes ax0.set_xticks([]) ax0.set_yticks([]) ax0.set_xlabel('my_general_xlabel', labelpad=25) ax0.set_ylabel('my_general_ylabel', labelpad=45) # Part of a follow up question: Modifying the fontsize of the titles: for i,axi in np.ndenumerate(ax): axi.set_title(axi.get_title(),{'size' : 16}) ``` [![enter image description here](https://i.stack.imgur.com/HmxUV.png)](https://i.stack.imgur.com/HmxUV.png)
42,372,532
I need to open an existing \*.xlsx Excel file, make some modifications, and then save it as a new file (or stream it to the frontend without saving). The original file must remain unchanged. For Memory reasons, I avoid using FileInputStream (as described here: <http://poi.apache.org/spreadsheet/quick-guide.html#FileInputStream> ) ``` // XSSFWorkbook, File OPCPackage pkg = OPCPackage.open(new File("file.xlsx")); XSSFWorkbook wb = new XSSFWorkbook(pkg); .... pkg.close(); ```
2017/02/21
[ "https://Stackoverflow.com/questions/42372532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6426882/" ]
X and y labels are bound to an axes in matplotlib. So it makes little sense to use `xlabel` or `ylabel` commands for the purpose of labeling several subplots. What is possible though, is to create a simple text and place it at the desired position. `fig.text(x,y, text)` places some text at coordinates `x` and `y` in figure coordinates, i.e. the lower left corner of the figure has coordinates `(0,0)` the upper right one `(1,1)`. ``` import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd')) axes = df.plot(kind="bar", subplots=True, layout=(2,2), sharey=True, sharex=True) fig=axes[0,0].figure fig.text(0.5,0.04, "Some very long and even longer xlabel", ha="center", va="center") fig.text(0.05,0.5, "Some quite extensive ylabel", ha="center", va="center", rotation=90) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/8A97k.png)](https://i.stack.imgur.com/8A97k.png) The drawback of this solution is that the coordinates of where to place the text need to be set manually and may depend on the figure size.
Another solution: create a big subplot and then set the common labels. Here is what I got. [enter image description here](https://i.stack.imgur.com/tiDKH.png) ------------------------------------------------------------------- The source code is below. ``` import pandas as pd import matplotlib.pyplot as plt fig = plt.figure() axarr = fig.add_subplot(221) df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd')) axes = df.plot(kind="bar", ax=axarr, subplots=True, layout=(2, 2), sharey=True, sharex=True, rot=0, fontsize=20) # Create a big subplot ax = fig.add_subplot(111, frameon=False) # hide tick and tick label of the big axes plt.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off') ax.set_xlabel('my_general_xlabel', labelpad=10) # Use argument `labelpad` to move label downwards. ax.set_ylabel('my_general_ylabel', labelpad=20) plt.show() ```
42,372,532
I need to open an existing \*.xlsx Excel file, make some modifications, and then save it as a new file (or stream it to the frontend without saving). The original file must remain unchanged. For Memory reasons, I avoid using FileInputStream (as described here: <http://poi.apache.org/spreadsheet/quick-guide.html#FileInputStream> ) ``` // XSSFWorkbook, File OPCPackage pkg = OPCPackage.open(new File("file.xlsx")); XSSFWorkbook wb = new XSSFWorkbook(pkg); .... pkg.close(); ```
2017/02/21
[ "https://Stackoverflow.com/questions/42372532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6426882/" ]
X and y labels are bound to an axes in matplotlib. So it makes little sense to use `xlabel` or `ylabel` commands for the purpose of labeling several subplots. What is possible though, is to create a simple text and place it at the desired position. `fig.text(x,y, text)` places some text at coordinates `x` and `y` in figure coordinates, i.e. the lower left corner of the figure has coordinates `(0,0)` the upper right one `(1,1)`. ``` import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd')) axes = df.plot(kind="bar", subplots=True, layout=(2,2), sharey=True, sharex=True) fig=axes[0,0].figure fig.text(0.5,0.04, "Some very long and even longer xlabel", ha="center", va="center") fig.text(0.05,0.5, "Some quite extensive ylabel", ha="center", va="center", rotation=90) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/8A97k.png)](https://i.stack.imgur.com/8A97k.png) The drawback of this solution is that the coordinates of where to place the text need to be set manually and may depend on the figure size.
**New: Recent matplotlib** (v3.4+; use `pip --upgrade matplotlib`) also has figure-level x- and y-labels: ``` fig.supxlabel('my general x-label') fig.supylabel('my general y-label') ``` While this is an important option to know about, it's not by default quite the same as having the font size and location matched as though it fit one of the subplots. See docs: <https://matplotlib.org/devdocs/api/figure_api.html#matplotlib.figure.FigureBase.supxlabel> to see that it comes with plenty of options to meet the requirements for the original question.
52,076,282
I am using @ngx/translate core for lang change. I want to define sass on the basic of ``` <body lang="en"> ``` or ``` <body lang="fr"> ``` by if else condition. ``` Inside my component sass i want to do something like this @if( bodylang = en) /these rules else // these rules ``` How can i achieve this?
2018/08/29
[ "https://Stackoverflow.com/questions/52076282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9419166/" ]
As it is SCSS you are able to use CSS attribute selectors for this, for example: ``` a[target="_blank"] { background-color: yellow; } ``` Which in your case would be: ``` body[lang="en"] { // Your code } body[lang="fr"] { // Your code } ``` You can also nest them like such: ``` body { background-color: orange; &[lang="en"] { background-color: blue; } } ``` This selector is more specific than just referring to the body tag itself. This means that it will apply the regular body CSS if none of the matching langcode tags are found. You can find more attribute selectors here: <https://www.w3schools.com/css/css_attribute_selectors.asp>
If you want to do it in your component SCSS file you have to do something like bellow code: ``` :host-context([lang="en"]){ // Your code } :host-context([lang="fa"]){ // Your code } ``` If you are doing it in your styles.scss file you can achieve your goal with following code: ``` [lang="en"] { // Your code } [lang="fr"] { // Your code } ```
52,076,282
I am using @ngx/translate core for lang change. I want to define sass on the basic of ``` <body lang="en"> ``` or ``` <body lang="fr"> ``` by if else condition. ``` Inside my component sass i want to do something like this @if( bodylang = en) /these rules else // these rules ``` How can i achieve this?
2018/08/29
[ "https://Stackoverflow.com/questions/52076282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9419166/" ]
As it is SCSS you are able to use CSS attribute selectors for this, for example: ``` a[target="_blank"] { background-color: yellow; } ``` Which in your case would be: ``` body[lang="en"] { // Your code } body[lang="fr"] { // Your code } ``` You can also nest them like such: ``` body { background-color: orange; &[lang="en"] { background-color: blue; } } ``` This selector is more specific than just referring to the body tag itself. This means that it will apply the regular body CSS if none of the matching langcode tags are found. You can find more attribute selectors here: <https://www.w3schools.com/css/css_attribute_selectors.asp>
rsangin's answer is the correct one. If you want to select every language that is not en, you can just use `:not([lang="en"])`
52,076,282
I am using @ngx/translate core for lang change. I want to define sass on the basic of ``` <body lang="en"> ``` or ``` <body lang="fr"> ``` by if else condition. ``` Inside my component sass i want to do something like this @if( bodylang = en) /these rules else // these rules ``` How can i achieve this?
2018/08/29
[ "https://Stackoverflow.com/questions/52076282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9419166/" ]
If you want to do it in your component SCSS file you have to do something like bellow code: ``` :host-context([lang="en"]){ // Your code } :host-context([lang="fa"]){ // Your code } ``` If you are doing it in your styles.scss file you can achieve your goal with following code: ``` [lang="en"] { // Your code } [lang="fr"] { // Your code } ```
rsangin's answer is the correct one. If you want to select every language that is not en, you can just use `:not([lang="en"])`
62,101
Just what the title says. Suppose I know the feature that I want to be used for splitting for the root node in a tree model in XGBoost; is there a way for me to tell XGBoost to split on this feature at the root node?
2019/10/22
[ "https://datascience.stackexchange.com/questions/62101", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/84189/" ]
I do not have the whole answer, but I believe that xgboost allows warm-starting, which implies starting from a provided point. ``` xgb.train(…,xgb_model=model_to_start_from) ```
Could you enforce this using [feature interactions](https://xgboost.readthedocs.io/en/stable/tutorials/feature_interaction_constraint.html)? Maybe create two sets of features with only that one feature in common? I’m not sure if it will guarantee that that shared feature is the one on which the first split is made.
62,101
Just what the title says. Suppose I know the feature that I want to be used for splitting for the root node in a tree model in XGBoost; is there a way for me to tell XGBoost to split on this feature at the root node?
2019/10/22
[ "https://datascience.stackexchange.com/questions/62101", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/84189/" ]
It's hard to prove a negative, but I think the answer is no. Especially in xgboost compared to other tree-model packages, it's rather hard to even access the base trees, let alone modify their build.
Could you enforce this using [feature interactions](https://xgboost.readthedocs.io/en/stable/tutorials/feature_interaction_constraint.html)? Maybe create two sets of features with only that one feature in common? I’m not sure if it will guarantee that that shared feature is the one on which the first split is made.
54,882,263
The text of button is not displaying in Safari,I can return the text using jquery in the console. But it is recognising the click event e.g ```html <div class="btn-group btn-group-lg"> <button onclick="change();" id="face-btn" type="button" class="btn btn-primary">Face</button> ```
2019/02/26
[ "https://Stackoverflow.com/questions/54882263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7430286/" ]
I couldn't write a comment that why am writing a suggestion here, try to add a height to your button style This answer is based on this Articel: [Button-not-displaying-well-in-Safari](https://www.sitepoint.com/forums/showthread.php?597261-Button-not-displaying-well-in-Safari)
I am using Safari browser and I can see the text in the button. For better support use `value` attribute to provide support for all browsers. ```html <div class="btn-group btn-group-lg"> <button onclick="change();" id="face-btn" type="button" value="Face" class="btn btn-primary">Face</button> ``` Hope it helps.
54,882,263
The text of button is not displaying in Safari,I can return the text using jquery in the console. But it is recognising the click event e.g ```html <div class="btn-group btn-group-lg"> <button onclick="change();" id="face-btn" type="button" class="btn btn-primary">Face</button> ```
2019/02/26
[ "https://Stackoverflow.com/questions/54882263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7430286/" ]
Issue was with the line -webkit-text-fill-color: transparent;
I am using Safari browser and I can see the text in the button. For better support use `value` attribute to provide support for all browsers. ```html <div class="btn-group btn-group-lg"> <button onclick="change();" id="face-btn" type="button" value="Face" class="btn btn-primary">Face</button> ``` Hope it helps.
95,170
I was curious if the half life of Gold is 186 Days, then why does it 'Last forever' ... Wouldn't the ancient Egyptian gold artifacts be decayed to lighter elements by now like platinum? I know gold was able to withstand corrosion very well, but the relatively short half-life is kinda throwing off my understanding of why it 'last forever'.
2018/04/14
[ "https://chemistry.stackexchange.com/questions/95170", "https://chemistry.stackexchange.com", "https://chemistry.stackexchange.com/users/62802/" ]
Gold has only one stable isotope, $\ce{^197Au}$, which has $100\%$ natural abundance, thus considered to be one of monoisotopic elements (one of 26 chemical elements which have only a single stable isotope). As a matter of facts, it is now considered to be the heaviest monoisotopic element. For more info, read [Isotopes of gold](https://en.wikipedia.org/wiki/Isotopes_of_gold). Aside $\ce{^197Au}$, there are 36 unstable isotopes of gold been known ranging from $\ce{^169Au}$ to $\ce{^205Au}$. All of these are radioisotopes (radioactive nuclides). The $\ce{^195Au}$ isotope is the most stable amongst unstable isopopes, with a half-life ($t\_{1/2}$) of $\pu{186 d}$. The heaviest, $\ce{^205Au}$, has $t\_{1/2}$ of $\pu{31 s}$ ([ref](http://periodictable.com/Isotopes/079.205/index.p.full.html)).
Gold has a [number of isotopes](https://en.wikipedia.org/wiki/Isotopes_of_gold). $\ce{^{197}Au}$ is stable and is the only isotope which is. So all the gold that is mined is $\ce{^{197}Au}$.
107,732
I've tried researching this question myself, but the only data I can find is over huge timescales, like situations where the continents have reformed back into a Neo-Pangea. I'm not looking for any real drastic changes in positioning, just relatively minor things like seas disappearing or continents slightly shrinking or pushing into each other. Would there be any noteworthy changes at all, or would it be pretty much the same as today aside from some minor changes that wouldn't affect anything? Let's just assume humanity suddenly stopped existing today for the purposes of the question, so they don't make any more changes to the world than they already have. As always, I'm very grateful for any answers, and if you need anything clarified feel free to leave a comment and I'll do my best to clear things up.
2018/03/23
[ "https://worldbuilding.stackexchange.com/questions/107732", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/48871/" ]
A millennium is a blink of an eye on a geological scale. But interesting things can happen in a blink of an eye. Even disegarding the changes which may happen as a result of the present climatological instability, small but important modification can occur here and there. I have no idea of the geographical changes between today and 3000 CE; but I do know of *some* geographical changes between 1 CE and today, either because they happened in places in which I have a local interest, or because they are somehow important to various historical events, or because I found out about them by accident and found them interesting enough to remember. Geographical changes during the last 1000 or 2000 years ------------------------------------------------------- * While sea level is today not very different from what it was in the first century, *in some places the sea advanced or retreated considerably:* + Some cities which used to be seaports in the first century are now several miles inland. For example: - In the Antiquity [Ephesus](https://en.wikipedia.org/wiki/Ephesus) and [Miletus](https://en.wikipedia.org/wiki/Miletus) were major ports on the Ionian coast; they are now several kilometers inland. [![Silting of the gulf of Miletus](https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Miletus_Bay_silting_evolution_map-en.svg/640px-Miletus_Bay_silting_evolution_map-en.svg.png)](https://en.wikipedia.org/wiki/Miletus#/media/File:Miletus_Bay_silting_evolution_map-en.svg) *The silting evolution of Miletus Bay due to the alluvium brought by the Maeander River during Antiquity. Map by Eric Gaba, available on Wikimedia under the CC-BY-SA-3.0 license.* - Closer to me, in the Antiquity the city of Histria was a seaport on the western coast of the Black Sea. Now its ruins lay on the shore of a shallow lagoon, and the sea is kilometers away. [![Greek colonies in Dobruja](https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Scythia_Minor_map.jpg/488px-Scythia_Minor_map.jpg)](https://en.wikipedia.org/wiki/Histria_(ancient_city)#/media/File:Scythia_Minor_map.jpg) *Ancient towns and colonies in Dobruja; modern coastline shown as a dotted line. Map by Bogdan, available on Wikimedia under the CC-BY-SA-3.0 license.* + On the other hand, in some places the sea advanced. For example, what is now the [IJselmeer](https://en.wikipedia.org/wiki/IJsselmeer) in the Netherlands used to be a low-lying plain in the first century, with a large lake known by the Romans as [Lake Flevo](https://en.wikipedia.org/wiki/Lake_Flevo). In 1287, [Saint Lucia's flood](https://en.wikipedia.org/wiki/St._Lucia%27s_flood) broke through and submerged the former river [Vlie](https://en.wikipedia.org/wiki/Vlie), creating a large shallow gulf which was called the [Zuiderzee](https://en.wikipedia.org/wiki/Zuiderzee). [![The region of the Netherlands in the 1st century CE](https://upload.wikimedia.org/wikipedia/commons/a/aa/50nc_ex_leg_copy.jpg)](https://en.wikipedia.org/wiki/Lake_Flevo#/media/File:50nc_ex_leg_copy.jpg) *The region of the Netherlands in the 1st century CE. Map by the Dutch Nationale Onderzoeksagenda Archeologie (www.noaa.nl), available on Wikimedia under the CC-BY-SA-3.0 license.* Then in 1932 the long effort of the Dutch to build the [Afsluitdijk](https://en.wikipedia.org/wiki/Afsluitdijk) was brough to completion, and the gulf was separated from the sea and became a lake, which the Dutch then proceeded to drain in order to increase the territory of their country; and now the Netherlands has a new 1500 square kilometer province, called [Flevoland](https://en.wikipedia.org/wiki/Flevoland). * Rivers sometimes change course dramatically. For me, the most spectacular example is the [Oxus](https://en.wikipedia.org/wiki/Amu_Darya), which is today known as the Amu Darya. Until the 16th century it used to flow into the Caspian Sea, through what is now the dry [Uzboy](https://en.wikipedia.org/wiki/Uzboy) valley; it then changed its mind, abandoned the Caspian and went to empty into the Aral Sea. [![The old course of the Oxus (Amu Darya), when it flew into the Caspian](https://upload.wikimedia.org/wikipedia/commons/thumb/4/4e/XXth_Century_Citizen%27s_Atlas_map_of_Central_Asia.png/640px-XXth_Century_Citizen%27s_Atlas_map_of_Central_Asia.png)](https://en.wikipedia.org/wiki/Uzboy#/media/File:XXth_Century_Citizen%27s_Atlas_map_of_Central_Asia.png) *The old course of the Oxus (Amu Darya), when it flew into the Caspian Sea, marked as "Old Bed of the Oxus". Map from 1903, available on Wikimedia. Public domain.* At the beginning of the 18th century, [Peter the Great](https://en.wikipedia.org/wiki/Peter_the_Great), emperor of Russia, sent prince [Alexander Bekovich-Cherkassky](https://en.wikipedia.org/wiki/Alexander_Bekovich-Cherkassky) to find the mouth of the Oxus, with the intention of establishing a trade route from the Caspian to Transoxiana. The prince dutifully mapped the coast and returned with the sad news that the river no longer flowed into the Caspian... * Speaking of the [Aral Sea](https://en.wikipedia.org/wiki/Aral_Sea), the Soviet Union killed it in the 20th century. The former immense lake of 68,000 square kilometers is now a desert, the [Aralkum](https://en.wikipedia.org/wiki/Aralkum_Desert). * Speaking of the Soviet Union and Transoxiana: in the 1930s the Soviet Union conceived a titanic project to *"divert the flow of the Northern rivers in the Soviet Union, which "uselessly" drain into the Arctic Ocean, southwards towards the populated agricultural areas of Central Asia, which lack water"* (Wikipedia). The [Northern River Reversal](https://en.wikipedia.org/wiki/Northern_river_reversal) eventually grew and grew, design and planning progressed through the 1960s and 1970s, so that by 1980 the Soviets were talking of diverting 12 major Siberian rivers into the Central Asian desert. They even envisaged using atomic bombs to move massive amounts of dirt speedily. Then the Soviet Union fell; but who knows? * Speaking of using atomic bombs to dig canals, Egypt is considering a [plan to dig a canal](https://en.wikipedia.org/wiki/Qattara_Depression_Project) from the Mediterranean to the [Qattara Depression](https://en.wikipedia.org/wiki/Qattara_Depression), flooding it and creating a solar-powered 2000 megawatt hydropower plant. [![Map of the flooded Qattara Depression, with several proposal waterway routes](https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/All_proposed_routes.PNG/640px-All_proposed_routes.PNG)](https://en.wikipedia.org/wiki/Qattara_Depression_Project#/media/File:All_proposed_routes.PNG) *All proposed routes for a tunnel and/or canal route from the Mediterranean Sea towards the Qattara Depression. Map by AlwaysUnite, available on Wikimedia under the CC-BY-SA-3.0 license.* And yes, in the 1950s the international Board of Advisers led by Prof. [Friedrich Bassler](https://en.wikipedia.org/wiki/Friedrich_Bassler) proposed to dig the canal using atomic blasts, part of President Eisenhower's [Atoms for Peace](https://en.wikipedia.org/wiki/Atoms_for_Peace) program. * The [Frisian Islands](https://en.wikipedia.org/wiki/Frisian_Islands) on the eastern edge of the North Sea are notoriously shifty, so that the approaches to the Dutch ports have changed considerably from the Middle Ages to the present. For example, the northern part of what is now the island of [Texel](https://en.wikipedia.org/wiki/Texel) was until the 13th century the southern part of the island of [Vlieland](https://en.wikipedia.org/wiki/Vlieland); it then left Vlieland and became a separate island, the [Eierland](https://en.wikipedia.org/wiki/Eierland); in the 17th century the Dutch reclaimed the land between the Texel and Eierland, and the two islands became one. [![Eierland when it was a separate island](https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/PaysBas_delisle_1743_fragment.jpg/627px-PaysBas_delisle_1743_fragment.jpg)](https://en.wikipedia.org/wiki/Eierland#/media/File:PaysBas_delisle_1743_fragment.jpg) *Eierland when it was a separate island. Map from 1702, available on Wikimedia. Public domain.* Geography is not static ----------------------- The list could be very much expanded. The Panama Canal. The proposed Nicaragua Canal. The lockless Suez Canal, which has brought the marine life of the Red Sea into the Mediterranean. The Hot Gates of Greece. The shifting barrier islands off the coast of Texas. The absent-minded [Yellow River](https://en.wikipedia.org/wiki/Yellow_River) of China. The wandering lake [Lop Nor](https://en.wikipedia.org/wiki/Lop_Nur). The unstable coastline of England -- how many of the medieval [Cinque Ports](https://en.wikipedia.org/wiki/Cinque_Ports) are still ports, that is, if they exist at all? Geography changes wherever you look closely.
> > Would there be any noteworthy changes at all, > > > just assume humanity suddenly stopped existing today for the purposes of the question > > > Global Warming would continue for a while, if for no other reason than approximately 2.5% of CO2 is sequestered per annum. <http://euanmearns.com/the-half-life-of-co2-in-earths-atmosphere-part-1/> > > Sequestration of CO2 from the atmosphere can be modelled using a single exponential decay constant of 2.5% per annum. > > > At that rate, it would take 14 years to return to a CO2 value of 280ppm. But in the meantime, 1. much polar ice has disappeared, and blue ocean absorbs more energy than white ice, and 2. the permafrosts are thawing, releasing lots of methane, which an even stronger greenhouse gas. This northern warming is causing even more methane to be released, in a vicious cycle. Thus, it's very possible that most of the Greenland icecap will be melted, and also Antarctica, raising the ocean levels by 70 meters.
107,732
I've tried researching this question myself, but the only data I can find is over huge timescales, like situations where the continents have reformed back into a Neo-Pangea. I'm not looking for any real drastic changes in positioning, just relatively minor things like seas disappearing or continents slightly shrinking or pushing into each other. Would there be any noteworthy changes at all, or would it be pretty much the same as today aside from some minor changes that wouldn't affect anything? Let's just assume humanity suddenly stopped existing today for the purposes of the question, so they don't make any more changes to the world than they already have. As always, I'm very grateful for any answers, and if you need anything clarified feel free to leave a comment and I'll do my best to clear things up.
2018/03/23
[ "https://worldbuilding.stackexchange.com/questions/107732", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/48871/" ]
> > Would there be any noteworthy changes at all, > > > just assume humanity suddenly stopped existing today for the purposes of the question > > > Global Warming would continue for a while, if for no other reason than approximately 2.5% of CO2 is sequestered per annum. <http://euanmearns.com/the-half-life-of-co2-in-earths-atmosphere-part-1/> > > Sequestration of CO2 from the atmosphere can be modelled using a single exponential decay constant of 2.5% per annum. > > > At that rate, it would take 14 years to return to a CO2 value of 280ppm. But in the meantime, 1. much polar ice has disappeared, and blue ocean absorbs more energy than white ice, and 2. the permafrosts are thawing, releasing lots of methane, which an even stronger greenhouse gas. This northern warming is causing even more methane to be released, in a vicious cycle. Thus, it's very possible that most of the Greenland icecap will be melted, and also Antarctica, raising the ocean levels by 70 meters.
In addition to the previously noted changes due to climate and normal geology, the sudden removal of humans a la Discovery Channel's [Life After People](https://www.history.com/shows/life-after-people) would quickly lead to the breakdown of electrical and mechanical infrastructure, including pumping stations (e.g., the [California Aqueduct](https://en.wikipedia.org/wiki/California_Aqueduct), [New Orleans' pumping stations](https://en.wikipedia.org/wiki/Drainage_in_New_Orleans), and the Netherlands' [pumping stations in Flevoland](https://www.visitflevoland.nl/en/on-expedition/heritage/pumping-stations-in-flevoland/)), with the obvious results. In the longer term (a few centuries at most, according to Discovery), the majority of earthen and concrete structures are likely to fail, which includes essentially all of the world's dams, dikes, and levees. Their collapses will cause significant flooding, erosion, and scouring of low-lying areas downstream, and some river channels will be changed significantly enough to still show the effects a millennium hence. Earth's cities and highways are also likely to be largely buried in vegetation (again, per Discovery), with the result that urban and linear features that are prominent from the air or even space will become much harder to see. The disappearance of humans will also eliminate agriculture and logging, which is likely to reduce silt and fertilizer runoff in most places, with at least some visible changes in watersheds. (For example, [mangroves](https://go.nasa.gov/2FY1CnO) can be expected to make a larger comeback in some rivers; clear-cut areas of the Amazon and other forests will recover to some extent; and a number of river deltas like the [Ebro's](https://go.nasa.gov/2Ik9OQV) will stop growing so quickly and may actually erode.) The Aral Sea may make a comeback as well. Astronomy might also play a small part; according to [Wikipedia](https://en.wikipedia.org/wiki/Impact_event), there's about a 20% chance of an asteroid strike large enough to create a crater actually hitting land and doing so. By the way, spacecraft, even the ISS, are too small to make much of a mark, and what little damage they do cause would be hidden by vegetation and weathering very quickly (years, or decades at most).