qid
int64
2
74.7M
question
stringlengths
31
65.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
4
63.3k
response_k
stringlengths
4
60.5k
18,253,581
I recently updated my Java to the most up to date version and this caused an applet that I work with to not run correctly. I have changed the security parameters for Java through the Control Panel to the lowest possible settings but my applet still does not run. Here is what my applet looked like: ``` <HTML> <BODY BGCOLOR="#003333"> <p> <APPLET name=IpixViewer code=IpixViewer.class archive="IpixViewer.jar" width=450 height=450> <PARAM NAME="url" VALUE="209_a_CHEM.ipx"> </APPLET> </p> </BODY> </HTML> ``` I tried to use the HTML tag as a work around but this also is failing. Here is that code: ``` <HTML> <body> <p> <object type="application/x-java-applet;version=1.6" name="IpixViewer" id="ipixviewer" style="width:450px;height:450px" > <param name="code" value="IpixViewer.class" > <param name="archive" value="IpixViewer.jar" > <param name="codebase" value="Z:\filepath\"> <param name="url" value="205_a_CHEM.ipx" > </object> </p> </body> </HTML> ``` I think the issue is when I try to pass the url parameter into the applet but I am not sure. Any help would be appreciated.
2013/08/15
[ "https://Stackoverflow.com/questions/18253581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2660737/" ]
Declaring a function called `hello` in the derived class *hides* all functions with the same name in the base class. You can unhide them with a using declaration: ``` struct B : A { using A::hello; virtual void hello(int arg) {} }; ``` or access them via a base-class pointer or reference: ``` static_cast<A*>(b)->hello(); ```
The `hello(int)` member function in `B` takes an int argument and hides the `hello()` member of `A`. If you want the `hello` member function of `B` not to hide the one in `A`, add `using A::hello` to `B`.
18,253,581
I recently updated my Java to the most up to date version and this caused an applet that I work with to not run correctly. I have changed the security parameters for Java through the Control Panel to the lowest possible settings but my applet still does not run. Here is what my applet looked like: ``` <HTML> <BODY BGCOLOR="#003333"> <p> <APPLET name=IpixViewer code=IpixViewer.class archive="IpixViewer.jar" width=450 height=450> <PARAM NAME="url" VALUE="209_a_CHEM.ipx"> </APPLET> </p> </BODY> </HTML> ``` I tried to use the HTML tag as a work around but this also is failing. Here is that code: ``` <HTML> <body> <p> <object type="application/x-java-applet;version=1.6" name="IpixViewer" id="ipixviewer" style="width:450px;height:450px" > <param name="code" value="IpixViewer.class" > <param name="archive" value="IpixViewer.jar" > <param name="codebase" value="Z:\filepath\"> <param name="url" value="205_a_CHEM.ipx" > </object> </p> </body> </HTML> ``` I think the issue is when I try to pass the url parameter into the applet but I am not sure. Any help would be appreciated.
2013/08/15
[ "https://Stackoverflow.com/questions/18253581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2660737/" ]
Because your overriding of `hello(int arg)` hides other functions with the same name. What you can do is to explicitly introduce those base class functions to subclass: ``` struct B : A { using A::hello; // Make other overloaded version of hello() to show up in subclass. virtual void hello(int arg) {} }; ```
Declaring a function called `hello` in the derived class *hides* all functions with the same name in the base class. You can unhide them with a using declaration: ``` struct B : A { using A::hello; virtual void hello(int arg) {} }; ``` or access them via a base-class pointer or reference: ``` static_cast<A*>(b)->hello(); ```
52,472,804
How to remove > > Property 'queryBuilder' does not exist on type 'JQuery < HTMLElement>' > > > on integration of Jquery query builder in Angular. **angular.json:** ``` "scripts": [ "node_modules/jquery/dist/jquery.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js", "node_modules/jQuery-QueryBuilder/dist/js/query-builder.standalone.min.js", ...] ``` **app.componenet.ts** ``` import * as $ from 'jquery'; import 'jQuery-QueryBuilder/dist/js/query-builder.standalone.js'; import 'jQuery-QueryBuilder/dist/js/query-builder.js'; ... private getQueryBuilder() { $('#builder').queryBuilder({ //plugins: ['bt-tooltip-errors'], filters: [{ id: 'name', label: 'Name', type: 'string' }, { id: 'category', label: 'Category', type: 'integer', input: 'select', values: { 1: 'Books', 2: 'Movies', 3: 'Music', 4: 'Tools', 5: 'Goodies', 6: 'Clothes' }, operators: ['equal', 'not_equal', 'in', 'not_in', 'is_null', 'is_not_null'] }, { id: 'in_stock', label: 'In stock', type: 'integer', input: 'radio', values: { 1: 'Yes', 0: 'No' }, operators: ['equal'] }], rules: this.rules_basic }); ``` } ``` ngAfterViewInit() { this.getQueryBuilder(); } ``` I did things in this ([How to use Jquery Query Builder in Angular](https://stackoverflow.com/questions/44820788/how-to-use-jquery-query-builder-in-angular)) thread but It throws error and leads failed compilation. Sometimes application is running with this error also.
2018/09/24
[ "https://Stackoverflow.com/questions/52472804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9176895/" ]
try this one, it will work. ``` import 'jquery'; import 'jQuery-QueryBuilder/dist/js/query-builder.min.js'; import 'jQuery-QueryBuilder/dist/js/query-builder.standalone.min.js'; declare var $: any; ```
The path to your queryBuilder plugin is either wrong ``` node_modules/jQuery-QueryBuilder/dist/js/query-builder.standalone.min.js ``` or you have not NPM installed it.
129,099
I am in my 5th year as a developer (3.5 years as junior/mid level and now a senior dev). My current role is not going well (people issues). Anyway, I said to one of the managers I was thinking of looking for another job and he told me there is no way I could get the same salary or position in another organization as I'm not a real developer yet. ***How do I know if he is right?*** Unfortunately, I agree with him. I only know the fundamentals of the languages I work with (C# & JavaScript), although I do consider myself an advanced SQL guy (but I'm regularly told that doesn't count). So, how will I know when I know enough to call myself a developer? Is there some kind of matrix/test I can use? I am regularly studying (2 - 3 hours per day) on PluralSight and by making my own projects, but I feel like a complete beginner in most aspects of software. ***Update - November 2020. Well, don't believe what haters tell you. I have been working as a full-stack developer for almost 2 years now, have dramatically increased my expertise through self-learning and through my job, and recently got promoted to a lead developer. If you ever find yourself asking the above - don't give up, work & study hard and believe in yourself!***
2019/02/14
[ "https://workplace.stackexchange.com/questions/129099", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/91131/" ]
**You are already a real developer.** I'm guessing that your boss is belittling you in order to keep your morale down, so that you're less likely to look for another job or ask for a better salary. Five years of experience is more than enough to consider yourself a qualified developer. Given that your current role is not going well, and you have an emotionally manipulative manager above you right now, I would definitely start looking for another job that gives you the respect that you've earned.
I agree with all other answers, but there is a point you need to ensure before you go looking elsewhere : do you know to sell yourself as a software developer? You already began by describing your current skills, but you need to work on your narrative; a job interview goes deeper than a Workplace stack entry. Rethink about everything you did the last 5 years, everything you did learn, everything you did make right, every hard lesson you did get, everything that makes you a real developper. If possible, practice with a friend(not in your current firm) speaking about you. In the eyes of recruiters, you'll be a software developper as soon as you'll be able to tell them a narrative on how you became a developper. That's the real meaning of your boss's speech(*even if it's not what he thinks*). Other answers already gave you great beginnings to your own storytelling. Work from that, show that you are a problem solver, remember that recruiters want people who remove them problems, show that in your story, and then you'll be a software developper in the eyes of the people who really count.
129,099
I am in my 5th year as a developer (3.5 years as junior/mid level and now a senior dev). My current role is not going well (people issues). Anyway, I said to one of the managers I was thinking of looking for another job and he told me there is no way I could get the same salary or position in another organization as I'm not a real developer yet. ***How do I know if he is right?*** Unfortunately, I agree with him. I only know the fundamentals of the languages I work with (C# & JavaScript), although I do consider myself an advanced SQL guy (but I'm regularly told that doesn't count). So, how will I know when I know enough to call myself a developer? Is there some kind of matrix/test I can use? I am regularly studying (2 - 3 hours per day) on PluralSight and by making my own projects, but I feel like a complete beginner in most aspects of software. ***Update - November 2020. Well, don't believe what haters tell you. I have been working as a full-stack developer for almost 2 years now, have dramatically increased my expertise through self-learning and through my job, and recently got promoted to a lead developer. If you ever find yourself asking the above - don't give up, work & study hard and believe in yourself!***
2019/02/14
[ "https://workplace.stackexchange.com/questions/129099", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/91131/" ]
Since you are a senior developer, I assume you have gone through several promotions to get there and weren't hired into the position as a fluke. A senior developer should have a wealth of experience, and can perform most job tasks with little guidance. Your company should have a career matrix you can check to see what boxes you clearly checked off in order to get promoted to where you are. You're a developer (that's what your job description says, doesn't it?). I think your mistake was telling your supervisor you were planning to look for another job. He might have made those comments out of bitterness. Just look for another job and let him know you're leaving **after** you have an offer somewhere else.
> > I am in my 5th year as a developer. > > > That's how you know you are a real developer, e.g. if your current employer is not hiring a **real developer** to replace you, shows that you **are** a real developer. Period! --- I have been in a similar situation just a few months ago, * Getting paid higher than market rate * People issues (suffering due to petty politics) * Working hard on improving my skills through Pluralsight, Edx, Youtube * Feeling like a beginner in some respects * ...I even worked with C#, Javascript and SQL The truth is, your current manager is trying to demoralize you, so that you wouldn't leave. You have people issues because your manager is incompetent in his job, i.e. *managing people*. You are getting paid higher because your company isn't being able to find other equally competent people who would be ready to work there. --- > > So, how will I know when I know enough to call myself a developer? Is there some kind of matrix/test I can use? > > > I would say the ideal first step would be to start looking for a job on the side. Don't put in your resignation, but start interviewing to decent companies. If you get relatively good offers, that should give you some confidence, and you might even consider switching. Second, you can look for professional certifications. Microsoft's 70-480, 70-483 and 70-761 may apply to your work. Having such a certification should not only boost your confidence but also help you demonstrate your skills whenever questioned by your manager or other superiors. --- Bottom line, stop doubting yourself. See how other employers perceive your skills. Find a way to validate your skills through suitable of certifications.
129,099
I am in my 5th year as a developer (3.5 years as junior/mid level and now a senior dev). My current role is not going well (people issues). Anyway, I said to one of the managers I was thinking of looking for another job and he told me there is no way I could get the same salary or position in another organization as I'm not a real developer yet. ***How do I know if he is right?*** Unfortunately, I agree with him. I only know the fundamentals of the languages I work with (C# & JavaScript), although I do consider myself an advanced SQL guy (but I'm regularly told that doesn't count). So, how will I know when I know enough to call myself a developer? Is there some kind of matrix/test I can use? I am regularly studying (2 - 3 hours per day) on PluralSight and by making my own projects, but I feel like a complete beginner in most aspects of software. ***Update - November 2020. Well, don't believe what haters tell you. I have been working as a full-stack developer for almost 2 years now, have dramatically increased my expertise through self-learning and through my job, and recently got promoted to a lead developer. If you ever find yourself asking the above - don't give up, work & study hard and believe in yourself!***
2019/02/14
[ "https://workplace.stackexchange.com/questions/129099", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/91131/" ]
> > he told me there is no way I could get the same salary or position in another organization as I'm not a real developer yet. > > > And yet, here you are, getting paid by your current company. There is no such thing as a "real developer". It's just how good you are at your job, and that is not a binary thing. It is a scale. If as you say, you have identified holes in your knowledge, it's time to rectify them. However, you also need to realise that no developer worth their salt feels comfortable/knowledgeable every single day, as they are constantly stretching beyond their comfort zone and feeling like beginners everytime they learn something new. That is a good thing. Lastly, being a developer is not just about programming knowledge. It's also learning to be a professional, and part of that is understanding what kinds of feedback to take in and what to ignore/push back. I'll leave you to decide which category this kind of feedback belongs in.
> > My current role is not going well (people issues). Anyway, I said to > one of the managers I was thinking of looking for another job > > > A few points here... First, unless this guy is of high moral fiber, it is never a good idea to notify your current workplace that you are looking for a new position. And the reason why: > > ...he told me there is no way I could get the same salary or position in > another organization as I'm not a real developer yet. > > > is because now he is trying to control the situation, but not in a moral way. I'd guess he is already planning his next move after you because he assumes you are on your way out, but he isn't quite ready for that yet. Not that he is completely in the wrong here if he is planning his next move because why wouldn't you move on if someone has verbally told you, in person, that they are thinking of looking for a new position? Be the manager and look at the cards on the table... I learned the hard way about trying to be upfront. As much as it seems like the right thing, there are very, very few workplaces where it is. It's best to just stick to giving ample notice when you have secured a new position (again, unless you are certain that you are working for someone that you know won't pull this kind of stuff; they do exist, but rare...) As far as whether or not that is true... First frank question is *"ok, then why are you paying me in this position?"* This honestly sounds like a reverse martyr position IE *"This place would never survive without me!"* but instead *"You'll never survive without this place!"* which is rarely ever true. You survived before, you'll survive after, same goes for the workplace.
129,099
I am in my 5th year as a developer (3.5 years as junior/mid level and now a senior dev). My current role is not going well (people issues). Anyway, I said to one of the managers I was thinking of looking for another job and he told me there is no way I could get the same salary or position in another organization as I'm not a real developer yet. ***How do I know if he is right?*** Unfortunately, I agree with him. I only know the fundamentals of the languages I work with (C# & JavaScript), although I do consider myself an advanced SQL guy (but I'm regularly told that doesn't count). So, how will I know when I know enough to call myself a developer? Is there some kind of matrix/test I can use? I am regularly studying (2 - 3 hours per day) on PluralSight and by making my own projects, but I feel like a complete beginner in most aspects of software. ***Update - November 2020. Well, don't believe what haters tell you. I have been working as a full-stack developer for almost 2 years now, have dramatically increased my expertise through self-learning and through my job, and recently got promoted to a lead developer. If you ever find yourself asking the above - don't give up, work & study hard and believe in yourself!***
2019/02/14
[ "https://workplace.stackexchange.com/questions/129099", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/91131/" ]
**You are already a real developer.** I'm guessing that your boss is belittling you in order to keep your morale down, so that you're less likely to look for another job or ask for a better salary. Five years of experience is more than enough to consider yourself a qualified developer. Given that your current role is not going well, and you have an emotionally manipulative manager above you right now, I would definitely start looking for another job that gives you the respect that you've earned.
**How to know if I am a 'real developer'** You've been working in software development for five years, I am sure that your company isn't employing you just to be nice to you and they are getting something out of the deal. It's not your current managers place to tell you whether or not you are up to the task of working elsewhere. It will be down to the people who interview you for other positions who will decide if you are up to the task. I would suggest you get your CV together and apply at some other companies and maybe you'll see your worth then. I've never walked into any job and known all the the company jargon and everything in their tech stack, there has always been something to learn and I don't know anybody different. Believe in yourself, and I hope you find something you like where you are appreciated.
129,099
I am in my 5th year as a developer (3.5 years as junior/mid level and now a senior dev). My current role is not going well (people issues). Anyway, I said to one of the managers I was thinking of looking for another job and he told me there is no way I could get the same salary or position in another organization as I'm not a real developer yet. ***How do I know if he is right?*** Unfortunately, I agree with him. I only know the fundamentals of the languages I work with (C# & JavaScript), although I do consider myself an advanced SQL guy (but I'm regularly told that doesn't count). So, how will I know when I know enough to call myself a developer? Is there some kind of matrix/test I can use? I am regularly studying (2 - 3 hours per day) on PluralSight and by making my own projects, but I feel like a complete beginner in most aspects of software. ***Update - November 2020. Well, don't believe what haters tell you. I have been working as a full-stack developer for almost 2 years now, have dramatically increased my expertise through self-learning and through my job, and recently got promoted to a lead developer. If you ever find yourself asking the above - don't give up, work & study hard and believe in yourself!***
2019/02/14
[ "https://workplace.stackexchange.com/questions/129099", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/91131/" ]
What you are feeling is known as "impostor syndrome", the thought that you don't really know what you are doing and people assume you are better than you are. Here's a secret: Everyone feels that way, and it's rarely the case. Ask yourself, if I am given a new task that I need to learn some specific tech for, am I capable of doing it? Because few people are experts in multiple languages and never come across anything they don't understand immediately. Your boss is "negging" you, saying you are not a real developer because they don't want you to quit. That tells you that you are actually a valuable asset for the company and worth more than you think.
"Nearly forty *(wheeze!)* years later, I'm still wondering!" Hope I never find out.
129,099
I am in my 5th year as a developer (3.5 years as junior/mid level and now a senior dev). My current role is not going well (people issues). Anyway, I said to one of the managers I was thinking of looking for another job and he told me there is no way I could get the same salary or position in another organization as I'm not a real developer yet. ***How do I know if he is right?*** Unfortunately, I agree with him. I only know the fundamentals of the languages I work with (C# & JavaScript), although I do consider myself an advanced SQL guy (but I'm regularly told that doesn't count). So, how will I know when I know enough to call myself a developer? Is there some kind of matrix/test I can use? I am regularly studying (2 - 3 hours per day) on PluralSight and by making my own projects, but I feel like a complete beginner in most aspects of software. ***Update - November 2020. Well, don't believe what haters tell you. I have been working as a full-stack developer for almost 2 years now, have dramatically increased my expertise through self-learning and through my job, and recently got promoted to a lead developer. If you ever find yourself asking the above - don't give up, work & study hard and believe in yourself!***
2019/02/14
[ "https://workplace.stackexchange.com/questions/129099", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/91131/" ]
You should read the Wikipedia page on [Impostor Syndrome](https://en.wikipedia.org/wiki/Impostor_syndrome). I've also questioned whether I'm a "real developer", especially while working with people who are much more accomplished than me, or who seem to do what I can do, only much, much faster. But I still believe I'm a real developer, and the reason for that is because I can write code that does what my users need it to do. That's the baseline: can you get your application to do what your users need it to do? If the answer is yes, then you are a real developer. Sure, there will be bugs, and sometimes it's because you did something dumb, but that doesn't mean you're not a real developer. If a tennis player misses a return, does that make them not a real tennis player? Then only way you can know for sure whether you can get another role with the same (or higher) pay, and the same position, is to put yourself out there and interview for it. The interviewers will have steps in place to filter out the people who don't meet their requirements. > > Unfortunately, I agree with him. I only know the fundamentals of the languages I work with (C# & JavaScript), although I do consider myself an advanced SQL guy (but I'm regularly told that doesn't count). > > > So, how will I know when I know enough to call myself a developer? > > > With regards to your question, being a developer isn't just about having X amounts of knowledge. A more important skill is to know how to find the knowledge you need to get the job done. Lastly, don't discount the non-coding skills you've picked up over the years: being able to debug code, analyse requirements / use cases, come up with solution designs, etc.
This is very close to many other questions - amI a True Believer? Am I a real activist? Am I a real man/woman or do I meet criteria for being a real transgender person? Am I a real Jew,real Muslim, real Hindu, real expert, real authority, real Lesbian, true believer in Christ, true follower of the Prophet, true leader, real vegan,true whatever? You are what you are, someone who has learned, and will always learn more. Labels can help sometimes, but the label isn't helping here, it's strangling you. Read up on "imposter syndrome". You are you. You are good enough to justify your right to existence (philosophically or in the workplace), and you are always able to choose to learn more. End of.
129,099
I am in my 5th year as a developer (3.5 years as junior/mid level and now a senior dev). My current role is not going well (people issues). Anyway, I said to one of the managers I was thinking of looking for another job and he told me there is no way I could get the same salary or position in another organization as I'm not a real developer yet. ***How do I know if he is right?*** Unfortunately, I agree with him. I only know the fundamentals of the languages I work with (C# & JavaScript), although I do consider myself an advanced SQL guy (but I'm regularly told that doesn't count). So, how will I know when I know enough to call myself a developer? Is there some kind of matrix/test I can use? I am regularly studying (2 - 3 hours per day) on PluralSight and by making my own projects, but I feel like a complete beginner in most aspects of software. ***Update - November 2020. Well, don't believe what haters tell you. I have been working as a full-stack developer for almost 2 years now, have dramatically increased my expertise through self-learning and through my job, and recently got promoted to a lead developer. If you ever find yourself asking the above - don't give up, work & study hard and believe in yourself!***
2019/02/14
[ "https://workplace.stackexchange.com/questions/129099", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/91131/" ]
LOL I remember when I was working for a major NY based newspaper and our entire team was slapped with that "Not a real developer" moniker. (We were separate from the main group and handled everything from development to desktop support, back in the 1990s and early 2000's) The "Real developers", in the main IT group insisted they do the work. Management decided to let each of the two groups do half the work (it was feasible) and let the end users, who would be using the solution, decide which way to go. After calling our work "sh\*t code" to our faces, and delivering their "masterpiece" to the end users, the end users chose our work over theirs and we quickly redid the job the "Real developers" made a mess of. You're doing development, you are a real developer. You may need to branch out, and given the attitude at your company, I strongly suggest it. Don't listen to anyone who says "SQL doesn't count". It sure does, many people can't even write basic SQL, and the reversed order of processing can screw up programmers badly. Being able to do both is a rare, and valued skillset. Trust yourself a bit more. Don't listen to your detractors. IF you are lacking in an area, do freelance work to strengthen yourself, but don't let anyone discourage you.
There are a lot of supportive answers. My answer will try to objectively address your question but might not be very supportive. The ugly truths: * 5 years may or may not mean anything * SQL expert knowledge may or may not mean anything * You seem to be in a toxic environment and you should plan on leaving. Any work environment that allows/tolerates a manager telling you something like that is an environment you don't want to work in. How to know if you are a real developer? Short answer: When you can take on a medium-large project alone and program them from the ground up. It's not about how many programming languages or frameworks you know. It's about solving problems and achieving a result through the best practices. Long answer: I used to work in a company that had a base code developed by a team that is treated as a first class citizen of the company. Then this base code is customized and sold to the clients by another team that is considered second class citizen and are generally treated as useless parasites by the first team. The whole work environment is very confined and restricted in terms of access and tools you use. The job boils down to filling the blanks in that base code and do minor styling changes. I was on that second team and I didn't consider my work there a real developer work, simply because the amount and magnitude of problems I face are very limited due to the fact that most of the work is already done in the base code. Architecture is already decided on and all libraries are developed and you just consume it and extend the existing functionality. If that sounds familiar to you, I recommend you invest some of your time into building applications from the ground up all the way to publishing them into the web.
129,099
I am in my 5th year as a developer (3.5 years as junior/mid level and now a senior dev). My current role is not going well (people issues). Anyway, I said to one of the managers I was thinking of looking for another job and he told me there is no way I could get the same salary or position in another organization as I'm not a real developer yet. ***How do I know if he is right?*** Unfortunately, I agree with him. I only know the fundamentals of the languages I work with (C# & JavaScript), although I do consider myself an advanced SQL guy (but I'm regularly told that doesn't count). So, how will I know when I know enough to call myself a developer? Is there some kind of matrix/test I can use? I am regularly studying (2 - 3 hours per day) on PluralSight and by making my own projects, but I feel like a complete beginner in most aspects of software. ***Update - November 2020. Well, don't believe what haters tell you. I have been working as a full-stack developer for almost 2 years now, have dramatically increased my expertise through self-learning and through my job, and recently got promoted to a lead developer. If you ever find yourself asking the above - don't give up, work & study hard and believe in yourself!***
2019/02/14
[ "https://workplace.stackexchange.com/questions/129099", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/91131/" ]
Since you are a senior developer, I assume you have gone through several promotions to get there and weren't hired into the position as a fluke. A senior developer should have a wealth of experience, and can perform most job tasks with little guidance. Your company should have a career matrix you can check to see what boxes you clearly checked off in order to get promoted to where you are. You're a developer (that's what your job description says, doesn't it?). I think your mistake was telling your supervisor you were planning to look for another job. He might have made those comments out of bitterness. Just look for another job and let him know you're leaving **after** you have an offer somewhere else.
"Nearly forty *(wheeze!)* years later, I'm still wondering!" Hope I never find out.
129,099
I am in my 5th year as a developer (3.5 years as junior/mid level and now a senior dev). My current role is not going well (people issues). Anyway, I said to one of the managers I was thinking of looking for another job and he told me there is no way I could get the same salary or position in another organization as I'm not a real developer yet. ***How do I know if he is right?*** Unfortunately, I agree with him. I only know the fundamentals of the languages I work with (C# & JavaScript), although I do consider myself an advanced SQL guy (but I'm regularly told that doesn't count). So, how will I know when I know enough to call myself a developer? Is there some kind of matrix/test I can use? I am regularly studying (2 - 3 hours per day) on PluralSight and by making my own projects, but I feel like a complete beginner in most aspects of software. ***Update - November 2020. Well, don't believe what haters tell you. I have been working as a full-stack developer for almost 2 years now, have dramatically increased my expertise through self-learning and through my job, and recently got promoted to a lead developer. If you ever find yourself asking the above - don't give up, work & study hard and believe in yourself!***
2019/02/14
[ "https://workplace.stackexchange.com/questions/129099", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/91131/" ]
You already *are* a developer. There is a meme doing the rounds on LinkedIn at the moment which is worth quoting here: > > Your value does not decrease by somebody else's failure to see your > worth > > > Developers are in huge demand. There have been [recent articles](https://www.cnbc.com/2018/09/06/companies-worry-more-about-access-to-software-developers-than-capital.html) stating that developers are more important to companies than gaining access to capital - and that value is rising all the time. I suspect their ploy is to make you stay but if they're openly putting you down - why should you?
I'd agree with all the comments above that you're probably a great developer already, but if you are looking for areas to improve, these are a few I can think of: **Reliability:** Why do bugs and rework happen in your environment? Can you change process (TDD, integration tests, better stories) to help this? Are tools or code structure at fault? **Performance:** Why is the system slow or unscalable? How can we drill down and debug this? (clue, find the real answers, don't trot out received knowledge from the internet) **Productivity:** How can we work smarter? What is taking time, and does this relate to real business needs? Are we using appropriate toolsets and process? **Domain knowledge:** Do you understand the needs of customers? How can you improve on this, whether it's by visiting the shopfloor, reading a textbook or going on a course. Even if it isn't a direct part of your workflow, understanding the why and how of requirements makes you a better developer. And if you aren't able to move in those directions because your works sets barriers, then it's *definitely* time to move on.
129,099
I am in my 5th year as a developer (3.5 years as junior/mid level and now a senior dev). My current role is not going well (people issues). Anyway, I said to one of the managers I was thinking of looking for another job and he told me there is no way I could get the same salary or position in another organization as I'm not a real developer yet. ***How do I know if he is right?*** Unfortunately, I agree with him. I only know the fundamentals of the languages I work with (C# & JavaScript), although I do consider myself an advanced SQL guy (but I'm regularly told that doesn't count). So, how will I know when I know enough to call myself a developer? Is there some kind of matrix/test I can use? I am regularly studying (2 - 3 hours per day) on PluralSight and by making my own projects, but I feel like a complete beginner in most aspects of software. ***Update - November 2020. Well, don't believe what haters tell you. I have been working as a full-stack developer for almost 2 years now, have dramatically increased my expertise through self-learning and through my job, and recently got promoted to a lead developer. If you ever find yourself asking the above - don't give up, work & study hard and believe in yourself!***
2019/02/14
[ "https://workplace.stackexchange.com/questions/129099", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/91131/" ]
**You are already a real developer.** I'm guessing that your boss is belittling you in order to keep your morale down, so that you're less likely to look for another job or ask for a better salary. Five years of experience is more than enough to consider yourself a qualified developer. Given that your current role is not going well, and you have an emotionally manipulative manager above you right now, I would definitely start looking for another job that gives you the respect that you've earned.
What you are feeling is known as "impostor syndrome", the thought that you don't really know what you are doing and people assume you are better than you are. Here's a secret: Everyone feels that way, and it's rarely the case. Ask yourself, if I am given a new task that I need to learn some specific tech for, am I capable of doing it? Because few people are experts in multiple languages and never come across anything they don't understand immediately. Your boss is "negging" you, saying you are not a real developer because they don't want you to quit. That tells you that you are actually a valuable asset for the company and worth more than you think.
24,967,747
I'm new to JavaScript so I was curious about the flexibility of JS variable assignment. Using the following code as an example: ``` var container = "hello"; container = 43; ``` Is it good practice (or a common practice) to change the data type of a variable in JavaScript? Or is it a matter of preference?
2014/07/26
[ "https://Stackoverflow.com/questions/24967747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3875002/" ]
While the language totally allows you to do that, I would avoid it as much as possible. It is just error prone and misleading. Usually the variable name will describe its contents and if you pass something totally different I consider you are abusing the language features. In JS there is the concept of `duck typing`, for instance if you have: ``` function doStuff(myComplexType){ var i = myComplexType.myProperty; } ``` It does not matter what the actual type of `myComplexObject` is as long as it satisfies the *contract* and has a `myProperty` defined.
It's always better to be consistent. Especially if you work in a team. It can really frustrate people who has to walk through your code, because sometimes people just don't have time and they jump from one place to another, so it's very easy to not notice that kind of changes in the code. Also, never mix data types in the array. Believe me, you don't want to be that guy.
24,967,747
I'm new to JavaScript so I was curious about the flexibility of JS variable assignment. Using the following code as an example: ``` var container = "hello"; container = 43; ``` Is it good practice (or a common practice) to change the data type of a variable in JavaScript? Or is it a matter of preference?
2014/07/26
[ "https://Stackoverflow.com/questions/24967747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3875002/" ]
While the language totally allows you to do that, I would avoid it as much as possible. It is just error prone and misleading. Usually the variable name will describe its contents and if you pass something totally different I consider you are abusing the language features. In JS there is the concept of `duck typing`, for instance if you have: ``` function doStuff(myComplexType){ var i = myComplexType.myProperty; } ``` It does not matter what the actual type of `myComplexObject` is as long as it satisfies the *contract* and has a `myProperty` defined.
It is a "good practice" to use the same variable for the same type of data. Especially, don't mixup types in an array, as the javascript engines like V8(chrome) and SpiderMonkey(Firefox) optimize your code at runtime, and mixed-types in array (among other things) won't let that happen. You'd also like to build up this habit, so that later, if you're using things like [Typed Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays), it would come in handy. But pedanticism aside, you can play fast and loose with javascript, as it is [designed that way](https://www.w3.org/community/webed/wiki/A_Short_History_of_JavaScript). Sometimes, it is unavoidable too, as an argument in a function may have an integer as it's argument or, if not passed, then 'undefined', which is ~~an object~~ not an integer! Have fun with JS, it's a pretty fun language to learn, and fast to experiment with.
24,967,747
I'm new to JavaScript so I was curious about the flexibility of JS variable assignment. Using the following code as an example: ``` var container = "hello"; container = 43; ``` Is it good practice (or a common practice) to change the data type of a variable in JavaScript? Or is it a matter of preference?
2014/07/26
[ "https://Stackoverflow.com/questions/24967747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3875002/" ]
Javascript gives you lots of rope. You can either build a masterpiece with that rope or you can write horrible code. Because the language does not stop you from doing bad things, you must know when different things in the language are appropriate or inappropriate. To that end, the use or purpose of the variable should match its name and should not change. In other words, you should not use the same variable for many different purposes. If you have a different use, then create a different variable and give that new variable a different descriptive name that describes its use. It is possible to have a single variable that has a consistent use that fits with one descriptive name and that use can contain different types, but that is not particularly common. Most of the time you're using different types, it's because you have a different use that would fit better in a different variable. I tend to think of my coding objectives in this order: 1. Correct, reliable code 2. Clear, easy to understand, maintainable and extensible code 3. Appropriate performance for the situation 4. Concise and compact Note that clear, maintainable code is given a fairly high priority. This will allow me to come back and work on this code years later to fix a bug or add a feature and still understand how it works. Or, it will allow someone else on the team to work on the code immediately and have little trouble understanding how it works or how to modify it safely. Overloading the same variable for multiple purposes with different types is unlikely to be clear and easy to understand and maintain. I'm not saying that there is never an OK situation to do that, but the code better make it very, very clear that that is expected and a possibility as this will usually not be the case. --- Note, in your code example, the name of your variable `container` is not descriptive for either of your uses when it contains `"hello"` or `43`.
While the language totally allows you to do that, I would avoid it as much as possible. It is just error prone and misleading. Usually the variable name will describe its contents and if you pass something totally different I consider you are abusing the language features. In JS there is the concept of `duck typing`, for instance if you have: ``` function doStuff(myComplexType){ var i = myComplexType.myProperty; } ``` It does not matter what the actual type of `myComplexObject` is as long as it satisfies the *contract* and has a `myProperty` defined.
24,967,747
I'm new to JavaScript so I was curious about the flexibility of JS variable assignment. Using the following code as an example: ``` var container = "hello"; container = 43; ``` Is it good practice (or a common practice) to change the data type of a variable in JavaScript? Or is it a matter of preference?
2014/07/26
[ "https://Stackoverflow.com/questions/24967747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3875002/" ]
It's always better to be consistent. Especially if you work in a team. It can really frustrate people who has to walk through your code, because sometimes people just don't have time and they jump from one place to another, so it's very easy to not notice that kind of changes in the code. Also, never mix data types in the array. Believe me, you don't want to be that guy.
It is a "good practice" to use the same variable for the same type of data. Especially, don't mixup types in an array, as the javascript engines like V8(chrome) and SpiderMonkey(Firefox) optimize your code at runtime, and mixed-types in array (among other things) won't let that happen. You'd also like to build up this habit, so that later, if you're using things like [Typed Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays), it would come in handy. But pedanticism aside, you can play fast and loose with javascript, as it is [designed that way](https://www.w3.org/community/webed/wiki/A_Short_History_of_JavaScript). Sometimes, it is unavoidable too, as an argument in a function may have an integer as it's argument or, if not passed, then 'undefined', which is ~~an object~~ not an integer! Have fun with JS, it's a pretty fun language to learn, and fast to experiment with.
24,967,747
I'm new to JavaScript so I was curious about the flexibility of JS variable assignment. Using the following code as an example: ``` var container = "hello"; container = 43; ``` Is it good practice (or a common practice) to change the data type of a variable in JavaScript? Or is it a matter of preference?
2014/07/26
[ "https://Stackoverflow.com/questions/24967747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3875002/" ]
Javascript gives you lots of rope. You can either build a masterpiece with that rope or you can write horrible code. Because the language does not stop you from doing bad things, you must know when different things in the language are appropriate or inappropriate. To that end, the use or purpose of the variable should match its name and should not change. In other words, you should not use the same variable for many different purposes. If you have a different use, then create a different variable and give that new variable a different descriptive name that describes its use. It is possible to have a single variable that has a consistent use that fits with one descriptive name and that use can contain different types, but that is not particularly common. Most of the time you're using different types, it's because you have a different use that would fit better in a different variable. I tend to think of my coding objectives in this order: 1. Correct, reliable code 2. Clear, easy to understand, maintainable and extensible code 3. Appropriate performance for the situation 4. Concise and compact Note that clear, maintainable code is given a fairly high priority. This will allow me to come back and work on this code years later to fix a bug or add a feature and still understand how it works. Or, it will allow someone else on the team to work on the code immediately and have little trouble understanding how it works or how to modify it safely. Overloading the same variable for multiple purposes with different types is unlikely to be clear and easy to understand and maintain. I'm not saying that there is never an OK situation to do that, but the code better make it very, very clear that that is expected and a possibility as this will usually not be the case. --- Note, in your code example, the name of your variable `container` is not descriptive for either of your uses when it contains `"hello"` or `43`.
It's always better to be consistent. Especially if you work in a team. It can really frustrate people who has to walk through your code, because sometimes people just don't have time and they jump from one place to another, so it's very easy to not notice that kind of changes in the code. Also, never mix data types in the array. Believe me, you don't want to be that guy.
24,967,747
I'm new to JavaScript so I was curious about the flexibility of JS variable assignment. Using the following code as an example: ``` var container = "hello"; container = 43; ``` Is it good practice (or a common practice) to change the data type of a variable in JavaScript? Or is it a matter of preference?
2014/07/26
[ "https://Stackoverflow.com/questions/24967747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3875002/" ]
Javascript gives you lots of rope. You can either build a masterpiece with that rope or you can write horrible code. Because the language does not stop you from doing bad things, you must know when different things in the language are appropriate or inappropriate. To that end, the use or purpose of the variable should match its name and should not change. In other words, you should not use the same variable for many different purposes. If you have a different use, then create a different variable and give that new variable a different descriptive name that describes its use. It is possible to have a single variable that has a consistent use that fits with one descriptive name and that use can contain different types, but that is not particularly common. Most of the time you're using different types, it's because you have a different use that would fit better in a different variable. I tend to think of my coding objectives in this order: 1. Correct, reliable code 2. Clear, easy to understand, maintainable and extensible code 3. Appropriate performance for the situation 4. Concise and compact Note that clear, maintainable code is given a fairly high priority. This will allow me to come back and work on this code years later to fix a bug or add a feature and still understand how it works. Or, it will allow someone else on the team to work on the code immediately and have little trouble understanding how it works or how to modify it safely. Overloading the same variable for multiple purposes with different types is unlikely to be clear and easy to understand and maintain. I'm not saying that there is never an OK situation to do that, but the code better make it very, very clear that that is expected and a possibility as this will usually not be the case. --- Note, in your code example, the name of your variable `container` is not descriptive for either of your uses when it contains `"hello"` or `43`.
It is a "good practice" to use the same variable for the same type of data. Especially, don't mixup types in an array, as the javascript engines like V8(chrome) and SpiderMonkey(Firefox) optimize your code at runtime, and mixed-types in array (among other things) won't let that happen. You'd also like to build up this habit, so that later, if you're using things like [Typed Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays), it would come in handy. But pedanticism aside, you can play fast and loose with javascript, as it is [designed that way](https://www.w3.org/community/webed/wiki/A_Short_History_of_JavaScript). Sometimes, it is unavoidable too, as an argument in a function may have an integer as it's argument or, if not passed, then 'undefined', which is ~~an object~~ not an integer! Have fun with JS, it's a pretty fun language to learn, and fast to experiment with.
50,469,150
I have an array in JavaScript that have defined these values: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; ``` And when I call a function the first time function, I need to get this: ``` 1 2 3 ``` Calling it again I need to get: ``` 4 5 6 ``` Calling it again: ``` 7 8 9 ``` Calling it again: ``` 10 1 2 ``` Calling again: ``` 3 4 5 ``` And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values). I try using this: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { if (i<(6)) { console.log(myStringArray[i]); } } ``` But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter?
2018/05/22
[ "https://Stackoverflow.com/questions/50469150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8592693/" ]
**@Igor Petev**, JavaScript's closures are a nice concept that you can use to solve your problem. > > Please read [JavaScript's Closures - w3schools](https://www.w3schools.com/js/js_function_closures.asp) article. It's really nice and excellent. > > > I have used the concept of closures to solve this problem. Please leave a comment if you don't understand my code or anything else related to this problem. > > > Please have a look at the below code. ``` var get3items = (function () { var index = 0; var myStringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]; var len = myStringArray.length return function () { for(var count = 0; count < 3; count += 1) { console.log(myStringArray[index]); if(index == (len - 1)) { index = 0; } else { index += 1; } } } })(); get3items (); // First call console.log() get3items (); // Second call console.log() get3items (); // Third call console.log() get3items (); // Fourth call console.log() get3items (); // Fifth call /* 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 */ ```
How about using a generator: ``` function* get3() { var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var index = 0; while (true) { yield [0, 1, 2].map(i => myStringArray[(index + i) % myStringArray.length]) index = (index + 3) % myStringArray.length; } } ``` Calling this function returns an object which you can call `.next()` on, to get the next set of 3: ``` var getter = get3(); console.log(getter.next().value); // ["1","2","3"] console.log(getter.next().value); // ["4","5","6"] console.log(getter.next().value); // ["7","8","9"] // etc. ```
50,469,150
I have an array in JavaScript that have defined these values: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; ``` And when I call a function the first time function, I need to get this: ``` 1 2 3 ``` Calling it again I need to get: ``` 4 5 6 ``` Calling it again: ``` 7 8 9 ``` Calling it again: ``` 10 1 2 ``` Calling again: ``` 3 4 5 ``` And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values). I try using this: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { if (i<(6)) { console.log(myStringArray[i]); } } ``` But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter?
2018/05/22
[ "https://Stackoverflow.com/questions/50469150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8592693/" ]
You could take a function which slices three elements and if not possible, it takes the needed first values of the array as well. ```js function take3() { var temp = array.slice(index, index += 3) index %= array.length; console.log(temp.concat(temp.length < 3 ? array.slice(0, index) : []).join(' ')); } var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], index = 0; ``` ```html <button onclick="take3()">take 3</button> ``` With a mapping of a dynamic count. ```js function take(length) { console.log(Array.from({ length }, _ => array[++index, index %= array.length])); } var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], index = -1; ``` ```html <button onclick="take(3)">take 3</button> ```
How about using a generator: ``` function* get3() { var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var index = 0; while (true) { yield [0, 1, 2].map(i => myStringArray[(index + i) % myStringArray.length]) index = (index + 3) % myStringArray.length; } } ``` Calling this function returns an object which you can call `.next()` on, to get the next set of 3: ``` var getter = get3(); console.log(getter.next().value); // ["1","2","3"] console.log(getter.next().value); // ["4","5","6"] console.log(getter.next().value); // ["7","8","9"] // etc. ```
50,469,150
I have an array in JavaScript that have defined these values: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; ``` And when I call a function the first time function, I need to get this: ``` 1 2 3 ``` Calling it again I need to get: ``` 4 5 6 ``` Calling it again: ``` 7 8 9 ``` Calling it again: ``` 10 1 2 ``` Calling again: ``` 3 4 5 ``` And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values). I try using this: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { if (i<(6)) { console.log(myStringArray[i]); } } ``` But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter?
2018/05/22
[ "https://Stackoverflow.com/questions/50469150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8592693/" ]
If you are OK with manipulating your original array as you loop through it you could `splice` and `concat` similar to below (or you could use a clone of the array if you need to persist the original array): ```js var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var loopByX = function(x){ var y = myStringArray.splice(0,x); myStringArray = myStringArray.concat(y); return y; } console.log(loopByX(3)); console.log(loopByX(3)); console.log(loopByX(3)); console.log(loopByX(3)); console.log(loopByX(3)); ``` If you want to go bi-directional (is that what you call it?), as mentioned in the comments, you could do it as below which then gives you the ability to go backwards or forward and the flexibility to do so in an arbitrary number: ```js var myStringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]; var loopByX = function(x) { var len = myStringArray.length; // Ensure x is always valid but you can add any behaviour here in that case yourself. As an example I return an empty array. if (Math.abs(x) > len) { return []; } var y = x > 0 ? myStringArray.splice(0, x) : myStringArray.splice(len + x, len); myStringArray = x > 0 ? myStringArray.concat(y) : y.concat(myStringArray); return y; } console.log(loopByX(20)); // invalid number console.log(loopByX(-20)); // invalid number console.log(loopByX(-3)); console.log(loopByX(-6)); console.log(loopByX(3)); console.log(loopByX(4)); ```
``` function* employeeNames(){ var empList = ["1","2","3","4","5","6","7","8","9","10"]; for(var i =0; i<=empList.length; i++){ yield empList[i]; } } var emp; emp = employeeNames(); ``` It uses a generator function...
50,469,150
I have an array in JavaScript that have defined these values: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; ``` And when I call a function the first time function, I need to get this: ``` 1 2 3 ``` Calling it again I need to get: ``` 4 5 6 ``` Calling it again: ``` 7 8 9 ``` Calling it again: ``` 10 1 2 ``` Calling again: ``` 3 4 5 ``` And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values). I try using this: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { if (i<(6)) { console.log(myStringArray[i]); } } ``` But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter?
2018/05/22
[ "https://Stackoverflow.com/questions/50469150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8592693/" ]
Your variable `i` is local to the `for` loop which means it basically resets every time the loop is started. So first make your variable `i` global. ```js var i=0; function employeeNames(){ var empList = ["1","2","3","4","5","6","7","8","9","10"]; var output = []; var j=0; while(j<3) { output.push(empList[i]) i=(i+1)%empList.length; j++; } return output; } console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); ```
The fancy solution with generator functions: ``` function* cycle(arr) { let i=0; while (true) { yield arr[i++]; i %= arr.length; } } function* chunksOf(n, iterable) { let chunk = []; for (const x of iterable) { chunk.push(x) if (chunk.length >= n) { yield chunk; chunk = []; } } if (chunk.length > 0) yield chunk; } function toFunction(iterator) { return () => iterator.next().value; } var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; const f = toFunction(chunksOf(3, cycle(myStringArray))); console.log(f()); console.log(f()); console.log(f()); // … ```
50,469,150
I have an array in JavaScript that have defined these values: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; ``` And when I call a function the first time function, I need to get this: ``` 1 2 3 ``` Calling it again I need to get: ``` 4 5 6 ``` Calling it again: ``` 7 8 9 ``` Calling it again: ``` 10 1 2 ``` Calling again: ``` 3 4 5 ``` And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values). I try using this: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { if (i<(6)) { console.log(myStringArray[i]); } } ``` But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter?
2018/05/22
[ "https://Stackoverflow.com/questions/50469150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8592693/" ]
You could take a function which slices three elements and if not possible, it takes the needed first values of the array as well. ```js function take3() { var temp = array.slice(index, index += 3) index %= array.length; console.log(temp.concat(temp.length < 3 ? array.slice(0, index) : []).join(' ')); } var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], index = 0; ``` ```html <button onclick="take3()">take 3</button> ``` With a mapping of a dynamic count. ```js function take(length) { console.log(Array.from({ length }, _ => array[++index, index %= array.length])); } var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], index = -1; ``` ```html <button onclick="take(3)">take 3</button> ```
**@Igor Petev**, JavaScript's closures are a nice concept that you can use to solve your problem. > > Please read [JavaScript's Closures - w3schools](https://www.w3schools.com/js/js_function_closures.asp) article. It's really nice and excellent. > > > I have used the concept of closures to solve this problem. Please leave a comment if you don't understand my code or anything else related to this problem. > > > Please have a look at the below code. ``` var get3items = (function () { var index = 0; var myStringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]; var len = myStringArray.length return function () { for(var count = 0; count < 3; count += 1) { console.log(myStringArray[index]); if(index == (len - 1)) { index = 0; } else { index += 1; } } } })(); get3items (); // First call console.log() get3items (); // Second call console.log() get3items (); // Third call console.log() get3items (); // Fourth call console.log() get3items (); // Fifth call /* 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 */ ```
50,469,150
I have an array in JavaScript that have defined these values: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; ``` And when I call a function the first time function, I need to get this: ``` 1 2 3 ``` Calling it again I need to get: ``` 4 5 6 ``` Calling it again: ``` 7 8 9 ``` Calling it again: ``` 10 1 2 ``` Calling again: ``` 3 4 5 ``` And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values). I try using this: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { if (i<(6)) { console.log(myStringArray[i]); } } ``` But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter?
2018/05/22
[ "https://Stackoverflow.com/questions/50469150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8592693/" ]
If you want the immutable way to achieve your circular looping ``` function loopArray(arr, step=3) { let i = 0; return function inner() { for (let j = 0; j < step; j++) { console.log(arr[i]); i = (i + 1) % arr.length; } }; } const func = loopArray(["1","2","3","4","5","6","7","8","9","10"], 3); func(); func(); func(); func(); func(); ```
How about using a generator: ``` function* get3() { var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var index = 0; while (true) { yield [0, 1, 2].map(i => myStringArray[(index + i) % myStringArray.length]) index = (index + 3) % myStringArray.length; } } ``` Calling this function returns an object which you can call `.next()` on, to get the next set of 3: ``` var getter = get3(); console.log(getter.next().value); // ["1","2","3"] console.log(getter.next().value); // ["4","5","6"] console.log(getter.next().value); // ["7","8","9"] // etc. ```
50,469,150
I have an array in JavaScript that have defined these values: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; ``` And when I call a function the first time function, I need to get this: ``` 1 2 3 ``` Calling it again I need to get: ``` 4 5 6 ``` Calling it again: ``` 7 8 9 ``` Calling it again: ``` 10 1 2 ``` Calling again: ``` 3 4 5 ``` And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values). I try using this: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { if (i<(6)) { console.log(myStringArray[i]); } } ``` But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter?
2018/05/22
[ "https://Stackoverflow.com/questions/50469150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8592693/" ]
How about using a generator: ``` function* get3() { var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var index = 0; while (true) { yield [0, 1, 2].map(i => myStringArray[(index + i) % myStringArray.length]) index = (index + 3) % myStringArray.length; } } ``` Calling this function returns an object which you can call `.next()` on, to get the next set of 3: ``` var getter = get3(); console.log(getter.next().value); // ["1","2","3"] console.log(getter.next().value); // ["4","5","6"] console.log(getter.next().value); // ["7","8","9"] // etc. ```
``` function* employeeNames(){ var empList = ["1","2","3","4","5","6","7","8","9","10"]; for(var i =0; i<=empList.length; i++){ yield empList[i]; } } var emp; emp = employeeNames(); ``` It uses a generator function...
50,469,150
I have an array in JavaScript that have defined these values: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; ``` And when I call a function the first time function, I need to get this: ``` 1 2 3 ``` Calling it again I need to get: ``` 4 5 6 ``` Calling it again: ``` 7 8 9 ``` Calling it again: ``` 10 1 2 ``` Calling again: ``` 3 4 5 ``` And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values). I try using this: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { if (i<(6)) { console.log(myStringArray[i]); } } ``` But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter?
2018/05/22
[ "https://Stackoverflow.com/questions/50469150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8592693/" ]
The fancy solution with generator functions: ``` function* cycle(arr) { let i=0; while (true) { yield arr[i++]; i %= arr.length; } } function* chunksOf(n, iterable) { let chunk = []; for (const x of iterable) { chunk.push(x) if (chunk.length >= n) { yield chunk; chunk = []; } } if (chunk.length > 0) yield chunk; } function toFunction(iterator) { return () => iterator.next().value; } var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; const f = toFunction(chunksOf(3, cycle(myStringArray))); console.log(f()); console.log(f()); console.log(f()); // … ```
``` function* employeeNames(){ var empList = ["1","2","3","4","5","6","7","8","9","10"]; for(var i =0; i<=empList.length; i++){ yield empList[i]; } } var emp; emp = employeeNames(); ``` It uses a generator function...
50,469,150
I have an array in JavaScript that have defined these values: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; ``` And when I call a function the first time function, I need to get this: ``` 1 2 3 ``` Calling it again I need to get: ``` 4 5 6 ``` Calling it again: ``` 7 8 9 ``` Calling it again: ``` 10 1 2 ``` Calling again: ``` 3 4 5 ``` And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values). I try using this: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { if (i<(6)) { console.log(myStringArray[i]); } } ``` But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter?
2018/05/22
[ "https://Stackoverflow.com/questions/50469150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8592693/" ]
Your variable `i` is local to the `for` loop which means it basically resets every time the loop is started. So first make your variable `i` global. ```js var i=0; function employeeNames(){ var empList = ["1","2","3","4","5","6","7","8","9","10"]; var output = []; var j=0; while(j<3) { output.push(empList[i]) i=(i+1)%empList.length; j++; } return output; } console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); ```
If you want the immutable way to achieve your circular looping ``` function loopArray(arr, step=3) { let i = 0; return function inner() { for (let j = 0; j < step; j++) { console.log(arr[i]); i = (i + 1) % arr.length; } }; } const func = loopArray(["1","2","3","4","5","6","7","8","9","10"], 3); func(); func(); func(); func(); func(); ```
50,469,150
I have an array in JavaScript that have defined these values: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; ``` And when I call a function the first time function, I need to get this: ``` 1 2 3 ``` Calling it again I need to get: ``` 4 5 6 ``` Calling it again: ``` 7 8 9 ``` Calling it again: ``` 10 1 2 ``` Calling again: ``` 3 4 5 ``` And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values). I try using this: ``` var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { if (i<(6)) { console.log(myStringArray[i]); } } ``` But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter?
2018/05/22
[ "https://Stackoverflow.com/questions/50469150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8592693/" ]
Your variable `i` is local to the `for` loop which means it basically resets every time the loop is started. So first make your variable `i` global. ```js var i=0; function employeeNames(){ var empList = ["1","2","3","4","5","6","7","8","9","10"]; var output = []; var j=0; while(j<3) { output.push(empList[i]) i=(i+1)%empList.length; j++; } return output; } console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); ```
How about using a generator: ``` function* get3() { var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var index = 0; while (true) { yield [0, 1, 2].map(i => myStringArray[(index + i) % myStringArray.length]) index = (index + 3) % myStringArray.length; } } ``` Calling this function returns an object which you can call `.next()` on, to get the next set of 3: ``` var getter = get3(); console.log(getter.next().value); // ["1","2","3"] console.log(getter.next().value); // ["4","5","6"] console.log(getter.next().value); // ["7","8","9"] // etc. ```
392,132
...I wanted to find the source before writing this Q, sadly I couldn't. My mental model was that exceptions were thought as an alternative to returning error codes from a function, which is the C way to signalize failure. Returning error codes and managing them is error-prone, cumbersome and tedious; which is why a more right-handed mechanism was thought. Problem is, then I started reading and hearing opinions that abusing exceptions is bad. Well of course - if I want to see if an array contains element X then it would probably not be a good idea to assume it does and then throw and almost immediatelly catch an exception if it doesn't. But these opinions were more strict than that. An example of an improper use of exceptions was if, for example, we have a web app and a user requests something that is not there / sends invalid data / any other condition arises that requires displaying an error page to the user. In this case, I was told, it would be a bad practice to throw an exception deep down in the server code, catch it before the request stops being processed and then display an error page. If I understand this mentality correctly (which doesn't have to be the case), the justification was that, since throwing the exception is not intended to crash an app (the situation is recoverable), then the situation is "sensible business-wise"; while exceptions should be reserved for situations "insensible business-wise", which I suppose means "unrecoverable"? But this seems to imply that if the app can continue and is not supposed to crash, I should not throw exceptions; I should only throw if the app cannot continue and must crash. Is this commonly agreed upon? If so, then why? I have feeling this is supposed to apply to almost all programming languages (but, notably, not Python.) I must admit [in my anti-pattern ridden game](https://softwareengineering.stackexchange.com/questions/371977/write-some-code-and-plague-it-with-anti-patterns-or-not-write-it-at-all-any-esc) I do otherwise. For example, when the user sends a JSON with a team, I obviously must validate this data. I seem to be doing precisely what is condemned above: I pass the JSON data to the pieces of code that are responsible for validating it and, if it's valid, constructing an instantiation of the `Team` class. If the data is invalid, an exception is thrown. I thought this would be convenient for me, especially since this seems to mix well with C# facilities I use to construct the team: for example, to instantiate a `Monster` subclass from a monster name present in the JSON, I use `Activator.CreateInstance` which naturally throws if the monster name present in the JSON doesn't match any subclass of `Monster`. But, well, others are more experienced than me, I marked this with a TODO that I should refactor this to `if(isValid(teamJson)) team = new Team(teamJson)` even though I don't understand why and even thought I don't like this idea because `isValid()` would have to share a lot of code with the `Team()` constructor. Yesterday, however, I read something surprising: [Throwing exceptions on assertion failures is, generally, a bad idea, because assertion failure should crash the program while an exception can be caught](https://stackoverflow.com/a/56210376/4385532)\*. This seems to go against the mentality I presented above, which would assert that exceptions should be thrown precisely when the program must crash. Could you clear my confusion? When should exceptions be thrown? In particular, should exceptions be thrown then and only then when the program should crash? --- \*(Yes, this applies to C++ while remarks about my game were about C#; but again - I don't want to discuss language facilities of this or other language, but when exceptions should be thrown in general, which - again - is AFAIK language-agnostic, although with few exceptions like Python.)
2019/05/20
[ "https://softwareengineering.stackexchange.com/questions/392132", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/212639/" ]
No, exceptions are not always thrown just to "crash" the program. Many exceptions are recoverable. For example, in Java you may get a `FileNotFoundException` if you try to open a file that doesn't exist. If that file was originally specified by the user, it stands to reason that you will get catch it fairly often and display an appropriate message to the user. > > others are more experienced than me, I marked this with a TODO that I should refactor this to if(isValid(teamJson)) team = new Team(teamJson) > > > I would also suggest refactoring this and having the Team constructor throw an `InvalidTeamException`. In my opinion, the decision to use an exception or return an error comes down to expectation. You can probably expect that `teamJson` is valid most of the time so when it isn't, you throw/raise an exception. To use a different example, say you were doing some kind of networking app that required authentication. So you have a `login()` method. Bad/incorrect username and password are common and thus the `login()` method would return an error. However, what if the network connection dropped in the middle of the process? That's unlikely and thus requires an exception. In general you want to catch all of your exceptions somewhere. Even it's just to say, "I can't recover from this error" and stop. The reality is, most code we write throws exceptions that are recoverable. It's just a question of who catches and handles the exception.
> > In particular, should exceptions be thrown then and only then when the program should crash? > > > Absolutely not. Exceptions are there to signal the caller that something went wrong. If the caller can handle the situation and recover from it, then he can handle the exception. Let's say someone calls a method that writes a string into a file. A situation might occur where the file that he is trying to write to is being locked by another process. So we have to notify the caller of that situation. We can't just return `false` and leave the caller in the dark about why the operation didn't succeed. Instead we throw a `FileLockedByAnotherProcessException` (or however you would call it). The caller can now decide if he can handle this exception and whether it makes sense for him to handle it. If for example the caller is on UI layer, he might want to catch the exception and display an error dialog to the user instead of letting it crash the whole program. There are however situation that are not possible to recover from. These situations are usually caused by a programming error and not by user input. Say stuff like division by 0, NullPointerExceptions, accessing array out of it's range etc. In these cases you would normally either leave the exceptions unhandled and let to program crash or let them propagate all the way down where you would catch them, display an error message and terminate the program yourself.
392,132
...I wanted to find the source before writing this Q, sadly I couldn't. My mental model was that exceptions were thought as an alternative to returning error codes from a function, which is the C way to signalize failure. Returning error codes and managing them is error-prone, cumbersome and tedious; which is why a more right-handed mechanism was thought. Problem is, then I started reading and hearing opinions that abusing exceptions is bad. Well of course - if I want to see if an array contains element X then it would probably not be a good idea to assume it does and then throw and almost immediatelly catch an exception if it doesn't. But these opinions were more strict than that. An example of an improper use of exceptions was if, for example, we have a web app and a user requests something that is not there / sends invalid data / any other condition arises that requires displaying an error page to the user. In this case, I was told, it would be a bad practice to throw an exception deep down in the server code, catch it before the request stops being processed and then display an error page. If I understand this mentality correctly (which doesn't have to be the case), the justification was that, since throwing the exception is not intended to crash an app (the situation is recoverable), then the situation is "sensible business-wise"; while exceptions should be reserved for situations "insensible business-wise", which I suppose means "unrecoverable"? But this seems to imply that if the app can continue and is not supposed to crash, I should not throw exceptions; I should only throw if the app cannot continue and must crash. Is this commonly agreed upon? If so, then why? I have feeling this is supposed to apply to almost all programming languages (but, notably, not Python.) I must admit [in my anti-pattern ridden game](https://softwareengineering.stackexchange.com/questions/371977/write-some-code-and-plague-it-with-anti-patterns-or-not-write-it-at-all-any-esc) I do otherwise. For example, when the user sends a JSON with a team, I obviously must validate this data. I seem to be doing precisely what is condemned above: I pass the JSON data to the pieces of code that are responsible for validating it and, if it's valid, constructing an instantiation of the `Team` class. If the data is invalid, an exception is thrown. I thought this would be convenient for me, especially since this seems to mix well with C# facilities I use to construct the team: for example, to instantiate a `Monster` subclass from a monster name present in the JSON, I use `Activator.CreateInstance` which naturally throws if the monster name present in the JSON doesn't match any subclass of `Monster`. But, well, others are more experienced than me, I marked this with a TODO that I should refactor this to `if(isValid(teamJson)) team = new Team(teamJson)` even though I don't understand why and even thought I don't like this idea because `isValid()` would have to share a lot of code with the `Team()` constructor. Yesterday, however, I read something surprising: [Throwing exceptions on assertion failures is, generally, a bad idea, because assertion failure should crash the program while an exception can be caught](https://stackoverflow.com/a/56210376/4385532)\*. This seems to go against the mentality I presented above, which would assert that exceptions should be thrown precisely when the program must crash. Could you clear my confusion? When should exceptions be thrown? In particular, should exceptions be thrown then and only then when the program should crash? --- \*(Yes, this applies to C++ while remarks about my game were about C#; but again - I don't want to discuss language facilities of this or other language, but when exceptions should be thrown in general, which - again - is AFAIK language-agnostic, although with few exceptions like Python.)
2019/05/20
[ "https://softwareengineering.stackexchange.com/questions/392132", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/212639/" ]
No, exceptions are not always thrown just to "crash" the program. Many exceptions are recoverable. For example, in Java you may get a `FileNotFoundException` if you try to open a file that doesn't exist. If that file was originally specified by the user, it stands to reason that you will get catch it fairly often and display an appropriate message to the user. > > others are more experienced than me, I marked this with a TODO that I should refactor this to if(isValid(teamJson)) team = new Team(teamJson) > > > I would also suggest refactoring this and having the Team constructor throw an `InvalidTeamException`. In my opinion, the decision to use an exception or return an error comes down to expectation. You can probably expect that `teamJson` is valid most of the time so when it isn't, you throw/raise an exception. To use a different example, say you were doing some kind of networking app that required authentication. So you have a `login()` method. Bad/incorrect username and password are common and thus the `login()` method would return an error. However, what if the network connection dropped in the middle of the process? That's unlikely and thus requires an exception. In general you want to catch all of your exceptions somewhere. Even it's just to say, "I can't recover from this error" and stop. The reality is, most code we write throws exceptions that are recoverable. It's just a question of who catches and handles the exception.
> > In particular, should exceptions be thrown then and only then when the program should crash? > > > Yes, they should only be thrown in those circumstances. Exceptions should be exceptional and should indicate that something has gone seriously wrong... ... but in practice there's a *lot* of code out there already that doesn't follow that principle. As Matthew points out, methods in many frameworks, including Java and .NET, will throw exceptions for the most trivial of reasons, such as a file not existing when trying to open it. The latter sets a precedent and creates a defacto standard that others follow. So you have a choice: use exceptions properly (but risk facing criticism for not following framework standards) or follow the crowd and use them as returning state for control flow. > > Returning error codes and managing them is error-prone, cumbersome and tedious... > > > Sure. But so are exceptions. That's why code like: ``` try { DoSomethingThatMayThrowATrivialException(); } catch {} ``` is so common.
392,132
...I wanted to find the source before writing this Q, sadly I couldn't. My mental model was that exceptions were thought as an alternative to returning error codes from a function, which is the C way to signalize failure. Returning error codes and managing them is error-prone, cumbersome and tedious; which is why a more right-handed mechanism was thought. Problem is, then I started reading and hearing opinions that abusing exceptions is bad. Well of course - if I want to see if an array contains element X then it would probably not be a good idea to assume it does and then throw and almost immediatelly catch an exception if it doesn't. But these opinions were more strict than that. An example of an improper use of exceptions was if, for example, we have a web app and a user requests something that is not there / sends invalid data / any other condition arises that requires displaying an error page to the user. In this case, I was told, it would be a bad practice to throw an exception deep down in the server code, catch it before the request stops being processed and then display an error page. If I understand this mentality correctly (which doesn't have to be the case), the justification was that, since throwing the exception is not intended to crash an app (the situation is recoverable), then the situation is "sensible business-wise"; while exceptions should be reserved for situations "insensible business-wise", which I suppose means "unrecoverable"? But this seems to imply that if the app can continue and is not supposed to crash, I should not throw exceptions; I should only throw if the app cannot continue and must crash. Is this commonly agreed upon? If so, then why? I have feeling this is supposed to apply to almost all programming languages (but, notably, not Python.) I must admit [in my anti-pattern ridden game](https://softwareengineering.stackexchange.com/questions/371977/write-some-code-and-plague-it-with-anti-patterns-or-not-write-it-at-all-any-esc) I do otherwise. For example, when the user sends a JSON with a team, I obviously must validate this data. I seem to be doing precisely what is condemned above: I pass the JSON data to the pieces of code that are responsible for validating it and, if it's valid, constructing an instantiation of the `Team` class. If the data is invalid, an exception is thrown. I thought this would be convenient for me, especially since this seems to mix well with C# facilities I use to construct the team: for example, to instantiate a `Monster` subclass from a monster name present in the JSON, I use `Activator.CreateInstance` which naturally throws if the monster name present in the JSON doesn't match any subclass of `Monster`. But, well, others are more experienced than me, I marked this with a TODO that I should refactor this to `if(isValid(teamJson)) team = new Team(teamJson)` even though I don't understand why and even thought I don't like this idea because `isValid()` would have to share a lot of code with the `Team()` constructor. Yesterday, however, I read something surprising: [Throwing exceptions on assertion failures is, generally, a bad idea, because assertion failure should crash the program while an exception can be caught](https://stackoverflow.com/a/56210376/4385532)\*. This seems to go against the mentality I presented above, which would assert that exceptions should be thrown precisely when the program must crash. Could you clear my confusion? When should exceptions be thrown? In particular, should exceptions be thrown then and only then when the program should crash? --- \*(Yes, this applies to C++ while remarks about my game were about C#; but again - I don't want to discuss language facilities of this or other language, but when exceptions should be thrown in general, which - again - is AFAIK language-agnostic, although with few exceptions like Python.)
2019/05/20
[ "https://softwareengineering.stackexchange.com/questions/392132", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/212639/" ]
No, exceptions are not always thrown just to "crash" the program. Many exceptions are recoverable. For example, in Java you may get a `FileNotFoundException` if you try to open a file that doesn't exist. If that file was originally specified by the user, it stands to reason that you will get catch it fairly often and display an appropriate message to the user. > > others are more experienced than me, I marked this with a TODO that I should refactor this to if(isValid(teamJson)) team = new Team(teamJson) > > > I would also suggest refactoring this and having the Team constructor throw an `InvalidTeamException`. In my opinion, the decision to use an exception or return an error comes down to expectation. You can probably expect that `teamJson` is valid most of the time so when it isn't, you throw/raise an exception. To use a different example, say you were doing some kind of networking app that required authentication. So you have a `login()` method. Bad/incorrect username and password are common and thus the `login()` method would return an error. However, what if the network connection dropped in the middle of the process? That's unlikely and thus requires an exception. In general you want to catch all of your exceptions somewhere. Even it's just to say, "I can't recover from this error" and stop. The reality is, most code we write throws exceptions that are recoverable. It's just a question of who catches and handles the exception.
I think it helps to understand the reason exceptions exist as a language feature. If you aren't familiar with [this](http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html), it's an old classic that can give you some context around the history of programming languages. Essentially, back in the day, people wrote code that jumped around from here to there based on line numbers or labels. If you've ever read a 'choose your own adventure' book, that's basically how programs were written. Do something and if x goto y. This made programs hard to debug and limited what compilers could do to check for errors optimize the execution. It was then proven that gotos were not required i.e. any program that could be written with gotos could be rewritten without them. However, no one would want to write code like that. There were certain patterns that were useful and considered OK (by language designers): methods, classes, breaks, returns, for loops, while loops, etc. These were refined and augmented to the point that gotos are not even allowed in some languages (e.g. Java) One of the most challenging parts of writing real software is dealing with errors and other alternate path cases. Gotos were often used in a well defined pattern to set aside a section of code for error handling in those alternate path scenarios. The basic constructs of ifs and methods and loops were not adequate to replace this pattern. try-catch-finally filled this void. And this has even been refined to try-with type constructs. The upshot is that in most languages, exceptions are used to handle alternate paths that need special handling (usually errors.) That's it. Nothing more, nothing less. It allows you to keep the 'happy-path' code simple and straight-forward and deal with these alternate paths where it makes the most sense. Without them, you need have mechanisms for passing around not only the data that you need for your main scenario but also the data for all the alternate paths and make sure you are constantly checking for whether you are on the alternate path after every method call. Using them to avoid that kind of mess is not abusing them in any way. Note that there are performance implications of using exceptions. Often these are overblown but if you are in a very deep call stack, throwing an exception can introduce a significant cost. A large number of bad requests could be used to create a DoS attack, for example, if your exceptions are expensive.
392,132
...I wanted to find the source before writing this Q, sadly I couldn't. My mental model was that exceptions were thought as an alternative to returning error codes from a function, which is the C way to signalize failure. Returning error codes and managing them is error-prone, cumbersome and tedious; which is why a more right-handed mechanism was thought. Problem is, then I started reading and hearing opinions that abusing exceptions is bad. Well of course - if I want to see if an array contains element X then it would probably not be a good idea to assume it does and then throw and almost immediatelly catch an exception if it doesn't. But these opinions were more strict than that. An example of an improper use of exceptions was if, for example, we have a web app and a user requests something that is not there / sends invalid data / any other condition arises that requires displaying an error page to the user. In this case, I was told, it would be a bad practice to throw an exception deep down in the server code, catch it before the request stops being processed and then display an error page. If I understand this mentality correctly (which doesn't have to be the case), the justification was that, since throwing the exception is not intended to crash an app (the situation is recoverable), then the situation is "sensible business-wise"; while exceptions should be reserved for situations "insensible business-wise", which I suppose means "unrecoverable"? But this seems to imply that if the app can continue and is not supposed to crash, I should not throw exceptions; I should only throw if the app cannot continue and must crash. Is this commonly agreed upon? If so, then why? I have feeling this is supposed to apply to almost all programming languages (but, notably, not Python.) I must admit [in my anti-pattern ridden game](https://softwareengineering.stackexchange.com/questions/371977/write-some-code-and-plague-it-with-anti-patterns-or-not-write-it-at-all-any-esc) I do otherwise. For example, when the user sends a JSON with a team, I obviously must validate this data. I seem to be doing precisely what is condemned above: I pass the JSON data to the pieces of code that are responsible for validating it and, if it's valid, constructing an instantiation of the `Team` class. If the data is invalid, an exception is thrown. I thought this would be convenient for me, especially since this seems to mix well with C# facilities I use to construct the team: for example, to instantiate a `Monster` subclass from a monster name present in the JSON, I use `Activator.CreateInstance` which naturally throws if the monster name present in the JSON doesn't match any subclass of `Monster`. But, well, others are more experienced than me, I marked this with a TODO that I should refactor this to `if(isValid(teamJson)) team = new Team(teamJson)` even though I don't understand why and even thought I don't like this idea because `isValid()` would have to share a lot of code with the `Team()` constructor. Yesterday, however, I read something surprising: [Throwing exceptions on assertion failures is, generally, a bad idea, because assertion failure should crash the program while an exception can be caught](https://stackoverflow.com/a/56210376/4385532)\*. This seems to go against the mentality I presented above, which would assert that exceptions should be thrown precisely when the program must crash. Could you clear my confusion? When should exceptions be thrown? In particular, should exceptions be thrown then and only then when the program should crash? --- \*(Yes, this applies to C++ while remarks about my game were about C#; but again - I don't want to discuss language facilities of this or other language, but when exceptions should be thrown in general, which - again - is AFAIK language-agnostic, although with few exceptions like Python.)
2019/05/20
[ "https://softwareengineering.stackexchange.com/questions/392132", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/212639/" ]
> > In particular, should exceptions be thrown then and only then when the program should crash? > > > Absolutely not. Exceptions are there to signal the caller that something went wrong. If the caller can handle the situation and recover from it, then he can handle the exception. Let's say someone calls a method that writes a string into a file. A situation might occur where the file that he is trying to write to is being locked by another process. So we have to notify the caller of that situation. We can't just return `false` and leave the caller in the dark about why the operation didn't succeed. Instead we throw a `FileLockedByAnotherProcessException` (or however you would call it). The caller can now decide if he can handle this exception and whether it makes sense for him to handle it. If for example the caller is on UI layer, he might want to catch the exception and display an error dialog to the user instead of letting it crash the whole program. There are however situation that are not possible to recover from. These situations are usually caused by a programming error and not by user input. Say stuff like division by 0, NullPointerExceptions, accessing array out of it's range etc. In these cases you would normally either leave the exceptions unhandled and let to program crash or let them propagate all the way down where you would catch them, display an error message and terminate the program yourself.
> > In particular, should exceptions be thrown then and only then when the program should crash? > > > Yes, they should only be thrown in those circumstances. Exceptions should be exceptional and should indicate that something has gone seriously wrong... ... but in practice there's a *lot* of code out there already that doesn't follow that principle. As Matthew points out, methods in many frameworks, including Java and .NET, will throw exceptions for the most trivial of reasons, such as a file not existing when trying to open it. The latter sets a precedent and creates a defacto standard that others follow. So you have a choice: use exceptions properly (but risk facing criticism for not following framework standards) or follow the crowd and use them as returning state for control flow. > > Returning error codes and managing them is error-prone, cumbersome and tedious... > > > Sure. But so are exceptions. That's why code like: ``` try { DoSomethingThatMayThrowATrivialException(); } catch {} ``` is so common.
392,132
...I wanted to find the source before writing this Q, sadly I couldn't. My mental model was that exceptions were thought as an alternative to returning error codes from a function, which is the C way to signalize failure. Returning error codes and managing them is error-prone, cumbersome and tedious; which is why a more right-handed mechanism was thought. Problem is, then I started reading and hearing opinions that abusing exceptions is bad. Well of course - if I want to see if an array contains element X then it would probably not be a good idea to assume it does and then throw and almost immediatelly catch an exception if it doesn't. But these opinions were more strict than that. An example of an improper use of exceptions was if, for example, we have a web app and a user requests something that is not there / sends invalid data / any other condition arises that requires displaying an error page to the user. In this case, I was told, it would be a bad practice to throw an exception deep down in the server code, catch it before the request stops being processed and then display an error page. If I understand this mentality correctly (which doesn't have to be the case), the justification was that, since throwing the exception is not intended to crash an app (the situation is recoverable), then the situation is "sensible business-wise"; while exceptions should be reserved for situations "insensible business-wise", which I suppose means "unrecoverable"? But this seems to imply that if the app can continue and is not supposed to crash, I should not throw exceptions; I should only throw if the app cannot continue and must crash. Is this commonly agreed upon? If so, then why? I have feeling this is supposed to apply to almost all programming languages (but, notably, not Python.) I must admit [in my anti-pattern ridden game](https://softwareengineering.stackexchange.com/questions/371977/write-some-code-and-plague-it-with-anti-patterns-or-not-write-it-at-all-any-esc) I do otherwise. For example, when the user sends a JSON with a team, I obviously must validate this data. I seem to be doing precisely what is condemned above: I pass the JSON data to the pieces of code that are responsible for validating it and, if it's valid, constructing an instantiation of the `Team` class. If the data is invalid, an exception is thrown. I thought this would be convenient for me, especially since this seems to mix well with C# facilities I use to construct the team: for example, to instantiate a `Monster` subclass from a monster name present in the JSON, I use `Activator.CreateInstance` which naturally throws if the monster name present in the JSON doesn't match any subclass of `Monster`. But, well, others are more experienced than me, I marked this with a TODO that I should refactor this to `if(isValid(teamJson)) team = new Team(teamJson)` even though I don't understand why and even thought I don't like this idea because `isValid()` would have to share a lot of code with the `Team()` constructor. Yesterday, however, I read something surprising: [Throwing exceptions on assertion failures is, generally, a bad idea, because assertion failure should crash the program while an exception can be caught](https://stackoverflow.com/a/56210376/4385532)\*. This seems to go against the mentality I presented above, which would assert that exceptions should be thrown precisely when the program must crash. Could you clear my confusion? When should exceptions be thrown? In particular, should exceptions be thrown then and only then when the program should crash? --- \*(Yes, this applies to C++ while remarks about my game were about C#; but again - I don't want to discuss language facilities of this or other language, but when exceptions should be thrown in general, which - again - is AFAIK language-agnostic, although with few exceptions like Python.)
2019/05/20
[ "https://softwareengineering.stackexchange.com/questions/392132", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/212639/" ]
It seems to me that most discussions about exceptions are missing the point. Most people reiterate "exceptions should be used only for exceptional circumstances" and then argue about their differing opinions of what does or does not qualify as "exceptional circumstances". That is a meaningless semantic game. Instead, I propose that **the use of exceptions should be based on their nature as language features**. Exceptions have three core properties: 1. They can transfer control flow up the call stack without requiring any changes in the code in between. 2. They cannot be ignored silently. If there is no code handling them, your application will crash with a nice stack trace telling you what happened. And code that catches and ignores them is at least a very visible red flag. 3. They syntactically represent alternative results of a method, you can have an arbitrary number of different ones, and catch clauses allow you to handle them selectively. And therefore exceptions should be used when these properties provide a benefit: 1. When you want to give the caller freedom to decide the granularity of error handling - i.e. if sometimes it would make sense for a caller to immediately do something specific, but in other circumstances it could be handled by a generic error handler (e.g. one that returns a HTTP 500 response). 2. When there is a case that callers are likely to ignore and you don't want them to. 3. When your method has a natural return value, but also special cases where the return value doesn't exist, and they might need to be handled in different places. Especially points 2 and 3 are a good match for the "exceptional circumstances" definition, which is probably where exceptions got their name, but these more specific properties allow for a more concrete reasoning why exceptions should or should not be used in a concrete case. And to finally answe the question as stated: No, exceptions are useful in many cases where you do not want the program to crash.
> > In particular, should exceptions be thrown then and only then when the program should crash? > > > Absolutely not. Exceptions are there to signal the caller that something went wrong. If the caller can handle the situation and recover from it, then he can handle the exception. Let's say someone calls a method that writes a string into a file. A situation might occur where the file that he is trying to write to is being locked by another process. So we have to notify the caller of that situation. We can't just return `false` and leave the caller in the dark about why the operation didn't succeed. Instead we throw a `FileLockedByAnotherProcessException` (or however you would call it). The caller can now decide if he can handle this exception and whether it makes sense for him to handle it. If for example the caller is on UI layer, he might want to catch the exception and display an error dialog to the user instead of letting it crash the whole program. There are however situation that are not possible to recover from. These situations are usually caused by a programming error and not by user input. Say stuff like division by 0, NullPointerExceptions, accessing array out of it's range etc. In these cases you would normally either leave the exceptions unhandled and let to program crash or let them propagate all the way down where you would catch them, display an error message and terminate the program yourself.
392,132
...I wanted to find the source before writing this Q, sadly I couldn't. My mental model was that exceptions were thought as an alternative to returning error codes from a function, which is the C way to signalize failure. Returning error codes and managing them is error-prone, cumbersome and tedious; which is why a more right-handed mechanism was thought. Problem is, then I started reading and hearing opinions that abusing exceptions is bad. Well of course - if I want to see if an array contains element X then it would probably not be a good idea to assume it does and then throw and almost immediatelly catch an exception if it doesn't. But these opinions were more strict than that. An example of an improper use of exceptions was if, for example, we have a web app and a user requests something that is not there / sends invalid data / any other condition arises that requires displaying an error page to the user. In this case, I was told, it would be a bad practice to throw an exception deep down in the server code, catch it before the request stops being processed and then display an error page. If I understand this mentality correctly (which doesn't have to be the case), the justification was that, since throwing the exception is not intended to crash an app (the situation is recoverable), then the situation is "sensible business-wise"; while exceptions should be reserved for situations "insensible business-wise", which I suppose means "unrecoverable"? But this seems to imply that if the app can continue and is not supposed to crash, I should not throw exceptions; I should only throw if the app cannot continue and must crash. Is this commonly agreed upon? If so, then why? I have feeling this is supposed to apply to almost all programming languages (but, notably, not Python.) I must admit [in my anti-pattern ridden game](https://softwareengineering.stackexchange.com/questions/371977/write-some-code-and-plague-it-with-anti-patterns-or-not-write-it-at-all-any-esc) I do otherwise. For example, when the user sends a JSON with a team, I obviously must validate this data. I seem to be doing precisely what is condemned above: I pass the JSON data to the pieces of code that are responsible for validating it and, if it's valid, constructing an instantiation of the `Team` class. If the data is invalid, an exception is thrown. I thought this would be convenient for me, especially since this seems to mix well with C# facilities I use to construct the team: for example, to instantiate a `Monster` subclass from a monster name present in the JSON, I use `Activator.CreateInstance` which naturally throws if the monster name present in the JSON doesn't match any subclass of `Monster`. But, well, others are more experienced than me, I marked this with a TODO that I should refactor this to `if(isValid(teamJson)) team = new Team(teamJson)` even though I don't understand why and even thought I don't like this idea because `isValid()` would have to share a lot of code with the `Team()` constructor. Yesterday, however, I read something surprising: [Throwing exceptions on assertion failures is, generally, a bad idea, because assertion failure should crash the program while an exception can be caught](https://stackoverflow.com/a/56210376/4385532)\*. This seems to go against the mentality I presented above, which would assert that exceptions should be thrown precisely when the program must crash. Could you clear my confusion? When should exceptions be thrown? In particular, should exceptions be thrown then and only then when the program should crash? --- \*(Yes, this applies to C++ while remarks about my game were about C#; but again - I don't want to discuss language facilities of this or other language, but when exceptions should be thrown in general, which - again - is AFAIK language-agnostic, although with few exceptions like Python.)
2019/05/20
[ "https://softwareengineering.stackexchange.com/questions/392132", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/212639/" ]
It seems to me that most discussions about exceptions are missing the point. Most people reiterate "exceptions should be used only for exceptional circumstances" and then argue about their differing opinions of what does or does not qualify as "exceptional circumstances". That is a meaningless semantic game. Instead, I propose that **the use of exceptions should be based on their nature as language features**. Exceptions have three core properties: 1. They can transfer control flow up the call stack without requiring any changes in the code in between. 2. They cannot be ignored silently. If there is no code handling them, your application will crash with a nice stack trace telling you what happened. And code that catches and ignores them is at least a very visible red flag. 3. They syntactically represent alternative results of a method, you can have an arbitrary number of different ones, and catch clauses allow you to handle them selectively. And therefore exceptions should be used when these properties provide a benefit: 1. When you want to give the caller freedom to decide the granularity of error handling - i.e. if sometimes it would make sense for a caller to immediately do something specific, but in other circumstances it could be handled by a generic error handler (e.g. one that returns a HTTP 500 response). 2. When there is a case that callers are likely to ignore and you don't want them to. 3. When your method has a natural return value, but also special cases where the return value doesn't exist, and they might need to be handled in different places. Especially points 2 and 3 are a good match for the "exceptional circumstances" definition, which is probably where exceptions got their name, but these more specific properties allow for a more concrete reasoning why exceptions should or should not be used in a concrete case. And to finally answe the question as stated: No, exceptions are useful in many cases where you do not want the program to crash.
> > In particular, should exceptions be thrown then and only then when the program should crash? > > > Yes, they should only be thrown in those circumstances. Exceptions should be exceptional and should indicate that something has gone seriously wrong... ... but in practice there's a *lot* of code out there already that doesn't follow that principle. As Matthew points out, methods in many frameworks, including Java and .NET, will throw exceptions for the most trivial of reasons, such as a file not existing when trying to open it. The latter sets a precedent and creates a defacto standard that others follow. So you have a choice: use exceptions properly (but risk facing criticism for not following framework standards) or follow the crowd and use them as returning state for control flow. > > Returning error codes and managing them is error-prone, cumbersome and tedious... > > > Sure. But so are exceptions. That's why code like: ``` try { DoSomethingThatMayThrowATrivialException(); } catch {} ``` is so common.
392,132
...I wanted to find the source before writing this Q, sadly I couldn't. My mental model was that exceptions were thought as an alternative to returning error codes from a function, which is the C way to signalize failure. Returning error codes and managing them is error-prone, cumbersome and tedious; which is why a more right-handed mechanism was thought. Problem is, then I started reading and hearing opinions that abusing exceptions is bad. Well of course - if I want to see if an array contains element X then it would probably not be a good idea to assume it does and then throw and almost immediatelly catch an exception if it doesn't. But these opinions were more strict than that. An example of an improper use of exceptions was if, for example, we have a web app and a user requests something that is not there / sends invalid data / any other condition arises that requires displaying an error page to the user. In this case, I was told, it would be a bad practice to throw an exception deep down in the server code, catch it before the request stops being processed and then display an error page. If I understand this mentality correctly (which doesn't have to be the case), the justification was that, since throwing the exception is not intended to crash an app (the situation is recoverable), then the situation is "sensible business-wise"; while exceptions should be reserved for situations "insensible business-wise", which I suppose means "unrecoverable"? But this seems to imply that if the app can continue and is not supposed to crash, I should not throw exceptions; I should only throw if the app cannot continue and must crash. Is this commonly agreed upon? If so, then why? I have feeling this is supposed to apply to almost all programming languages (but, notably, not Python.) I must admit [in my anti-pattern ridden game](https://softwareengineering.stackexchange.com/questions/371977/write-some-code-and-plague-it-with-anti-patterns-or-not-write-it-at-all-any-esc) I do otherwise. For example, when the user sends a JSON with a team, I obviously must validate this data. I seem to be doing precisely what is condemned above: I pass the JSON data to the pieces of code that are responsible for validating it and, if it's valid, constructing an instantiation of the `Team` class. If the data is invalid, an exception is thrown. I thought this would be convenient for me, especially since this seems to mix well with C# facilities I use to construct the team: for example, to instantiate a `Monster` subclass from a monster name present in the JSON, I use `Activator.CreateInstance` which naturally throws if the monster name present in the JSON doesn't match any subclass of `Monster`. But, well, others are more experienced than me, I marked this with a TODO that I should refactor this to `if(isValid(teamJson)) team = new Team(teamJson)` even though I don't understand why and even thought I don't like this idea because `isValid()` would have to share a lot of code with the `Team()` constructor. Yesterday, however, I read something surprising: [Throwing exceptions on assertion failures is, generally, a bad idea, because assertion failure should crash the program while an exception can be caught](https://stackoverflow.com/a/56210376/4385532)\*. This seems to go against the mentality I presented above, which would assert that exceptions should be thrown precisely when the program must crash. Could you clear my confusion? When should exceptions be thrown? In particular, should exceptions be thrown then and only then when the program should crash? --- \*(Yes, this applies to C++ while remarks about my game were about C#; but again - I don't want to discuss language facilities of this or other language, but when exceptions should be thrown in general, which - again - is AFAIK language-agnostic, although with few exceptions like Python.)
2019/05/20
[ "https://softwareengineering.stackexchange.com/questions/392132", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/212639/" ]
I think it helps to understand the reason exceptions exist as a language feature. If you aren't familiar with [this](http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html), it's an old classic that can give you some context around the history of programming languages. Essentially, back in the day, people wrote code that jumped around from here to there based on line numbers or labels. If you've ever read a 'choose your own adventure' book, that's basically how programs were written. Do something and if x goto y. This made programs hard to debug and limited what compilers could do to check for errors optimize the execution. It was then proven that gotos were not required i.e. any program that could be written with gotos could be rewritten without them. However, no one would want to write code like that. There were certain patterns that were useful and considered OK (by language designers): methods, classes, breaks, returns, for loops, while loops, etc. These were refined and augmented to the point that gotos are not even allowed in some languages (e.g. Java) One of the most challenging parts of writing real software is dealing with errors and other alternate path cases. Gotos were often used in a well defined pattern to set aside a section of code for error handling in those alternate path scenarios. The basic constructs of ifs and methods and loops were not adequate to replace this pattern. try-catch-finally filled this void. And this has even been refined to try-with type constructs. The upshot is that in most languages, exceptions are used to handle alternate paths that need special handling (usually errors.) That's it. Nothing more, nothing less. It allows you to keep the 'happy-path' code simple and straight-forward and deal with these alternate paths where it makes the most sense. Without them, you need have mechanisms for passing around not only the data that you need for your main scenario but also the data for all the alternate paths and make sure you are constantly checking for whether you are on the alternate path after every method call. Using them to avoid that kind of mess is not abusing them in any way. Note that there are performance implications of using exceptions. Often these are overblown but if you are in a very deep call stack, throwing an exception can introduce a significant cost. A large number of bad requests could be used to create a DoS attack, for example, if your exceptions are expensive.
> > In particular, should exceptions be thrown then and only then when the program should crash? > > > Yes, they should only be thrown in those circumstances. Exceptions should be exceptional and should indicate that something has gone seriously wrong... ... but in practice there's a *lot* of code out there already that doesn't follow that principle. As Matthew points out, methods in many frameworks, including Java and .NET, will throw exceptions for the most trivial of reasons, such as a file not existing when trying to open it. The latter sets a precedent and creates a defacto standard that others follow. So you have a choice: use exceptions properly (but risk facing criticism for not following framework standards) or follow the crowd and use them as returning state for control flow. > > Returning error codes and managing them is error-prone, cumbersome and tedious... > > > Sure. But so are exceptions. That's why code like: ``` try { DoSomethingThatMayThrowATrivialException(); } catch {} ``` is so common.
392,132
...I wanted to find the source before writing this Q, sadly I couldn't. My mental model was that exceptions were thought as an alternative to returning error codes from a function, which is the C way to signalize failure. Returning error codes and managing them is error-prone, cumbersome and tedious; which is why a more right-handed mechanism was thought. Problem is, then I started reading and hearing opinions that abusing exceptions is bad. Well of course - if I want to see if an array contains element X then it would probably not be a good idea to assume it does and then throw and almost immediatelly catch an exception if it doesn't. But these opinions were more strict than that. An example of an improper use of exceptions was if, for example, we have a web app and a user requests something that is not there / sends invalid data / any other condition arises that requires displaying an error page to the user. In this case, I was told, it would be a bad practice to throw an exception deep down in the server code, catch it before the request stops being processed and then display an error page. If I understand this mentality correctly (which doesn't have to be the case), the justification was that, since throwing the exception is not intended to crash an app (the situation is recoverable), then the situation is "sensible business-wise"; while exceptions should be reserved for situations "insensible business-wise", which I suppose means "unrecoverable"? But this seems to imply that if the app can continue and is not supposed to crash, I should not throw exceptions; I should only throw if the app cannot continue and must crash. Is this commonly agreed upon? If so, then why? I have feeling this is supposed to apply to almost all programming languages (but, notably, not Python.) I must admit [in my anti-pattern ridden game](https://softwareengineering.stackexchange.com/questions/371977/write-some-code-and-plague-it-with-anti-patterns-or-not-write-it-at-all-any-esc) I do otherwise. For example, when the user sends a JSON with a team, I obviously must validate this data. I seem to be doing precisely what is condemned above: I pass the JSON data to the pieces of code that are responsible for validating it and, if it's valid, constructing an instantiation of the `Team` class. If the data is invalid, an exception is thrown. I thought this would be convenient for me, especially since this seems to mix well with C# facilities I use to construct the team: for example, to instantiate a `Monster` subclass from a monster name present in the JSON, I use `Activator.CreateInstance` which naturally throws if the monster name present in the JSON doesn't match any subclass of `Monster`. But, well, others are more experienced than me, I marked this with a TODO that I should refactor this to `if(isValid(teamJson)) team = new Team(teamJson)` even though I don't understand why and even thought I don't like this idea because `isValid()` would have to share a lot of code with the `Team()` constructor. Yesterday, however, I read something surprising: [Throwing exceptions on assertion failures is, generally, a bad idea, because assertion failure should crash the program while an exception can be caught](https://stackoverflow.com/a/56210376/4385532)\*. This seems to go against the mentality I presented above, which would assert that exceptions should be thrown precisely when the program must crash. Could you clear my confusion? When should exceptions be thrown? In particular, should exceptions be thrown then and only then when the program should crash? --- \*(Yes, this applies to C++ while remarks about my game were about C#; but again - I don't want to discuss language facilities of this or other language, but when exceptions should be thrown in general, which - again - is AFAIK language-agnostic, although with few exceptions like Python.)
2019/05/20
[ "https://softwareengineering.stackexchange.com/questions/392132", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/212639/" ]
It seems to me that most discussions about exceptions are missing the point. Most people reiterate "exceptions should be used only for exceptional circumstances" and then argue about their differing opinions of what does or does not qualify as "exceptional circumstances". That is a meaningless semantic game. Instead, I propose that **the use of exceptions should be based on their nature as language features**. Exceptions have three core properties: 1. They can transfer control flow up the call stack without requiring any changes in the code in between. 2. They cannot be ignored silently. If there is no code handling them, your application will crash with a nice stack trace telling you what happened. And code that catches and ignores them is at least a very visible red flag. 3. They syntactically represent alternative results of a method, you can have an arbitrary number of different ones, and catch clauses allow you to handle them selectively. And therefore exceptions should be used when these properties provide a benefit: 1. When you want to give the caller freedom to decide the granularity of error handling - i.e. if sometimes it would make sense for a caller to immediately do something specific, but in other circumstances it could be handled by a generic error handler (e.g. one that returns a HTTP 500 response). 2. When there is a case that callers are likely to ignore and you don't want them to. 3. When your method has a natural return value, but also special cases where the return value doesn't exist, and they might need to be handled in different places. Especially points 2 and 3 are a good match for the "exceptional circumstances" definition, which is probably where exceptions got their name, but these more specific properties allow for a more concrete reasoning why exceptions should or should not be used in a concrete case. And to finally answe the question as stated: No, exceptions are useful in many cases where you do not want the program to crash.
I think it helps to understand the reason exceptions exist as a language feature. If you aren't familiar with [this](http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html), it's an old classic that can give you some context around the history of programming languages. Essentially, back in the day, people wrote code that jumped around from here to there based on line numbers or labels. If you've ever read a 'choose your own adventure' book, that's basically how programs were written. Do something and if x goto y. This made programs hard to debug and limited what compilers could do to check for errors optimize the execution. It was then proven that gotos were not required i.e. any program that could be written with gotos could be rewritten without them. However, no one would want to write code like that. There were certain patterns that were useful and considered OK (by language designers): methods, classes, breaks, returns, for loops, while loops, etc. These were refined and augmented to the point that gotos are not even allowed in some languages (e.g. Java) One of the most challenging parts of writing real software is dealing with errors and other alternate path cases. Gotos were often used in a well defined pattern to set aside a section of code for error handling in those alternate path scenarios. The basic constructs of ifs and methods and loops were not adequate to replace this pattern. try-catch-finally filled this void. And this has even been refined to try-with type constructs. The upshot is that in most languages, exceptions are used to handle alternate paths that need special handling (usually errors.) That's it. Nothing more, nothing less. It allows you to keep the 'happy-path' code simple and straight-forward and deal with these alternate paths where it makes the most sense. Without them, you need have mechanisms for passing around not only the data that you need for your main scenario but also the data for all the alternate paths and make sure you are constantly checking for whether you are on the alternate path after every method call. Using them to avoid that kind of mess is not abusing them in any way. Note that there are performance implications of using exceptions. Often these are overblown but if you are in a very deep call stack, throwing an exception can introduce a significant cost. A large number of bad requests could be used to create a DoS attack, for example, if your exceptions are expensive.
38,420,756
I have a large, globalised web site (not a web app), with 50k+ pages of content which is rendered on a cluster of servers using quite straightforward NodeJS + Nunjucks to generate HTML. For 90% of the site, this is perfectly acceptable, and necessary to achieve SEO visibility, particularly in non-Google search engines which don't index JS well (Yandex, Baidu, etc) The site is a bit clunky as complexity has increased over time, and I'd like to re-architect some of the functional components that are built mostly using progressively enhanced jQuery as they are quite clunky. I've been looking at React for this with the Redux implementation of the Flux pattern. Now my question is simply around the following - nearly 100% of the tutorials assume I'm building some sort of SPA, which I'm not. I just want to build a set of containerised reusable components that I can plug into replace the jQuery components. Oh, they have to be WCAG AA/508 accessible as well Does React play well with being retrofitted into websites and are there any specific considerations around SEO, bootstrapping, accessibility? Examples of implementations or tutorials would be appreciated.
2016/07/17
[ "https://Stackoverflow.com/questions/38420756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/526790/" ]
You open a connection per query and then when you close it, it goes back to the connection pool and the framework will manage the rest So you do not have to worry about keeping connection alive, timeouts etc... MSDN Article <https://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx>
I think what he meant was not to keep a global connection object that is open. But you need to create an `SqlConnection` when you need it, execute all the queries needed at the point (Not a single connection per each query) and then close the connection. So if you have a bunch of queries that needs to be executed, you don't need a single sql connection for each but one is only enough. But if you're executing a query each time the user clicks a button for example, it's better to open a connection on each click, because that way it is easier to manage closing and disposing the connection.
24,738,264
I'm new to ansible (and docker). I would like to test my ansible playbook before using it on any staging/production servers. Since I don't have access to an empty remote server, I thought the easiest way to test would be to use Docker container and then just run my playbook with the Docker container as the host. I have a basic DockerFile that creates a standard ubuntu container. How would I configure the ansible hosts in order to run it against the docker container? Also, I suspect I would need to "run" the docker container to allow ansible to connect to it.
2014/07/14
[ "https://Stackoverflow.com/questions/24738264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433267/" ]
Running the playbook in a docker container may not actually be the best approach unless your stage and production servers are also Docker containers. The Docker ubuntu image is stripped down and will have some differences from a full installation. A better option might be to run the playbook in an Ubuntu VM that matches your staging and production installations. That said, in order to run the ansible playbook within the container you should write a Dockerfile that runs your playbook. Here's a sample Dockerfile: ``` # Start with the ubuntu image FROM ubuntu # Update apt cache RUN apt-get -y update # Install ansible dependencies RUN apt-get install -y python-yaml python-jinja2 git # Clone ansible repo (could also add the ansible PPA and do an apt-get install instead) RUN git clone http://github.com/ansible/ansible.git /tmp/ansible # Set variables for ansible WORKDIR /tmp/ansible ENV PATH /tmp/ansible/bin:/sbin:/usr/sbin:/usr/bin ENV ANSIBLE_LIBRARY /tmp/ansible/library ENV PYTHONPATH /tmp/ansible/lib:$PYTHON_PATH # add playbooks to the image. This might be a git repo instead ADD playbooks/ /etc/ansible/ ADD inventory /etc/ansible/hosts WORKDIR /etc/ansible # Run ansible using the site.yml playbook RUN ansible-playbook /etc/ansible/site.yml -c local ``` The ansible inventory file would look like ``` [local] localhost ``` Then you can just `docker build .` (where `.` is the root of the directory where your playbooks and Dockerfile live), then `docker run` on the resulting image. Michael DeHaan, the CTO of Ansible, has an informative [blog post on this topic](http://www.ansible.com/blog/2014/02/12/installing-and-building-docker-with-ansible).
There's a working example regarding this: <https://github.com/William-Yeh/docker-ansible> First, choose the base image you'd like to begin with from the following list: * `williamyeh/ansible:debian8-onbuild` * `williamyeh/ansible:debian7-onbuild` * `williamyeh/ansible:ubuntu14.04-onbuild` * `williamyeh/ansible:ubuntu12.04-onbuild` * `williamyeh/ansible:centos7-onbuild` * `williamyeh/ansible:centos6-onbuild` Second, put the following `Dockerfile` along with your playbook directory: ``` FROM williamyeh/ansible:ubuntu14.04-onbuild # ==> Specify playbook filename; default = "playbook.yml" #ENV PLAYBOOK playbook.yml # ==> Specify inventory filename; default = "/etc/ansible/hosts" #ENV INVENTORY inventory.ini # ==> Executing Ansible... RUN ansible-playbook-wrapper ``` Third, `docker build .` For more advanced usage, the role in Ansible Galaxy [`williamyeh/nginx`](https://github.com/William-Yeh/ansible-nginx) also demonstrates how to do a simple integration test for a variety of Linux distributions on [Travis CI](https://travis-ci.org/)’s Ubuntu 12.04 worker instances. Disclosure: I am the author of the `docker-ansible` and `wiliamyeh/nginx` projects.
24,738,264
I'm new to ansible (and docker). I would like to test my ansible playbook before using it on any staging/production servers. Since I don't have access to an empty remote server, I thought the easiest way to test would be to use Docker container and then just run my playbook with the Docker container as the host. I have a basic DockerFile that creates a standard ubuntu container. How would I configure the ansible hosts in order to run it against the docker container? Also, I suspect I would need to "run" the docker container to allow ansible to connect to it.
2014/07/14
[ "https://Stackoverflow.com/questions/24738264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433267/" ]
Running the playbook in a docker container may not actually be the best approach unless your stage and production servers are also Docker containers. The Docker ubuntu image is stripped down and will have some differences from a full installation. A better option might be to run the playbook in an Ubuntu VM that matches your staging and production installations. That said, in order to run the ansible playbook within the container you should write a Dockerfile that runs your playbook. Here's a sample Dockerfile: ``` # Start with the ubuntu image FROM ubuntu # Update apt cache RUN apt-get -y update # Install ansible dependencies RUN apt-get install -y python-yaml python-jinja2 git # Clone ansible repo (could also add the ansible PPA and do an apt-get install instead) RUN git clone http://github.com/ansible/ansible.git /tmp/ansible # Set variables for ansible WORKDIR /tmp/ansible ENV PATH /tmp/ansible/bin:/sbin:/usr/sbin:/usr/bin ENV ANSIBLE_LIBRARY /tmp/ansible/library ENV PYTHONPATH /tmp/ansible/lib:$PYTHON_PATH # add playbooks to the image. This might be a git repo instead ADD playbooks/ /etc/ansible/ ADD inventory /etc/ansible/hosts WORKDIR /etc/ansible # Run ansible using the site.yml playbook RUN ansible-playbook /etc/ansible/site.yml -c local ``` The ansible inventory file would look like ``` [local] localhost ``` Then you can just `docker build .` (where `.` is the root of the directory where your playbooks and Dockerfile live), then `docker run` on the resulting image. Michael DeHaan, the CTO of Ansible, has an informative [blog post on this topic](http://www.ansible.com/blog/2014/02/12/installing-and-building-docker-with-ansible).
I've created a role for this vary scenario: <https://github.com/chrismeyersfsu/provision_docker>. Easily start Docker containers and use them in your role or playbook, as inventory, to test. Includes: * Curated Dockerfile for Ubuntu 12.04 & 14.04 as well as CentOS 6 & 7 that put back in the distro-removed init systems * start ssh Also note the examples all have a `.travis.yml` file to form a CI pipeline using Travis CI. **Examples:** * Simple: <https://github.com/chrismeyersfsu/provision_docker/tree/master/test> * Simple: <https://github.com/chrismeyersfsu/role-iptables/tree/master/test> * Advanced: <https://github.com/chrismeyersfsu/role-install_mongod/tree/master/test>
24,738,264
I'm new to ansible (and docker). I would like to test my ansible playbook before using it on any staging/production servers. Since I don't have access to an empty remote server, I thought the easiest way to test would be to use Docker container and then just run my playbook with the Docker container as the host. I have a basic DockerFile that creates a standard ubuntu container. How would I configure the ansible hosts in order to run it against the docker container? Also, I suspect I would need to "run" the docker container to allow ansible to connect to it.
2014/07/14
[ "https://Stackoverflow.com/questions/24738264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433267/" ]
Running the playbook in a docker container may not actually be the best approach unless your stage and production servers are also Docker containers. The Docker ubuntu image is stripped down and will have some differences from a full installation. A better option might be to run the playbook in an Ubuntu VM that matches your staging and production installations. That said, in order to run the ansible playbook within the container you should write a Dockerfile that runs your playbook. Here's a sample Dockerfile: ``` # Start with the ubuntu image FROM ubuntu # Update apt cache RUN apt-get -y update # Install ansible dependencies RUN apt-get install -y python-yaml python-jinja2 git # Clone ansible repo (could also add the ansible PPA and do an apt-get install instead) RUN git clone http://github.com/ansible/ansible.git /tmp/ansible # Set variables for ansible WORKDIR /tmp/ansible ENV PATH /tmp/ansible/bin:/sbin:/usr/sbin:/usr/bin ENV ANSIBLE_LIBRARY /tmp/ansible/library ENV PYTHONPATH /tmp/ansible/lib:$PYTHON_PATH # add playbooks to the image. This might be a git repo instead ADD playbooks/ /etc/ansible/ ADD inventory /etc/ansible/hosts WORKDIR /etc/ansible # Run ansible using the site.yml playbook RUN ansible-playbook /etc/ansible/site.yml -c local ``` The ansible inventory file would look like ``` [local] localhost ``` Then you can just `docker build .` (where `.` is the root of the directory where your playbooks and Dockerfile live), then `docker run` on the resulting image. Michael DeHaan, the CTO of Ansible, has an informative [blog post on this topic](http://www.ansible.com/blog/2014/02/12/installing-and-building-docker-with-ansible).
Apart from provisioning localhost (the machine where you have Ansible installed), you can also tell Ansible to: 1. create a new docker container, 2. provision that container, 3. destroy that container. For this to work you need such a `hosts.yaml` file: ``` all: hosts: mycontainer: ansible_connection: docker localhost: ansible_connection: local ``` such a `playbook.yaml` file: ``` --- - name: Create a container to be provisioned later hosts: localhost tasks: - name: create docker container docker_container: name: mycontainer image: python:2.7.16-slim-stretch command: ["sleep", "1d"] - name: Provision the container created above hosts: mycontainer roles: - simple ``` and another playbook file: `destroy.yaml` used to destroy the container: ``` --- - name: Destroy a container hosts: localhost tasks: - name: destroy docker container docker_container: name: mycontainer state: absent ``` Create also a simple role: `roles/simple/taksks/main.yaml` ``` --- - name: Create a file copy: content: "hi!!" dest: /tmp/hello force: yes mode: 0555 ``` And now to create a container and provision it, run: ``` ansible-playbook -i ./hosts.yaml ./playbook.yml ``` Verify that container was provisioned (the file was created): ``` docker exec mycontainer cat /tmp/hello ``` To destroy the container run: ``` ansible-playbook -i ./hosts.yaml ./destroy.yml ``` There are of course disadvantages: * the container must have python installed * some Ansible modules might not work, because additional python packages have to be installed. E.g. if you wanted to deploy docker containers (in the docker container), you have to install docker python SDK (`pip3 install docker`) I was inspired by this blog post: <https://medium.com/@andreilhicas/provision-docker-containers-with-ansible-30cc5ee6d950>
24,738,264
I'm new to ansible (and docker). I would like to test my ansible playbook before using it on any staging/production servers. Since I don't have access to an empty remote server, I thought the easiest way to test would be to use Docker container and then just run my playbook with the Docker container as the host. I have a basic DockerFile that creates a standard ubuntu container. How would I configure the ansible hosts in order to run it against the docker container? Also, I suspect I would need to "run" the docker container to allow ansible to connect to it.
2014/07/14
[ "https://Stackoverflow.com/questions/24738264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433267/" ]
There's a working example regarding this: <https://github.com/William-Yeh/docker-ansible> First, choose the base image you'd like to begin with from the following list: * `williamyeh/ansible:debian8-onbuild` * `williamyeh/ansible:debian7-onbuild` * `williamyeh/ansible:ubuntu14.04-onbuild` * `williamyeh/ansible:ubuntu12.04-onbuild` * `williamyeh/ansible:centos7-onbuild` * `williamyeh/ansible:centos6-onbuild` Second, put the following `Dockerfile` along with your playbook directory: ``` FROM williamyeh/ansible:ubuntu14.04-onbuild # ==> Specify playbook filename; default = "playbook.yml" #ENV PLAYBOOK playbook.yml # ==> Specify inventory filename; default = "/etc/ansible/hosts" #ENV INVENTORY inventory.ini # ==> Executing Ansible... RUN ansible-playbook-wrapper ``` Third, `docker build .` For more advanced usage, the role in Ansible Galaxy [`williamyeh/nginx`](https://github.com/William-Yeh/ansible-nginx) also demonstrates how to do a simple integration test for a variety of Linux distributions on [Travis CI](https://travis-ci.org/)’s Ubuntu 12.04 worker instances. Disclosure: I am the author of the `docker-ansible` and `wiliamyeh/nginx` projects.
I've created a role for this vary scenario: <https://github.com/chrismeyersfsu/provision_docker>. Easily start Docker containers and use them in your role or playbook, as inventory, to test. Includes: * Curated Dockerfile for Ubuntu 12.04 & 14.04 as well as CentOS 6 & 7 that put back in the distro-removed init systems * start ssh Also note the examples all have a `.travis.yml` file to form a CI pipeline using Travis CI. **Examples:** * Simple: <https://github.com/chrismeyersfsu/provision_docker/tree/master/test> * Simple: <https://github.com/chrismeyersfsu/role-iptables/tree/master/test> * Advanced: <https://github.com/chrismeyersfsu/role-install_mongod/tree/master/test>
24,738,264
I'm new to ansible (and docker). I would like to test my ansible playbook before using it on any staging/production servers. Since I don't have access to an empty remote server, I thought the easiest way to test would be to use Docker container and then just run my playbook with the Docker container as the host. I have a basic DockerFile that creates a standard ubuntu container. How would I configure the ansible hosts in order to run it against the docker container? Also, I suspect I would need to "run" the docker container to allow ansible to connect to it.
2014/07/14
[ "https://Stackoverflow.com/questions/24738264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433267/" ]
There's a working example regarding this: <https://github.com/William-Yeh/docker-ansible> First, choose the base image you'd like to begin with from the following list: * `williamyeh/ansible:debian8-onbuild` * `williamyeh/ansible:debian7-onbuild` * `williamyeh/ansible:ubuntu14.04-onbuild` * `williamyeh/ansible:ubuntu12.04-onbuild` * `williamyeh/ansible:centos7-onbuild` * `williamyeh/ansible:centos6-onbuild` Second, put the following `Dockerfile` along with your playbook directory: ``` FROM williamyeh/ansible:ubuntu14.04-onbuild # ==> Specify playbook filename; default = "playbook.yml" #ENV PLAYBOOK playbook.yml # ==> Specify inventory filename; default = "/etc/ansible/hosts" #ENV INVENTORY inventory.ini # ==> Executing Ansible... RUN ansible-playbook-wrapper ``` Third, `docker build .` For more advanced usage, the role in Ansible Galaxy [`williamyeh/nginx`](https://github.com/William-Yeh/ansible-nginx) also demonstrates how to do a simple integration test for a variety of Linux distributions on [Travis CI](https://travis-ci.org/)’s Ubuntu 12.04 worker instances. Disclosure: I am the author of the `docker-ansible` and `wiliamyeh/nginx` projects.
Apart from provisioning localhost (the machine where you have Ansible installed), you can also tell Ansible to: 1. create a new docker container, 2. provision that container, 3. destroy that container. For this to work you need such a `hosts.yaml` file: ``` all: hosts: mycontainer: ansible_connection: docker localhost: ansible_connection: local ``` such a `playbook.yaml` file: ``` --- - name: Create a container to be provisioned later hosts: localhost tasks: - name: create docker container docker_container: name: mycontainer image: python:2.7.16-slim-stretch command: ["sleep", "1d"] - name: Provision the container created above hosts: mycontainer roles: - simple ``` and another playbook file: `destroy.yaml` used to destroy the container: ``` --- - name: Destroy a container hosts: localhost tasks: - name: destroy docker container docker_container: name: mycontainer state: absent ``` Create also a simple role: `roles/simple/taksks/main.yaml` ``` --- - name: Create a file copy: content: "hi!!" dest: /tmp/hello force: yes mode: 0555 ``` And now to create a container and provision it, run: ``` ansible-playbook -i ./hosts.yaml ./playbook.yml ``` Verify that container was provisioned (the file was created): ``` docker exec mycontainer cat /tmp/hello ``` To destroy the container run: ``` ansible-playbook -i ./hosts.yaml ./destroy.yml ``` There are of course disadvantages: * the container must have python installed * some Ansible modules might not work, because additional python packages have to be installed. E.g. if you wanted to deploy docker containers (in the docker container), you have to install docker python SDK (`pip3 install docker`) I was inspired by this blog post: <https://medium.com/@andreilhicas/provision-docker-containers-with-ansible-30cc5ee6d950>
66,778,728
**I want to get data from user in `<textarea>` and show it on the DOM page with edit button and with breaklines if user click on edit user old data send to new `<textarea>` with breaklines** Adding an item. ``` <form name="add" method="POST" action="{% url 'notepad:addnote' %}">{% csrf_token %} <div class="modal-body"> Title : <input name="title" class="w-50" type="text" required><br> Note :<br> <textarea name="text" id="" cols="60" rows="10" required></textarea> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> ``` Showing an items. ``` <div id="content"> {% for items in allitems %} <ul class="list-group d-inline-block my-4 "> <li class="list-group-item list-group-item-info list-group-item-action {{items.id}}" aria-current="true">{{items.title}}<button onclick="editContent({{items.id}})" data-bs-toggle="modal" data-bs-target="#update" type="button" class="save mx-2"><i class="fa fa-pencil-square-o"></i></button></li> <li class="list-group-item list-group-item-action {{items.id}}">{{items.text}}</li> </ul> {% endfor %} </div> ``` But if i show an items it removes break lines. So I'll try pre tag to show that content with breaklines. ``` <div id="content"> {% for items in allitems %} <ul class="list-group d-inline-block my-4 "> <li class="list-group-item list-group-item-info list-group-item-action {{items.id}}" aria-current="true">{{items.title}}<button onclick="editContent({{items.id}})" data-bs-toggle="modal" data-bs-target="#update" type="button" class="save mx-2"><i class="fa fa-pencil-square-o"></i></button></li> <pre><li class="list-group-item list-group-item-action {{items.id}}">{{items.text}}</li></pre> </ul> {% endfor %} </div> ``` It shows break lines, but i again want to edit and send this content to my input and textarea to edit that's content , So i do that with JavaScript. And my place that i want to get data is ``` <div class="modal-body"> Title : <input name="title" class="w-50" type="text" id="update_title" required value=""><br> Note :<br> <textarea name="text" cols="60" rows="10" id="update_text" required></textarea> ``` My JavaScript code is ``` function editContent(cls){ content = document.getElementsByClassName(`${cls}`); oldtitle = content[0].innerText; editeTitlePlace = document.getElementById('update_title'); editeTitlePlace.value = oldtitle editTextPlace = document.getElementById('update_text'); oldtext = content[1].innerText; newstr = "" for(i=0;i < oldtext.length ;){ char = oldtext.charAt(i); if (char == "\n"){ newstr += " "; } else{ newstr += char; } i++; } editeTextPlace.innerText = newstr } ``` **It shows my content ,and replace "\n" with " " but if i do to add "\n" or "\n\t" it again shows me spaces not breaks a line in textarea. But i want that it shows me breakline in textarea.**
2021/03/24
[ "https://Stackoverflow.com/questions/66778728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15468289/" ]
Add `white-space: pre-wrap` styling to the place you are showing the items. This is preserve line breaks if they are found in `textarea`. Your code should look something like this. ``` <div id="content" style="white-space: pre-wrap;"> {% for items in allitems %} <ul class="list-group d-inline-block my-4 "> <li class="list-group-item list-group-item-info list-group-item-action {{items.id}}" aria-current="true">{{items.title}}<button onclick="editContent({{items.id}})" data-bs-toggle="modal" data-bs-target="#update" type="button" class="save mx-2"><i class="fa fa-pencil-square-o"></i></button></li> <li class="list-group-item list-group-item-action {{items.id}}">{{items.text}}</li> </ul> {% endfor %} </div> ``` **NOTE:** You can add the mentioned `css` tag where needed.
In my JavaScript While i using for loop i choose `\n` to replace with `<br>` in forloop and `newstr` add as `<textarea>` innerHTML and my `<br>` will change into break line in `<textarea>` ``` function editContent(cls){ content = document.getElementsByClassName(`${cls}`); oldtitle = content[0].innerText; editeTitlePlace = document.getElementById('update_title'); editeTitlePlace.value = oldtitle editTextPlace = document.getElementById('update_text'); oldtext = content[1].innerText; newstr = "" for(i=0;i < oldtext.length ;){ char = oldtext.charAt(i); if (char == "\n"){ newstr += " "; } else{ newstr += char; } i++; } editeTextPlace.innerHTML = newstr } ```
48,327,164
At the moment we have one huge API which is used by our backoffice, our frontend, and also our public API. This causes me a lot of headaches because when building new endpoints I find a lot of application specific logic in the code which I don't necessarily want to include in my endpoint. For example, the code to create a user might contain code to send a welcome email, but because that's not needed for the backoffice endpoint I will then need to add a new endpoint without that logic. I was thinking about a large refactor to break our code base in to a number of smaller highly specific service APIs, then building a set of small application APIs on top of those. So for example, an application endpoint to create a new user might do something like this after the refactor: ``` customerService.createCustomer(); paymentService.chargeCard(); emailService.sendWelcomeEmail(); ``` The application and service APIs will be entirely separate code bases (perhaps a separate code base per service), they may also be built using different languages. They will only interact through REST API calls. They will be on the same local network, so latency shouldn't be a huge issue. Is this a bad idea? I've never seen/worked on a codebase which has separated the two before, so perhaps there is a better architecture to achieve the flexibility and maintainability I'm looking for? Advise, links, or comments would all be appreciated.
2018/01/18
[ "https://Stackoverflow.com/questions/48327164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7862512/" ]
Your idea of making multiple, well-defined services is sound and really it is the best way to approach this. Going with purely micro-services approach however trendy it might seem, proves to be an overkill most often than not. This is why I'd just redesign the existing API/services properly and follow solid and sound SOA design principles below. Good Resources could be found on both [serviceorientation.com](http://serviceorientation.com/) and [soapatterns.org](http://soapatterns.org/) I've always used them as reference in my career. Consider what types of services you need ---------------------------------------- [![Service types and Layers](https://i.stack.imgur.com/F9Scf.png)](https://i.stack.imgur.com/F9Scf.png) (image from serviceorientation.com) * **Entity** services are generally your Client, Payment services - e.g. services centered around an entity in your domain. They should be business-agnostic, and be able to be reused in all scenarios. They could be called sometimes by clients directly if sufficient for their needs. They could be called by Task services. * **Utility** services contain logic you're likely to reuse in other services, but are generally not called by the clients directly. Rather, they'd be called by Task and Entity services. An example might be a Transliteration service. * **Task** services combine and reuse Entity and Utility services into meaningful tasks. Most often they are not that agnostic and they do implement some specific business logic. They have meaningful business operations and they are what clients mostly call. Principles to follow when redesigning ------------------------------------- I strongly recommend going [over this cheat sheet](http://serviceorientation.com/static/pdf/SOA_Principles_Poster.pdf) and making sure everything there is covered when you do your redesign. It's great help. In general, you should make sure that: 1. Each service has a **common context and follows the separation of concerns principle**. E.g. `Clients` service is only for clients related operations, etc. 2. Each of the Entity and Utility services is **business-agnostic and basic enough**. So it can be reused in multiple scenarios and context without being changed. Contract must be simple - CRUD and only common operations that make sense in most usage scenarios. 3. **Services follow a common data model** - make sure all the data structures you use are used uniformly in all services in order to prevent need for integration efforts in the future and promote combination of services for clients to exploit. If you need to receive a customer that another service returns, this should be happening without the need for transformation OK, but where to put the non-agnostic logic? -------------------------------------------- Now, you have multiple options for abstracting business logic whenever you have a need for complex business functionality. It depends on your scenario what you're going to chose: * Leave logic to all clients. Let them combine your simplified services * If there is business logic that is commonly implemented in multiple of your applications and has the potential to be reused heavily you can implement a **composite service** that reuses multiple existing underlying services and exposing the logic. Service Composability. Concerns on multiple API calls communication overhead. ----------------------------------------------------------------------------- Well, this is an age-old question - should you make multiple API calls when they will probably create some communication overhead? The answer is - it depends on how complex your scenario is, how much reuse you expect and how flexible you want to be. Also is speed critical? To what extent? In Service Oriented Architecture though, this is a very common approach - to reuse your existing services and combine them in new configurations as needed. Yes, it does add some overhead, but I've seen implementations in very complex environments, for example Telecoms, where thanks to the use of ESB solutions, message queues, etc the overhead is negligible compared to the benefits. Here is a common architecture approach (image from serviceorientation.com): [![Composing Web Services to Solve a Bigger Problem](https://i.stack.imgur.com/b4jCn.jpg)](https://i.stack.imgur.com/b4jCn.jpg) The mandatory legacy refactoring heads-up ----------------------------------------- More often than not, changing the established contract for multiple existing client systems is a messy business and could very well lead to lots of refactoring and need for looking for needle-in-a-stack functionality that's somewhere deep in the (possibly) legacy code. Business logic might be dispersed everywhere. So make sure you're ready and have the controls, time and will to lead this battle. Hope this helps
> > Is this a bad idea? > > > No, but this is a big overall question to be able to provide very specific advice. I'd like to separate this into 3 areas: * Approach * Design * Technology Working backwards, the **Technology** is the final and most-specific part, and totally depends on what your current environment is (platforms, skills), and (hopefully) will be reasonable self-evident to you once the other things are in progress. The **Design** that you outlined above seems like a good end-state - having multiple, specific, focused APIs, each with their own responsibility. Again, the details of the design will depend on the skills of you and your organization, and the existing platforms that you have. E.g. if you are already using TIBCO (for example) and have a lot invested (licenses, platforms, tools, people) then leveraging some of their published patterns/designs/templates makes sense; but (probably) not if you don't already have TIBCO exposure. In the abstract, the REST API services seems like a good starting point - there are a lot of tools and platforms at all levels of the system for security, deployment, monitoring, scalability, etc. If you are NGINX users, they have a lot of (platform-independent) thoughts on how to do this also [NGINX blog](https://www.nginx.com/blog/refactoring-a-monolith-into-microservices/), including some smart thinking on scalability and performance. If you are more adventurous, and have an smart, eager team, a look at Event-driven architecture - see [this](https://thenewstack.io/event-driven-architecture-wave-future/) **Approach (or Process)** is the **key thing** here. Ultimately, this is a refactoring, though your description of "a large refactor" does scare me a little - put that way, it sounds like you are talking about a big-bang change and calling it refactoring. Perhaps it is just language, but what's in my mind would be "an evolution of the 'one huge API' into multiple, specific, focused APIs (by refactoring the architecture)". One place to start is [Martin Fowler](https://martinfowler.com/books/refactoring.html), while this book is about refactoring software, the principles and approach are the same, just at a higher-level. Indeed, he talks about just this [here](https://www.martinfowler.com/bliki/StranglerApplication.html) IBM talk about [refactoring to microservices](https://www.ibm.com/developerworks/cloud/library/cl-refactor-microservices-bluemix-trs-1/index.html) and make it sound easy to do in one step, but it never is (outside the lab). You have an existing API, serving multiple internal and external clients. I will suggest that you'll want to keep this interface solid for these clients - separate your refactoring of the implementation from the additional concerns of liaising with and coordinating external systems/groups. My high-level starting approach would be: * identify a small (3-7) number of related methods on the API + ideally if a significant, limited-scope change is needed anyway with these methods, that is good - business value with the code change * design/specify a new stand-alone API specifically for these methods + at first, clone the existing model/naming/style * code a new service just for these + with proper automated CI/CD testing and deployment practices + with associated monitoring * modify the existing API to have calls to these methods re-direct to call the new service + perhaps have a run-time switch to change between the old implementation and the new implementation * remove the old implementation from codebase * capture issues, assumptions and problems along the way + the first pass will involve a lot of learning about what works and doesn't. * then repeat the process over & over, incorporating improvements each time. At some point in the future, when appropriate due to other business-driven needs, the API published to the back-end, front-end and/or public clients can change, but that is a whole different project. As you can see, if the API is huge (1,000 methods => 140 releases) this is a many-months process, and having a reasonably frequent release schedule is important. And there may be no value improving code that works reliably and never changes, so a (potentially) large portion of the existing API may remain, just wrapped by a new API. Other considerations: * public API? Maybe a new version (significant changes) will be needed sooner than the internal APIs + focus on the methods/services used by it * what parts/services change the most (have the most enhancement requests *approved*) + these are the bits most likely to change, and could benefit most from a better process/architecture * what are future plans for change and where would the API be impacted + e.g. change to user management, change to payment processors, change to fulfilment systems + e.g. new business plans (new products/services) + consider affected methods in the API * Also see: + [Using Microservices for Legacy System Modernization](https://www.altexsoft.com/blog/engineering/using-microservices-for-legacy-system-modernization/) + [Migrating From a Monolith to APIs and Microservices](http://Migrating%20From%20a%20Monolith%20to%20APIs%20and%20Microservices) + [Break the Monolith! Loosely Coupled Architecture Brings DevOps Success](https://dzone.com/articles/break-the-monolith-loosely-coupled-architecture-br) + From the CEO’s Desk: Application Modernization – Assess, Strategize, Modernize! 9 + [Microservices Architecture As A Large-Scale Refactoring Tool 10 Probably the biggest **4 pieces of advice** that I can give is: * think refactoring: **small** changes that don't affect function * think agile: **small** increments that are valuable, testable, achievable * think continuous: have a vision for where you will (eventually) get to, then work the process continuously + script & automate the processes from code, documentation, testing, deployment, monitoring... + improving it every time! * you have an application/API that works - keep it working! + That is always the first priority (you just need to work to carve-out time/budget for maintenance)
48,327,164
At the moment we have one huge API which is used by our backoffice, our frontend, and also our public API. This causes me a lot of headaches because when building new endpoints I find a lot of application specific logic in the code which I don't necessarily want to include in my endpoint. For example, the code to create a user might contain code to send a welcome email, but because that's not needed for the backoffice endpoint I will then need to add a new endpoint without that logic. I was thinking about a large refactor to break our code base in to a number of smaller highly specific service APIs, then building a set of small application APIs on top of those. So for example, an application endpoint to create a new user might do something like this after the refactor: ``` customerService.createCustomer(); paymentService.chargeCard(); emailService.sendWelcomeEmail(); ``` The application and service APIs will be entirely separate code bases (perhaps a separate code base per service), they may also be built using different languages. They will only interact through REST API calls. They will be on the same local network, so latency shouldn't be a huge issue. Is this a bad idea? I've never seen/worked on a codebase which has separated the two before, so perhaps there is a better architecture to achieve the flexibility and maintainability I'm looking for? Advise, links, or comments would all be appreciated.
2018/01/18
[ "https://Stackoverflow.com/questions/48327164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7862512/" ]
Your idea of making multiple, well-defined services is sound and really it is the best way to approach this. Going with purely micro-services approach however trendy it might seem, proves to be an overkill most often than not. This is why I'd just redesign the existing API/services properly and follow solid and sound SOA design principles below. Good Resources could be found on both [serviceorientation.com](http://serviceorientation.com/) and [soapatterns.org](http://soapatterns.org/) I've always used them as reference in my career. Consider what types of services you need ---------------------------------------- [![Service types and Layers](https://i.stack.imgur.com/F9Scf.png)](https://i.stack.imgur.com/F9Scf.png) (image from serviceorientation.com) * **Entity** services are generally your Client, Payment services - e.g. services centered around an entity in your domain. They should be business-agnostic, and be able to be reused in all scenarios. They could be called sometimes by clients directly if sufficient for their needs. They could be called by Task services. * **Utility** services contain logic you're likely to reuse in other services, but are generally not called by the clients directly. Rather, they'd be called by Task and Entity services. An example might be a Transliteration service. * **Task** services combine and reuse Entity and Utility services into meaningful tasks. Most often they are not that agnostic and they do implement some specific business logic. They have meaningful business operations and they are what clients mostly call. Principles to follow when redesigning ------------------------------------- I strongly recommend going [over this cheat sheet](http://serviceorientation.com/static/pdf/SOA_Principles_Poster.pdf) and making sure everything there is covered when you do your redesign. It's great help. In general, you should make sure that: 1. Each service has a **common context and follows the separation of concerns principle**. E.g. `Clients` service is only for clients related operations, etc. 2. Each of the Entity and Utility services is **business-agnostic and basic enough**. So it can be reused in multiple scenarios and context without being changed. Contract must be simple - CRUD and only common operations that make sense in most usage scenarios. 3. **Services follow a common data model** - make sure all the data structures you use are used uniformly in all services in order to prevent need for integration efforts in the future and promote combination of services for clients to exploit. If you need to receive a customer that another service returns, this should be happening without the need for transformation OK, but where to put the non-agnostic logic? -------------------------------------------- Now, you have multiple options for abstracting business logic whenever you have a need for complex business functionality. It depends on your scenario what you're going to chose: * Leave logic to all clients. Let them combine your simplified services * If there is business logic that is commonly implemented in multiple of your applications and has the potential to be reused heavily you can implement a **composite service** that reuses multiple existing underlying services and exposing the logic. Service Composability. Concerns on multiple API calls communication overhead. ----------------------------------------------------------------------------- Well, this is an age-old question - should you make multiple API calls when they will probably create some communication overhead? The answer is - it depends on how complex your scenario is, how much reuse you expect and how flexible you want to be. Also is speed critical? To what extent? In Service Oriented Architecture though, this is a very common approach - to reuse your existing services and combine them in new configurations as needed. Yes, it does add some overhead, but I've seen implementations in very complex environments, for example Telecoms, where thanks to the use of ESB solutions, message queues, etc the overhead is negligible compared to the benefits. Here is a common architecture approach (image from serviceorientation.com): [![Composing Web Services to Solve a Bigger Problem](https://i.stack.imgur.com/b4jCn.jpg)](https://i.stack.imgur.com/b4jCn.jpg) The mandatory legacy refactoring heads-up ----------------------------------------- More often than not, changing the established contract for multiple existing client systems is a messy business and could very well lead to lots of refactoring and need for looking for needle-in-a-stack functionality that's somewhere deep in the (possibly) legacy code. Business logic might be dispersed everywhere. So make sure you're ready and have the controls, time and will to lead this battle. Hope this helps
Not a bad idea at all. Also what are your looking is microservices arch. and with that the question comes is how you break your system into well defined services. We use Domain Driven Design Arch. to break our system into microservices and [lagom](https://www.lagomframework.com/) framework , which allows every service to be in diff. code base and event driven arch. between microservices. Now lets look at your problem at low level: you said a service contains code like creating a user and sending a email and one with just creating a user and there might be other code as well. First we need to understand how many type of code you are writing: 1. Domain Object Logic (eg: User Object) -- what parameters are valid and all -- this should be independent of service endpoint and should be encapsulated in one Class like user class and we say it an Aggregate in Domain Driven Design terms 2. Business Reactions -- like on user creation send a email -- using event driven arch. these type of logics are separated into process managers or sagas which could most cases work conditionally like a for user created externally send a mail and for user created internally send a email , by having extra data in the event Also the current way you are doing it , how are you handling transaction across services???
24,256,713
I'm trying to use the Django-simple-captcha <http://django-simple-captcha.readthedocs.org/en/latest/usage.html> in my django app. But the captcha image is not showing up in the templates. I get the following error when I viewed the source code in my browser. I've followed the documenation carefully and have syncdb everything. ``` Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response 114. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Python/2.7/site-packages/captcha/views.py" in captcha_image 46. font = ImageFont.truetype(settings.CAPTCHA_FONT_PATH, settings.CAPTCHA_FONT_SIZE * scale) File "/Library/Python/2.7/site-packages/PIL/ImageFont.py" in truetype 228. return FreeTypeFont(font, size, index, encoding) File "/Library/Python/2.7/site-packages/PIL/ImageFont.py" in __init__ 131. self.font = core.getfont(font, size, index, encoding) File "/Library/Python/2.7/site-packages/PIL/ImageFont.py" in __getattr__ 42. raise ImportError("The _imagingft C module is not installed") Exception Type: ImportError at /captcha/image/f02c7bf84cd31c4caf8d6b2f8931a01689902c83/ Exception Value: The _imagingft C module is not installed ``` I know that this question has been asked several times before and I've read several stackoverflow answers but I'm still very confused about the course of action. I've Pillow installed on my OSX Mavericks.
2014/06/17
[ "https://Stackoverflow.com/questions/24256713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3473635/" ]
I solved the above error by installing freetype and freetype2 devel packages before running `pip install Pillow`. Worked on SuSE Linux.
Works for me in ubuntu 14.04: ``` pip uninstall pil ``` or(depends what you are using) ``` pip uninstall pillow ``` then ``` sudo apt-get update apt-get install libfreetype6-dev libxft-dev libjpeg62 libjpeg-devel ``` in the output, make sure the installation was complete And finnaly ``` pip install pil ``` or ``` pip install pillow ```
36,771,881
I am trying to calculate how many minutes a worker works from the input starting and ending time(e.g. 10:30 am to 3:30pm). Could u guys help how to calculate them? Could u check my code and correct them? I am very new in Javascript. ``` function myFunction(){ var sTime=document.getElementById("startTime").value; var eTime=document.getElementById("endTime").value; var diff = sTime-eTime; var result= diff.getMinutes(); document.getElementById("demo").innerHTML=result`; ``` <https://jsbin.com/bolapox/edit?html,output>
2016/04/21
[ "https://Stackoverflow.com/questions/36771881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6235973/" ]
For the memoization you can use [`functools.lru_cache()`](https://docs.python.org/3/library/functools.html#functools.lru_cache). **Edit:** The problem with this for your use case is that it does not consider two function calls to be the same if the way they specify their arguments differs. To address this we can write our own decorator which sits on top of `lru_cache()` and transforms arguments into a single canonical form: ``` from functools import lru_cache, wraps import inspect def canonicalize_args(f): """Wrapper for functools.lru_cache() to canonicalize default and keyword arguments so cache hits are maximized.""" @wraps(f) def wrapper(*args, **kwargs): sig = inspect.getfullargspec(f.__wrapped__) # build newargs by filling in defaults, args, kwargs newargs = [None] * len(sig.args) newargs[-len(sig.defaults):] = sig.defaults newargs[:len(args)] = args for name, value in kwargs.items(): newargs[sig.args.index(name)] = value return f(*newargs) return wrapper @canonicalize_args @lru_cache() def add(a, b, negative=False): print("Computing") return (a + b) * (1 if negative is False else -1) ``` Now `add()` is called only once for the entire set of calls in the question. Every call is made with all three arguments specified positionally.
You can use [`inspect.getcallargs()`](https://docs.python.org/3/library/inspect.html#inspect.getcallargs) to get a canonical argument list for a function. Wrapping it in a decorator shouldn't be too hard. ``` In [1]: def add(a, b, negative=False): ...: print("Computing") ...: return (a + b) * (1 if negative is False else -1) ...: ...: In [2]: inspect.getcallargs(add, 1, 2) Out[2]: {'a': 1, 'b': 2, 'negative': False} In [3]: inspect.getcallargs(add, 1, 2, True) Out[3]: {'a': 1, 'b': 2, 'negative': True} In [4]: inspect.getcallargs(add, 1, 2, negative=False) Out[4]: {'a': 1, 'b': 2, 'negative': False} In [5]: inspect.getcallargs(add, 1, b=2, negative=False) Out[5]: {'a': 1, 'b': 2, 'negative': False} In [6]: inspect.getcallargs(add, 1, b=2) Out[6]: {'a': 1, 'b': 2, 'negative': False} ```
38,915,476
I am running my node application on AWS EC2 server. For continuous integration I installed Jenkins, on EC2, jenkins polls a code commit continuously and when a commit occurs executes some commands written in a script. The last command is **pm2 start server.js** Everything works fine and the build is shown successful but later when I access the URL the site doesn't show. I have a nginx server in front of node server, it gives **502 Bad Gateway** On checking I realised the node application is not running, so I cehcked pm2 logs and found this happening - **2016-08-12 07:53:28: [[[[ PM2/God daemon launched ]]]]** **2016-08-12 07:53:28: BUS system [READY] on port /var/lib/jenkins/.pm2/pub.sock** **2016-08-12 07:53:28: RPC interface [READY] on port /var/lib/jenkins/.pm2/rpc.sock** **2016-08-12 07:53:28: Starting execution sequence in -fork mode- for app name:server id:0** **2016-08-12 07:53:28: App name:server id:0 online** **2016-08-12 07:53:28: pm2 has been killed by signal, dumping process list before exit...** **2016-08-12 07:53:28: Deleting process 0** **2016-08-12 07:53:28: Stopping app:server id:0** **2016-08-12 07:53:28: App [server] with id [0] and pid [25822], exited with code [0] via signal [SIGTERM]** **2016-08-12 07:53:28: Proc is not defined anymore or is being killed** **2016-08-12 07:53:28: [PM2] Exited peacefully** pm2 is getting killed as soon as starting, don't know why, tried reinstalling pm2 from npm didn't work. Ubuntu 14.04 LTS Node v4.4.7 LTS npm v2.15.8 pm2 v1.1.3 Work is halted, need help immediately, please.
2016/08/12
[ "https://Stackoverflow.com/questions/38915476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2737210/" ]
The answer is in the comments given by Dusan Bajic, if anyone is doing continous integration with jenkins on EC2 using a node application and similar thing happens with pm2 just add this line in script before starting pm2. **export BUILD\_ID=dontKillMePlease** and instead of **pm2 start server.js** use **pm2 restart server.js** server.js being your application or else build will fail if in jenkins if you commit and it runs script again cause pm2 is already running server.js and won't stop.
From [ProcessTreeKiller](https://wiki.jenkins-ci.org/display/JENKINS/ProcessTreeKiller) > > To reliably kill processes spawned by a job during a build, Jenkins > contains a bit of native code to list up such processes and kill them > > > ... > > **How it works** > > > The ProcessTreeKiller takes advantage of the fact that by > default a new process gets a copy of the environment variables of its > spawning/creating process. > > > It sets a specific environment variable in the process executing the > build job. Later, when the user requests to stop the build job's > process it gets a list of all processes running on the computer and > their environment variables, and looks for the environment variable > that it initially set for the build job's process. > > > Every job with that environment variable in its environment is then > terminated. > > > **If your build wants to leave a daemon running behind...** > > > A convenient way to achieve that is to change the environment variable > BUILD\_ID which Jenkins's ProcessTreeKiller is looking for. This will > cause Jenkins to assume that your daemon is not spawned by the Jenkins > build. For example: > > > `BUILD_ID=dontKillMe /usr/apache/bin/httpd` > > >
42,670,704
I want to simply display usernames and age on the webpage using Express Node.js and Mongoose/ The view should get updated on the left while the form is at the right. Refer [this](https://i.stack.imgur.com/Kifk0.jpg) image. Below is my **users.js** (/users route) followed by **html** of the form. Bodyparser has been included in **app.js** of this application. On clicking submit, 404 not found is thrown. [Refer this error image](https://i.stack.imgur.com/4L9rq.jpg) ```js var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { res.render('userview'); }); router.post('#', function(req, res, next) { //User is the model created in app.js of this project var newUser = userModel({ name:req.body.name, age: req.body.age }); console.log(newUser); // save the user newUser.save(function(err) { if (err) throw err; console.log('User created!'); }); }); module.exports = router; ``` ```html <form method="post"> Name: <input type="text" name="name"><br><br> Age: <input type="number" name="age"><br><br> <input type="submit" value="Submit"> </form> ``` Here is my **app.js** ```js var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/index'); var users = require('./routes/users'); var applist = require('./routes/applist'); var mongoose=require('mongoose'); var app = express(); //set database connection mongoose.connect('mongodb://localhost:27017/users'); mongoose.connection.on('error',function(){ console.log('MongoDB Connection Error. Please make sure that MongoDB is running'); process.exit(1); }); mongoose.connection.once('open',function(callback){ console.log('Connected to Database'); }); var userSchema = new mongoose.Schema({ name:{type:String,uppercase:true}, age:Number },{collection:'userlist'}); //make model var userModel = mongoose.model('userModel',userSchema); app.get('/users', function(req, res, next) { userModel.find({},function(err,userModel){ res.render('userview',{userlist:userModel}); }) }); module.exports = userModel; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', index); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app; ``` **userModel** is present in app.js
2017/03/08
[ "https://Stackoverflow.com/questions/42670704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7556634/" ]
On the view change > > name = "fullname" to name="name" > > > **userview** ``` <form method="post"> Name <input type="text" name="name"><br><br> Age<input type="number" name="age"><br><br> <input type="submit" value="Submit"> </form> ```
First of all, to use `req.body` you need to use `body-parser` or `busboy`, `connect-busboy`, `multiparty`, `connect-multiparty`, `formidable`, `multer` etc. - see: * <https://github.com/expressjs/body-parser> Also, what is this route supposed to be: ``` router.post('#', function(req, res, next) { ``` This character is not valid in the URL path amd needs to be URL-encoded on the client side to work. Are you sure that this is the route your need? If you are thinking about the fragment part of the URL (as in `http://host/path#fragment`) then it is not sent during the HTTP request at all. See: * <https://en.wikipedia.org/wiki/Fragment_identifier>
14,715,397
I know this question: [Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?](https://stackoverflow.com/questions/134845/href-attribute-for-javascript-links-or-javascriptvoid0) contains a discussion of what the correct href content should be for javascript links. How does this relate to 508 compliance? Does anyone know if the javascript:void(0) is acceptable when click handlers are defined elsewhere in the javascript code?
2013/02/05
[ "https://Stackoverflow.com/questions/14715397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/387361/" ]
This is where terminology becomes important - in terms of accessibility there is no such thing as "a javascript link". There are links, which are unadulterated anchor elements, and there are javascript behaviours, which should be assumed not-runnable for accessibility. An empty anchor element that triggers javascript (so something like href='#' onclick='...') is not a link, it's a UI element for triggering page behaviour. For accessibility, don't abuse the anchor element for this, use a real UI element with the correct ARIA role. For a click-through link (which do something like "click anchor" -> "magical JS is called" -> "window.location is changed to some new page") then be aware that you're semanticlaly misrepresenting your content. Even though you're using an anchor element, your use of it is not as a link, since it's not an anchor to another resource. Like in the above case, it's actually a button. The fact that the page location changes at the end does not change this. For true accessibility, you'll have to give up any JavaScript-in-the-middle. But don't worry, that's much less severe than it sounds: the simplest solution is to use rerouting links instead. If you've ever used google.com or duckduckgo.com, etc. you'll already be familiar with this: rather than link out to the actual URL, link out to the URL proxied over a page-less script. You can guarantee that an anchor with the URL "<http://our.domain.com/ref=http://the.actual.link.to.visit>", will end up redirecting to the actual site just fine, and you can tack on any desired operation that should take place "when people click" as a server side action when you resolve the redirect. 508 compliance will be hard if you think you rely on JavaScript. So for accessibility: actively try not to. Enrich if you can use it, ensure things still work without it.
I essentially agree with Mike. > > How does this relate to 508 compliance? > > > A common misconception about Section 508 is "oh I ran my site with JAWS (or maybe NVDA), and was fine. So I am compliant." Section 508 is therotically supposed to cover *all* disabilities not just blindness. When you wonder off into heavy JavaScripting, agencies tend to use the "Software applications and operating systems" (1194.21) Standards in addition to "Web-based intranet and internet information and systems" (1194.22) because they talk more about UI elements. Places like WebAIM, unfortunately deny this. So when 1194.21 is included, the Standards can be more easily read as "you put all the @alts and `<label>`s on, but can this site/app/system with the keyboard? AKA is it keyboard navigatiable?" Can you get to that `<span>` that looks like a link? As Mke said, one way to assist with this is using ARIA. So, that `<span>` now has to be: ``` <span onclick="Clicky()" role="link">Link</span> ``` (Ref: [MDN](https://developer.mozilla.org/en-US/docs/Accessibility/ARIA/ARIA_Techniques/Using_the_link_role)) Now back to your question: > > I know this question: Href attribute for JavaScript links: "#" or "javascript:void(0)"? Does anyone know if the javascript:void(0) is acceptable when click handlers are defined elsewhere in the javascript code? > > > I would advocate for the void because when a reference (think it is called an in-page ref)is not defined, the focus goes back to the browser frame, versus staying on the link. You would need to write some handlers to return the focus to the link.
63,161,573
I am trying to make a variable increase every second. What should I include inside the function autoClicker, so that the variable clicks increase by 1 every second? Also, if there are any more problems in the code, could you point them out to me? Sorry if this question seems basic, I am still quite new to JavaScript. ```js // The variable we are trying to increase var clicks = 0; var upgrade1 = 1; function getClicks() { clicks += upgrade1; document.getElementById("clicks").innerHTML = clicks; }; function buyAutoClicker() { if (clicks >= 50) { clicks -= 50 autoClicker() } else { alert = "Sorry, you don't have enough clicks to buy this"; } } // The function I will use to increase clicks function autoClicker() {} ```
2020/07/29
[ "https://Stackoverflow.com/questions/63161573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14018137/" ]
```js // The variable we are trying to increase var clicks = 0; var upgrade1 = 1; function getClicks() { clicks += upgrade1; document.getElementById("clicks").innerHTML = clicks; }; function buyAutoClicker() { if (clicks >= 50) { clicks -= 50 autoClicker() } else { alert = "Sorry, you don't have enough clicks to buy this"; } } // The function I will use to increase clicks setInterval(function(){ clicks++;console.log(clicks); }, 1000); ```
There might be several things to improve this code * the use of textContent is preferable to innerHTML, it checks if there are no html tags in the text * then using inline functions like ()=>{} are more useful but in this program it does'nt make a difference, where you to use it in object oriented context you could use it several ways * you don't need document.getElementById, you could just use id. And finaly (this is just à random tip which has nothing to do with much of anything) you may consider branchless programming because ifs are expensive. [Stackoverflow Branchless Programming Benefits](https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array/11227902#11227902) But anyways you should have fun :) ```js var clicks = 0; var upgrade1 = 1; function getClicks() { clk.textContent = (clicks += upgrade1); }; function buyAutoClicker() { if (clicks >= 50) { clicks -= 50 setInterval(()=>{getClicks();},1000); } else { alert("Sorry, you don't have enough clicks to buy this"); } } clk.onclick=()=>{getClicks();}; b.onclick=()=>{buyAutoClicker();}; ``` ```css html,body{height:100%;width:100%;margin:0;} p{height:50px;width:50px;background:red;} ``` ```html <p id="clk"></p> <p id="b"></p> ```
63,161,573
I am trying to make a variable increase every second. What should I include inside the function autoClicker, so that the variable clicks increase by 1 every second? Also, if there are any more problems in the code, could you point them out to me? Sorry if this question seems basic, I am still quite new to JavaScript. ```js // The variable we are trying to increase var clicks = 0; var upgrade1 = 1; function getClicks() { clicks += upgrade1; document.getElementById("clicks").innerHTML = clicks; }; function buyAutoClicker() { if (clicks >= 50) { clicks -= 50 autoClicker() } else { alert = "Sorry, you don't have enough clicks to buy this"; } } // The function I will use to increase clicks function autoClicker() {} ```
2020/07/29
[ "https://Stackoverflow.com/questions/63161573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14018137/" ]
You could create an `AutoClicker` class that has a start, pause, ad update function. It will be in charge of managing the `setInterval` id. **Edit:** I updated it to include upgrade buttons and the `target` can now be manually clicked. ```js const upgrades = [{ cost: 50, rate: 2 }, { cost: 100, rate: 4 }]; const main = () => { const target = document.querySelector('.auto-clicker'); const span = document.querySelector('.info > span'); const btn = document.querySelector('.btn-toggle'); const clicker = new AutoClicker(target, 1000, (clicks) => { span.textContent = clicks; }).start(); initializeUpgrades(clicker, upgrades); btn.addEventListener('click', (e) => { e.target.textContent = clicker.isRunning() ? 'Start' : 'Pause'; clicker.toggle(); }); }; const initializeUpgrades = (clicker, upgrades) => { const upgradeContainer = document.querySelector('.upgrades'); upgrades.forEach(upgrade => { const btn = document.createElement('button'); btn.textContent = upgrade.cost; btn.value = upgrade.rate; btn.addEventListener('click', (e) => { let cost = parseInt(e.target.textContent, 10); let value = parseInt(e.target.value, 10); if (clicker.clicks >= cost) { clicker.clicks -= cost; clicker.step = value } else { console.log(`Cannot afford the ${value} click upgrade, it costs ${cost} clicks`); } }); upgradeContainer.appendChild(btn); }); }; class AutoClicker { constructor(target, rate, callback) { if (typeof target === 'string') { target = document.querySelector(target); } this.target = target; this.rate = rate; this.callback = callback; this.init(); } init() { this.step = 1; this.clicks = 0; this._loopId = null; this.target.addEventListener('click', (e) => { this.update(); }); } isRunning() { return this._loopId != null; } toggle() { this.isRunning() ? this.pause() : this.start(); } update() { this.clicks += this.step; if (this.callback) { this.callback(this.clicks); } } start() { this.update(); // Update immediately this._loopId = setInterval(() => this.update(), this.rate); return this; } pause() { clearInterval(this._loopId); this._loopId = null; return this; } } main(); ``` ```css .wrapper { width: 10em; text-align: center; border: thin solid grey; padding: 0.5em; } .auto-clicker { width: 4em; height: 4em; background: #F00; border: none; border-radius: 2em; } .auto-clicker:focus { outline: none; } .auto-clicker:hover { background: #F44; cursor: pointer; } .info { margin: 1em 0; } .upgrades { display: inline-block; } .upgrades button { margin-right: 0.25em; } ``` ```html <div class="wrapper"> <button class="auto-clicker"></button> <div class="info">Clicks: <span class="clicks"></span></div> <button class="btn-toggle">Pause</button> <div class="upgrades"></div> </div> ```
```js // The variable we are trying to increase var clicks = 0; var upgrade1 = 1; function getClicks() { clicks += upgrade1; document.getElementById("clicks").innerHTML = clicks; }; function buyAutoClicker() { if (clicks >= 50) { clicks -= 50 autoClicker() } else { alert = "Sorry, you don't have enough clicks to buy this"; } } // The function I will use to increase clicks setInterval(function(){ clicks++;console.log(clicks); }, 1000); ```
63,161,573
I am trying to make a variable increase every second. What should I include inside the function autoClicker, so that the variable clicks increase by 1 every second? Also, if there are any more problems in the code, could you point them out to me? Sorry if this question seems basic, I am still quite new to JavaScript. ```js // The variable we are trying to increase var clicks = 0; var upgrade1 = 1; function getClicks() { clicks += upgrade1; document.getElementById("clicks").innerHTML = clicks; }; function buyAutoClicker() { if (clicks >= 50) { clicks -= 50 autoClicker() } else { alert = "Sorry, you don't have enough clicks to buy this"; } } // The function I will use to increase clicks function autoClicker() {} ```
2020/07/29
[ "https://Stackoverflow.com/questions/63161573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14018137/" ]
You could create an `AutoClicker` class that has a start, pause, ad update function. It will be in charge of managing the `setInterval` id. **Edit:** I updated it to include upgrade buttons and the `target` can now be manually clicked. ```js const upgrades = [{ cost: 50, rate: 2 }, { cost: 100, rate: 4 }]; const main = () => { const target = document.querySelector('.auto-clicker'); const span = document.querySelector('.info > span'); const btn = document.querySelector('.btn-toggle'); const clicker = new AutoClicker(target, 1000, (clicks) => { span.textContent = clicks; }).start(); initializeUpgrades(clicker, upgrades); btn.addEventListener('click', (e) => { e.target.textContent = clicker.isRunning() ? 'Start' : 'Pause'; clicker.toggle(); }); }; const initializeUpgrades = (clicker, upgrades) => { const upgradeContainer = document.querySelector('.upgrades'); upgrades.forEach(upgrade => { const btn = document.createElement('button'); btn.textContent = upgrade.cost; btn.value = upgrade.rate; btn.addEventListener('click', (e) => { let cost = parseInt(e.target.textContent, 10); let value = parseInt(e.target.value, 10); if (clicker.clicks >= cost) { clicker.clicks -= cost; clicker.step = value } else { console.log(`Cannot afford the ${value} click upgrade, it costs ${cost} clicks`); } }); upgradeContainer.appendChild(btn); }); }; class AutoClicker { constructor(target, rate, callback) { if (typeof target === 'string') { target = document.querySelector(target); } this.target = target; this.rate = rate; this.callback = callback; this.init(); } init() { this.step = 1; this.clicks = 0; this._loopId = null; this.target.addEventListener('click', (e) => { this.update(); }); } isRunning() { return this._loopId != null; } toggle() { this.isRunning() ? this.pause() : this.start(); } update() { this.clicks += this.step; if (this.callback) { this.callback(this.clicks); } } start() { this.update(); // Update immediately this._loopId = setInterval(() => this.update(), this.rate); return this; } pause() { clearInterval(this._loopId); this._loopId = null; return this; } } main(); ``` ```css .wrapper { width: 10em; text-align: center; border: thin solid grey; padding: 0.5em; } .auto-clicker { width: 4em; height: 4em; background: #F00; border: none; border-radius: 2em; } .auto-clicker:focus { outline: none; } .auto-clicker:hover { background: #F44; cursor: pointer; } .info { margin: 1em 0; } .upgrades { display: inline-block; } .upgrades button { margin-right: 0.25em; } ``` ```html <div class="wrapper"> <button class="auto-clicker"></button> <div class="info">Clicks: <span class="clicks"></span></div> <button class="btn-toggle">Pause</button> <div class="upgrades"></div> </div> ```
There might be several things to improve this code * the use of textContent is preferable to innerHTML, it checks if there are no html tags in the text * then using inline functions like ()=>{} are more useful but in this program it does'nt make a difference, where you to use it in object oriented context you could use it several ways * you don't need document.getElementById, you could just use id. And finaly (this is just à random tip which has nothing to do with much of anything) you may consider branchless programming because ifs are expensive. [Stackoverflow Branchless Programming Benefits](https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array/11227902#11227902) But anyways you should have fun :) ```js var clicks = 0; var upgrade1 = 1; function getClicks() { clk.textContent = (clicks += upgrade1); }; function buyAutoClicker() { if (clicks >= 50) { clicks -= 50 setInterval(()=>{getClicks();},1000); } else { alert("Sorry, you don't have enough clicks to buy this"); } } clk.onclick=()=>{getClicks();}; b.onclick=()=>{buyAutoClicker();}; ``` ```css html,body{height:100%;width:100%;margin:0;} p{height:50px;width:50px;background:red;} ``` ```html <p id="clk"></p> <p id="b"></p> ```
63,161,573
I am trying to make a variable increase every second. What should I include inside the function autoClicker, so that the variable clicks increase by 1 every second? Also, if there are any more problems in the code, could you point them out to me? Sorry if this question seems basic, I am still quite new to JavaScript. ```js // The variable we are trying to increase var clicks = 0; var upgrade1 = 1; function getClicks() { clicks += upgrade1; document.getElementById("clicks").innerHTML = clicks; }; function buyAutoClicker() { if (clicks >= 50) { clicks -= 50 autoClicker() } else { alert = "Sorry, you don't have enough clicks to buy this"; } } // The function I will use to increase clicks function autoClicker() {} ```
2020/07/29
[ "https://Stackoverflow.com/questions/63161573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14018137/" ]
Use [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) to run a function at a specified interval. This will run `increaseClicks` every 1000 milliseconds (every second): ```js function increaseClicks() { clicks++; } var interval = setInterval(increaseClicks, 1000); ``` Use [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) to stop running it: ```js clearInterval(interval); ``` You can omit `var interval =` if you don't want to use `clearInterval`: ```js setInterval(increaseClicks, 1000); ```
There might be several things to improve this code * the use of textContent is preferable to innerHTML, it checks if there are no html tags in the text * then using inline functions like ()=>{} are more useful but in this program it does'nt make a difference, where you to use it in object oriented context you could use it several ways * you don't need document.getElementById, you could just use id. And finaly (this is just à random tip which has nothing to do with much of anything) you may consider branchless programming because ifs are expensive. [Stackoverflow Branchless Programming Benefits](https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array/11227902#11227902) But anyways you should have fun :) ```js var clicks = 0; var upgrade1 = 1; function getClicks() { clk.textContent = (clicks += upgrade1); }; function buyAutoClicker() { if (clicks >= 50) { clicks -= 50 setInterval(()=>{getClicks();},1000); } else { alert("Sorry, you don't have enough clicks to buy this"); } } clk.onclick=()=>{getClicks();}; b.onclick=()=>{buyAutoClicker();}; ``` ```css html,body{height:100%;width:100%;margin:0;} p{height:50px;width:50px;background:red;} ``` ```html <p id="clk"></p> <p id="b"></p> ```
63,161,573
I am trying to make a variable increase every second. What should I include inside the function autoClicker, so that the variable clicks increase by 1 every second? Also, if there are any more problems in the code, could you point them out to me? Sorry if this question seems basic, I am still quite new to JavaScript. ```js // The variable we are trying to increase var clicks = 0; var upgrade1 = 1; function getClicks() { clicks += upgrade1; document.getElementById("clicks").innerHTML = clicks; }; function buyAutoClicker() { if (clicks >= 50) { clicks -= 50 autoClicker() } else { alert = "Sorry, you don't have enough clicks to buy this"; } } // The function I will use to increase clicks function autoClicker() {} ```
2020/07/29
[ "https://Stackoverflow.com/questions/63161573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14018137/" ]
You could create an `AutoClicker` class that has a start, pause, ad update function. It will be in charge of managing the `setInterval` id. **Edit:** I updated it to include upgrade buttons and the `target` can now be manually clicked. ```js const upgrades = [{ cost: 50, rate: 2 }, { cost: 100, rate: 4 }]; const main = () => { const target = document.querySelector('.auto-clicker'); const span = document.querySelector('.info > span'); const btn = document.querySelector('.btn-toggle'); const clicker = new AutoClicker(target, 1000, (clicks) => { span.textContent = clicks; }).start(); initializeUpgrades(clicker, upgrades); btn.addEventListener('click', (e) => { e.target.textContent = clicker.isRunning() ? 'Start' : 'Pause'; clicker.toggle(); }); }; const initializeUpgrades = (clicker, upgrades) => { const upgradeContainer = document.querySelector('.upgrades'); upgrades.forEach(upgrade => { const btn = document.createElement('button'); btn.textContent = upgrade.cost; btn.value = upgrade.rate; btn.addEventListener('click', (e) => { let cost = parseInt(e.target.textContent, 10); let value = parseInt(e.target.value, 10); if (clicker.clicks >= cost) { clicker.clicks -= cost; clicker.step = value } else { console.log(`Cannot afford the ${value} click upgrade, it costs ${cost} clicks`); } }); upgradeContainer.appendChild(btn); }); }; class AutoClicker { constructor(target, rate, callback) { if (typeof target === 'string') { target = document.querySelector(target); } this.target = target; this.rate = rate; this.callback = callback; this.init(); } init() { this.step = 1; this.clicks = 0; this._loopId = null; this.target.addEventListener('click', (e) => { this.update(); }); } isRunning() { return this._loopId != null; } toggle() { this.isRunning() ? this.pause() : this.start(); } update() { this.clicks += this.step; if (this.callback) { this.callback(this.clicks); } } start() { this.update(); // Update immediately this._loopId = setInterval(() => this.update(), this.rate); return this; } pause() { clearInterval(this._loopId); this._loopId = null; return this; } } main(); ``` ```css .wrapper { width: 10em; text-align: center; border: thin solid grey; padding: 0.5em; } .auto-clicker { width: 4em; height: 4em; background: #F00; border: none; border-radius: 2em; } .auto-clicker:focus { outline: none; } .auto-clicker:hover { background: #F44; cursor: pointer; } .info { margin: 1em 0; } .upgrades { display: inline-block; } .upgrades button { margin-right: 0.25em; } ``` ```html <div class="wrapper"> <button class="auto-clicker"></button> <div class="info">Clicks: <span class="clicks"></span></div> <button class="btn-toggle">Pause</button> <div class="upgrades"></div> </div> ```
Use [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) to run a function at a specified interval. This will run `increaseClicks` every 1000 milliseconds (every second): ```js function increaseClicks() { clicks++; } var interval = setInterval(increaseClicks, 1000); ``` Use [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) to stop running it: ```js clearInterval(interval); ``` You can omit `var interval =` if you don't want to use `clearInterval`: ```js setInterval(increaseClicks, 1000); ```
47,350,353
I'm trying to follow [this guide](https://github.com/kubernetes-incubator/external-dns/blob/master/docs/tutorials/azure.md) to setting up a K8s cluster with external-dns' Azure DNS provider. The guide states that: > > When your Kubernetes cluster is created by ACS, a file named `/etc/kubernetes/azure.json` is created to store the Azure credentials for API access. Kubernetes uses this file for the Azure cloud provider. > > > When I create a cluster using aks (e.g. `az aks create --resource-group myResourceGroup --name myK8sCluster --node-count 1 --generate-ssh-keys`) this file doesn't exist. Where do the API credentials get stored when using AKS? Essentially I'm trying to work out where to point this command: `kubectl create secret generic azure-config-file --from- file=/etc/kubernetes/azure.json`
2017/11/17
[ "https://Stackoverflow.com/questions/47350353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2428138/" ]
From what I can see when using AKS the `/etc/kubernetes/azure.json` doesn't get created. As an alternative I followed the instructions for use with non Azure hosted sites and created a service principal (<https://github.com/kubernetes-incubator/external-dns/blob/master/docs/tutorials/azure.md#optional-create-service-principal>) Creating the service principal produces some json that contains most of the detail. This can be used to manually create the azure.json file and the secret can be created from it.
Use this command to get credentials: ``` az aks get-credentials --resource-group myResourceGroup --name myK8sCluster ``` Source: <https://learn.microsoft.com/en-us/azure/aks/kubernetes-walkthrough>
47,350,353
I'm trying to follow [this guide](https://github.com/kubernetes-incubator/external-dns/blob/master/docs/tutorials/azure.md) to setting up a K8s cluster with external-dns' Azure DNS provider. The guide states that: > > When your Kubernetes cluster is created by ACS, a file named `/etc/kubernetes/azure.json` is created to store the Azure credentials for API access. Kubernetes uses this file for the Azure cloud provider. > > > When I create a cluster using aks (e.g. `az aks create --resource-group myResourceGroup --name myK8sCluster --node-count 1 --generate-ssh-keys`) this file doesn't exist. Where do the API credentials get stored when using AKS? Essentially I'm trying to work out where to point this command: `kubectl create secret generic azure-config-file --from- file=/etc/kubernetes/azure.json`
2017/11/17
[ "https://Stackoverflow.com/questions/47350353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2428138/" ]
From what I can see when using AKS the `/etc/kubernetes/azure.json` doesn't get created. As an alternative I followed the instructions for use with non Azure hosted sites and created a service principal (<https://github.com/kubernetes-incubator/external-dns/blob/master/docs/tutorials/azure.md#optional-create-service-principal>) Creating the service principal produces some json that contains most of the detail. This can be used to manually create the azure.json file and the secret can be created from it.
Did you try this command ? ``` cat ~/.kube/config ``` It provided all i needed for my CI to connect to the Kubernetes Cluster and use API
2,288,448
For my ecommece site, I want to store partial credit card numbers as string, for this I need to encrypt the information to store at the database and decrypt when users want to reuse the already entered credit card info from earlier purchases without typing it all over again. I am using Django thus I need to solve this via Python. What would be the clever algorithm to solve this issue ?
2010/02/18
[ "https://Stackoverflow.com/questions/2288448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
Before you go much further you should take a look at [PCI-DSS](https://www.pcisecuritystandards.org/), which governs exactly what processes you need to have in place to even consider storing encrypted card numbers. In short, you should seriously consider outsourcing to a 3rd party payment gateway. If once you've understood the consequences you do want to go ahead, then again - follow the PCI guidelines. For symmetric encryption of card numbers you probably want to use [AES](https://stackoverflow.com/questions/172486/what-pure-python-library-to-use-for-aes-256-encryption), and draw up very strict [key management policies](https://stackoverflow.com/questions/1583553/how-to-properly-do-private-key-management/1584586#1584586). If however you only want to store a partial card number, then PCI states you can store (at an absolute maximum) the first six and last four digits only. The first six digits are all you need to identify a card type. The last four digits you may deem necessary to help prevent issues where a customer has near identical card numbers. IMHO storing partial card numbers (in plain text) is what you want to do, and then outsource the handling of encryption, authorisation and settlement to a [3rd party gateway](https://stackoverflow.com/questions/2022067/looking-for-a-payment-gateway). The payment gateway will give you a unique token id for each card you pass to them, so that you can reference a unique card to perform re-authorisation or refunds etc.
Are you absolutely sure you want to hash sensitive information like this? It might be worth reading [this article](http://benlog.com/articles/2008/06/19/dont-hash-secrets/) to get an idea of some of the pitfalls trying to store any sensitive information in a database. In your case it's even worse because you want the transformation to be reversible. Just remember, if you can reverse it, so can an attacker. Think carefully before you embark on this course... Perhaps you might be better of outsourcing this kind of work to someone who specializes in it (such as [Paypal](http://www.paypal.com) or [Google Checkout](https://www.google.com/accounts/ServiceLogin?service=sierra&continue=https://checkout.google.com/%3Fgl%3DGB%26saveUserPref%3Dtrue%26gsessionid%3DjA_dzdd2q3o%26upgrade%3Dtrue&hl=en_GB&nui=1&ltmpl=default&gsessionid=jA_dzdd2q3o) etc).
296,755
I am using Salesforce Connect with a cross-org adapter to connect two orgs. I have configured the external data source with oAuth and an Authentication Provider. The data source was successfully created but when I try to Validate and Sync data, it is throwing me the following error : > > We encountered an unexpected error. Try again later, or contact your > administrator, who can verify the external data source settings and > the external system's availability. Error received from the external > system: This session is not valid for use with the REST API > > >
2020/03/04
[ "https://salesforce.stackexchange.com/questions/296755", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/55791/" ]
Remember that triggers will be called in chunks if you create/update/delete (generally in chunks of 200 items). Perhaps you could adjust this to track operations against ID, something like: ``` static Map<TriggerOperation, Set<Id>> blockedObjectIdsByOperation; ``` That way if the object has already been through the trigger for the given operation type the execution can be suppressed but this won't interfere with chunked trigger calls. I don't think there's an issue with before insert since such a trigger shouldn't get invoked iteratively on an object (though there could be some edge cases).
The way I've come to accept recursive blocking is to block only during operations where I feel I may end up with recursion. I use the blocks only during known recursive updates. For example: ``` public class AccountTriggerHandler { static Boolean isInAccountUpdate = false; ... public static void afterUpdate(Account[] oldValues, Account[] newValues) { if(!isInAccountUpdate) { if(shouldDoUpdate()) { isInAccountUpdate = true; updateRecords(oldValues, newValues); isInAccountUpdate = false; } } } } ``` Note that an even better idea is to make your triggers "rising edge" when possible: ``` public static void afterUpdate(Account[] oldValues, Account[] newValues) { Account[] oldChanges = new Account[0], newChanges = new Account[0]; for(Integer i = 0, s = newValues.size(); i < s; i++) { if(recordChanged(oldValues[i], newValues[i])) { oldChanges.add(oldValues[i]); newChanges.add(newValues[i]); } } processChangedRecords(oldChanges, newChanges); } ``` This pattern almost always (but exceptions obviously exist) eliminates recursion without any extra variables at all. If you want to avoid recursions in the face of potential updates to multiple records of the same type, you can then use a set. However, one specific caveat here is that you should always reset this set at the end of the trigger to avoid logic bugs when dealing with retries/workflow/process updates. ``` public class AccountTriggerHandler { static Set<Id> accountIds = new Set<id>(); public static void afterUpdate(Account[] oldValues, Account[] newValues, Set<Id> accountIdSet) { if(accountIds.containsAll(accountIdSet)) { return; } accountIds.addAll(accountIdSet); doMainLogicHere(); accountIds.removeAll(accountIdSet); } } ``` If you don't do this, you're blocking the ability to react to workflow field updates, process builder updates, approval process updates, valid recursive updates, updates involving more than 200 records, etc. You'll also restrict the ability for unit tests to perform multiple DML operations. A proper strategy must include the ability to handle partial updates (I've specifically had this happen to me once before I started doing this), as well as only performing necessary updates (e.g. rising edge triggers, checking if any data changed). There is no single magic bullet to stopping "recursion", and often all of the strategies above (or variants) should be employed, all possible consequences considered. Always "unlock" your trigger at the end of a trigger context, even if you don't think you'll need it. Always minimize the "lock time", and definitely clear out the lock when the trigger ends.
67,878,975
I want to find out when an alert happens so I can automatically accept. I've placed `self.driver.switch_to.alert.accept()` in various places in the code but I always get a `selenium.common.exceptions.NoAlertPresentException`. When I don't place it anywhere I get an `selenium.common.exceptions.UnexpectedAlertPresentException`. When I use expected\_conditions I get a `selenium.common.exceptions.TimeoutException`. I don't know what to do at this point. Can anyone help? Python/Django Backend. Using Selenium (Firefox)
2021/06/07
[ "https://Stackoverflow.com/questions/67878975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4001300/" ]
img will target all images on page as you already experienced. You can use the different CSS selectors such as the class .rose for targeting the rose only. Since the cat is wrapped in a div with the ID of #yes, you can use that for targeting the cat only. Here updated code: ```html <style> #yes:hover { /* Start the shake animation and make the animation last for 0.5 seconds */ animation: shake 0.5s; /* When the animation is finished, start again */ animation-iteration-count: infinite; } @keyframes shake { 0% { transform: translate(1px, 1px) rotate(0deg); } 10% { transform: translate(-1px, -2px) rotate(-1deg); } 20% { transform: translate(-3px, 0px) rotate(1deg); } 30% { transform: translate(3px, 2px) rotate(0deg); } 40% { transform: translate(1px, -1px) rotate(1deg); } 50% { transform: translate(-1px, 2px) rotate(-1deg); } 60% { transform : translate(-3px, 1px) rotate(0deg); } 70% { transform: translate(3px, 1px) rotate(-1deg); } 80% { transform: translate(-1px, -1px) rotate(1deg); } 90% { transform: translate(1px, 2px) rotate(0deg); } 100% { transform: translate(1px, -2px) rotate(-1deg); } } .rose { position:absolute; height: 60px; position: absolute; right: 10%; bottom: 65%; z-index: 10; } </style> <a href="link"><img class=rose src="https://lh3.googleusercontent.com/proxy/yE37tIxmy_UX0kF8GPWUE8IENQgG5N5LWThSxPW2Hf98oV2okclLeqBa9eoB8dafwEc2xryoRZZEdsyboPpFmz-NMi2nQOPhy2QU3hu5fJ5EBXCQOA_QpDnz"></a> <div id="yes"><img src="https://media.tenor.com/images/eff22afc2220e9df92a7aa2f53948f9f/tenor.gif"></div> ```
``` img:hover ``` does effect all images on hover. So you have to seperate animations with different selectors. For example: ``` .rose:hover .cat:hover ```
67,878,975
I want to find out when an alert happens so I can automatically accept. I've placed `self.driver.switch_to.alert.accept()` in various places in the code but I always get a `selenium.common.exceptions.NoAlertPresentException`. When I don't place it anywhere I get an `selenium.common.exceptions.UnexpectedAlertPresentException`. When I use expected\_conditions I get a `selenium.common.exceptions.TimeoutException`. I don't know what to do at this point. Can anyone help? Python/Django Backend. Using Selenium (Firefox)
2021/06/07
[ "https://Stackoverflow.com/questions/67878975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4001300/" ]
img will target all images on page as you already experienced. You can use the different CSS selectors such as the class .rose for targeting the rose only. Since the cat is wrapped in a div with the ID of #yes, you can use that for targeting the cat only. Here updated code: ```html <style> #yes:hover { /* Start the shake animation and make the animation last for 0.5 seconds */ animation: shake 0.5s; /* When the animation is finished, start again */ animation-iteration-count: infinite; } @keyframes shake { 0% { transform: translate(1px, 1px) rotate(0deg); } 10% { transform: translate(-1px, -2px) rotate(-1deg); } 20% { transform: translate(-3px, 0px) rotate(1deg); } 30% { transform: translate(3px, 2px) rotate(0deg); } 40% { transform: translate(1px, -1px) rotate(1deg); } 50% { transform: translate(-1px, 2px) rotate(-1deg); } 60% { transform : translate(-3px, 1px) rotate(0deg); } 70% { transform: translate(3px, 1px) rotate(-1deg); } 80% { transform: translate(-1px, -1px) rotate(1deg); } 90% { transform: translate(1px, 2px) rotate(0deg); } 100% { transform: translate(1px, -2px) rotate(-1deg); } } .rose { position:absolute; height: 60px; position: absolute; right: 10%; bottom: 65%; z-index: 10; } </style> <a href="link"><img class=rose src="https://lh3.googleusercontent.com/proxy/yE37tIxmy_UX0kF8GPWUE8IENQgG5N5LWThSxPW2Hf98oV2okclLeqBa9eoB8dafwEc2xryoRZZEdsyboPpFmz-NMi2nQOPhy2QU3hu5fJ5EBXCQOA_QpDnz"></a> <div id="yes"><img src="https://media.tenor.com/images/eff22afc2220e9df92a7aa2f53948f9f/tenor.gif"></div> ```
You can put your animation into a class that you only use for it. Like: ``` img { width: 50px; height: 50px; } .imgAnimation:hover { animation: example 4s ease-in-out infinit; } @keyframes shake { 0% { transform: translate(1px, 1px) rotate(0deg); } 10% { transform: translate(-1px, -2px) rotate(-1deg); } 20% { transform: translate(-3px, 0px) rotate(1deg); } 30% { transform: translate(3px, 2px) rotate(0deg); } 40% { transform: translate(1px, -1px) rotate(1deg); } 50% { transform: translate(-1px, 2px) rotate(-1deg); } 60% { transform : translate(-3px, 1px) rotate(0deg); } 70% { transform: translate(3px, 1px) rotate(-1deg); } 80% { transform: translate(-1px, -1px) rotate(1deg); } 90% { transform: translate(1px, 2px) rotate(0deg); } 100% { transform: translate(1px, -2px) rotate(-1deg); } } ``` And then you can put a class that has you hover animation just into the images you want ``` <div class="container"> <img src="img1.png"> <img class="imgAnimation" src="img2.jpg"> <img class="imgAnimation" src="img3.jpg"> </div> ```
39,006,669
So I am pulling some json data using an API and it initially looks like this: ``` { "result": { "elements": [ { "id": "SV_3s0FmbrNancSmsB", "name": "Test Survey", "ownerId": "sdfsdfasdf", "lastModified": "2016-08-09T21:33:27Z", "isActive": false }, { "id": "SV_dgJOVyJvwZR0593", "name": "Test Survey", "ownerId": "sdfdsfsdfs", "lastModified": "2016-08-04T17:53:37Z", "isActive": true } ], "nextPage": null }, "meta": { "httpStatus": "200 - OK" } } ``` So I want to pull all of the ids within this JSON using Python, and here is my code: ``` url = "random.com" headers = { 'x-api-token': "dsfsdagdfa" } response = requests.get(url, headers=headers) data = json.loads(response.text) id_0 = data['result']['elements'][0]['id'] print(id_0) ``` This will basically just print the first Id within the created array. What would I do to get all of the ids?
2016/08/17
[ "https://Stackoverflow.com/questions/39006669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6332399/" ]
You can use this oneliner: ``` ids = [element['id'] for element in data['result']['elements']] ```
This should work. Im sure there is a more elegant way with map or list comprehension. ``` ids = [] for elem in data['result']['elements']: ids.append(elem['id']) ``` If you want to evaluate this lazily, make a generator comprehension! `ids = (element['id'] for element in data['result']['elements'])`
39,006,669
So I am pulling some json data using an API and it initially looks like this: ``` { "result": { "elements": [ { "id": "SV_3s0FmbrNancSmsB", "name": "Test Survey", "ownerId": "sdfsdfasdf", "lastModified": "2016-08-09T21:33:27Z", "isActive": false }, { "id": "SV_dgJOVyJvwZR0593", "name": "Test Survey", "ownerId": "sdfdsfsdfs", "lastModified": "2016-08-04T17:53:37Z", "isActive": true } ], "nextPage": null }, "meta": { "httpStatus": "200 - OK" } } ``` So I want to pull all of the ids within this JSON using Python, and here is my code: ``` url = "random.com" headers = { 'x-api-token': "dsfsdagdfa" } response = requests.get(url, headers=headers) data = json.loads(response.text) id_0 = data['result']['elements'][0]['id'] print(id_0) ``` This will basically just print the first Id within the created array. What would I do to get all of the ids?
2016/08/17
[ "https://Stackoverflow.com/questions/39006669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6332399/" ]
You can use this oneliner: ``` ids = [element['id'] for element in data['result']['elements']] ```
How about: ``` ids = [element['id'] for element in data['result']['elements']] ```
14,723,383
In my web application, I allow users to login using the auth command in the API Client Library but I cannot find a Logout option for the Google API JavaScript Client Library. Can any one suggest how can i Logout of my application as well as google account?? My Login Code is: ``` var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?'; var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='; var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile'; var CLIENTID = googleAPI; var REDIRECT = redirectUrl; var TYPE = 'token'; var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE; var acToken; var tokenType; var expiresIn; var user; $('#googleLogin').click(function(){ var win = window.open(_url, "windowname1", 'width=800, height=600'); var pollTimer = window.setInterval(function () { if (win.document.URL.indexOf(REDIRECT) != -1) { window.clearInterval(pollTimer); var url = win.document.URL; acToken = gup(url, 'access_token'); tokenType = gup(url, 'token_type'); expiresIn = gup(url, 'expires_in'); win.close(); validateToken(acToken); } }, 100); }); function validateToken(token) { $.ajax({ url: VALIDURL + token, data: null, success: function (responseText) { getUserInfo(); }, dataType: "jsonp" }); } ```
2013/02/06
[ "https://Stackoverflow.com/questions/14723383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1791464/" ]
Do not log your users out of their Google Account when they sign out of your application. This behavior is unexpected and annoying to users. You should, at most, be trying to figure out how to "log out" users of your application. (I put it in quotes, because depending on your implementation, the app might be faking it). If you care only about hiding elements in the UI, you can set a variable, e.g. `signedIn`, and set or unset it when the user hits a login/logout button. If you care about persisting this state across sessions, use a cookie that stores the same value. If you want to make sure the person on the other side of the keyboard is really the signed in user, you can use the `max_auth_age` parameter on the `authorize` call. If you set it to `0`, users will need to re-authenticate with Google before your app gets a valid token. If you pair this with an automatic session expiration (like you'd see on a bank or health website), you can be relatively confident of the identity of the current user.
If you relax the requirement to log out users from their Google account (as Dan explained, it's not a good idea) you can just revoke the OAuth token as explained in [this other question](https://stackoverflow.com/questions/12809339/how-to-revoke-an-authentication-token-client-side-against-the-google-api/19205371#19205371).
44,124,914
Is it possible to have multiple versions of service(s) deployed in production at the same time. From my assumption, this should be pretty common pattern for microservice/api based projects or mobile projects. I want to know how do you do it and what are common pattern in industry for this kind of problems. It would be helpful if your answers around AWS environment or Kubernetes environment. Thanks in Advance.
2017/05/23
[ "https://Stackoverflow.com/questions/44124914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7261916/" ]
> > Is it possible to have multiple versions of service(s) deployed in production at the same time > > > Yes, it is possible. The idea is to keep all *used* microservices in production (v1, v2 ...) at the same time and to bring down the versions that are not used anymore. For this, you *should* somehow know when a version is not used anymore. AFAIK, you have to options: 1. For every new version you make a new endpoint (like /v2/someApiCall) that is connected to the same (now upgraded) microservice and gradually instruct clients to use the new endpoind; when the old endpoint is not used anymore you deleted it; this is the preferred way. 2. For every new version you make a new microservice that share the same persistence with the old microservice; you should avoid the use of this solution; Netflix uses this strategy in *rare* occasions when the cost of changing old consumers is too high. You can read more at page 62 from [Building microservices by Sam Newman](https://rads.stackoverflow.com/amzn/click/com/1491950358).
Assuming your are exposing services over An HTTP REST API, the general standard is to always base line your service urls with a version. Eg, ``` /v1/account/getUserInfo ``` If you need to release a new version, expose it over: ``` /v2/account/getUserInfo ``` Where v2 can run over a different branch of the codebase.
44,124,914
Is it possible to have multiple versions of service(s) deployed in production at the same time. From my assumption, this should be pretty common pattern for microservice/api based projects or mobile projects. I want to know how do you do it and what are common pattern in industry for this kind of problems. It would be helpful if your answers around AWS environment or Kubernetes environment. Thanks in Advance.
2017/05/23
[ "https://Stackoverflow.com/questions/44124914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7261916/" ]
With AWS API Gateway you could deploy multiple versions of your code and switch between them from the mapping templates, as explained [here](https://aws.amazon.com/blogs/compute/using-api-gateway-mapping-templates-to-handle-changes-in-your-back-end-apis/). You might also want to look into [stage variables](http://docs.aws.amazon.com/apigateway/latest/developerguide/stage-variables.html).
Assuming your are exposing services over An HTTP REST API, the general standard is to always base line your service urls with a version. Eg, ``` /v1/account/getUserInfo ``` If you need to release a new version, expose it over: ``` /v2/account/getUserInfo ``` Where v2 can run over a different branch of the codebase.
44,124,914
Is it possible to have multiple versions of service(s) deployed in production at the same time. From my assumption, this should be pretty common pattern for microservice/api based projects or mobile projects. I want to know how do you do it and what are common pattern in industry for this kind of problems. It would be helpful if your answers around AWS environment or Kubernetes environment. Thanks in Advance.
2017/05/23
[ "https://Stackoverflow.com/questions/44124914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7261916/" ]
> > Is it possible to have multiple versions of service(s) deployed in production at the same time > > > Yes, it is possible. The idea is to keep all *used* microservices in production (v1, v2 ...) at the same time and to bring down the versions that are not used anymore. For this, you *should* somehow know when a version is not used anymore. AFAIK, you have to options: 1. For every new version you make a new endpoint (like /v2/someApiCall) that is connected to the same (now upgraded) microservice and gradually instruct clients to use the new endpoind; when the old endpoint is not used anymore you deleted it; this is the preferred way. 2. For every new version you make a new microservice that share the same persistence with the old microservice; you should avoid the use of this solution; Netflix uses this strategy in *rare* occasions when the cost of changing old consumers is too high. You can read more at page 62 from [Building microservices by Sam Newman](https://rads.stackoverflow.com/amzn/click/com/1491950358).
With AWS API Gateway you could deploy multiple versions of your code and switch between them from the mapping templates, as explained [here](https://aws.amazon.com/blogs/compute/using-api-gateway-mapping-templates-to-handle-changes-in-your-back-end-apis/). You might also want to look into [stage variables](http://docs.aws.amazon.com/apigateway/latest/developerguide/stage-variables.html).
44,124,914
Is it possible to have multiple versions of service(s) deployed in production at the same time. From my assumption, this should be pretty common pattern for microservice/api based projects or mobile projects. I want to know how do you do it and what are common pattern in industry for this kind of problems. It would be helpful if your answers around AWS environment or Kubernetes environment. Thanks in Advance.
2017/05/23
[ "https://Stackoverflow.com/questions/44124914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7261916/" ]
> > Is it possible to have multiple versions of service(s) deployed in production at the same time > > > Yes, it is possible. The idea is to keep all *used* microservices in production (v1, v2 ...) at the same time and to bring down the versions that are not used anymore. For this, you *should* somehow know when a version is not used anymore. AFAIK, you have to options: 1. For every new version you make a new endpoint (like /v2/someApiCall) that is connected to the same (now upgraded) microservice and gradually instruct clients to use the new endpoind; when the old endpoint is not used anymore you deleted it; this is the preferred way. 2. For every new version you make a new microservice that share the same persistence with the old microservice; you should avoid the use of this solution; Netflix uses this strategy in *rare* occasions when the cost of changing old consumers is too high. You can read more at page 62 from [Building microservices by Sam Newman](https://rads.stackoverflow.com/amzn/click/com/1491950358).
I have blogged about this: [Multi-version Service Discovery using Spring Cloud Netflix Eureka and Ribbon](http://tech.asimio.net/2017/03/06/Multi-version-Service-Discovery-using-Spring-Cloud-Netflix-Eureka-and-Ribbon.html), focussed on `Spring Cloud Netflix` components / libraries though. But the idea is to deploy a new version of the artifact / binary in a new host / VPS / Container and have the service register with a registry server (Eureka, Consul, ....) and include metadata about the API versions it supports (v1, v2, ...). Client apps would discover which host / container / ... serves the API version needed.
44,124,914
Is it possible to have multiple versions of service(s) deployed in production at the same time. From my assumption, this should be pretty common pattern for microservice/api based projects or mobile projects. I want to know how do you do it and what are common pattern in industry for this kind of problems. It would be helpful if your answers around AWS environment or Kubernetes environment. Thanks in Advance.
2017/05/23
[ "https://Stackoverflow.com/questions/44124914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7261916/" ]
With AWS API Gateway you could deploy multiple versions of your code and switch between them from the mapping templates, as explained [here](https://aws.amazon.com/blogs/compute/using-api-gateway-mapping-templates-to-handle-changes-in-your-back-end-apis/). You might also want to look into [stage variables](http://docs.aws.amazon.com/apigateway/latest/developerguide/stage-variables.html).
I have blogged about this: [Multi-version Service Discovery using Spring Cloud Netflix Eureka and Ribbon](http://tech.asimio.net/2017/03/06/Multi-version-Service-Discovery-using-Spring-Cloud-Netflix-Eureka-and-Ribbon.html), focussed on `Spring Cloud Netflix` components / libraries though. But the idea is to deploy a new version of the artifact / binary in a new host / VPS / Container and have the service register with a registry server (Eureka, Consul, ....) and include metadata about the API versions it supports (v1, v2, ...). Client apps would discover which host / container / ... serves the API version needed.
11,083,069
I am developing a Java web application in `Netbeans IDE 7.1.1`. The IDE comes with pre-installed `Apache Tomcat 7.0`. The folder structure in Netbeans looks like this ![enter image description here](https://i.stack.imgur.com/6gAhh.jpg) All the servlet are in `Source Packages` and have added two in `Libraries` - MySQL JDBC Driver and Apache Commons Collection in `Libraries` folder. Now I want to deploy this on `Amazon Web Services - Elastic Beanstalk'. The documentation of AWS Elastic Beanstalk (beta) says`Package your deployable code into a standard Java Web Application Archive (WAR file) and Upload your WAR file to Elastic Beanstalk using the AWS Management Console` **My Question** How to package my deployable code into `WAR file`?
2012/06/18
[ "https://Stackoverflow.com/questions/11083069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932307/" ]
If you are already running your app, then `WAR` should be in `Files/dist` folder in the root of your project. Otherwise deploying your app should create this folder with the war file.
**With NetBeans 7.2, you can use the new cloud feature:** <http://wiki.netbeans.org/AmazonBeanstalkSupport> :-)
11,083,069
I am developing a Java web application in `Netbeans IDE 7.1.1`. The IDE comes with pre-installed `Apache Tomcat 7.0`. The folder structure in Netbeans looks like this ![enter image description here](https://i.stack.imgur.com/6gAhh.jpg) All the servlet are in `Source Packages` and have added two in `Libraries` - MySQL JDBC Driver and Apache Commons Collection in `Libraries` folder. Now I want to deploy this on `Amazon Web Services - Elastic Beanstalk'. The documentation of AWS Elastic Beanstalk (beta) says`Package your deployable code into a standard Java Web Application Archive (WAR file) and Upload your WAR file to Elastic Beanstalk using the AWS Management Console` **My Question** How to package my deployable code into `WAR file`?
2012/06/18
[ "https://Stackoverflow.com/questions/11083069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932307/" ]
If you are already running your app, then `WAR` should be in `Files/dist` folder in the root of your project. Otherwise deploying your app should create this folder with the war file.
is the <http://wiki.netbeans.org/AmazonBeanstalkSupport> support gone in Netbeans 8? as I can't find it and also when search online it indicates that option only in NetBeans 7.2.
11,083,069
I am developing a Java web application in `Netbeans IDE 7.1.1`. The IDE comes with pre-installed `Apache Tomcat 7.0`. The folder structure in Netbeans looks like this ![enter image description here](https://i.stack.imgur.com/6gAhh.jpg) All the servlet are in `Source Packages` and have added two in `Libraries` - MySQL JDBC Driver and Apache Commons Collection in `Libraries` folder. Now I want to deploy this on `Amazon Web Services - Elastic Beanstalk'. The documentation of AWS Elastic Beanstalk (beta) says`Package your deployable code into a standard Java Web Application Archive (WAR file) and Upload your WAR file to Elastic Beanstalk using the AWS Management Console` **My Question** How to package my deployable code into `WAR file`?
2012/06/18
[ "https://Stackoverflow.com/questions/11083069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932307/" ]
**With NetBeans 7.2, you can use the new cloud feature:** <http://wiki.netbeans.org/AmazonBeanstalkSupport> :-)
is the <http://wiki.netbeans.org/AmazonBeanstalkSupport> support gone in Netbeans 8? as I can't find it and also when search online it indicates that option only in NetBeans 7.2.
64,629,210
I have containers running in docker-compose networks on a remote VPS. I would like to be able to access a database running in one of these containers from my localhost. Eg, if the containers `app` and `db` are in a container network on the VPS, I want to access `db:5432` from *my machine's* `localhost:5432`. Kubernetes' CLI allows this with `kubectl port-forward <service-name> 5432:5432`. Are there any existing solutions to achieve this effect within existing unix commands and Docker's API? My searching around the Internet hasn't yielded any CLI to do this. Cheers. --- **Edit:** I have accepted Ali Tou's answer, however, it would be great to see a solution which does not require restarting a container to re-configure its ports to expose them onto the host. **Edit 2:** I found a clever method for forwarding traffic in the Docker network using socat in a tangentially-related post <https://stackoverflow.com/a/42071577/12406113>. This is, however, publicly exposing the port instead of creating a tunnel, such as in the SSH solution.
2020/11/01
[ "https://Stackoverflow.com/questions/64629210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12406113/" ]
Assuming you have SSH access to the target machine where the container is running, you can achieve this in two steps: 1. Expose container port into your VPS port, binding to its loopback IP for security: ```yaml ports: - 127.0.0.1:5432:5432 ``` 2. Use SSH port-forwarding to access port 5432 of that container: ```sh ssh -f -N -L 127.0.0.1:5432:127.0.0.1:5432 <VPS_IP> ``` The above command might seem confusing, but it's requesting SSH to listen on `127.0.0.1:5432` on your client system (first ip:port pair) and port forward its connections through an ssh tunnel to `127.0.0.1:5432` (second ip:port pair) of the remote system (demonstrated with `<VPS_IP>`). See [this answer](https://unix.stackexchange.com/a/156813/343873) for more info. Note that this ssh connection is persistent until your network remains connected. If you want to close this connection, do a `ps aux | grep ssh` to find PID of ssh-forwarding process, then use `sudo kill -9 $PID` to kill it. P.S. However, this is not different with the case you connect directly to `VPS_IP:5432` if you don't have security concerns.
You can just use ports section where you can specify host port and container port to forward request <https://docs.docker.com/compose/networking/>
28,261,312
I have searched a lot and tried many solutions but I can't get the server to run. I am trying to make a login app using `jsp` and `servlets`. First I created the `index.jsp` file which looks like this: ``` <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form name="loginform" action="login" method="post"> <p>User Name: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit"> </form> </body> </html> ``` When I selected the `Run on Server` option it worked just fine and displayed the form. After that I created a new servlet named `Login`: ``` package servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Login */ @WebServlet("/Login") public class Login extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Login() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("We are in Post method servlet"); String username = "user"; String password = "rood"; String un = request.getParameter(username); String pw = request.getParameter(password); String msg = " "; if (un.equals(username) && pw.equals(password)) { msg = "Hello " + un + " Your login is sucessful"; } else { msg = "Hello " + un + "Your login failed"; } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<font size='6' color=red>" + msg + "</font>"); } } ``` and I have configured the `web.xml` file like this: ``` <?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>LoginExample</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>Login</servlet-name> <servlet-class>servlets.Login</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>Login</url-pattern> </servlet-mapping> </web-app> ``` Now when I click again `Run on server` I get an error `Server Tomcat v7.0 Server at localhost failed to start.` I will post all the output I get in the console. I appologise for this post being so long but I said to post everything maybe it will be more easier for someone to figure it out what is wrong. So: ``` Feb 01, 2015 11:24:27 AM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:LoginExample' did not find a matching property. Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Server version: Apache Tomcat/7.0.57 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Server built: Nov 3 2014 08:39:16 UTC Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Server number: 7.0.57.0 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: OS Name: Windows 8.1 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: OS Version: 6.3 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Architecture: x86 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: JAVA_HOME: C:\Program Files\Java\jre1.8.0_31 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: JVM Version: 1.8.0_31-b13 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: JVM Vendor: Oracle Corporation Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: CATALINA_BASE: C:\Users\W7\Desktop\drept\.metadata\.plugins\org.eclipse.wst.server.core\tmp0 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: CATALINA_HOME: C:\Users\W7\Desktop\apache-tomcat-7.0.57 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dcatalina.base=C:\Users\W7\Desktop\drept\.metadata\.plugins\org.eclipse.wst.server.core\tmp0 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dcatalina.home=C:\Users\W7\Desktop\apache-tomcat-7.0.57 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dwtp.deploy=C:\Users\W7\Desktop\drept\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Djava.endorsed.dirs=C:\Users\W7\Desktop\apache-tomcat-7.0.57\endorsed Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dfile.encoding=Cp1252 Feb 01, 2015 11:24:28 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_31\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_31/bin/client;C:/Program Files/Java/jre1.8.0_31/bin;C:/Program Files/Java/jre1.8.0_31/lib/i386;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\MinGW\bin;C:\MinGW\msys\1.0\bin\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Qt\4.8.4\bin;C:\Users\W7\Documents\mingw\bin;C:\Program Files\Java\jdk1.7.0_17\bin;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\;C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\;C:\Program Files\Java\jdk1.8.0\bin;C:\strawberry\c\bin;C:\strawberry\perl\site\bin;C:\strawberry\perl\bin;C:\Dwimperl\perl\bin;C:\Dwimperl\perl\site\bin;C:\Dwimperl\c\bin;C:\Program Files\Rational\common;;C:\Users\W7\Desktop\eclipse-web\eclipse;;. Feb 01, 2015 11:24:28 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["http-bio-8080"] Feb 01, 2015 11:24:28 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["ajp-bio-8009"] Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 1466 ms Feb 01, 2015 11:24:28 AM org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina Feb 01, 2015 11:24:28 AM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/7.0.57 Feb 01, 2015 11:24:29 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [142] milliseconds. Feb 01, 2015 11:24:29 AM org.apache.catalina.core.ContainerBase startInternal SEVERE: A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/LoginExample]] at java.util.concurrent.FutureTask.report(Unknown Source) at java.util.concurrent.FutureTask.get(Unknown Source) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:816) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/LoginExample]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) ... 6 more Caused by: java.lang.IllegalArgumentException: Invalid <url-pattern> Login in servlet mapping at org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:3300) at org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:3275) at org.apache.catalina.deploy.WebXml.configureContext(WebXml.java:1438) at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1357) at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:889) at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:386) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5380) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 6 more Feb 01, 2015 11:24:29 AM org.apache.catalina.core.ContainerBase startInternal SEVERE: A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]] at java.util.concurrent.FutureTask.report(Unknown Source) at java.util.concurrent.FutureTask.get(Unknown Source) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123) at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.startup.Catalina.start(Catalina.java:689) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455) Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.apache.catalina.LifecycleException: A child container failed during start at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:816) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 6 more Feb 01, 2015 11:24:29 AM org.apache.catalina.startup.Catalina start SEVERE: The required Server component failed to start so Tomcat is unable to start. org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) at org.apache.catalina.startup.Catalina.start(Catalina.java:689) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455) Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 7 more Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 9 more Caused by: org.apache.catalina.LifecycleException: A child container failed during start at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131) at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 11 more Feb 01, 2015 11:24:29 AM org.apache.coyote.AbstractProtocol pause INFO: Pausing ProtocolHandler ["http-bio-8080"] Feb 01, 2015 11:24:29 AM org.apache.coyote.AbstractProtocol pause INFO: Pausing ProtocolHandler ["ajp-bio-8009"] Feb 01, 2015 11:24:29 AM org.apache.catalina.core.StandardService stopInternal INFO: Stopping service Catalina Feb 01, 2015 11:24:29 AM org.apache.coyote.AbstractProtocol destroy INFO: Destroying ProtocolHandler ["http-bio-8080"] Feb 01, 2015 11:24:29 AM org.apache.coyote.AbstractProtocol destroy INFO: Destroying ProtocolHandler ["ajp-bio-8009"] ``` I will be really greatful if someone could help me solve my problem, so that I can move on.Thanks!
2015/02/01
[ "https://Stackoverflow.com/questions/28261312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3845409/" ]
That is the root cause of the error: ``` Caused by: java.lang.IllegalArgumentException: Invalid <url-pattern> Login in servlet mapping ``` Think you have to change: ``` <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>Login</url-pattern> </servlet-mapping> ``` To: ``` <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/Login</url-pattern> </servlet-mapping> ```
You are using web.xml version 3.0 http://java.sun.com/xml/ns/javaee/web-app\_3\_0.xsd" id="WebApp\_ID" \*\*version="3.0"\*\*> Its not mandatory to make ur servlets entry in web.xml. Just try to remove it from web.xml. and put this line before class defination starts. @WebServlet("/Login") now try to hit url: localhost:port on which ur server is running (Default is 8080)/project\_name/Login
28,261,312
I have searched a lot and tried many solutions but I can't get the server to run. I am trying to make a login app using `jsp` and `servlets`. First I created the `index.jsp` file which looks like this: ``` <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form name="loginform" action="login" method="post"> <p>User Name: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit"> </form> </body> </html> ``` When I selected the `Run on Server` option it worked just fine and displayed the form. After that I created a new servlet named `Login`: ``` package servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Login */ @WebServlet("/Login") public class Login extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Login() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("We are in Post method servlet"); String username = "user"; String password = "rood"; String un = request.getParameter(username); String pw = request.getParameter(password); String msg = " "; if (un.equals(username) && pw.equals(password)) { msg = "Hello " + un + " Your login is sucessful"; } else { msg = "Hello " + un + "Your login failed"; } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<font size='6' color=red>" + msg + "</font>"); } } ``` and I have configured the `web.xml` file like this: ``` <?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>LoginExample</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>Login</servlet-name> <servlet-class>servlets.Login</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>Login</url-pattern> </servlet-mapping> </web-app> ``` Now when I click again `Run on server` I get an error `Server Tomcat v7.0 Server at localhost failed to start.` I will post all the output I get in the console. I appologise for this post being so long but I said to post everything maybe it will be more easier for someone to figure it out what is wrong. So: ``` Feb 01, 2015 11:24:27 AM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:LoginExample' did not find a matching property. Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Server version: Apache Tomcat/7.0.57 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Server built: Nov 3 2014 08:39:16 UTC Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Server number: 7.0.57.0 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: OS Name: Windows 8.1 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: OS Version: 6.3 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Architecture: x86 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: JAVA_HOME: C:\Program Files\Java\jre1.8.0_31 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: JVM Version: 1.8.0_31-b13 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: JVM Vendor: Oracle Corporation Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: CATALINA_BASE: C:\Users\W7\Desktop\drept\.metadata\.plugins\org.eclipse.wst.server.core\tmp0 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: CATALINA_HOME: C:\Users\W7\Desktop\apache-tomcat-7.0.57 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dcatalina.base=C:\Users\W7\Desktop\drept\.metadata\.plugins\org.eclipse.wst.server.core\tmp0 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dcatalina.home=C:\Users\W7\Desktop\apache-tomcat-7.0.57 Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dwtp.deploy=C:\Users\W7\Desktop\drept\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Djava.endorsed.dirs=C:\Users\W7\Desktop\apache-tomcat-7.0.57\endorsed Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dfile.encoding=Cp1252 Feb 01, 2015 11:24:28 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_31\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_31/bin/client;C:/Program Files/Java/jre1.8.0_31/bin;C:/Program Files/Java/jre1.8.0_31/lib/i386;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\MinGW\bin;C:\MinGW\msys\1.0\bin\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Qt\4.8.4\bin;C:\Users\W7\Documents\mingw\bin;C:\Program Files\Java\jdk1.7.0_17\bin;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\;C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\;C:\Program Files\Java\jdk1.8.0\bin;C:\strawberry\c\bin;C:\strawberry\perl\site\bin;C:\strawberry\perl\bin;C:\Dwimperl\perl\bin;C:\Dwimperl\perl\site\bin;C:\Dwimperl\c\bin;C:\Program Files\Rational\common;;C:\Users\W7\Desktop\eclipse-web\eclipse;;. Feb 01, 2015 11:24:28 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["http-bio-8080"] Feb 01, 2015 11:24:28 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["ajp-bio-8009"] Feb 01, 2015 11:24:28 AM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 1466 ms Feb 01, 2015 11:24:28 AM org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina Feb 01, 2015 11:24:28 AM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/7.0.57 Feb 01, 2015 11:24:29 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [142] milliseconds. Feb 01, 2015 11:24:29 AM org.apache.catalina.core.ContainerBase startInternal SEVERE: A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/LoginExample]] at java.util.concurrent.FutureTask.report(Unknown Source) at java.util.concurrent.FutureTask.get(Unknown Source) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:816) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/LoginExample]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) ... 6 more Caused by: java.lang.IllegalArgumentException: Invalid <url-pattern> Login in servlet mapping at org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:3300) at org.apache.catalina.core.StandardContext.addServletMapping(StandardContext.java:3275) at org.apache.catalina.deploy.WebXml.configureContext(WebXml.java:1438) at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1357) at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:889) at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:386) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5380) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 6 more Feb 01, 2015 11:24:29 AM org.apache.catalina.core.ContainerBase startInternal SEVERE: A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]] at java.util.concurrent.FutureTask.report(Unknown Source) at java.util.concurrent.FutureTask.get(Unknown Source) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123) at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.startup.Catalina.start(Catalina.java:689) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455) Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.apache.catalina.LifecycleException: A child container failed during start at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:816) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 6 more Feb 01, 2015 11:24:29 AM org.apache.catalina.startup.Catalina start SEVERE: The required Server component failed to start so Tomcat is unable to start. org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) at org.apache.catalina.startup.Catalina.start(Catalina.java:689) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455) Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 7 more Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 9 more Caused by: org.apache.catalina.LifecycleException: A child container failed during start at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131) at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 11 more Feb 01, 2015 11:24:29 AM org.apache.coyote.AbstractProtocol pause INFO: Pausing ProtocolHandler ["http-bio-8080"] Feb 01, 2015 11:24:29 AM org.apache.coyote.AbstractProtocol pause INFO: Pausing ProtocolHandler ["ajp-bio-8009"] Feb 01, 2015 11:24:29 AM org.apache.catalina.core.StandardService stopInternal INFO: Stopping service Catalina Feb 01, 2015 11:24:29 AM org.apache.coyote.AbstractProtocol destroy INFO: Destroying ProtocolHandler ["http-bio-8080"] Feb 01, 2015 11:24:29 AM org.apache.coyote.AbstractProtocol destroy INFO: Destroying ProtocolHandler ["ajp-bio-8009"] ``` I will be really greatful if someone could help me solve my problem, so that I can move on.Thanks!
2015/02/01
[ "https://Stackoverflow.com/questions/28261312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3845409/" ]
``` Since you have added @WebServlet("/Login") , so no need to map url pattern again in web.xml remove this tags from web.xml and run again or remove @WebServlet("/Login") and keep tags in web.xml and change action in form as action="/Login". <servlet> <servlet-name>Login</servlet-name> <servlet-class>servlets.Login</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>Login</url-pattern> </servlet-mapping> ```
You are using web.xml version 3.0 http://java.sun.com/xml/ns/javaee/web-app\_3\_0.xsd" id="WebApp\_ID" \*\*version="3.0"\*\*> Its not mandatory to make ur servlets entry in web.xml. Just try to remove it from web.xml. and put this line before class defination starts. @WebServlet("/Login") now try to hit url: localhost:port on which ur server is running (Default is 8080)/project\_name/Login
62,652,044
*I have reviewed several great Questions along the way, so many that I earned my badge for 40 votes in one day. But, nearly all Questions use a non-Vanilla dependency like jQuery or don't address my specific need. Here are two examples of wonderful, yet to-my-sorrow unrelated, Questions:* * *[Ajax Form submit with preventDefault](https://stackoverflow.com/questions/20352799/ajax-form-submit-with-preventdefault) (jQuery)* * *[preventDefault() on $.ajax complete](https://stackoverflow.com/questions/52485085/preventdefault-on-ajax-complete) (jQuery, and its pilgrimage of dup dups)* *I'm surprised this Question has not been asked because I don't regard myself to be so imaginative. If this Question is already out there, I want to please open a Meta discussion on how to update that Question so searches can find it.* The situation: ============== This is Vanilla JS, no dependencies. The script uses `preventDefault()` to interrupt a `form`-`submit` button identified by `id` and call AJAX instead. AJAX works and changes content correctly. Then, the problem begins... This AJAX responds with a replaced `div` containing the same `form` that `preventDefault()` interrupts. But, AJAX doesn't recognize that updated `form`-`submit` button after the AJAX response JS-alters the `div` containing that `form` with the same `id`. Workflow: --------- 1. HTML -> `<form id="same">` (success) 2. `<form id="same">` -> AJAX (success, first AJAX call) 3. AJAX -> `<form id="same">` (success, first AJAX response) 4. `<form id="same">` -> AJAX (broken, second AJAX call) It works the first time only; I need it to work infinitely. ----------------------------------------------------------- Note, I need to process this specific `form`. Other elements, including possible other forms, may be included in this `div` that AJAX changes. The code: ========= **index.php**: (AJAX adapted from [MDN - Sending forms through JavaScript: Using FormData bound to a form element](https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript#Using_FormData_bound_to_a_form_element)) ```html <script> window.addEventListener( "load", function () { function sendData() { const AJAX = new XMLHttpRequest(); // AJAX handler const FD = new FormData( form ); // Bind to-send data to form element AJAX.addEventListener( "load", function(event) { document.getElementById("ajax_changes").innerHTML = event.target.responseText; } ); // Change HTML on successful response AJAX.addEventListener( "error", function( event ) { document.getElementById("ajax_changes").innerHTML = 'Oops! Something went wrong.'; } ); AJAX.open( "POST", "ajax_responder.php" ); // Send data, ajax_responder.php can be any file or URL AJAX.send( FD ); // Data sent is from the form } // sendData() function const form = document.getElementById( "ajaxForm" ); // Access <form id="ajaxForm">, id="ajaxForm" can be anything form.addEventListener( "submit", function ( event ) { // Takeover <input type="submit"> event.preventDefault(); sendData(); } ); } ); </script> <div id="ajax_changes">Replace me with AJAX<br> <form id="ajaxForm"> <input type="text" value="AJAX" name="foo"> <input type="text" value="5" name="bar"> <input type="submit" value="Form AJAX!"> </form> <!-- Possible other HTML elements and/or forms I do not want to process with that same AJAX --> </div> ``` **ajax\_responder.php** : ```php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $foo = $_POST['foo']; $bar = $_POST['bar']; echo ' '.$foo.' <br> '.$bar.' <br> <form id="ajaxForm"> <input type="text" value="'.$foo.'" name="foo"> <input type="text" value="'.$bar.'" name="bar"> <input type="submit" value="Form AJAX!"> </form> <!-- Possible other HTML elements and/or forms --> '; } ``` The question ============ What is the "right" way to get AJAX to keep acting on the same response-contained `form`-`submit` element? ---------------------------------------------------------------------------------------------------------- I have considered ways that do not respond with the same `form`: * Having AJAX only respond and change specific, small elements * Relocating the `form` outside of the AJAX-changed content But both of those seem complicated. There must be some way to tell AJAX to `preventDefault()` on a `form`-`submit` button *after* that button has been updated by AJAX. I just don't know what that way is. Or, is there another solution that still involves Vanilla JS?
2020/06/30
[ "https://Stackoverflow.com/questions/62652044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10343144/" ]
You are binding the eventListener to the `<form>` `ajaxForm`. Then you replace it (= remove `<form>` from DOM and add new `<form>` to the DOM). In that case the eventListener is also removed. To have an eventListener on the new form, you can either: • Replace only the content of the `<form>`. In that case the DOM element isn't removed and so the eventListener keeps intact (don't forget to remove the `<form>` tag in the php response). This is imho the easiest way. ``` document.getElementById("ajaxForm").innerHTML= event.target.responseText; ``` • Bind a new eventListener everytime the `<form>` is changed: ``` AJAX.addEventListener( "load", function(event) { document.getElementById("ajax_changes").innerHTML = event.target.responseText; //=====> bind new eventListener here <====== } ); ``` You can create a function that can be called on load as well in the ajax response ``` function addListenerToForm(){ document.getElementById( "ajaxForm" ).addEventListener( "submit", function ( event ) { event.preventDefault(); sendData(); }); } ``` • bind the eventListener once to the container `<div>` ``` document.getElementById( "ajax_changes" ).addEventListener( "submit", function ( event ) { event.preventDefault(); sendData(); }); function sendData(){ const AJAX = new XMLHttpRequest(); // AJAX handler const form = document.getElementById( "ajaxForm"); const FD = new FormData( form ); ... } ```
Given the [above answer](https://stackoverflow.com/a/62652938/10343144)'s solution *"Bind a new eventListener everytime the `<form>` is changed"*, I changed `const` ```js const form = document.getElementById( "ajaxForm" ); ``` to `var` ```js var form = document.getElementById( "ajaxForm" ); ``` Then placed it with its listener in this line ```js //=====> bind new eventListener here <====== ``` without any declaration as ```js form = document.getElementById( "ajaxForm" ); form.addEventListener( "submit", function ( event ) {... ``` And it worked! Many thanks! I am a happy coding potato. My new JavaScript was: ```js <script> window.addEventListener( "load", function () { function sendData() { const AJAX = new XMLHttpRequest(); // AJAX handler const FD = new FormData( form ); // Bind to-send data to form element AJAX.addEventListener( "load", function(event) { document.getElementById("ajax_changes").innerHTML = event.target.responseText; } ); // Change HTML on successful response AJAX.addEventListener( "error", function( event ) { document.getElementById("ajax_changes").innerHTML = 'Oops! Something went wrong.'; } ); AJAX.open( "POST", "ajax_responder.php" ); // Send data, ajax_responder.php can be any file or URL AJAX.send( FD ); // Data sent is from the form AJAX.addEventListener( "load", function(event) { document.getElementById("ajax_changes").innerHTML = event.target.responseText; // Bind a new eventListener everytime the <form> is changed: form = document.getElementById( "ajaxForm" ); // Access <form id="ajaxForm">, id="ajaxForm" can be anything form.addEventListener( "submit", function ( event ) { // Takeover <input type="submit"> event.preventDefault(); sendData(); } ); // End new event listener } ); } // sendData() function var form = document.getElementById( "ajaxForm" ); // Access <form id="ajaxForm">, id="ajaxForm" can be anything form.addEventListener( "submit", function ( event ) { // Takeover <input type="submit"> event.preventDefault(); sendData(); } ); } ); </script> ```
44,845,638
I am trying to retrieve time data from MongoDB using AngularJS. The tricky part is that I am using MongoJS without having a schema for my time data thus I cannot query it directly. Whenever I pull data from my database, I receive it in a format of: > > 2017-06-29T23:00:00.000Z > > > my main issue is that I don't use schema to set up a specific format of the data and I want it to display in: > > dd/mm/yyyy > > > This is my NodeJS code used for the overall data input, get, delete and edit: ``` app.post('/posts', function(req,res){ dbc.posts.insert(req.body, function(err, doc){ res.json(doc); }) }); app.delete('/posts/:id', function(req,res){ var id = req.params.id; console.log(id); dbc.posts.remove({_id: mongojs.ObjectId(id)}, function(err, doc){ res.json(doc); }) }); app.get('/posts/:id', function(req,res){ var id = req.params.id; console.log(id); dbc.posts.findOne({_id: mongojs.ObjectId(id)}, function(err, doc){ res.json(doc); }); }); app.put('/posts/:id', function(req, res){ var id = req.params.id; console.log(req.body.system); dbc.posts.findAndModify({query:{_id:mongojs.ObjectId(id)}, update: {$set: {issue: req.body.issue, system: req.body.system, date: req.body.date, priority: req.body.priority, description: req.body.description, status: req.body.status}}, new:true}, function(err, doc){ res.json(doc); console.log(req.body.date); }); }); ``` > > How can I filter my data in my **AngularJS** controller to display it > in the format I want, since I don't use a specific schema for the > database? > > >
2017/06/30
[ "https://Stackoverflow.com/questions/44845638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5894918/" ]
There is a time filter that angularjs provides by defualt. You can use it directly ``` {{ date_expression | date : format : timezone}} ``` Read the docs [here](https://docs.angularjs.org/api/ng/filter/date) You can change this to suit your need. ``` {{date_expression| date:'dd MMM, yyyy '}} ```
[MomentJs](https://momentjs.com/) is always batter option if we talk about date formatting or date conversion. so in controller you need to create a helper function like: ``` function getFormateDate(date){ moment(date).format("DD/MM/YYYY") } ``` and don't forget to add this script in index.html ``` <script type="text/javascript" src="https://momentjs.com/downloads/moment.min.js"></script> ``` For more details you can check : <https://momentjs.com/>
38,646,631
I ran a Flask boilerplate app running on Docker using `docker run -d -p 80:80 p0bailey/docker-flask` and it works (`192.168.99.100` displayed a page). Next I cloned same app from [github](https://github.com/p0bailey/docker-flask) and try to mount from host directory into container using: ``` docker run -d -p 80:80 -v /Users/username/docker-flask/app:/var/www/app p0bailey/docker-flask ``` I went to url `92.168.99.100` and got `502 Bad Gateway` What am I doing wrong? Host is a cent os 7 ``` $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 721e7cfac4de p0bailey/docker-flask "/usr/bin/supervisord" 10 seconds ago Up 8 seconds 0.0.0.0:80->80/tcp stoic_newton ``` Here's the log ``` $ docker logs 721e7cfac4de /usr/lib/python2.7/dist-packages/supervisor/options.py:295: UserWarning: Supervisord is running as root and it is searching for its configuration file in default locations (including its current working directory); you probably want to specify a "-c" argument specifying an absolute path to a configuration file for improved security. 'Supervisord is running as root and it is searching ' 2016-07-28 21:14:32,788 CRIT Supervisor running as root (no user in config file) 2016-07-28 21:14:32,788 WARN Included extra file "/etc/supervisor/conf.d/supervisord.conf" during parsing 2016-07-28 21:14:32,808 INFO RPC interface 'supervisor' initialized 2016-07-28 21:14:32,808 CRIT Server 'unix_http_server' running without any HTTP authentication checking 2016-07-28 21:14:32,808 INFO supervisord started with pid 1 2016-07-28 21:14:33,812 INFO spawned: 'nginx' with pid 10 2016-07-28 21:14:33,813 INFO spawned: 'uwsgi' with pid 11 2016-07-28 21:14:33,869 INFO exited: uwsgi (exit status 1; not expected) 2016-07-28 21:14:34,908 INFO success: nginx entered RUNNING state, process has stayed up for > than 1 seconds (startsecs) 2016-07-28 21:14:34,909 INFO spawned: 'uwsgi' with pid 16 2016-07-28 21:14:34,915 INFO exited: uwsgi (exit status 1; not expected) 2016-07-28 21:14:36,920 INFO spawned: 'uwsgi' with pid 17 2016-07-28 21:14:36,926 INFO exited: uwsgi (exit status 1; not expected) 2016-07-28 21:14:39,934 INFO spawned: 'uwsgi' with pid 18 2016-07-28 21:14:39,942 INFO exited: uwsgi (exit status 1; not expected) 2016-07-28 21:14:40,943 INFO gave up: uwsgi entered FATAL state, too many start retries too quickly ```
2016/07/28
[ "https://Stackoverflow.com/questions/38646631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1102806/" ]
My understanding that by "c" you meant "i" and by "d" you meant "f" Below does this. It identifies those Prod's that are in "i" group but not in "f" group ``` SELECT Prod FROM ( SELECT Prod, CONCAT('|', GROUP_CONCAT_UNQUOTED(group, '|'), '|') AS list FROM YourTable GROUP BY Prod ) WHERE list CONTAINS '|i|' AND NOT list CONTAINS '|f|' ``` You can test this with below ``` SELECT Prod FROM ( SELECT Prod, CONCAT('|', GROUP_CONCAT_UNQUOTED(group, '|'), '|') AS list FROM (SELECT 'prod1' AS Prod, 'i' AS group), (SELECT 'prod1' AS Prod, 'f' AS group), (SELECT 'prod1' AS Prod, 'f' AS group), (SELECT 'prod2' AS Prod, 'i' AS group), (SELECT 'prod3' AS Prod, 'i' AS group), (SELECT 'prod4' AS Prod, 'i' AS group), (SELECT 'prod4' AS Prod, 'f' AS group), (SELECT 'prod4' AS Prod, 'f' AS group), (SELECT 'prod4' AS Prod, 'f' AS group), GROUP BY Prod ) WHERE list CONTAINS '|i|' AND NOT list CONTAINS '|f|' ``` so you final query can look something like ``` SELECT <list of needed fields> FROM YourTable WHERE Prod IN ( SELECT Prod FROM ( SELECT Prod, CONCAT('|', GROUP_CONCAT_UNQUOTED(group, '|'), '|') AS list FROM YourTable GROUP BY Prod ) WHERE list CONTAINS '|i|' AND NOT list CONTAINS '|f|' ) ```
By using the most basic of SQL i.e. use `WHERE`: ``` SELECT <the_cols_you_want> FROM [<Dataset.Table>] WHERE Prod in ('prod2','prod3') and Group = 'i' ``` * <https://cloud.google.com/bigquery/query-reference> * <https://cloud.google.com/bigquery/sql-reference/>
69,214,301
Running elasticsearch in win10 [wsl2] docker-desktop requires to increase mmap counts to 262144 through `sysctl -w vm.max_map_count=262144` ``` C:\Users\<username>>wsl -d docker-desktop <hostname>:/tmp/docker-desktop-root/mnt/host/c/Users/<username># sysctl -w vm.max_map_count=262144 ``` In [an answer to this question](https://stackoverflow.com/questions/56937171/efk-elasticsearch-1-exited-with-code-78-when-install-elasticsearch#56982026) and [elastic's doc](https://www.elastic.co/guide/en/elasticsearch/reference/current/vm-max-map-count.html) it is suggested to accordingly update the `vm.max_map_count` in `/etc/sysctl.conf` to set this value permanent, i. e. making it survive the reboot. Please note the output below, showing the effective mmap count did not adapt to the value defined in sysctl.conf, after my attempt to follow this suggestion and after reboot. Why didn't it? ``` PS C:\Users\<username>> wsl -d docker-desktop <hostname>:/tmp/docker-desktop-root/mnt/host/c/Users/<username># sysctl vm.max_map_count vm.max_map_count = 65530 <hostname>:/tmp/docker-desktop-root/mnt/host/c/Users/<username># cd /etc <hostname>:/etc# cat sysctl.conf # content of this file will override /etc/sysctl.d/* vm.max_map_count=262144 ``` Considering to have changed the wrong sysctl.conf in `etc/` I tried to change the sysctl.conf in `<hostname>:/tmp/docker-desktop-root/etc#`. This was not allowed as this is a `Read-only file system`. Can/should this be parameterized in .wslconfig instead, if so, how? Using openSUSE Leap 15.2 instead of Win10's PowerShell did not change the outcome. ``` <username@hostname>:~> sysctl vm.max_map_count vm.max_map_count = 65530 <username@hostname>:~> cat /etc/sysctl.conf #### # # /etc/sysctl.conf is meant for local sysctl settings # # sysctl reads settings from the following locations: # /boot/sysctl.conf-<kernelversion> # /lib/sysctl.d/*.conf # /usr/lib/sysctl.d/*.conf # /usr/local/lib/sysctl.d/*.conf # /etc/sysctl.d/*.conf # /run/sysctl.d/*.conf # /etc/sysctl.conf # # To disable or override a distribution provided file just place a # file with the same name in /etc/sysctl.d/ # # See sysctl.conf(5), sysctl.d(5) and sysctl(8) for more information # #### vm.max_map_count=262144 ``` Notably, the header in the above sysctl.conf file refers to a `/boot/sysctl.conf-<kernelversion>`. Taking into account, mmap count might need to be defined in this file in order to be considered when booting, I tried to set the required parameter there, but had no permission to do so. ``` <username@hostname>:/boot> sudo echo 'vm.max_map_count=262144' >> sysctl.conf-5.10.16.3-microsoft-standard-WSL2 -bash: sysctl.conf-5.10.16.3-microsoft-standard-WSL2: Permission denied ``` One of the known issues and limitations reported in [openSUSE:WSL - openSUSE Wiki](https://en.opensuse.org/openSUSE:WSL) is > > A system in WSL does not actually boot and does not use systemd. A proprietary Microsoft /init binary initializes the system. Therefore service management does not work like in a VM. It rather behaves like an interactive container. > > > Can anyone verify this to be the reason why parameterizing sysctl.conf cannot be an effective approach to the purpose at hand? System ------ Host OS: Microsoft Windows 10 Enterprise Version: 10.0.18363 Build 18363 \ Docker Client: Version: 20.10.8 API version: 1.41 Go version: go1.16.6 Git commit: 3967b7d Built: Fri Jul 30 19:54:02 2021 OS/Arch: linux/amd64 Plugins: compose: Docker Compose (Docker Inc., v2.0.0-rc.2) scan: Docker Scan (Docker Inc., v0.8.0) Server: Engine: Version: 20.10.8 API version: 1.41 (minimum version 1.12) Go version: go1.16.6 Git commit: 75249d8 Built: Fri Jul 30 19:52:10 2021 OS/Arch: linux/amd64 containerd: Version: 1.4.9 GitCommit: e25210fe30a0a703442421b0f60afac609f950a3 runc: Version: 1.0.1 GitCommit: v1.0.1-0-g4144b63 docker-init: Version: 0.19.0 GitCommit: de40ad0 \ Kernel Version: 5.10.16.3-microsoft-standard-WSL2 Operating System: Docker Desktop OSType: linux Architecture: x86\_64 CPUs: 4 Total Memory: 12.39GiB Name: docker-desktop
2021/09/16
[ "https://Stackoverflow.com/questions/69214301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10071239/" ]
*Short answer:* In your Windows `%userprofile%` directory (typically `C:\Users\<username>`) create or edit the file `.wslconfig` with the following: ``` [wsl2] kernelCommandLine = "sysctl.vm.max_map_count=262144" ``` Then exit any WSL instance, `wsl --shutdown`, and restart. ``` > sysctl vm.max_map_count vm.max_map_count = 262144 ``` --- *More Detail:* You really have three (closely related) questions: * (Mainly) How to best persist this setting * Can it be done via `.wslconfig`? > > *Can/should this be parameterized in .wslconfig instead, if so, how?* > > > * Why isn't `/etc/sysctl.conf` working to persist it? > > */etc/sysctl.conf to set this value permanent, i. e. making it survive the reboot .... Why didn't it?* > > > We'll combine the first two, since the answer is "Yes, you can do it via `.wslconfig`. This wasn't easy to find, since the change is fairly recent. It comes curtesy [this answer](https://unix.stackexchange.com/a/593688/432493). Starting with kernel release 5.8, you can set `sysctl` values on the kernel command-line using the `sysctl.*` prefix to the value. So as long as you have upgraded your WSL kernel (which I had *not* on two of my systems since `wsl --update` only recently was released in 21H1), you can set your `%userprofile%\.wslconfig` as above. --- #### `/etc/sysctl.conf` > > */etc/sysctl.conf to set this value permanent, i. e. making it survive the reboot .... Why didn't it?* > > > There's a lot more to this section than is really needed since I went down this rabbit trail first and posted it as the original answer. But first, "why" it wasn't working ... This is a [known issue](https://github.com/microsoft/WSL/issues/4232) of sorts with WSL2. While `sysctl` and Systemd/`systemctl` are two completely different things, in that issue therealkenc (of the Microsoft WSL team) points out that *something* must read and process `/etc/sysctl.conf`. In most Linux distributions, that's Systemd or the SysVInit scripts. WSL, on the other, uses it's own `/init` in place of SysVInit or Systemd. The WSL init process does not (currently) have a mechanism for running services at startup, as you found in the openSUSE doc. So ... nothing reads and acts on `/etc/sysctl.conf` at startup. --- *The remainder of this answer includes some `systcl.conf` workarounds that aren't needed given we can do this with `.wslconfig`. This is left in just in case anyone finds it useful for some reason.* There are a few workarounds for this. All of them are going to involve finding a way to run `sysctl -w vm.max_map_count=262144` (as root) automatically: * First, in Windows 11, WSL has a new feature to simplify this. Simply create/edit `/etc/wsl.conf` (via `sudo`) with: ``` [boot] command="sysctl -w vm.max_map_count=262144" ``` This will run at root each time the WSL instance starts. As far as I know, this will also work from within the `docker-desktop` instance, but I have not been able to test that. **Important Note**: Please back up your WSL instance using `wsl --export`, or at least backup your Docker volumes, images, and containers, before attempting this change. It's my experience that it is possible via a stalled boot command to completely prevent the instance from booting, with no recovery mechanism that I have (yet) found. Fortunately, I was working in a newly installed test instance, so I was able to `wsl --unregister` it (completely destroying it) without losing anything other than a few minutes. --- For the many of us who will be on Windows 10 for some time to come, there are several options. Unfortunately I haven't been able to test these against Docker, but I've used similar techniques with other WSL instances in the past: * If Docker Desktop is set to run when you log in, then you could add a scheduled task (via Windows Task Scheduler) to also run at login. This would be a: + "Basic Task" + With the "Program" set to `wsl.exe` + And the Arguments set to `-d docker-desktop sh -c "sysctl -w vm.max_map_count=262144"`Note that if the docker-desktop WSL instance terminates at any point, then the change will be lost until next reboot. However, because Docker Desktop is running at boot/login, the instance *should* remain up with this change in place. --- * Depending on your workflow, this may or may not fit. If you are using a separate WSL instance (e.g. Ubuntu) for development purposes, you can have *that* instance modify the `docker-desktop` instance when you start up. So that you don't have to type the `sudo` password each time you start up, use the following line in your `.bashrc` (or equivalent): ``` wsl.exe -d docker-desktop sh -c "sysctl -w vm.max_map_count=262144" ``` --- One final suggestion -- Submit a feature request to the Docker Desktop team. It would, IMHO, be easiest for Docker Desktop's startup process to read `/etc/sysctl.conf` and process it accordingly.
I have Windows 10 with Docker Desktop and Git installed. Following the instructions provided by @NotTheDr01ds, I opened a Git bash console with: ``` $ wsl -d docker-desktop sh -c "sysctl -w vm.max_map_count=262144" vm.max_map_count = 262144 ``` After that change, SonarQube's ElasticSearch started with no error.
37,087,869
I've been trying to implement a basic cookie storage function in Javascript, which works as intended in most browsers, but not Safari (8.0.3). I've stripped it down to the below example, where every other browser changes the text to the date that is stored in the cookie, but Safari doesn't store a cookie at all and gives out an empty string (no error messages in the console either). Safari is set to accept all cookies. If I enter the code in the testbed at W3Schools.com, it works in every browser, so is it somehow related to the domain? (In JSFiddle it doesn't seem to work at all, with the console complaining that myFunction is not defined.) I've only found two older problems of the same type, but in one case the solution was adding the "; path=/" part, which is already in here, and in the other there was a comma in place of a semicolon. ``` <!DOCTYPE html> <html> <body> <p id="doesitwork" onclick="myFunction()">Does it work?</p> <script> function myFunction() { d = new Date(); document.cookie = (d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"); var x = document.cookie; document.getElementById("doesitwork").innerHTML = x; } </script> </body> </html> ```
2016/05/07
[ "https://Stackoverflow.com/questions/37087869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6303683/" ]
You can have a look at [this nice article](http://clubmate.fi/setting-and-reading-cookies-with-javascript/) and they show you a function for creating, reading and deleting cookies also it shows pure JS and jQuery. The code on the blog is shown like so: ``` // Create cookie function createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); expires = "; expires="+date.toGMTString(); } else { expires = ""; } document.cookie = name+"="+value+expires+"; path=/"; } // Read cookie function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1,c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); } } return null; } // Erase cookie function eraseCookie(name) { createCookie(name,"",-1); } ``` Creating cookies like this: ``` createCookie("cookie-name", "cookie-value", 30); ``` Reading cookie like this: ``` readCookie("cookie-name"); // Usually you set it as a variable and then use it somewhere var colorTheme = readCookie("color-theme"); // Then do some conditional crap with it if (colorTheme == "Blue") { // Add a class to the body or elswere } else { // Add a different class maybe... } ```
Well you are not setting a name value pair ``` document.cookie = (d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"); ``` should be something like ``` document.cookie = "time=" + d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"; ```
37,087,869
I've been trying to implement a basic cookie storage function in Javascript, which works as intended in most browsers, but not Safari (8.0.3). I've stripped it down to the below example, where every other browser changes the text to the date that is stored in the cookie, but Safari doesn't store a cookie at all and gives out an empty string (no error messages in the console either). Safari is set to accept all cookies. If I enter the code in the testbed at W3Schools.com, it works in every browser, so is it somehow related to the domain? (In JSFiddle it doesn't seem to work at all, with the console complaining that myFunction is not defined.) I've only found two older problems of the same type, but in one case the solution was adding the "; path=/" part, which is already in here, and in the other there was a comma in place of a semicolon. ``` <!DOCTYPE html> <html> <body> <p id="doesitwork" onclick="myFunction()">Does it work?</p> <script> function myFunction() { d = new Date(); document.cookie = (d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"); var x = document.cookie; document.getElementById("doesitwork").innerHTML = x; } </script> </body> </html> ```
2016/05/07
[ "https://Stackoverflow.com/questions/37087869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6303683/" ]
By default cookie not allowed for iOS safari browser. We have to enable cookies setting from safari browser So we have implemented local storage(javascript concept)to overcome the cookie problems in safari browser.
You can have a look at [this nice article](http://clubmate.fi/setting-and-reading-cookies-with-javascript/) and they show you a function for creating, reading and deleting cookies also it shows pure JS and jQuery. The code on the blog is shown like so: ``` // Create cookie function createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); expires = "; expires="+date.toGMTString(); } else { expires = ""; } document.cookie = name+"="+value+expires+"; path=/"; } // Read cookie function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1,c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); } } return null; } // Erase cookie function eraseCookie(name) { createCookie(name,"",-1); } ``` Creating cookies like this: ``` createCookie("cookie-name", "cookie-value", 30); ``` Reading cookie like this: ``` readCookie("cookie-name"); // Usually you set it as a variable and then use it somewhere var colorTheme = readCookie("color-theme"); // Then do some conditional crap with it if (colorTheme == "Blue") { // Add a class to the body or elswere } else { // Add a different class maybe... } ```
37,087,869
I've been trying to implement a basic cookie storage function in Javascript, which works as intended in most browsers, but not Safari (8.0.3). I've stripped it down to the below example, where every other browser changes the text to the date that is stored in the cookie, but Safari doesn't store a cookie at all and gives out an empty string (no error messages in the console either). Safari is set to accept all cookies. If I enter the code in the testbed at W3Schools.com, it works in every browser, so is it somehow related to the domain? (In JSFiddle it doesn't seem to work at all, with the console complaining that myFunction is not defined.) I've only found two older problems of the same type, but in one case the solution was adding the "; path=/" part, which is already in here, and in the other there was a comma in place of a semicolon. ``` <!DOCTYPE html> <html> <body> <p id="doesitwork" onclick="myFunction()">Does it work?</p> <script> function myFunction() { d = new Date(); document.cookie = (d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"); var x = document.cookie; document.getElementById("doesitwork").innerHTML = x; } </script> </body> </html> ```
2016/05/07
[ "https://Stackoverflow.com/questions/37087869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6303683/" ]
You can have a look at [this nice article](http://clubmate.fi/setting-and-reading-cookies-with-javascript/) and they show you a function for creating, reading and deleting cookies also it shows pure JS and jQuery. The code on the blog is shown like so: ``` // Create cookie function createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); expires = "; expires="+date.toGMTString(); } else { expires = ""; } document.cookie = name+"="+value+expires+"; path=/"; } // Read cookie function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1,c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); } } return null; } // Erase cookie function eraseCookie(name) { createCookie(name,"",-1); } ``` Creating cookies like this: ``` createCookie("cookie-name", "cookie-value", 30); ``` Reading cookie like this: ``` readCookie("cookie-name"); // Usually you set it as a variable and then use it somewhere var colorTheme = readCookie("color-theme"); // Then do some conditional crap with it if (colorTheme == "Blue") { // Add a class to the body or elswere } else { // Add a different class maybe... } ```
Best way to show/hide cookie in all the browser, including mobile browser also. **Demo:** <http://jsfiddle.net/a4fur7k3/1/> **Notes :** *By default message should be hidden* > > **HTML** > > > ``` <div id="es_cookie_msg" style="display:none;"> <div class="es-cookie-msg-container"> <!-- Cookie Message --> <span class="es-cookie-msg-text">We use cookies to help ensure our website meets your needs. By continuing to use this site you agree to our policy. </span> <!-- Close button --> <a id="es_cookie_close_btn" href="#" class="es-cookie-button"> <svg class="es_cookie_close_icon" width="64" version="1.1" xmlns="http://www.w3.org/2000/svg" height="64" viewBox="0 0 64 64" xmlns:xlink="http://www.w3.org/1999/xlink" enable-background="new 0 0 64 64"> <g> <path fill="" d="M28.941,31.786L0.613,60.114c-0.787,0.787-0.787,2.062,0,2.849c0.393,0.394,0.909,0.59,1.424,0.59 c0.516,0,1.031-0.196,1.424-0.59l28.541-28.541l28.541,28.541c0.394,0.394,0.909,0.59,1.424,0.59c0.515,0,1.031-0.196,1.424-0.59 c0.787-0.787,0.787-2.062,0-2.849L35.064,31.786L63.41,3.438c0.787-0.787,0.787-2.062,0-2.849c-0.787-0.786-2.062-0.786-2.848,0 L32.003,29.15L3.441,0.59c-0.787-0.786-2.061-0.786-2.848,0c-0.787,0.787-0.787,2.062,0,2.849L28.941,31.786z"></path> </g> </svg> </a> </div> </div> ``` > > **jQuery** > > > ``` jQuery( document ).ready(function() { jQuery('#es_cookie_close_btn').click(function() { jQuery('#es_cookie_msg').slideUp(); // Set cookie cookieHelper.create('accepted', true); }); }); jQuery(function () { // If cookie hasnt reveioly been accepted, show banner if( !cookieHelper.read('accepted') ) { jQuery('#es_cookie_msg').slideDown(); } }); // Cookies set inside object var cookieHelper = { // Cookies create: function (name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; }, read: function(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; }, erase: function(name) { createCookie(name, "", -1); } } ```
37,087,869
I've been trying to implement a basic cookie storage function in Javascript, which works as intended in most browsers, but not Safari (8.0.3). I've stripped it down to the below example, where every other browser changes the text to the date that is stored in the cookie, but Safari doesn't store a cookie at all and gives out an empty string (no error messages in the console either). Safari is set to accept all cookies. If I enter the code in the testbed at W3Schools.com, it works in every browser, so is it somehow related to the domain? (In JSFiddle it doesn't seem to work at all, with the console complaining that myFunction is not defined.) I've only found two older problems of the same type, but in one case the solution was adding the "; path=/" part, which is already in here, and in the other there was a comma in place of a semicolon. ``` <!DOCTYPE html> <html> <body> <p id="doesitwork" onclick="myFunction()">Does it work?</p> <script> function myFunction() { d = new Date(); document.cookie = (d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"); var x = document.cookie; document.getElementById("doesitwork").innerHTML = x; } </script> </body> </html> ```
2016/05/07
[ "https://Stackoverflow.com/questions/37087869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6303683/" ]
By default cookie not allowed for iOS safari browser. We have to enable cookies setting from safari browser So we have implemented local storage(javascript concept)to overcome the cookie problems in safari browser.
Well you are not setting a name value pair ``` document.cookie = (d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"); ``` should be something like ``` document.cookie = "time=" + d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"; ```
37,087,869
I've been trying to implement a basic cookie storage function in Javascript, which works as intended in most browsers, but not Safari (8.0.3). I've stripped it down to the below example, where every other browser changes the text to the date that is stored in the cookie, but Safari doesn't store a cookie at all and gives out an empty string (no error messages in the console either). Safari is set to accept all cookies. If I enter the code in the testbed at W3Schools.com, it works in every browser, so is it somehow related to the domain? (In JSFiddle it doesn't seem to work at all, with the console complaining that myFunction is not defined.) I've only found two older problems of the same type, but in one case the solution was adding the "; path=/" part, which is already in here, and in the other there was a comma in place of a semicolon. ``` <!DOCTYPE html> <html> <body> <p id="doesitwork" onclick="myFunction()">Does it work?</p> <script> function myFunction() { d = new Date(); document.cookie = (d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"); var x = document.cookie; document.getElementById("doesitwork").innerHTML = x; } </script> </body> </html> ```
2016/05/07
[ "https://Stackoverflow.com/questions/37087869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6303683/" ]
Well you are not setting a name value pair ``` document.cookie = (d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"); ``` should be something like ``` document.cookie = "time=" + d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"; ```
Best way to show/hide cookie in all the browser, including mobile browser also. **Demo:** <http://jsfiddle.net/a4fur7k3/1/> **Notes :** *By default message should be hidden* > > **HTML** > > > ``` <div id="es_cookie_msg" style="display:none;"> <div class="es-cookie-msg-container"> <!-- Cookie Message --> <span class="es-cookie-msg-text">We use cookies to help ensure our website meets your needs. By continuing to use this site you agree to our policy. </span> <!-- Close button --> <a id="es_cookie_close_btn" href="#" class="es-cookie-button"> <svg class="es_cookie_close_icon" width="64" version="1.1" xmlns="http://www.w3.org/2000/svg" height="64" viewBox="0 0 64 64" xmlns:xlink="http://www.w3.org/1999/xlink" enable-background="new 0 0 64 64"> <g> <path fill="" d="M28.941,31.786L0.613,60.114c-0.787,0.787-0.787,2.062,0,2.849c0.393,0.394,0.909,0.59,1.424,0.59 c0.516,0,1.031-0.196,1.424-0.59l28.541-28.541l28.541,28.541c0.394,0.394,0.909,0.59,1.424,0.59c0.515,0,1.031-0.196,1.424-0.59 c0.787-0.787,0.787-2.062,0-2.849L35.064,31.786L63.41,3.438c0.787-0.787,0.787-2.062,0-2.849c-0.787-0.786-2.062-0.786-2.848,0 L32.003,29.15L3.441,0.59c-0.787-0.786-2.061-0.786-2.848,0c-0.787,0.787-0.787,2.062,0,2.849L28.941,31.786z"></path> </g> </svg> </a> </div> </div> ``` > > **jQuery** > > > ``` jQuery( document ).ready(function() { jQuery('#es_cookie_close_btn').click(function() { jQuery('#es_cookie_msg').slideUp(); // Set cookie cookieHelper.create('accepted', true); }); }); jQuery(function () { // If cookie hasnt reveioly been accepted, show banner if( !cookieHelper.read('accepted') ) { jQuery('#es_cookie_msg').slideDown(); } }); // Cookies set inside object var cookieHelper = { // Cookies create: function (name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; }, read: function(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; }, erase: function(name) { createCookie(name, "", -1); } } ```
37,087,869
I've been trying to implement a basic cookie storage function in Javascript, which works as intended in most browsers, but not Safari (8.0.3). I've stripped it down to the below example, where every other browser changes the text to the date that is stored in the cookie, but Safari doesn't store a cookie at all and gives out an empty string (no error messages in the console either). Safari is set to accept all cookies. If I enter the code in the testbed at W3Schools.com, it works in every browser, so is it somehow related to the domain? (In JSFiddle it doesn't seem to work at all, with the console complaining that myFunction is not defined.) I've only found two older problems of the same type, but in one case the solution was adding the "; path=/" part, which is already in here, and in the other there was a comma in place of a semicolon. ``` <!DOCTYPE html> <html> <body> <p id="doesitwork" onclick="myFunction()">Does it work?</p> <script> function myFunction() { d = new Date(); document.cookie = (d + "; expires=" + "May 31 2016 23:59:59 GMT+09:00" + "; path=/"); var x = document.cookie; document.getElementById("doesitwork").innerHTML = x; } </script> </body> </html> ```
2016/05/07
[ "https://Stackoverflow.com/questions/37087869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6303683/" ]
By default cookie not allowed for iOS safari browser. We have to enable cookies setting from safari browser So we have implemented local storage(javascript concept)to overcome the cookie problems in safari browser.
Best way to show/hide cookie in all the browser, including mobile browser also. **Demo:** <http://jsfiddle.net/a4fur7k3/1/> **Notes :** *By default message should be hidden* > > **HTML** > > > ``` <div id="es_cookie_msg" style="display:none;"> <div class="es-cookie-msg-container"> <!-- Cookie Message --> <span class="es-cookie-msg-text">We use cookies to help ensure our website meets your needs. By continuing to use this site you agree to our policy. </span> <!-- Close button --> <a id="es_cookie_close_btn" href="#" class="es-cookie-button"> <svg class="es_cookie_close_icon" width="64" version="1.1" xmlns="http://www.w3.org/2000/svg" height="64" viewBox="0 0 64 64" xmlns:xlink="http://www.w3.org/1999/xlink" enable-background="new 0 0 64 64"> <g> <path fill="" d="M28.941,31.786L0.613,60.114c-0.787,0.787-0.787,2.062,0,2.849c0.393,0.394,0.909,0.59,1.424,0.59 c0.516,0,1.031-0.196,1.424-0.59l28.541-28.541l28.541,28.541c0.394,0.394,0.909,0.59,1.424,0.59c0.515,0,1.031-0.196,1.424-0.59 c0.787-0.787,0.787-2.062,0-2.849L35.064,31.786L63.41,3.438c0.787-0.787,0.787-2.062,0-2.849c-0.787-0.786-2.062-0.786-2.848,0 L32.003,29.15L3.441,0.59c-0.787-0.786-2.061-0.786-2.848,0c-0.787,0.787-0.787,2.062,0,2.849L28.941,31.786z"></path> </g> </svg> </a> </div> </div> ``` > > **jQuery** > > > ``` jQuery( document ).ready(function() { jQuery('#es_cookie_close_btn').click(function() { jQuery('#es_cookie_msg').slideUp(); // Set cookie cookieHelper.create('accepted', true); }); }); jQuery(function () { // If cookie hasnt reveioly been accepted, show banner if( !cookieHelper.read('accepted') ) { jQuery('#es_cookie_msg').slideDown(); } }); // Cookies set inside object var cookieHelper = { // Cookies create: function (name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; }, read: function(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; }, erase: function(name) { createCookie(name, "", -1); } } ```
72,944,012
I am very new to Python and I am looking for advice on how to extract data from the JSON file below. I would like a Python script that does the following Find Label "Car" if confidence is >90 then count "BoundingBox" and output "The are x Cars" else output "there are no Cars". Find Label "Person" if confidence is >85 then count "BoundingBox" and output "The are x People" else output "there are no People". Would you use the "import json" import json I appreciate any help you can provide on this ``` { "Labels": [{ "Name": "Car", "Confidence": 97.12930297851562, "Instances": [{ "BoundingBox": { "Width": 0.3040655553340912 }, "Confidence": 97.12930297851562 }, { "BoundingBox": { "Width": 0.21719124913215637 }, "Confidence": 87.27943420410156 }, { "BoundingBox": { "Width": 0.1468130648136139 }, "Confidence": 63.32168960571289 } ], "Parents": [{ "Name": "Vehicle" }, { "Name": "Transportation" } ] }, { "Name": "Automobile", "Confidence": 97.12930297851562, "Instances": [], "Parents": [{ "Name": "Vehicle" }, { "Name": "Transportation" } ] }, { "Name": "Person", "Confidence": 85.63351440429688, "Instances": [{ "BoundingBox": { "Width": 0.024131836369633675 }, "Confidence": 85.63351440429688 }], "Parents": [] }, { "Name": "Freeway", "Confidence": 55.29652786254883, "Instances": [], "Parents": [{ "Name": "Road" }] } ], "LabelModelVersion": "2.0" } ```
2022/07/11
[ "https://Stackoverflow.com/questions/72944012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19495665/" ]
There are 2 options: 1. Create an event trigger for the 2nd pipeline and add a copy file activity at the end of 1st pipeline. So whenever the 1st pipeline gets completed, it would generate a file and trigger the 2nd pipeline 2. Use execute pipeline activity at the end of 1st pipeline and trigger the 2nd pipeline ( you can even use web activity but there would be additional efforts for it)
1. Create a [tumbling window trigger](https://learn.microsoft.com/en-us/azure/data-factory/how-to-create-tumbling-window-trigger?tabs=data-factory%2Cazure-powershell) for both pipelines. 2. While creating a tumbling window trigger for the second pipeline, you can add a dependency trigger under Advance property and select pipeline1 trigger. 3. The second trigger runs only upon completion of the dependency trigger.
3,069,283
I have an image with a class of "actions\_image" that when clicked shows a menu. This image with hidden menu appears several times on the same page. I'm having issues with the code below for 2 reasons: 1 - In the Javascript code, the first line is to ensure that if there's already a menu open, this will be closed before the new menu is shown. But when this line is added, then the second line with the toggle command no longer toggles. It only shows the div when you click, but won't hide it when you click again. All the rest of the actions work perfectly, as in the div hides when anything but the image that shows it is clicked 2 - IE 7 is throwing up an error for the 2nd line of javascript because of the use of :hover and won't show the menu at all (grrr...!) Can anyone help? **Javascript code:** ``` section_actions_menu: function(event){ $(".actions_image").next().hide(); $(".actions_image:hover").next().toggle(); $("body").click(function(e){ if(e.target.className !== "actions_image") { $(".actions_image").next().hide(); } }); ``` } **HTML Code:** ``` <img src="/media/images/spacer.gif" width="31" height="18" alt="Section Actions Menu" title="Section Actions Menu" class="actions_image" onclick="section_actions_menu(event);"/> <div class="toggle"> <ul> <li><a title="Add">Add</a></li> <li><a title="Edit">Edit</a></li> <li><a title="Remove">Remove</a></li> </ul> </div> ``` Any help would be much appreciated.
2010/06/18
[ "https://Stackoverflow.com/questions/3069283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369134/" ]
`rake stats` will give you a simple comparison based on line count. [Rcov](http://eigenclass.org/hiki.rb?rcov) will give you a good picture of your test-coverage. But you should absolutely check out [metric-fu](http://metric-fu.rubyforge.org/)! Includes all kinds of packages, all analysis tools can be run from with a simple `rake metrics:all`, and generates nice reporting ... in short: awesome ;) Hope this helps :)
The StyleCop equivalent is called RuboCop: <https://github.com/rubocop/rubocop> There is no exact equivalent for FxCop, but there are some tools like Scientist, rails\_best\_practices, Reek etc.
31,830,002
I've been using the simulator to test my app. Today I decided to test it using other devices in the simulator and to my surprise it crashes on startup on some devices, on others it works perfectly **My app builds an runs on :** * iPad Air * resizable iPad * iPhone 5S * iPhone 6 * iPhone 6plus * resizable iPhone **My App crashes on:** * iPad 2 * iPad Retina * iPhone 4S * iPhone 5 The Error I'm Getting is : dyld: Library not loaded: @rpath/SwiftyJSON.framework/SwiftyJSON ``` Referenced from: /Users/data/Library/Developer/CoreSimulator/Devices/2ACCFF1F-D35F-444A-B709-2A41AC9CC7D2/data/Containers/Bundle/Application/DA7480F6-4032-4EB5-A51F-5D028088FFE1/Demo Mobile.app/Demo Mobile Reason: no suitable image found. (lldb) ``` Sometimes I even get more information : ``` Referenced from: /Users/data/Library/Developer/CoreSimulator/Devices/2ACCFF1F-D35F-444A-B709-2A41AC9CC7D2/data/Containers/Bundle/Application/DA7480F6-4032-4EB5-A51F-5D028088FFE1/Demo Mobile.app/Demo Mobile Reason: no suitable image found. Did find: /Users/data/Library/Developer/CoreSimulator/Devices/2ACCFF1F-D35F-444A-B709-2A41AC9CC7D2/data/Containers/Bundle/Application/DA7480F6-4032-4EB5-A51F-5D028088FFE1/Demo Mobile.app/Frameworks/SwiftyJSON.framework/SwiftyJSON: mach-o, but wrong architecture /Users/data/Library/Developer/CoreSimulator/Devices/2ACCFF1F-D35F-444A-B709-2A41AC9CC7D2/data/Containers/Bundle/Application/DA7480F6-4032-4EB5-A51F-5D028088FFE1/Demo Mobile.app/Frameworks/SwiftyJSON.framework/SwiftyJSON: mach-o, but wrong architecture /Users/data/Library/Developer/CoreSimulator/Devices/2ACCFF1F-D35F-444A-B709-2A41AC9CC7D2/data/Containers/Bundle/Application/DA7480F6-4032-4EB5-A51F-5D028088FFE1/Demo Mobile.app/Frameworks/SwiftyJSON.framework/SwiftyJSON: mach-o, but wrong architecture (lldb) ``` I installed SwiftyJson via Cocoapods. My Podfile contains ``` platform :ios, '8.0' use_frameworks! pod 'SQLite.swift', git: 'https://github.com/stephencelis/SQLite.swift.git' target 'thinx Mobile' do pod 'SwiftyJSON', '~> 2.2.1' end ``` I tried : * clean & rebuild * solutions 1, 2, 3 from [dyld: Library not loaded: @rpath/libswift\_stdlib\_core.dylib](https://stackoverflow.com/questions/24002836/dyld-library-not-loaded-rpath-libswift-stdlib-core-dylib)
2015/08/05
[ "https://Stackoverflow.com/questions/31830002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439673/" ]
After searching for almost a day I rebuild the project from scratch (new project, new podfile, new files but in each file copy-paste the source code from the original project) the app compiles now and runs perfectly on every simulator! No Errors. But I still got a similar error (but different reason) on actual devices. I closed this question but there is a follow up question for that problem: [dyld: Library not loaded: @rpath/SwiftyJSON.framework/SwiftyJSON](https://stackoverflow.com/questions/31836514/dyld-library-not-loaded-rpath-swiftyjson-framework-swiftyjson).
The question is related to [iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta](https://stackoverflow.com/questions/24333981/ios-app-with-framework-crashed-on-device-dyld-library-not-loaded-xcode-6-beta), that solved the issue and is a general answer for this kind of error I'd say I experienced this at the moment of writing this post with `Xcode 8.0` (Swift 3.0) and `SwiftyJSON 3.1.3`
37,058,573
I want to change my image and description based on the selected value in my field. I have done it but the problem is that I can only use the .val() for description and image. I'm in the test stage right now, later after I've done the jQuery I will get the values from the database Here is my Javascript: ``` <script> var base_url = "<?php echo base_url();?>"; $(document).ready(function() { $("#field_6").change(function() { $('#description').html($(this).val()); $('#image').attr("src", base_url + "img/" + $(this).val()); }).change(); }); </script> ``` Here is my HTML code: ``` <select class="form-control" id="field_6" name="field_6"> <option value="1.jpg">Online Portal for FGC</option> <option value="2.png">Restaurant Management for Wit Cafe</option> <option value="3.jpg">Hotel Reservation for TWIECO</option> </select> <img src="<?php echo base_url()?>img/1.jpg" id="image" class="img-responsive" style="height:300px;width:100%;" name="myImage" /><br> <label class="form_field">Title Description: <span id="description"></span>?</label> ``` The output right now is like this: I got the image and then ex.(1.jpg) My problem is that it will not be good if both image name and description will be the same for example the image name will be The Online portal for FGC.jpg and the description will be like that too.
2016/05/05
[ "https://Stackoverflow.com/questions/37058573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5765840/" ]
1. The server is "smtp.gmail.com". 2. The port must match the type of security used. * If using STARTTLS with `MAIL_USE_TLS = True`, then use `MAIL_PORT = 587`. * If using SSL/TLS directly with `MAIL_USE_SSL = True`, then use `MAIL_PORT = 465`. * Enable either STARTTLS or SSL/TLS, not both. 3. Depending on your Google account's security settings, you may need to generate and use an [app password](https://security.google.com/settings/security/apppasswords) rather than the account password. This may also require enabling 2-step verification. You should probably set this up anyway. ``` MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USERNAME = 'username@gmail.com' MAIL_PASSWORD = 'app password generated in step 3' ```
A small but important addition to davidism's answer: You must have '2-step verification' enabled on your Google account before you're able to set up app-specific passwords.
74,065,921
i'm getting this new error while running 'Docker-compose build' on my server. it was working perfectly just yesterday. i did't change the Dockerfile. ps: this error is occuring with every service i run and has the 'COPY' function in it Error: [enter image description here](https://i.stack.imgur.com/l9fgA.png) Dockerfile: [enter image description here](https://i.stack.imgur.com/jDs1Z.png)
2022/10/14
[ "https://Stackoverflow.com/questions/74065921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20238469/" ]
The preprocessor has no knowledge of variables or any language construct. It is just a token processor. In `#define a(b) ( b + 1 )` this means that anytime the preprocessor encounters `a(foo)` in the source text, it will replace it with `( foo + 1 )`. Then the compiler will check whether it is correct C.
This is the normal way to define macro with arguments: <https://gcc.gnu.org/onlinedocs/cpp/Macro-Arguments.html#Macro-Arguments> Macros just replace text basically so you have to take care about variable type.
74,065,921
i'm getting this new error while running 'Docker-compose build' on my server. it was working perfectly just yesterday. i did't change the Dockerfile. ps: this error is occuring with every service i run and has the 'COPY' function in it Error: [enter image description here](https://i.stack.imgur.com/l9fgA.png) Dockerfile: [enter image description here](https://i.stack.imgur.com/jDs1Z.png)
2022/10/14
[ "https://Stackoverflow.com/questions/74065921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20238469/" ]
The preprocessor has no knowledge of variables or any language construct. It is just a token processor. In `#define a(b) ( b + 1 )` this means that anytime the preprocessor encounters `a(foo)` in the source text, it will replace it with `( foo + 1 )`. Then the compiler will check whether it is correct C.
No, macros only substitute text (more precisely tokens) and it is done before actual C code compilation. The preprocessor does not know anything about C language. The preprocessed source code then is compiled by the C compiler. ``` #define CAN_SET_DLC(dlc) ((DLC) |= CANCDMOB) #define CANCMOB 0x34 int foo(uint8_t z) { CAN_SET_DLC(z); return z; } ``` will result in ``` int foo(uint8_t z) { ((z) |= 0x34); return z; } ```
36,500,281
i think my question is pretty simple but i still didn't find any answer that fits me, neither here nor out there.. so i'd be really happy if someone could help me out, it doesn't matter if it's by providing useful links or whatever... what i'm trying to achieve: i've got an Ignite UI Grid (igGrid), where i'd like to remove a row using javascript. it doesn't even matter which one. simple, right? what i've tried so far: * **$(row).remove();** -> in this case every single row is being removed * **$(row).remove(1);** -> JavaScript runtime error: Object doesn't support property or method 'replace' * **get\_rows():** not supported by javascript, it would work in c# though.. * **removeat-method:** not supported by javascript, it would work in c# though.. * **igGridSelection:** selected stuff that i want to keep will be removed, too and now the code snippet: ``` $sender = $(this).attr('id'); $varTablName = gridMap.getVarTable($sender); var rowCount = $("#" + $varTablName).igGrid("widget").igGrid('rows').length; $("#" + $varTablName).igGrid("widget").igGrid('rows').each(function (index) { var row = $("#" + $varTablName).igGrid("widget").igGrid("rowAt", index); if (rowCount > 1) { $(row).remove(); //the not quite working part } ``` it's doable, right? there's no need to go all the way and write it in c# and call it with js, right..? RIGHT??^^
2016/04/08
[ "https://Stackoverflow.com/questions/36500281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
[Infragistics guide to deleting a row programmatically](http://help.infragistics.com/Help/Doc/jQuery/2014.1/CLR4.0/html/igGrid_Updating.html#deleting_row_programmatically) ``` $('#grid').igGridUpdating('deleteRow', "AFG"); $('#grid').igGridUpdating('deleteRow', 1, $('#grid').igGrid("rowAt", 0)); ``` Following to the [api docs](http://help.infragistics.com/jQuery/2014.1/ui.igGridUpdating#methods:deleteRow) -- thnx @KonstantinDinev -- the code above will delete a row from the grid, creating a transaction and updates the UI. This functionality depends on [autoCommit](http://help.infragistics.com/Help/Doc/jQuery/2011.2/CLR4.0/HTML/igGrid_Updating.html) option of igGrid **the API should always be first option ^^** We can also target the dom element and remove or hide it ourselves. When removed the number of rows displayed changes but the data source will need to be updated <http://jsfiddle.net/gtw916um/6/> ``` $(function() { $("#grid").igGrid({}); //hides 2nd row (index starts at 0) $("#grid").igGrid("allRows").each(function(index) { if (index == 1) { $(this).css("display", 'none'); } }); //deletes 4th row (index starts at 0) var row = $("#grid").igGrid("widget").igGrid("rowAt", 3); $(row).remove(); //un-hiding 2nd row (index starts at 0) row = $("#grid").igGrid("widget").igGrid("rowAt", 1); $(row).css("display", 'table-row'); }); ``` *untested update data method* ``` $("#grid").data("igGrid").dataSource.deleteRow(3, true); $("#grid").data("igGrid").commit(); ```
You could try this or some jquery equivalent. I don't know how it will affect the ultragrid though, so doublecheck if you retain all other functionality. ``` var row = document.querySelector('myRowReference'); row.parentNode.removeChild(row); ```
36,500,281
i think my question is pretty simple but i still didn't find any answer that fits me, neither here nor out there.. so i'd be really happy if someone could help me out, it doesn't matter if it's by providing useful links or whatever... what i'm trying to achieve: i've got an Ignite UI Grid (igGrid), where i'd like to remove a row using javascript. it doesn't even matter which one. simple, right? what i've tried so far: * **$(row).remove();** -> in this case every single row is being removed * **$(row).remove(1);** -> JavaScript runtime error: Object doesn't support property or method 'replace' * **get\_rows():** not supported by javascript, it would work in c# though.. * **removeat-method:** not supported by javascript, it would work in c# though.. * **igGridSelection:** selected stuff that i want to keep will be removed, too and now the code snippet: ``` $sender = $(this).attr('id'); $varTablName = gridMap.getVarTable($sender); var rowCount = $("#" + $varTablName).igGrid("widget").igGrid('rows').length; $("#" + $varTablName).igGrid("widget").igGrid('rows').each(function (index) { var row = $("#" + $varTablName).igGrid("widget").igGrid("rowAt", index); if (rowCount > 1) { $(row).remove(); //the not quite working part } ``` it's doable, right? there's no need to go all the way and write it in c# and call it with js, right..? RIGHT??^^
2016/04/08
[ "https://Stackoverflow.com/questions/36500281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`deleteRow` is the method you're looking for as the [other answer suggests](https://stackoverflow.com/a/36500633/1348324). For this method you can provide the row element as parameter, or the row ID. [Here's the API docs](http://help.infragistics.com/jQuery/2014.1/ui.igGridUpdating#methods:deleteRow). Here's the code: ``` var row = $("#" + $varTablName).igGrid("rowAt", index); $("#" + $varTablName).igGridUpdating("deleteRow", row); ```
You could try this or some jquery equivalent. I don't know how it will affect the ultragrid though, so doublecheck if you retain all other functionality. ``` var row = document.querySelector('myRowReference'); row.parentNode.removeChild(row); ```
36,500,281
i think my question is pretty simple but i still didn't find any answer that fits me, neither here nor out there.. so i'd be really happy if someone could help me out, it doesn't matter if it's by providing useful links or whatever... what i'm trying to achieve: i've got an Ignite UI Grid (igGrid), where i'd like to remove a row using javascript. it doesn't even matter which one. simple, right? what i've tried so far: * **$(row).remove();** -> in this case every single row is being removed * **$(row).remove(1);** -> JavaScript runtime error: Object doesn't support property or method 'replace' * **get\_rows():** not supported by javascript, it would work in c# though.. * **removeat-method:** not supported by javascript, it would work in c# though.. * **igGridSelection:** selected stuff that i want to keep will be removed, too and now the code snippet: ``` $sender = $(this).attr('id'); $varTablName = gridMap.getVarTable($sender); var rowCount = $("#" + $varTablName).igGrid("widget").igGrid('rows').length; $("#" + $varTablName).igGrid("widget").igGrid('rows').each(function (index) { var row = $("#" + $varTablName).igGrid("widget").igGrid("rowAt", index); if (rowCount > 1) { $(row).remove(); //the not quite working part } ``` it's doable, right? there's no need to go all the way and write it in c# and call it with js, right..? RIGHT??^^
2016/04/08
[ "https://Stackoverflow.com/questions/36500281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
[Infragistics guide to deleting a row programmatically](http://help.infragistics.com/Help/Doc/jQuery/2014.1/CLR4.0/html/igGrid_Updating.html#deleting_row_programmatically) ``` $('#grid').igGridUpdating('deleteRow', "AFG"); $('#grid').igGridUpdating('deleteRow', 1, $('#grid').igGrid("rowAt", 0)); ``` Following to the [api docs](http://help.infragistics.com/jQuery/2014.1/ui.igGridUpdating#methods:deleteRow) -- thnx @KonstantinDinev -- the code above will delete a row from the grid, creating a transaction and updates the UI. This functionality depends on [autoCommit](http://help.infragistics.com/Help/Doc/jQuery/2011.2/CLR4.0/HTML/igGrid_Updating.html) option of igGrid **the API should always be first option ^^** We can also target the dom element and remove or hide it ourselves. When removed the number of rows displayed changes but the data source will need to be updated <http://jsfiddle.net/gtw916um/6/> ``` $(function() { $("#grid").igGrid({}); //hides 2nd row (index starts at 0) $("#grid").igGrid("allRows").each(function(index) { if (index == 1) { $(this).css("display", 'none'); } }); //deletes 4th row (index starts at 0) var row = $("#grid").igGrid("widget").igGrid("rowAt", 3); $(row).remove(); //un-hiding 2nd row (index starts at 0) row = $("#grid").igGrid("widget").igGrid("rowAt", 1); $(row).css("display", 'table-row'); }); ``` *untested update data method* ``` $("#grid").data("igGrid").dataSource.deleteRow(3, true); $("#grid").data("igGrid").commit(); ```
`deleteRow` is the method you're looking for as the [other answer suggests](https://stackoverflow.com/a/36500633/1348324). For this method you can provide the row element as parameter, or the row ID. [Here's the API docs](http://help.infragistics.com/jQuery/2014.1/ui.igGridUpdating#methods:deleteRow). Here's the code: ``` var row = $("#" + $varTablName).igGrid("rowAt", index); $("#" + $varTablName).igGridUpdating("deleteRow", row); ```
1,369,645
I'm reading the book "ASP.NET 3.5 Social Networking - Andrew Siemer" and I got confused when he uses Repositories to access the data. Here is the idea of his code: ``` public interface IAccountRepository { Account GetAcountByID(int acId); void SaveAccount(Account account); List<Account> GetAllAccounts(); } public class AccountRepositoryLINQ : IAccountRepository { Account GetAcountByID(int acId){ ..... LINQ query ..... ...... return..... } void SaveAccount(Account account){ ..... LINQ ..... } List<Account> GetAllAccounts(){ ..... LINQ query ..... ...... return..... } } ``` The class "Account" is the one generated automatically on the "LINQ to SQL Classes". **Some of the problems I see:** **1º** I code my business layer, GUI, etc... and later in time the table Accounts in the database is changed (example: change the name of one column), then I need to rebuild the "LINQ to SQL Classes" and all my code layers will need to be recoded because my "Account" object changed. **2º** If I need to have other repositories (MySQL, Oracle, XML, other), what "Account" class will I use? **What to do?** * Shouldn't I use a custom Account class? This will be used in all application layers. * How do the mapping from LINQ to my custom Account class? + Using simple "myClass.Name = linqClass.Name;" ??? - Isn't this consuming machine resources if I need to "map" all the classes? - There isn't a easiest/lightest way to do it? - Is this the correct approach? Is there other ways?
2009/09/02
[ "https://Stackoverflow.com/questions/1369645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162296/" ]
Good instinct.. My suggestion is to abstract away the LinqToSQL objects, and create a set of Business Domain Objects. Then the Repository can query for the needed data and map them to the Domain objects that your application uses, and return those. Now your Data Access layer is decoupled from your application, and you can now do all of the things you listed. The mapping can be a pain, so look at tools like [Automapper](http://www.codeplex.com/AutoMapper) to accomplish this.
I personally use a combination of NHibernate and FluentNHibernate and seperate my domain(business objects) from all other things. I use messages from my other layers, like a GUI, to my domain which has a handler which injects repositories inside that hydrate the object(s) in question and perform the business logic, the interfaces in the repositories above are a nice way to decouple if you want to use other implementations of repositories or data access.
1,369,645
I'm reading the book "ASP.NET 3.5 Social Networking - Andrew Siemer" and I got confused when he uses Repositories to access the data. Here is the idea of his code: ``` public interface IAccountRepository { Account GetAcountByID(int acId); void SaveAccount(Account account); List<Account> GetAllAccounts(); } public class AccountRepositoryLINQ : IAccountRepository { Account GetAcountByID(int acId){ ..... LINQ query ..... ...... return..... } void SaveAccount(Account account){ ..... LINQ ..... } List<Account> GetAllAccounts(){ ..... LINQ query ..... ...... return..... } } ``` The class "Account" is the one generated automatically on the "LINQ to SQL Classes". **Some of the problems I see:** **1º** I code my business layer, GUI, etc... and later in time the table Accounts in the database is changed (example: change the name of one column), then I need to rebuild the "LINQ to SQL Classes" and all my code layers will need to be recoded because my "Account" object changed. **2º** If I need to have other repositories (MySQL, Oracle, XML, other), what "Account" class will I use? **What to do?** * Shouldn't I use a custom Account class? This will be used in all application layers. * How do the mapping from LINQ to my custom Account class? + Using simple "myClass.Name = linqClass.Name;" ??? - Isn't this consuming machine resources if I need to "map" all the classes? - There isn't a easiest/lightest way to do it? - Is this the correct approach? Is there other ways?
2009/09/02
[ "https://Stackoverflow.com/questions/1369645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162296/" ]
I have a love hate relationship with LINQ to SQL classes myself, but I thought I'd play devils advocate :-), firstly addressing the points you made:- > > 1º I code my business layer, GUI, > etc... and later in time the table > Accounts in the database is changed > (example: change the name of one > column), then I need to rebuild the > "LINQ to SQL Classes" and all my code > layers will need to be recoded because > my "Account" object changed. > > > The general approach is that you'd add behaviour to the partial classes generated by LINQ to SQL, these files won't be replaced when you refresh a table from the data context. If you change the name of the column and don't want to change the rest of your code just update the class in the designer to use the old column name? Even if you used POCOs for persistence with NHibernate for instance you'd still need to change the mapping so I don't really see this as an issue. > > 2º If I need to have other repositories (MySQL, Oracle, XML, other), > what "Account" class will I use? > > > Personally I'd call YAGNI on this one, if you really anticipate needing support for multiple databases LINQ to SQL might not be the best solution to start with in any case (simply to keep your infrastructure consistent across the application), tools like NHibernate would have far better support for such situations. Moving on to adding a custom account class, mapping code can be taken care of by tools like AutoMapper, though this might mean you give up things like lazy loading (which may or may not be a big deal to you). In the end it can be quite empowering to have full control over your entities (e.g. not having to use a parameterless constructor, control over instatiation etc, simple user types that map to one or two columns) and if you feel that your application might benefit from this it's probably the way to go, but you will pay the price in the repository implementation which will be complicated by mapping code and handling whether things need to be updated / deleted / inserted. A good middle ground might be to simply code to an interface (e.g. IAccount) this should define the properties and method you expect from an account. Your repository would then become ``` IAccount GetById(int accountId); ``` You'll then give yourself freedom over what the implementation is (i.e. whether it's implemented by a LINQ to SQL class or a projection / mapping) and if you do opt for a custom class in future it'd be a simple case of moving the implementation to that class and altering the repository implementation. In the end it's down to the application, if you think it's going to end up a huge application with extremely complex business logic by all means I would opt for a segregated domain layer that at least tries to be persistence ignorant. If, however, it isn't and opting for the repository pattern is simply a means to achieve good testability and a simple abstraction above your data access. I don't see why explicitly referencing LINQ to SQL classes and using them as a simple domain layer is such a big deal.
I personally use a combination of NHibernate and FluentNHibernate and seperate my domain(business objects) from all other things. I use messages from my other layers, like a GUI, to my domain which has a handler which injects repositories inside that hydrate the object(s) in question and perform the business logic, the interfaces in the repositories above are a nice way to decouple if you want to use other implementations of repositories or data access.
4,480,066
Let's say I have the javascript function below: ``` function (msg) { var divForResult = document.getElementById("test"); if (typeof (msg) == "object") { divForResult.innerHTML = "Result: <b>" + msg.Message + "</b>"; } else { divForResult.innerHTML = "Result: <b>" + msg + "</b>"; } } ``` I know that if the `msg` variable is an object, it's as Exception, so I print the Message property. If not, the `msg` is a string, and I print the variable itself. My question is how do I let Visual Studio 2010 JavaScript IntelliSense "know" the type of object msg is, so that I'll get the correct properties/functions for the object type in a situation such as this?
2010/12/18
[ "https://Stackoverflow.com/questions/4480066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91617/" ]
Unfortunately, Visual Studio's "[pseudo-execution](http://weblogs.asp.net/scottgu/archive/2010/04/08/javascript-intellisense-improvements-with-vs-2010.aspx)" of JavaScript in order to provide better Intellisense support is still not comprehensive enough. For example, I wrote this little function: ``` var foo = function(obj) { if (typeof obj === "string") { // presumably Intellisense should know obj is a string // in this compound statement but it doesn't. // try "obj." here } if ((typeof obj === "object") && (obj.constructor === Date)) { // presumably Intellisense should know obj is a Date // in this compound statement but it doesn't. // try "obj." here } }; ``` And if you try it out VS2010 doesn't notice that in the two clauses I've tried to limit the type of the passed-in object and that therefore it could provide better suggestions. So, it seems that Intellisense is pretty limited to local variables.
Actually it's not limited to local variables. You can help VS by using xml comments like this: ``` function foo(message) { /// <param name="message" type="String"></param> message. //ctr+space here } ``` It is not exactly what you are asking for, but it works great when you are accepting argument of one type only.
47,917,485
I've released a native android app on Google Play. Then I published (in beta mode) a new apk with higher version code that build with React Native. If my device has installed the old version (native app) and I pressed update the app on Play Store, it throws error -504 while installing. What is the problem when updating from native app to react native app? [![enter image description here](https://i.stack.imgur.com/x2XrZ.png)](https://i.stack.imgur.com/x2XrZ.png)
2017/12/21
[ "https://Stackoverflow.com/questions/47917485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1679361/" ]
If anyone runs into this issue, the best way to see what is going on is to connect your device to ADB to view the log. The issue one of my co-workers was having was due to a change in the SDK version (previous version set to 23, new version set to 22).
I fixed my problem by changing the **targetSdkVersion** higher than the previous apk **targetSdkVersion**
71,711,330
My main question is: with docker compose on Docker Desktop with WSL 2, when using a bind mount where the host path is a relative path, where and what is the actual host path on the WSL distro used by the docker desktop backend? Sections below help understanding the context, what I searched and understood, and detail my questions. Actual source issue ------------------- I have a docker compose configuration and a container with an Angular application. The content of the project is located on the Windows file system, and the docker compose uses a *bind mount* with a relative path. The container does get the initial content, but it seems to never be updated: no live reload, no updated content when (hard-)refreshing the browser page. Note that this is with Docker Desktop on Windows, after switching from the Hyper-V backend to the WSL 2 one. With Hyper-V, everything worked as expected, it was just much slower (as they state in the documentation). My investigations ----------------- I really searched a lot... and got quite mad since I took many paths and always got badly stuck. * I tried to run a WSL shell inside `docker-desktop-data` which was running: it fails, returning immediately, and the process exit code is just the generic `1` for error. Btw, doing the same for `docker-desktop` does work. * I tried to find the content using the Windows explorer in the network folder `\\wsl$\docker-desktop-data`. There I could finally see the persisted volumes, but couldn't find any folder that would correspond to the bind mount * I couldn't find the information about what internal path the docker engine exposes to the container (which is what my question's title targets). I could see the WSL distro had mounted paths corresponding to the Windows file system drives, but it doesn't mean that this is what it uses (and in fact, there I could see my content updated, while, as I said, nothing was updated when refreshing the browser hence my hypothesis that the content is lying elsewhere) * I discovered the existence of the `ext4.vhdx` files located under `C:\Users\<username>\AppData\Local\Docker\wsl\{data,distro}`. I tried to mount it, but as expected it refused since it was already mounted. However I couldn't find any info about where to see the mounted content. It might by this `\\wsl$\docker-desktop[-data]` thing, but no doc, nor any command (I tried PowerShell's `Get-VHD` which just told me it's "attached") could tell me how to get that info. And probably a few other things which I don't even remember and that were probably already too far from the initial topic. I also checked the official Docker documentation pages with no luck finding these details. My next step would be to read the source code of the backends directly... My expectations --------------- The real, pragmatic outcome for me is to be able to have the container interact with the local Windows file system content, instead of what seems to be a copy, which I can't locate. As a bonus, I would love to understand what paths are involved, and what mechanisms are used to bind all of that (e.g. with the working Hyper-V backend, I expect a Hyper-V specific mechanism to have been used to make it possible for the virtualized docker process to expose a Linux path to the container which eventually was just a sort of hard link / shared folder - conceptually speaking - to the Windows file system folder). So, in docker compose's configuration I see a `host <=> container` path mapping, but being on Windows there's really a `windows host <=> linux host <=> container` mapping and it's that `windows host <=> linux host` mapping which seems to behave differently between Hyper-V and WSL 2, with me being unable to locate the `linux host` path. If all of that could be backed by links to documentations (preferably reference/official) it would make it **PERFECT**. But, really, getting a solution to the first point would already be extremely helpful.
2022/04/01
[ "https://Stackoverflow.com/questions/71711330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1590196/" ]
* As stated, **only ever use `Format-*` cmdlets to produce *for-display* output**, never for outputting *data* that must be processed programmatically later. What `Format-Table` outputs are objects representing *formatting instructions*, and it is *their* properties that ended up in your CSV file - see [this answer](https://stackoverflow.com/a/55174715/45375) for more information. * In **order to include *collections* (arrays) in CSV output, you must convert them to a *single string***, using a self-chosen separator. Otherwise, [`Export-Csv`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/export-csv) simply calls `.ToString()` on the *collection object itself*, which yields the collection's *type name*, and no information about its elements. Therefore, use something like the following, which uses `', '` as the separator string to represent the group names and descriptions in a single column each: ``` $UserGroups = [pscustomobject] @{ User = ($user = Read-Host -Prompt "What user do You want to look up Access for?") Groups = ($groups = (Get-ADUser $User -Properties MemberOf).MemberOf) -join ', ' GroupsDescriptions = ( $groups | ForEach-Object { (Get-ADGroup $_ -Properties *).Description } ) -join ', ' } $UserGroups | Export-Csv c:\tmp\test.csv ``` Note: * `[pscustomobject] @{ ... }` is used to *directly* construct a custom object, which is syntactic sugar available since PowerShell v3 that is simpler and more efficient than a [`New-Object`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/new-object) call. * In order to use the result from your `Read-Host` call in later properties of your object definition, you must cache it in aux. variable `$user` (note that enclosing the assignment in `(...)` passes its value through. * Similarly, the result of the `Get-ADUser` call is cached in aux. variable `$groups`, so that it doesn't have to be repeated in the `GroupsDescriptions` value. * However, as [zett42](https://stackoverflow.com/users/7571258/zett42) points out, it may be cleaner to make the `$user = ...` and `$groups = ...` assignments separate statements and place them *before* the object construction.
The problem is that you pipe to `Format-Table` before you pipe to `Export-Csv`. Only use `Format-Table` for displaying things on screen. The fix is to just remove that. ``` $Object | Export-Csv c:\tmp\test.csv ```