qid
int64
1
74.6M
question
stringlengths
45
24.2k
date
stringlengths
10
10
metadata
stringlengths
101
178
response_j
stringlengths
32
23.2k
response_k
stringlengths
21
13.2k
20,132,066
I have a form page where the users must put a code that I send them by email, this form has as action file redirect.php, which contain this code: ``` <?php header('Location: page.php?code='.$_POST['code']); ?> ``` now what I want to do with my form page is to show a error or to redirect to a page if the code they input on my form doesn's exist in code.txt file. Is it possible that? And if is it how to do it? **EDIT:** I think that must be easier: I want that this form: ``` <form action="page.php" method="post"> <input id="code" name="code" type="text" /> <input type="submit" value="Submit"/> </form> ``` I want this form to pass to the page.php only if the value of input id="code" match values from code.txt
2013/11/21
['https://Stackoverflow.com/questions/20132066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3016012/']
I'm reqesting a image from yahoo and it isn't using the `content-disposition` header but I am extracting the `date` and `content-type` headers to construct a filename. This seems close enough to what you're trying to do... ``` var request = require('request'), fs = require('fs'); var url2 = 'http://l4.yimg.com/nn/fp/rsz/112113/images/smush/aaroncarter_635x250_1385060042.jpg'; var r = request(url2); r.on('response', function (res) { res.pipe(fs.createWriteStream('./' + res.headers.date + '.' + res.headers['content-type'].split('/')[1])); }); ``` Ignore my image choice please :)
Question has been around a while, but I today faced the same problem and solved it differently: ``` var Request = require( 'request' ), Fs = require( 'fs' ); // RegExp to extract the filename from Content-Disposition var regexp = /filename=\"(.*)\"/gi; // initiate the download var req = Request.get( 'url.to/somewhere' ) .on( 'response', function( res ){ // extract filename var filename = regexp.exec( res.headers['content-disposition'] )[1]; // create file write stream var fws = Fs.createWriteStream( '/some/path/' + filename ); // setup piping res.pipe( fws ); res.on( 'end', function(){ // go on with processing }); }); ```
20,132,066
I have a form page where the users must put a code that I send them by email, this form has as action file redirect.php, which contain this code: ``` <?php header('Location: page.php?code='.$_POST['code']); ?> ``` now what I want to do with my form page is to show a error or to redirect to a page if the code they input on my form doesn's exist in code.txt file. Is it possible that? And if is it how to do it? **EDIT:** I think that must be easier: I want that this form: ``` <form action="page.php" method="post"> <input id="code" name="code" type="text" /> <input type="submit" value="Submit"/> </form> ``` I want this form to pass to the page.php only if the value of input id="code" match values from code.txt
2013/11/21
['https://Stackoverflow.com/questions/20132066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3016012/']
I'm reqesting a image from yahoo and it isn't using the `content-disposition` header but I am extracting the `date` and `content-type` headers to construct a filename. This seems close enough to what you're trying to do... ``` var request = require('request'), fs = require('fs'); var url2 = 'http://l4.yimg.com/nn/fp/rsz/112113/images/smush/aaroncarter_635x250_1385060042.jpg'; var r = request(url2); r.on('response', function (res) { res.pipe(fs.createWriteStream('./' + res.headers.date + '.' + res.headers['content-type'].split('/')[1])); }); ``` Ignore my image choice please :)
Here's my solution: ``` var fs = require('fs'); var request = require('request'); var through2 = require('through2'); var req = request(url); req.on('error', function (e) { // Handle connection errors console.log(e); }); var bufferedResponse = req.pipe(through2(function (chunk, enc, callback) { this.push(chunk); callback() })); req.on('response', function (res) { if (res.statusCode === 200) { try { var contentDisposition = res.headers['content-disposition']; var match = contentDisposition && contentDisposition.match(/(filename=|filename\*='')(.*)$/); var filename = match && match[2] || 'default-filename.out'; var dest = fs.createWriteStream(filename); dest.on('error', function (e) { // Handle write errors console.log(e); }); dest.on('finish', function () { // The file has been downloaded console.log('Downloaded ' + filename); }); bufferedResponse.pipe(dest); } catch (e) { // Handle request errors console.log(e); } } else { // Handle HTTP server errors console.log(res.statusCode); } }); ``` The other solutions posted here use `res.pipe`, which can fail if the content is transferred using `gzip` encoding, because the response stream contains the raw (compressed) HTTP data. To avoid this problem you have to use `request.pipe` instead. (See the second example at <https://github.com/request/request#examples>.) When using `request.pipe` I was getting an error: "You cannot pipe after data has been emitted from the response.", because I was doing some async stuff before actually piping (creating a directory to hold the downloaded file). I also had some problems where the file was being written with no content, which might have been due to `request` reading the HTTP response and buffering it. So I ended up creating an intermediate buffering stream with `through2`, so that I could pipe the request to it before the response handler fires, then later piping from the buffering stream into the file stream once the filename is known. Finally, I'm parsing the content disposition header whether the filename is encoded in plain form or in UTF-8 form using the `filename*=''file.txt` syntax. I hope this helps someone else who experiences the same issues that I had.
20,132,066
I have a form page where the users must put a code that I send them by email, this form has as action file redirect.php, which contain this code: ``` <?php header('Location: page.php?code='.$_POST['code']); ?> ``` now what I want to do with my form page is to show a error or to redirect to a page if the code they input on my form doesn's exist in code.txt file. Is it possible that? And if is it how to do it? **EDIT:** I think that must be easier: I want that this form: ``` <form action="page.php" method="post"> <input id="code" name="code" type="text" /> <input type="submit" value="Submit"/> </form> ``` I want this form to pass to the page.php only if the value of input id="code" match values from code.txt
2013/11/21
['https://Stackoverflow.com/questions/20132066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3016012/']
Question has been around a while, but I today faced the same problem and solved it differently: ``` var Request = require( 'request' ), Fs = require( 'fs' ); // RegExp to extract the filename from Content-Disposition var regexp = /filename=\"(.*)\"/gi; // initiate the download var req = Request.get( 'url.to/somewhere' ) .on( 'response', function( res ){ // extract filename var filename = regexp.exec( res.headers['content-disposition'] )[1]; // create file write stream var fws = Fs.createWriteStream( '/some/path/' + filename ); // setup piping res.pipe( fws ); res.on( 'end', function(){ // go on with processing }); }); ```
Here's my solution: ``` var fs = require('fs'); var request = require('request'); var through2 = require('through2'); var req = request(url); req.on('error', function (e) { // Handle connection errors console.log(e); }); var bufferedResponse = req.pipe(through2(function (chunk, enc, callback) { this.push(chunk); callback() })); req.on('response', function (res) { if (res.statusCode === 200) { try { var contentDisposition = res.headers['content-disposition']; var match = contentDisposition && contentDisposition.match(/(filename=|filename\*='')(.*)$/); var filename = match && match[2] || 'default-filename.out'; var dest = fs.createWriteStream(filename); dest.on('error', function (e) { // Handle write errors console.log(e); }); dest.on('finish', function () { // The file has been downloaded console.log('Downloaded ' + filename); }); bufferedResponse.pipe(dest); } catch (e) { // Handle request errors console.log(e); } } else { // Handle HTTP server errors console.log(res.statusCode); } }); ``` The other solutions posted here use `res.pipe`, which can fail if the content is transferred using `gzip` encoding, because the response stream contains the raw (compressed) HTTP data. To avoid this problem you have to use `request.pipe` instead. (See the second example at <https://github.com/request/request#examples>.) When using `request.pipe` I was getting an error: "You cannot pipe after data has been emitted from the response.", because I was doing some async stuff before actually piping (creating a directory to hold the downloaded file). I also had some problems where the file was being written with no content, which might have been due to `request` reading the HTTP response and buffering it. So I ended up creating an intermediate buffering stream with `through2`, so that I could pipe the request to it before the response handler fires, then later piping from the buffering stream into the file stream once the filename is known. Finally, I'm parsing the content disposition header whether the filename is encoded in plain form or in UTF-8 form using the `filename*=''file.txt` syntax. I hope this helps someone else who experiences the same issues that I had.
44,629,249
Im trying to find out how to detect a touch&hold on screen method in the game im making. Im using touches began for single taps (Making the character move up) When they touch and keep holding i want the character to move straight forward. ``` - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //code to make him move up } ``` Any ideas on how to detect a touch&hold ?
2017/06/19
['https://Stackoverflow.com/questions/44629249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6151911/']
**Objective-c** ``` // Add guesture recognizer UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonDidLongPress:)]; [self.button addGestureRecognizer:longPress]; // Call back event - (void)buttonDidLongPress:(UILongPressGestureRecognizer*)gesture { switch (gesture.state) { case UIGestureRecognizerStateBegan: { // Code } break; case UIGestureRecognizerStateEnded: { //Code } break; default: break; } } ``` **Swift** ``` // Add guesture recognizer let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:))) self.button.addGestureRecognizer(longPress) // Call back event func longPress(guesture: UILongPressGestureRecognizer) { switch guesture.state { case UIGestureRecognizerState.began: //Code break case UIGestureRecognizerState.ended: //Code break default: break } } ``` Don't forgot to extend you class with UIGestureRecognizerDelegate
Try: ``` UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; [self.view addGestureRecognizer:longPress]; -(void) handleLongPress: (UIGestureRecognizer *)longPress { switch (longPress.state) { case UIGestureRecognizerStateBegan: // Called when long press for minimum time duration break; case UIGestureRecognizerStateChanged: // Long pressed and dragged break; case UIGestureRecognizerStateRecognized: // Successfully recognised Long touch break; default: break; } if (longPress.state==UIGestureRecognizerStateEnded) { NSLog(@"LONG PRESSED"); } ``` }
3,206,951
I'm trying to use PostgreSQL's RETURNING clause on an UPDATE within in UPDATE statement, and running into trouble. Postgres allows a query clause in an INSERT, for example: ``` INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07'; ``` I would like to use the RETURNING clause from an UPDATE as the query clause for an INSERT, for example: ``` INSERT INTO user_status_history(status) UPDATE user_status SET status = 'ACTIVE' WHERE status = 'DISABLED' RETURNING status ``` All of the Postgres references I can find suggest that a RETURNING clause behaved exactly like a SELECT clause, however when I run something like the above, I get the following: > > ERROR: syntax error at or near "UPDATE" > > > LINE 2: UPDATE user\_statuses > > > Despite being able to execute the UPDATE portion of the above query without error. Is using the RETURNING clause from an UPDATE as the query clause for an INSERT's query clause possible? The goal is to update one table and insert into another with a single query, if possible.
2010/07/08
['https://Stackoverflow.com/questions/3206951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127044/']
Right now, no. There was a feature that *almost* made it into PostgreSQL 9.0 known as [Writeable CTE's](http://johtopg.blogspot.com/2010/06/writeable-ctes.html) that does what you're thinking (although the syntax is different). Currently, you could either do this via a trigger or as two separate statements.
I think this is not possible the way you are trying to do. I'd suggest you to write an AFTER UPDATE trigger, which could perform the insert, then.
3,206,951
I'm trying to use PostgreSQL's RETURNING clause on an UPDATE within in UPDATE statement, and running into trouble. Postgres allows a query clause in an INSERT, for example: ``` INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07'; ``` I would like to use the RETURNING clause from an UPDATE as the query clause for an INSERT, for example: ``` INSERT INTO user_status_history(status) UPDATE user_status SET status = 'ACTIVE' WHERE status = 'DISABLED' RETURNING status ``` All of the Postgres references I can find suggest that a RETURNING clause behaved exactly like a SELECT clause, however when I run something like the above, I get the following: > > ERROR: syntax error at or near "UPDATE" > > > LINE 2: UPDATE user\_statuses > > > Despite being able to execute the UPDATE portion of the above query without error. Is using the RETURNING clause from an UPDATE as the query clause for an INSERT's query clause possible? The goal is to update one table and insert into another with a single query, if possible.
2010/07/08
['https://Stackoverflow.com/questions/3206951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127044/']
With PostgreSQL 9.1 (or higher) you may use the new functionality that allows data-modification commands (INSERT/UPDATE/DELETE) in [WITH clauses](http://www.postgresql.org/docs/9.1/static/queries-with.html), such as: ``` WITH updated_rows AS ( UPDATE products SET ... WHERE ... RETURNING * ) INSERT INTO products_log SELECT * FROM updated_rows; ``` With PostgreSQL 9.0 (or lower) you may embed the UPDATE command inside one function, and then use that function from another function which performs the INSERT command, such as: ``` FUNCTION update_rows() RETURNS TABLE (id integer, descrip varchar) AS $$ BEGIN RETURN QUERY UPDATE products SET ... WHERE ... RETURNING *; END; $$ LANGUAGE plpgsql; FUNCTION insert_rows() RETURNS void AS $$ BEGIN INSERT INTO products_log SELECT * FROM update_rows() AS x; END; $$ LANGUAGE plpgsql; ```
I think this is not possible the way you are trying to do. I'd suggest you to write an AFTER UPDATE trigger, which could perform the insert, then.
3,206,951
I'm trying to use PostgreSQL's RETURNING clause on an UPDATE within in UPDATE statement, and running into trouble. Postgres allows a query clause in an INSERT, for example: ``` INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07'; ``` I would like to use the RETURNING clause from an UPDATE as the query clause for an INSERT, for example: ``` INSERT INTO user_status_history(status) UPDATE user_status SET status = 'ACTIVE' WHERE status = 'DISABLED' RETURNING status ``` All of the Postgres references I can find suggest that a RETURNING clause behaved exactly like a SELECT clause, however when I run something like the above, I get the following: > > ERROR: syntax error at or near "UPDATE" > > > LINE 2: UPDATE user\_statuses > > > Despite being able to execute the UPDATE portion of the above query without error. Is using the RETURNING clause from an UPDATE as the query clause for an INSERT's query clause possible? The goal is to update one table and insert into another with a single query, if possible.
2010/07/08
['https://Stackoverflow.com/questions/3206951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127044/']
With PostgreSQL 9.1 (or higher) you may use the new functionality that allows data-modification commands (INSERT/UPDATE/DELETE) in [WITH clauses](http://www.postgresql.org/docs/9.1/static/queries-with.html), such as: ``` WITH updated_rows AS ( UPDATE products SET ... WHERE ... RETURNING * ) INSERT INTO products_log SELECT * FROM updated_rows; ``` With PostgreSQL 9.0 (or lower) you may embed the UPDATE command inside one function, and then use that function from another function which performs the INSERT command, such as: ``` FUNCTION update_rows() RETURNS TABLE (id integer, descrip varchar) AS $$ BEGIN RETURN QUERY UPDATE products SET ... WHERE ... RETURNING *; END; $$ LANGUAGE plpgsql; FUNCTION insert_rows() RETURNS void AS $$ BEGIN INSERT INTO products_log SELECT * FROM update_rows() AS x; END; $$ LANGUAGE plpgsql; ```
Right now, no. There was a feature that *almost* made it into PostgreSQL 9.0 known as [Writeable CTE's](http://johtopg.blogspot.com/2010/06/writeable-ctes.html) that does what you're thinking (although the syntax is different). Currently, you could either do this via a trigger or as two separate statements.
62,205
I wanted to know if there is any contradiction when someone is learning several different instruments? For example, I am learning to play piano . Would becoming a good piano player in any way hold me back from playing another instrument professionally? P.S. Sorry i couldn't explain well
2017/09/25
['https://music.stackexchange.com/questions/62205', 'https://music.stackexchange.com', 'https://music.stackexchange.com/users/44336/']
It's good to keep in mind that it takes *a lot* of practice to learn an instrument. You have to dedicate a lot of time and it will take years to become a *good* piano player (same for all the instruments). So, if you want to learn how to play multiple instruments, you will have to practice all of them. If you don't have a lot of time, it will be hard to practice them at the same period of time. This doesn't mean you cannot. A lot of people practice their skills on multiple instruments. > > Would becoming a good piano player in any way hold me back from playing another instrument professionally? > > > Of course not. Quite the opposite, in fact! I started with double bass for a few years and then I started playing the piano and the fact that I already knew rhythm, melodies, harmony, theory etc, made it easier to learn the piano. If you already know an instrument, it's going to be easier to learn another one. To oversimplify it, you just have to learn the technique in the new instrument. So my advice would be to start with the one you want to start with (I guess piano in your case) and then if you have the time, take up another one. *But*, I would also suggest that you take up the second instrument after you have learnt quite decent piano, because otherwise, it'd be quite difficult to learn from scratch two totally new instruments when you don't know anything about music.
One of the more dangerous combinations is piano and piano accordion. The similarity of the keyboard leads to a conflation of technique that results in "lowest common denominator" approaches. The piano is a percussive string instrument featuring impetus-sensitive attack and rather fuzzy decay, the accordion is a continuous-tone wind instrument with an attack basically insensitive to key impulse and a very precise key release imprint that, through bellows inertia, also impacts the strength of the next attack, making leggiero articulation the core of fast play, and continuous bellows control the core of slow emotional play. You would not expect to change from hurdygurdy to violin without significant investment in bow technique, either... In this case it is more the "similarity" of the controllers that is masking core differences. In a similar vein, few people are renowned for *both* piano and organ playing skills, even though harpsichord and organ is not all that uncommon as combination. So when going for multiple instruments, it might be prudent to pick something which significantly differs in its controls. That way, you are less tempted to skip over basics that may make a difference in why people would rather hear you play a *real* instrument than a keyboard controller with sampled sounds of it.
62,205
I wanted to know if there is any contradiction when someone is learning several different instruments? For example, I am learning to play piano . Would becoming a good piano player in any way hold me back from playing another instrument professionally? P.S. Sorry i couldn't explain well
2017/09/25
['https://music.stackexchange.com/questions/62205', 'https://music.stackexchange.com', 'https://music.stackexchange.com/users/44336/']
It's good to keep in mind that it takes *a lot* of practice to learn an instrument. You have to dedicate a lot of time and it will take years to become a *good* piano player (same for all the instruments). So, if you want to learn how to play multiple instruments, you will have to practice all of them. If you don't have a lot of time, it will be hard to practice them at the same period of time. This doesn't mean you cannot. A lot of people practice their skills on multiple instruments. > > Would becoming a good piano player in any way hold me back from playing another instrument professionally? > > > Of course not. Quite the opposite, in fact! I started with double bass for a few years and then I started playing the piano and the fact that I already knew rhythm, melodies, harmony, theory etc, made it easier to learn the piano. If you already know an instrument, it's going to be easier to learn another one. To oversimplify it, you just have to learn the technique in the new instrument. So my advice would be to start with the one you want to start with (I guess piano in your case) and then if you have the time, take up another one. *But*, I would also suggest that you take up the second instrument after you have learnt quite decent piano, because otherwise, it'd be quite difficult to learn from scratch two totally new instruments when you don't know anything about music.
The first thing to emphasise is that "professional" and "highly skilled" do not necessarily go hand in hand. The Sex Pistols were professional musicians, but you wouldn't use them as examples of how to play their instruments well! It's also important to emphasise that *expecting* to become a professional musician when you're just starting is wildly over-optimistic. From all the people who start playing instruments, maybe 1 in 20 stick with it long enough that they can earn a bit of beer money playing in an pub band. Maybe 1 in 1000 are good enough to earn a living from it - and most of them will be working as music teachers. Something like 1 in 100,000 will be good enough to earn a living wage solely from performing. You certainly will find that different instruments need different techniques. Synth and piano will need different ways of playing and thinking about the sound, for instance. That doesn't make it impossible to learn both, but you do need to remember that they are different instruments, and you can't assume that skills on one will always transfer. Even different examples of the same instrument will need time to learn their specific characteristics - on a piano, for instance, the hammer action can be radically different between different pianos, and it can take a few hours of playing to really get the hang of a new one.
62,205
I wanted to know if there is any contradiction when someone is learning several different instruments? For example, I am learning to play piano . Would becoming a good piano player in any way hold me back from playing another instrument professionally? P.S. Sorry i couldn't explain well
2017/09/25
['https://music.stackexchange.com/questions/62205', 'https://music.stackexchange.com', 'https://music.stackexchange.com/users/44336/']
It's good to keep in mind that it takes *a lot* of practice to learn an instrument. You have to dedicate a lot of time and it will take years to become a *good* piano player (same for all the instruments). So, if you want to learn how to play multiple instruments, you will have to practice all of them. If you don't have a lot of time, it will be hard to practice them at the same period of time. This doesn't mean you cannot. A lot of people practice their skills on multiple instruments. > > Would becoming a good piano player in any way hold me back from playing another instrument professionally? > > > Of course not. Quite the opposite, in fact! I started with double bass for a few years and then I started playing the piano and the fact that I already knew rhythm, melodies, harmony, theory etc, made it easier to learn the piano. If you already know an instrument, it's going to be easier to learn another one. To oversimplify it, you just have to learn the technique in the new instrument. So my advice would be to start with the one you want to start with (I guess piano in your case) and then if you have the time, take up another one. *But*, I would also suggest that you take up the second instrument after you have learnt quite decent piano, because otherwise, it'd be quite difficult to learn from scratch two totally new instruments when you don't know anything about music.
Don't construct excuses. With the possible exception of some atheletic pursuits, where over-development of one set of muscles might hinder other requirements - a body-builder is probably not suited to the pole-vault for instance - getting good at one thing is very unlikely to prevent you from getting good at another. Of course, if you're aiming for virtuoso level with 8 hours of daily practice on piano or violin, you might run into a scheduling problem.
62,205
I wanted to know if there is any contradiction when someone is learning several different instruments? For example, I am learning to play piano . Would becoming a good piano player in any way hold me back from playing another instrument professionally? P.S. Sorry i couldn't explain well
2017/09/25
['https://music.stackexchange.com/questions/62205', 'https://music.stackexchange.com', 'https://music.stackexchange.com/users/44336/']
One of the more dangerous combinations is piano and piano accordion. The similarity of the keyboard leads to a conflation of technique that results in "lowest common denominator" approaches. The piano is a percussive string instrument featuring impetus-sensitive attack and rather fuzzy decay, the accordion is a continuous-tone wind instrument with an attack basically insensitive to key impulse and a very precise key release imprint that, through bellows inertia, also impacts the strength of the next attack, making leggiero articulation the core of fast play, and continuous bellows control the core of slow emotional play. You would not expect to change from hurdygurdy to violin without significant investment in bow technique, either... In this case it is more the "similarity" of the controllers that is masking core differences. In a similar vein, few people are renowned for *both* piano and organ playing skills, even though harpsichord and organ is not all that uncommon as combination. So when going for multiple instruments, it might be prudent to pick something which significantly differs in its controls. That way, you are less tempted to skip over basics that may make a difference in why people would rather hear you play a *real* instrument than a keyboard controller with sampled sounds of it.
The first thing to emphasise is that "professional" and "highly skilled" do not necessarily go hand in hand. The Sex Pistols were professional musicians, but you wouldn't use them as examples of how to play their instruments well! It's also important to emphasise that *expecting* to become a professional musician when you're just starting is wildly over-optimistic. From all the people who start playing instruments, maybe 1 in 20 stick with it long enough that they can earn a bit of beer money playing in an pub band. Maybe 1 in 1000 are good enough to earn a living from it - and most of them will be working as music teachers. Something like 1 in 100,000 will be good enough to earn a living wage solely from performing. You certainly will find that different instruments need different techniques. Synth and piano will need different ways of playing and thinking about the sound, for instance. That doesn't make it impossible to learn both, but you do need to remember that they are different instruments, and you can't assume that skills on one will always transfer. Even different examples of the same instrument will need time to learn their specific characteristics - on a piano, for instance, the hammer action can be radically different between different pianos, and it can take a few hours of playing to really get the hang of a new one.
62,205
I wanted to know if there is any contradiction when someone is learning several different instruments? For example, I am learning to play piano . Would becoming a good piano player in any way hold me back from playing another instrument professionally? P.S. Sorry i couldn't explain well
2017/09/25
['https://music.stackexchange.com/questions/62205', 'https://music.stackexchange.com', 'https://music.stackexchange.com/users/44336/']
One of the more dangerous combinations is piano and piano accordion. The similarity of the keyboard leads to a conflation of technique that results in "lowest common denominator" approaches. The piano is a percussive string instrument featuring impetus-sensitive attack and rather fuzzy decay, the accordion is a continuous-tone wind instrument with an attack basically insensitive to key impulse and a very precise key release imprint that, through bellows inertia, also impacts the strength of the next attack, making leggiero articulation the core of fast play, and continuous bellows control the core of slow emotional play. You would not expect to change from hurdygurdy to violin without significant investment in bow technique, either... In this case it is more the "similarity" of the controllers that is masking core differences. In a similar vein, few people are renowned for *both* piano and organ playing skills, even though harpsichord and organ is not all that uncommon as combination. So when going for multiple instruments, it might be prudent to pick something which significantly differs in its controls. That way, you are less tempted to skip over basics that may make a difference in why people would rather hear you play a *real* instrument than a keyboard controller with sampled sounds of it.
Don't construct excuses. With the possible exception of some atheletic pursuits, where over-development of one set of muscles might hinder other requirements - a body-builder is probably not suited to the pole-vault for instance - getting good at one thing is very unlikely to prevent you from getting good at another. Of course, if you're aiming for virtuoso level with 8 hours of daily practice on piano or violin, you might run into a scheduling problem.
5,336,413
I'm learning VHDL and I've come to a halt. I'd like to create a simple gate out of smaller gates (a NAND gate here). Here's the code: ``` library IEEE; use IEEE.STD_LOGIC_1164.all; entity ANDGATE2 is port( x,y : in STD_LOGIC; z : out STD_LOGIC ); end ANDGATE2; architecture ANDGATE2 of ANDGATE2 is begin z <= x AND y; end ANDGATE2; library IEEE; use IEEE.STD_LOGIC_1164.all; entity NOTGATE1 is port( x : in STD_LOGIC; z : out STD_LOGIC ); end NOTGATE1; architecture NOTGATE1 of NOTGATE1 is begin z <= NOT x; end NOTGATE1; library ieee; use ieee.std_logic_1164.all; entity NANDGATE2 is port( x : in STD_LOGIC; y : in STD_LOGIC; z : out STD_LOGIC ); end NANDGATE2; architecture NANDGATE2 of NANDGATE2 is signal c, d: std_logic; component NOTGATE1 port( n_in : in STD_LOGIC; n_out : out STD_LOGIC ); end component; component ANDGATE2 port( a_in1, a_in2 : in STD_LOGIC; a_out : out STD_LOGIC ); end component; begin N0: ANDGATE2 port map(x, y, c); N1: NOTGATE1 port map(c, d); z <= d; end NANDGATE2; ``` Here's the code from some tutorial I've been using as a template; it compiles with no problems. ``` library ieee; use ieee.std_logic_1164.all; -- definition of a full adder entity FULLADDER is port ( a, b, c: in std_logic; sum, carry: out std_logic ); end FULLADDER; architecture fulladder_behav of FULLADDER is begin sum <= (a xor b) xor c ; carry <= (a and b) or (c and (a xor b)); end fulladder_behav; -- 4-bit adder library ieee; use ieee.std_logic_1164.all; entity FOURBITADD is port ( a, b: in std_logic_vector(3 downto 0); Cin : in std_logic; sum: out std_logic_vector (3 downto 0); Cout, V: out std_logic ); end FOURBITADD; architecture fouradder_structure of FOURBITADD is signal c: std_logic_vector (4 downto 0); component FULLADDER port ( a, b, c: in std_logic; sum, carry: out std_logic ); end component; begin FA0: FULLADDER port map (a(0), b(0), Cin, sum(0), c(1)); FA1: FULLADDER port map (a(1), b(1), C(1), sum(1), c(2)); FA2: FULLADDER port map (a(2), b(2), C(2), sum(2), c(3)); FA3: FULLADDER port map (a(3), b(3), C(3), sum(3), c(4)); V <= c(3) xor c(4); Cout <= c(4); end fouradder_structure; ``` My code compiles with no errors, but with two warnings: ``` # Warning: ELAB1_0026: p2.vhd : (85, 0): There is no default binding for component "andgate2".(Port "a_in1" is not on the entity). # Warning: ELAB1_0026: p2.vhd : (87, 0): There is no default binding for component "notgate1".(Port "n_in" is not on the entity). ``` What gives?
2011/03/17
['https://Stackoverflow.com/questions/5336413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/663907/']
You need to use the same port names on your component and entity declarations. Right now, for example in your `NOTGATE1` entity declaration, you have input port `x` and output port `z`, but in the `NANDGATE2` architecture, you declare the `NOTGATE1` component to have ports `n_in` and `n_out`. This won't cause problems during compilation, since compilation looks at a single unit at a time, and won't see the actual entities. In the elaboration phase, your tools will try to match up the entities to components, but this will fail since the ports don't match.
Not 100% sure, but I think the pins in your `component` declarations need to match up to the ones in your `entity` blocks: ``` component NOTGATE1 port( x : in STD_LOGIC; z : out STD_LOGIC ); end component; component ANDGATE2 port( x,y : in STD_LOGIC; z : out STD_LOGIC ); ```
5,336,413
I'm learning VHDL and I've come to a halt. I'd like to create a simple gate out of smaller gates (a NAND gate here). Here's the code: ``` library IEEE; use IEEE.STD_LOGIC_1164.all; entity ANDGATE2 is port( x,y : in STD_LOGIC; z : out STD_LOGIC ); end ANDGATE2; architecture ANDGATE2 of ANDGATE2 is begin z <= x AND y; end ANDGATE2; library IEEE; use IEEE.STD_LOGIC_1164.all; entity NOTGATE1 is port( x : in STD_LOGIC; z : out STD_LOGIC ); end NOTGATE1; architecture NOTGATE1 of NOTGATE1 is begin z <= NOT x; end NOTGATE1; library ieee; use ieee.std_logic_1164.all; entity NANDGATE2 is port( x : in STD_LOGIC; y : in STD_LOGIC; z : out STD_LOGIC ); end NANDGATE2; architecture NANDGATE2 of NANDGATE2 is signal c, d: std_logic; component NOTGATE1 port( n_in : in STD_LOGIC; n_out : out STD_LOGIC ); end component; component ANDGATE2 port( a_in1, a_in2 : in STD_LOGIC; a_out : out STD_LOGIC ); end component; begin N0: ANDGATE2 port map(x, y, c); N1: NOTGATE1 port map(c, d); z <= d; end NANDGATE2; ``` Here's the code from some tutorial I've been using as a template; it compiles with no problems. ``` library ieee; use ieee.std_logic_1164.all; -- definition of a full adder entity FULLADDER is port ( a, b, c: in std_logic; sum, carry: out std_logic ); end FULLADDER; architecture fulladder_behav of FULLADDER is begin sum <= (a xor b) xor c ; carry <= (a and b) or (c and (a xor b)); end fulladder_behav; -- 4-bit adder library ieee; use ieee.std_logic_1164.all; entity FOURBITADD is port ( a, b: in std_logic_vector(3 downto 0); Cin : in std_logic; sum: out std_logic_vector (3 downto 0); Cout, V: out std_logic ); end FOURBITADD; architecture fouradder_structure of FOURBITADD is signal c: std_logic_vector (4 downto 0); component FULLADDER port ( a, b, c: in std_logic; sum, carry: out std_logic ); end component; begin FA0: FULLADDER port map (a(0), b(0), Cin, sum(0), c(1)); FA1: FULLADDER port map (a(1), b(1), C(1), sum(1), c(2)); FA2: FULLADDER port map (a(2), b(2), C(2), sum(2), c(3)); FA3: FULLADDER port map (a(3), b(3), C(3), sum(3), c(4)); V <= c(3) xor c(4); Cout <= c(4); end fouradder_structure; ``` My code compiles with no errors, but with two warnings: ``` # Warning: ELAB1_0026: p2.vhd : (85, 0): There is no default binding for component "andgate2".(Port "a_in1" is not on the entity). # Warning: ELAB1_0026: p2.vhd : (87, 0): There is no default binding for component "notgate1".(Port "n_in" is not on the entity). ``` What gives?
2011/03/17
['https://Stackoverflow.com/questions/5336413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/663907/']
You need to use the same port names on your component and entity declarations. Right now, for example in your `NOTGATE1` entity declaration, you have input port `x` and output port `z`, but in the `NANDGATE2` architecture, you declare the `NOTGATE1` component to have ports `n_in` and `n_out`. This won't cause problems during compilation, since compilation looks at a single unit at a time, and won't see the actual entities. In the elaboration phase, your tools will try to match up the entities to components, but this will fail since the ports don't match.
Always use explicit port bindings in your port maps, like ``` port map(a_in1 => x, a_in2 => y, a_out => c); ``` It will make your code also more clear. In big projects it is the first rule of thumb.
25,891,060
I have 2 NSArrays of 2 different types of custom objects. Object A properties: ID: Name: Author: Object B Properties: bookID: value: terminator: I need to filter an array of objects of type "A" that has the ID value equal to the bookID value of any of the objects of the second array that contains objects of type "B". I tried to use the intersectSet: method by converting the arrays to sets, but since both the objects are of different type, nothing happened. What will be the most efficient way to do the filtering? Can I specify the properties to look when I am doing an intersect?
2014/09/17
['https://Stackoverflow.com/questions/25891060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1200174/']
Here is a sample code with example: ``` NSDictionary *dictionaryA1 = @{@"ID":@"1", @"Name":@"NameA1", @"Author":@"AuthorA1"}; NSDictionary *dictionaryA2 = @{@"ID":@"2", @"Name":@"NameA2", @"Author":@"AuthorA2"}; NSDictionary *dictionaryA3 = @{@"ID":@"3", @"Name":@"NameA3", @"Author":@"AuthorA3"}; NSDictionary *dictionaryB0 = @{@"bookID":@"0", @"Name":@"NameB0", @"Author":@"AuthorB0"}; NSDictionary *dictionaryB1 = @{@"bookID":@"1", @"Name":@"NameB1", @"Author":@"AuthorB1"}; NSDictionary *dictionaryB3 = @{@"bookID":@"3", @"Name":@"NameB3", @"Author":@"AuthorB3"}; NSArray *arrayA = @[dictionaryA1, dictionaryA2, dictionaryA3]; NSArray *arrayB = @[dictionaryB0, dictionaryB1, dictionaryB3]; NSArray *intersectionWithBookID = [arrayA filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ID IN %@", [arrayB valueForKey:@"bookID"]]]; NSLog(@"intersectionWithBookID: %@", intersectionWithBookID); ``` Output: ``` intersectionWithBookID: ( { Author = AuthorA1; ID = 1; Name = NameA1; }, { Author = AuthorA3; ID = 3; Name = NameA3; } ```
I m hopping your 2 NSArrays are like arrayA = ( ObjectA1, ObjectA2, . . ObjectAn ) and arrayB = ( ObjectB1, ObjectB2, . . ObjectBn ) In this case you have to first extract the values into separate arrays using predicate like this for both arrayA and arrayB ``` NSPredicate *predicateA = [NSPredicate predicateWithFormat:@"id"]; NSArray *arrayAWithonlyIds = [arrayA filteredArrayUsingPredicate:predicateA]; NSPredicate *predicateB = [NSPredicate predicateWithFormat:@"bookId"]; NSArray *arrayBWithonlyBookIds = [arrayA filteredArrayUsingPredicate:predicateB]; ``` Now you have to convert these result array containing only ids to NSSet inorder to perform set operation like intersection like this ``` NSMutableset *setResult = [NSMutableSet setWithArray: arrayAWithonlyIds]; [setResult intersectSet:[NSSet setWithArray: arrayBWithonlyBookIds]]; ``` I hope this gives you an Idea.
25,891,060
I have 2 NSArrays of 2 different types of custom objects. Object A properties: ID: Name: Author: Object B Properties: bookID: value: terminator: I need to filter an array of objects of type "A" that has the ID value equal to the bookID value of any of the objects of the second array that contains objects of type "B". I tried to use the intersectSet: method by converting the arrays to sets, but since both the objects are of different type, nothing happened. What will be the most efficient way to do the filtering? Can I specify the properties to look when I am doing an intersect?
2014/09/17
['https://Stackoverflow.com/questions/25891060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1200174/']
Here is a sample code with example: ``` NSDictionary *dictionaryA1 = @{@"ID":@"1", @"Name":@"NameA1", @"Author":@"AuthorA1"}; NSDictionary *dictionaryA2 = @{@"ID":@"2", @"Name":@"NameA2", @"Author":@"AuthorA2"}; NSDictionary *dictionaryA3 = @{@"ID":@"3", @"Name":@"NameA3", @"Author":@"AuthorA3"}; NSDictionary *dictionaryB0 = @{@"bookID":@"0", @"Name":@"NameB0", @"Author":@"AuthorB0"}; NSDictionary *dictionaryB1 = @{@"bookID":@"1", @"Name":@"NameB1", @"Author":@"AuthorB1"}; NSDictionary *dictionaryB3 = @{@"bookID":@"3", @"Name":@"NameB3", @"Author":@"AuthorB3"}; NSArray *arrayA = @[dictionaryA1, dictionaryA2, dictionaryA3]; NSArray *arrayB = @[dictionaryB0, dictionaryB1, dictionaryB3]; NSArray *intersectionWithBookID = [arrayA filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ID IN %@", [arrayB valueForKey:@"bookID"]]]; NSLog(@"intersectionWithBookID: %@", intersectionWithBookID); ``` Output: ``` intersectionWithBookID: ( { Author = AuthorA1; ID = 1; Name = NameA1; }, { Author = AuthorA3; ID = 3; Name = NameA3; } ```
I used NSPredicate for filtering array; here is the code: ``` +(void)findIntersectionOfAuthors:(NSArray *)authors withBooks:(NSArray *)books { NSLog(@"CLASS A"); for (Author * aut in authors) [aut print]; NSLog(@"CLASS B"); for (Book * b in books) [b print]; NSMutableArray * resultOfpredicates = [NSMutableArray new]; for (Author * a in authors) { NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF.bookID == %d", a.authId];//this predicate search field of bookID equality in books array NSArray * bks = [books copy]; bks = [bks filteredArrayUsingPredicate:predicate];//filters here if ([bks count]) [resultOfpredicates addObject:a]; } NSLog(@"RESULT"); for (Author * a in resultOfpredicates) [a print]; } ``` i created Author (class A) and Book (class B) classes. here is the result of my code ``` 2014-09-17 18:10:27.803 Predicate[10725:60b] CLASS A 2014-09-17 18:10:27.803 Predicate[10725:60b] id:100 name:1 author:23 2014-09-17 18:10:27.803 Predicate[10725:60b] id:100 name:2 author:24 2014-09-17 18:10:27.804 Predicate[10725:60b] id:102 name:1 author:25 2014-09-17 18:10:27.804 Predicate[10725:60b] id:109 name:1 author:26 2014-09-17 18:10:27.804 Predicate[10725:60b] id:101 name:1 author:27 2014-09-17 18:10:27.805 Predicate[10725:60b] CLASS B 2014-09-17 18:10:27.805 Predicate[10725:60b] bookId:100 value:12 term:12 2014-09-17 18:10:27.805 Predicate[10725:60b] bookId:101 value:13 term:13 2014-09-17 18:10:27.805 Predicate[10725:60b] bookId:102 value:13 term:13 2014-09-17 18:10:27.806 Predicate[10725:60b] bookId:103 value:13 term:13 2014-09-17 18:10:27.806 Predicate[10725:60b] bookId:104 value:13 term:13 2014-09-17 18:10:27.808 Predicate[10725:60b] RESULT 2014-09-17 18:10:27.809 Predicate[10725:60b] id:100 name:1 author:23 2014-09-17 18:10:27.809 Predicate[10725:60b] id:100 name:2 author:24 2014-09-17 18:10:27.809 Predicate[10725:60b] id:102 name:1 author:25 2014-09-17 18:10:27.809 Predicate[10725:60b] id:101 name:1 author:27 ``` hope it helps.
25,891,060
I have 2 NSArrays of 2 different types of custom objects. Object A properties: ID: Name: Author: Object B Properties: bookID: value: terminator: I need to filter an array of objects of type "A" that has the ID value equal to the bookID value of any of the objects of the second array that contains objects of type "B". I tried to use the intersectSet: method by converting the arrays to sets, but since both the objects are of different type, nothing happened. What will be the most efficient way to do the filtering? Can I specify the properties to look when I am doing an intersect?
2014/09/17
['https://Stackoverflow.com/questions/25891060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1200174/']
I m hopping your 2 NSArrays are like arrayA = ( ObjectA1, ObjectA2, . . ObjectAn ) and arrayB = ( ObjectB1, ObjectB2, . . ObjectBn ) In this case you have to first extract the values into separate arrays using predicate like this for both arrayA and arrayB ``` NSPredicate *predicateA = [NSPredicate predicateWithFormat:@"id"]; NSArray *arrayAWithonlyIds = [arrayA filteredArrayUsingPredicate:predicateA]; NSPredicate *predicateB = [NSPredicate predicateWithFormat:@"bookId"]; NSArray *arrayBWithonlyBookIds = [arrayA filteredArrayUsingPredicate:predicateB]; ``` Now you have to convert these result array containing only ids to NSSet inorder to perform set operation like intersection like this ``` NSMutableset *setResult = [NSMutableSet setWithArray: arrayAWithonlyIds]; [setResult intersectSet:[NSSet setWithArray: arrayBWithonlyBookIds]]; ``` I hope this gives you an Idea.
I used NSPredicate for filtering array; here is the code: ``` +(void)findIntersectionOfAuthors:(NSArray *)authors withBooks:(NSArray *)books { NSLog(@"CLASS A"); for (Author * aut in authors) [aut print]; NSLog(@"CLASS B"); for (Book * b in books) [b print]; NSMutableArray * resultOfpredicates = [NSMutableArray new]; for (Author * a in authors) { NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF.bookID == %d", a.authId];//this predicate search field of bookID equality in books array NSArray * bks = [books copy]; bks = [bks filteredArrayUsingPredicate:predicate];//filters here if ([bks count]) [resultOfpredicates addObject:a]; } NSLog(@"RESULT"); for (Author * a in resultOfpredicates) [a print]; } ``` i created Author (class A) and Book (class B) classes. here is the result of my code ``` 2014-09-17 18:10:27.803 Predicate[10725:60b] CLASS A 2014-09-17 18:10:27.803 Predicate[10725:60b] id:100 name:1 author:23 2014-09-17 18:10:27.803 Predicate[10725:60b] id:100 name:2 author:24 2014-09-17 18:10:27.804 Predicate[10725:60b] id:102 name:1 author:25 2014-09-17 18:10:27.804 Predicate[10725:60b] id:109 name:1 author:26 2014-09-17 18:10:27.804 Predicate[10725:60b] id:101 name:1 author:27 2014-09-17 18:10:27.805 Predicate[10725:60b] CLASS B 2014-09-17 18:10:27.805 Predicate[10725:60b] bookId:100 value:12 term:12 2014-09-17 18:10:27.805 Predicate[10725:60b] bookId:101 value:13 term:13 2014-09-17 18:10:27.805 Predicate[10725:60b] bookId:102 value:13 term:13 2014-09-17 18:10:27.806 Predicate[10725:60b] bookId:103 value:13 term:13 2014-09-17 18:10:27.806 Predicate[10725:60b] bookId:104 value:13 term:13 2014-09-17 18:10:27.808 Predicate[10725:60b] RESULT 2014-09-17 18:10:27.809 Predicate[10725:60b] id:100 name:1 author:23 2014-09-17 18:10:27.809 Predicate[10725:60b] id:100 name:2 author:24 2014-09-17 18:10:27.809 Predicate[10725:60b] id:102 name:1 author:25 2014-09-17 18:10:27.809 Predicate[10725:60b] id:101 name:1 author:27 ``` hope it helps.
9,918,552
I have an image compression algorithm that I can train and then feed it with some test images. There seems to be something wrong with this code though. To test this, I tried to give it the same test image that I have trained it with (i.e. test set== train set). Now the general question that I have is as follows What will happen if you test an algorithm with the exact same data that you have trained it with? My suspicion is that I should get the same result, as if I had never trained the algorithm (i.e. just had tested it with the original data without any training at all) What do you think of this situation? And what general type of tests (like a sanity check) do you suggest to make sure that an algorithms training phase is done reasonably? --- Thank you for you answers. The algorithm uses context tree weighteting which is calculated probabilty of 0 or 1 in a certain point of grayescale images.It uses context before this certain point to estimate its probabilty(0/1).compression ratio(bit/byte)is as measure of goodness of a result. First,I run ctw on single image(x) and the compression was 0.75 and then I trained with for example 6 images and tested with the same image(x) which is out of training set. But the compression ratio after training is 0.80 bit/byte. Images are 2048\*2048 grayscale. After getting these results, I tried to test correctness of ctw through cross validation and I got strange results that I explained before. I hope this information would be helpful to give me answer. Thank you
2012/03/29
['https://Stackoverflow.com/questions/9918552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1299705/']
Your suspicion is not correct. A ML algorithm should generally give very good results (in some cases, perfect) on the set that was used to train it, except when the algorithm is completely unsuitable for the task, or if it is badly conceived and doesn't converge. It is hard to tell because I'm not sure how you are teaching a compression algorithm. Are you using a ratio of original and output file size as the measure of "goodness" of a result? How are you adjusting the algorithm based on this, and how are you making sure the adjustments cause convergence, and don't just have random effects? As far as sanity check goes, if the algorithm gives no-better-than-random results on the set that was used to train it, the algorithm doesn't work. The opposite isn't true - the training set testing well does not mean the algorithm works well.
This depends entirely on the algorithm and on your problem. Some (e.g. classification with nearest-neighbor approaches) will trivially get perfect answers. Most will show better performance than they would on different test data drawn from the same distribution as the training data, but not perfect. I guess there might be some where it's as if you never trained it, but for most algorithms testing without any training isn't even a defined operation, or it's just a completely random result. Testing on the training data can be a decent sanity check that your code is working correctly, because it should do pretty well. But it's better to just have a small training set / test set that you use to test with, and just make sure that it does reasonable things on the test set. With classification or regression you'd usually do some variant of cross-validation (to avoid testing on the training set) to do real performance evaluations, and you can just do that on some small dataset that's quick to run on for testing your code. I don't quite know what the setting you're dealing with is, though. Could you explain a little more? i.e. how does the algorithm use its training set to do image compression?
20,952,372
I need my application to log in on site with user defined login and password. Although sending POST data is very simple I can't manage how to check if returned page shows "logged in" or "wrong password" statement. Searching .html string for specified statement is too slow and comparing pre-seted error page is not working because page is dynamic loaded (with same url). Is there any lib for managing .html content? I could use java or python as well as c# if i had to
2014/01/06
['https://Stackoverflow.com/questions/20952372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2843974/']
Eat Your Cookies ================ The majority of websites will use cookies to track the current user's session across multiple requests. You'll have to attach a cookie storage to your WebRequest when sending the POST request, and inspect the storage for the login response. Each website will implement their session tracking differently. So there is no one solution fits all, but for most cases all you'll have to do is verify that a cookie exists under a given name. What the cookie contains doesn't matter, but when that cookie exists you know login was successful. That cookie storage will have to be used for additional requests from the server for that user session. So you'll likely need to track cookies anyway. Websites can use other methods to track user sessions, including a session ID in GET parameters or use the web servers persistent connection. I don't know to many websites that log user's in that don't use cookies to track user sessions. I'd look there first.
Problem with logging in via a script, web-sites return `200 OK` response on both of login outcomes: logged in or not logged in. So you'll have to parse the incoming html for the required string to verify successful credential check. There is no other way for that, unless the site provides some API. The best way to parse resulting HTML is using [HTML Agility Pack](http://htmlagilitypack.codeplex.com/). I've used it in the past and it was a blast to get the required strings out of the pages.
20,952,372
I need my application to log in on site with user defined login and password. Although sending POST data is very simple I can't manage how to check if returned page shows "logged in" or "wrong password" statement. Searching .html string for specified statement is too slow and comparing pre-seted error page is not working because page is dynamic loaded (with same url). Is there any lib for managing .html content? I could use java or python as well as c# if i had to
2014/01/06
['https://Stackoverflow.com/questions/20952372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2843974/']
I made some research and found that regular expression perfectly fits my problem as they are **easy to implement**, and **really fast in that case**. If anyone would also have a problem like that: ``` using System.Text.RegularExpressions; // .html document returned by page string webRequestResponse = getResponse(); // site error string const string REGEX = "Password is not correct."; // check if page contain that error bool wrongPassword = Regex.IsMatch(webRequestResponse, REGEX); ```
Problem with logging in via a script, web-sites return `200 OK` response on both of login outcomes: logged in or not logged in. So you'll have to parse the incoming html for the required string to verify successful credential check. There is no other way for that, unless the site provides some API. The best way to parse resulting HTML is using [HTML Agility Pack](http://htmlagilitypack.codeplex.com/). I've used it in the past and it was a blast to get the required strings out of the pages.
20,952,372
I need my application to log in on site with user defined login and password. Although sending POST data is very simple I can't manage how to check if returned page shows "logged in" or "wrong password" statement. Searching .html string for specified statement is too slow and comparing pre-seted error page is not working because page is dynamic loaded (with same url). Is there any lib for managing .html content? I could use java or python as well as c# if i had to
2014/01/06
['https://Stackoverflow.com/questions/20952372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2843974/']
Eat Your Cookies ================ The majority of websites will use cookies to track the current user's session across multiple requests. You'll have to attach a cookie storage to your WebRequest when sending the POST request, and inspect the storage for the login response. Each website will implement their session tracking differently. So there is no one solution fits all, but for most cases all you'll have to do is verify that a cookie exists under a given name. What the cookie contains doesn't matter, but when that cookie exists you know login was successful. That cookie storage will have to be used for additional requests from the server for that user session. So you'll likely need to track cookies anyway. Websites can use other methods to track user sessions, including a session ID in GET parameters or use the web servers persistent connection. I don't know to many websites that log user's in that don't use cookies to track user sessions. I'd look there first.
I made some research and found that regular expression perfectly fits my problem as they are **easy to implement**, and **really fast in that case**. If anyone would also have a problem like that: ``` using System.Text.RegularExpressions; // .html document returned by page string webRequestResponse = getResponse(); // site error string const string REGEX = "Password is not correct."; // check if page contain that error bool wrongPassword = Regex.IsMatch(webRequestResponse, REGEX); ```
61,539,234
I'm trying to create Espresso tests and using a `mockWebServer` the thing is when I try to create my `mockWebServer` it calls the real api call and I want to intercept it and mock the response. My dagger organisation is : My App ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this) .inject(this) this.application = this } } ``` Then MyAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, RetrofitModule::class, RoomModule::class, AppFeaturesModule::class ] ) interface AppComponent : AndroidInjector<App> { @Component.Factory interface Factory { fun create(@BindsInstance application: App): AppComponent } } ``` Then I've created this TestApp ``` class TestApp : App() { override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { DaggerTestAppComponent.factory() .create(this) .inject(this) } } ``` And this is my TestAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } } ``` Note: Here I've created a new module, called `TestRetrofitModule` where the BASE\_URL is "<http://localhost:8080>", I don't know if I need something else. Also I've created the `TestRunner` ``` class TestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, TestApp::class.java.name, context) } } ``` And put it on the `testInstrumentationRunner` Problem 1 --------- I can not use ``` @Inject lateinit var okHttpClient: OkHttpClient ``` because it says that it's not initialised. Problem 2 (Solved thanks Skizo) ------------------------------- My mockWebServer is not dispatching the responses even-though is not pointing the real api call, is pointing the one that I've put to the TestRetrofitModule, the thing is that I have to link that mockWebServer and Retrofit.
2020/05/01
['https://Stackoverflow.com/questions/61539234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4329781/']
The setup you posted looks correct. As for `App` not being provided, you probably need to bind it in your component, since right now you're binding `TestApp` only. So you need to replace ```kotlin fun create(@BindsInstance application: TestApp): TestAppComponent ``` with ```kotlin fun create(@BindsInstance application: App): TestAppComponent ```
When I try to do something similar, I don't create two types of application-components, just one. I provide them with different inputs, based on whether it's for the actual `App` or for the `TestApp`. No need for `TestAppComponent` at all. E.g. ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this, createRetrofitModule()) .inject(this) this.application = this } protected fun createRetrofitModule() = RetrofitModule(BuildConfig.BASE_URL) } class TestApp : App() { override fun createRetrofitModule() = RetrofitModule("http://localhost:8080") } @Module class RetrofitModule(private val baseUrl: String) { ... provide your Retrofit and OkHttpClients here and use the 'baseUrl'. ... } ``` (not sure if this 'compiles' or not; I usually use the `builder()` pattern on a dagger-component, not the `factory()` pattern, but you get the idea). The pattern here is to provide your app-component or its modules with inputs for the 'edge-of-the-world', stuff that needs to be configured differently based on the context in which the app would run (contexts such as build-flavors, app running on consumer device vs running in instrumentation mode, etc). Examples are `BuildConfig` values (such as base-urls for networking), interface-implementations to real or fake hardware, interfaces to 3rd party libs, etc.
61,539,234
I'm trying to create Espresso tests and using a `mockWebServer` the thing is when I try to create my `mockWebServer` it calls the real api call and I want to intercept it and mock the response. My dagger organisation is : My App ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this) .inject(this) this.application = this } } ``` Then MyAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, RetrofitModule::class, RoomModule::class, AppFeaturesModule::class ] ) interface AppComponent : AndroidInjector<App> { @Component.Factory interface Factory { fun create(@BindsInstance application: App): AppComponent } } ``` Then I've created this TestApp ``` class TestApp : App() { override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { DaggerTestAppComponent.factory() .create(this) .inject(this) } } ``` And this is my TestAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } } ``` Note: Here I've created a new module, called `TestRetrofitModule` where the BASE\_URL is "<http://localhost:8080>", I don't know if I need something else. Also I've created the `TestRunner` ``` class TestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, TestApp::class.java.name, context) } } ``` And put it on the `testInstrumentationRunner` Problem 1 --------- I can not use ``` @Inject lateinit var okHttpClient: OkHttpClient ``` because it says that it's not initialised. Problem 2 (Solved thanks Skizo) ------------------------------- My mockWebServer is not dispatching the responses even-though is not pointing the real api call, is pointing the one that I've put to the TestRetrofitModule, the thing is that I have to link that mockWebServer and Retrofit.
2020/05/01
['https://Stackoverflow.com/questions/61539234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4329781/']
I had the same problem with `mockWebServer` recently, what you need to do is to put a breakpoint and see what's the error, in my case I put it on my `BaseRepository` where I was doing the call, and found that the exception was : ``` java.net.UnknownServiceException: CLEARTEXT communication to localhost not permitted by network security policy ``` What I did to solve the problem is add this on my `manifest.xml` ``` android:usesCleartextTraffic="true" ``` But you may have to use other approaches you can take a look on [android-8-cleartext-http-traffic-not-permitted](https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted).
The setup you posted looks correct. As for `App` not being provided, you probably need to bind it in your component, since right now you're binding `TestApp` only. So you need to replace ```kotlin fun create(@BindsInstance application: TestApp): TestAppComponent ``` with ```kotlin fun create(@BindsInstance application: App): TestAppComponent ```
61,539,234
I'm trying to create Espresso tests and using a `mockWebServer` the thing is when I try to create my `mockWebServer` it calls the real api call and I want to intercept it and mock the response. My dagger organisation is : My App ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this) .inject(this) this.application = this } } ``` Then MyAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, RetrofitModule::class, RoomModule::class, AppFeaturesModule::class ] ) interface AppComponent : AndroidInjector<App> { @Component.Factory interface Factory { fun create(@BindsInstance application: App): AppComponent } } ``` Then I've created this TestApp ``` class TestApp : App() { override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { DaggerTestAppComponent.factory() .create(this) .inject(this) } } ``` And this is my TestAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } } ``` Note: Here I've created a new module, called `TestRetrofitModule` where the BASE\_URL is "<http://localhost:8080>", I don't know if I need something else. Also I've created the `TestRunner` ``` class TestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, TestApp::class.java.name, context) } } ``` And put it on the `testInstrumentationRunner` Problem 1 --------- I can not use ``` @Inject lateinit var okHttpClient: OkHttpClient ``` because it says that it's not initialised. Problem 2 (Solved thanks Skizo) ------------------------------- My mockWebServer is not dispatching the responses even-though is not pointing the real api call, is pointing the one that I've put to the TestRetrofitModule, the thing is that I have to link that mockWebServer and Retrofit.
2020/05/01
['https://Stackoverflow.com/questions/61539234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4329781/']
The setup you posted looks correct. As for `App` not being provided, you probably need to bind it in your component, since right now you're binding `TestApp` only. So you need to replace ```kotlin fun create(@BindsInstance application: TestApp): TestAppComponent ``` with ```kotlin fun create(@BindsInstance application: App): TestAppComponent ```
I am presuming that you are trying to inject OkHttpClient: ``` @Inject lateinit var okHttpClient: OkHttpClient ``` in your TestApp class, and it fails. In order to make it work, you will need to add an inject method in your `TestAppComponent`, to inject the overriden TestApp, so that it becomes: ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } fun inject(testApp: TestApp) } ``` The reason why this is required, is because Dagger is type based, and uses the type of each class to be injected/provided to determine how to generate the code at compile-time. In your case, when you try to inject the TestApp, dagger will inject its superclass (the App class), because it only know that it has to inject the App class. If you have a look at the AndroidInjector interface (that you use in your AppComponent), you will see that it is declared like: ``` public interface AndroidInjector<T> { void inject(T instance) .... } ``` This means that it will generate a method: ``` fun inject(app App) ``` in the AppComponent. And this is why @Inject works in your App class, but does not work in your TestApp class, unless you explicitly provided it in the TestAppComponent.
61,539,234
I'm trying to create Espresso tests and using a `mockWebServer` the thing is when I try to create my `mockWebServer` it calls the real api call and I want to intercept it and mock the response. My dagger organisation is : My App ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this) .inject(this) this.application = this } } ``` Then MyAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, RetrofitModule::class, RoomModule::class, AppFeaturesModule::class ] ) interface AppComponent : AndroidInjector<App> { @Component.Factory interface Factory { fun create(@BindsInstance application: App): AppComponent } } ``` Then I've created this TestApp ``` class TestApp : App() { override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { DaggerTestAppComponent.factory() .create(this) .inject(this) } } ``` And this is my TestAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } } ``` Note: Here I've created a new module, called `TestRetrofitModule` where the BASE\_URL is "<http://localhost:8080>", I don't know if I need something else. Also I've created the `TestRunner` ``` class TestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, TestApp::class.java.name, context) } } ``` And put it on the `testInstrumentationRunner` Problem 1 --------- I can not use ``` @Inject lateinit var okHttpClient: OkHttpClient ``` because it says that it's not initialised. Problem 2 (Solved thanks Skizo) ------------------------------- My mockWebServer is not dispatching the responses even-though is not pointing the real api call, is pointing the one that I've put to the TestRetrofitModule, the thing is that I have to link that mockWebServer and Retrofit.
2020/05/01
['https://Stackoverflow.com/questions/61539234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4329781/']
The setup you posted looks correct. As for `App` not being provided, you probably need to bind it in your component, since right now you're binding `TestApp` only. So you need to replace ```kotlin fun create(@BindsInstance application: TestApp): TestAppComponent ``` with ```kotlin fun create(@BindsInstance application: App): TestAppComponent ```
How about `a dagger module` for your `Test Class` with a `ContributeAndroidInjector` in there and do `Inject` on a `@Before` method. Your `TestAppComponent`: ``` @Component(modules = [AndroidInjectionModule::class, TestAppModule::class]) interface TestAppComponent { fun inject(app: TestApp) @Component.Builder interface Builder { @BindsInstance fun application(application: TestApp): Builder fun build(): TestAppComponent } } ``` `TestAppModule` like: ``` @Module interface TestAppModule { @ContributesAndroidInjector(modules = [Provider::class]) fun activity(): MainActivity @Module object Provider { @Provides @JvmStatic fun provideString(): String = "This is test." } // Your other dependencies here } ``` And `@Before` method of `Test Class` you must be do: ``` @Before fun setUp() { val instrumentation = InstrumentationRegistry.getInstrumentation() val app = instrumentation.targetContext.applicationContext as TestApp DaggerTestAppComponent.builder().application(app).build().inject(app) // Some things other } ``` An important thing, you must be have (on `build.gradle` module `app`): ``` kaptAndroidTest "com.google.dagger:dagger-compiler:$version_dagger" kaptAndroidTest "com.google.dagger:dagger-android-processor:$version" ``` Now, when you launch an `Activity` like `MainActivity`, Dagger will inject `dependencies` from your `TestAppModule` instead of `AppModule` before. Moreover, If you want to `@Inject` to `Test Class`, you can add: ``` fun inject(testClass: TestClass) // On Your TestAppComponent ``` And then, you can call: ``` DaggerTestAppComponent.builder().application(app).build().inject(this) // This is on your TestClass ``` to Inject some dependencies to your `TestClass`. Hope this can help you!!
61,539,234
I'm trying to create Espresso tests and using a `mockWebServer` the thing is when I try to create my `mockWebServer` it calls the real api call and I want to intercept it and mock the response. My dagger organisation is : My App ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this) .inject(this) this.application = this } } ``` Then MyAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, RetrofitModule::class, RoomModule::class, AppFeaturesModule::class ] ) interface AppComponent : AndroidInjector<App> { @Component.Factory interface Factory { fun create(@BindsInstance application: App): AppComponent } } ``` Then I've created this TestApp ``` class TestApp : App() { override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { DaggerTestAppComponent.factory() .create(this) .inject(this) } } ``` And this is my TestAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } } ``` Note: Here I've created a new module, called `TestRetrofitModule` where the BASE\_URL is "<http://localhost:8080>", I don't know if I need something else. Also I've created the `TestRunner` ``` class TestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, TestApp::class.java.name, context) } } ``` And put it on the `testInstrumentationRunner` Problem 1 --------- I can not use ``` @Inject lateinit var okHttpClient: OkHttpClient ``` because it says that it's not initialised. Problem 2 (Solved thanks Skizo) ------------------------------- My mockWebServer is not dispatching the responses even-though is not pointing the real api call, is pointing the one that I've put to the TestRetrofitModule, the thing is that I have to link that mockWebServer and Retrofit.
2020/05/01
['https://Stackoverflow.com/questions/61539234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4329781/']
I had the same problem with `mockWebServer` recently, what you need to do is to put a breakpoint and see what's the error, in my case I put it on my `BaseRepository` where I was doing the call, and found that the exception was : ``` java.net.UnknownServiceException: CLEARTEXT communication to localhost not permitted by network security policy ``` What I did to solve the problem is add this on my `manifest.xml` ``` android:usesCleartextTraffic="true" ``` But you may have to use other approaches you can take a look on [android-8-cleartext-http-traffic-not-permitted](https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted).
When I try to do something similar, I don't create two types of application-components, just one. I provide them with different inputs, based on whether it's for the actual `App` or for the `TestApp`. No need for `TestAppComponent` at all. E.g. ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this, createRetrofitModule()) .inject(this) this.application = this } protected fun createRetrofitModule() = RetrofitModule(BuildConfig.BASE_URL) } class TestApp : App() { override fun createRetrofitModule() = RetrofitModule("http://localhost:8080") } @Module class RetrofitModule(private val baseUrl: String) { ... provide your Retrofit and OkHttpClients here and use the 'baseUrl'. ... } ``` (not sure if this 'compiles' or not; I usually use the `builder()` pattern on a dagger-component, not the `factory()` pattern, but you get the idea). The pattern here is to provide your app-component or its modules with inputs for the 'edge-of-the-world', stuff that needs to be configured differently based on the context in which the app would run (contexts such as build-flavors, app running on consumer device vs running in instrumentation mode, etc). Examples are `BuildConfig` values (such as base-urls for networking), interface-implementations to real or fake hardware, interfaces to 3rd party libs, etc.
61,539,234
I'm trying to create Espresso tests and using a `mockWebServer` the thing is when I try to create my `mockWebServer` it calls the real api call and I want to intercept it and mock the response. My dagger organisation is : My App ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this) .inject(this) this.application = this } } ``` Then MyAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, RetrofitModule::class, RoomModule::class, AppFeaturesModule::class ] ) interface AppComponent : AndroidInjector<App> { @Component.Factory interface Factory { fun create(@BindsInstance application: App): AppComponent } } ``` Then I've created this TestApp ``` class TestApp : App() { override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { DaggerTestAppComponent.factory() .create(this) .inject(this) } } ``` And this is my TestAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } } ``` Note: Here I've created a new module, called `TestRetrofitModule` where the BASE\_URL is "<http://localhost:8080>", I don't know if I need something else. Also I've created the `TestRunner` ``` class TestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, TestApp::class.java.name, context) } } ``` And put it on the `testInstrumentationRunner` Problem 1 --------- I can not use ``` @Inject lateinit var okHttpClient: OkHttpClient ``` because it says that it's not initialised. Problem 2 (Solved thanks Skizo) ------------------------------- My mockWebServer is not dispatching the responses even-though is not pointing the real api call, is pointing the one that I've put to the TestRetrofitModule, the thing is that I have to link that mockWebServer and Retrofit.
2020/05/01
['https://Stackoverflow.com/questions/61539234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4329781/']
When I try to do something similar, I don't create two types of application-components, just one. I provide them with different inputs, based on whether it's for the actual `App` or for the `TestApp`. No need for `TestAppComponent` at all. E.g. ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this, createRetrofitModule()) .inject(this) this.application = this } protected fun createRetrofitModule() = RetrofitModule(BuildConfig.BASE_URL) } class TestApp : App() { override fun createRetrofitModule() = RetrofitModule("http://localhost:8080") } @Module class RetrofitModule(private val baseUrl: String) { ... provide your Retrofit and OkHttpClients here and use the 'baseUrl'. ... } ``` (not sure if this 'compiles' or not; I usually use the `builder()` pattern on a dagger-component, not the `factory()` pattern, but you get the idea). The pattern here is to provide your app-component or its modules with inputs for the 'edge-of-the-world', stuff that needs to be configured differently based on the context in which the app would run (contexts such as build-flavors, app running on consumer device vs running in instrumentation mode, etc). Examples are `BuildConfig` values (such as base-urls for networking), interface-implementations to real or fake hardware, interfaces to 3rd party libs, etc.
I am presuming that you are trying to inject OkHttpClient: ``` @Inject lateinit var okHttpClient: OkHttpClient ``` in your TestApp class, and it fails. In order to make it work, you will need to add an inject method in your `TestAppComponent`, to inject the overriden TestApp, so that it becomes: ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } fun inject(testApp: TestApp) } ``` The reason why this is required, is because Dagger is type based, and uses the type of each class to be injected/provided to determine how to generate the code at compile-time. In your case, when you try to inject the TestApp, dagger will inject its superclass (the App class), because it only know that it has to inject the App class. If you have a look at the AndroidInjector interface (that you use in your AppComponent), you will see that it is declared like: ``` public interface AndroidInjector<T> { void inject(T instance) .... } ``` This means that it will generate a method: ``` fun inject(app App) ``` in the AppComponent. And this is why @Inject works in your App class, but does not work in your TestApp class, unless you explicitly provided it in the TestAppComponent.
61,539,234
I'm trying to create Espresso tests and using a `mockWebServer` the thing is when I try to create my `mockWebServer` it calls the real api call and I want to intercept it and mock the response. My dagger organisation is : My App ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this) .inject(this) this.application = this } } ``` Then MyAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, RetrofitModule::class, RoomModule::class, AppFeaturesModule::class ] ) interface AppComponent : AndroidInjector<App> { @Component.Factory interface Factory { fun create(@BindsInstance application: App): AppComponent } } ``` Then I've created this TestApp ``` class TestApp : App() { override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { DaggerTestAppComponent.factory() .create(this) .inject(this) } } ``` And this is my TestAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } } ``` Note: Here I've created a new module, called `TestRetrofitModule` where the BASE\_URL is "<http://localhost:8080>", I don't know if I need something else. Also I've created the `TestRunner` ``` class TestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, TestApp::class.java.name, context) } } ``` And put it on the `testInstrumentationRunner` Problem 1 --------- I can not use ``` @Inject lateinit var okHttpClient: OkHttpClient ``` because it says that it's not initialised. Problem 2 (Solved thanks Skizo) ------------------------------- My mockWebServer is not dispatching the responses even-though is not pointing the real api call, is pointing the one that I've put to the TestRetrofitModule, the thing is that I have to link that mockWebServer and Retrofit.
2020/05/01
['https://Stackoverflow.com/questions/61539234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4329781/']
I had the same problem with `mockWebServer` recently, what you need to do is to put a breakpoint and see what's the error, in my case I put it on my `BaseRepository` where I was doing the call, and found that the exception was : ``` java.net.UnknownServiceException: CLEARTEXT communication to localhost not permitted by network security policy ``` What I did to solve the problem is add this on my `manifest.xml` ``` android:usesCleartextTraffic="true" ``` But you may have to use other approaches you can take a look on [android-8-cleartext-http-traffic-not-permitted](https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted).
I am presuming that you are trying to inject OkHttpClient: ``` @Inject lateinit var okHttpClient: OkHttpClient ``` in your TestApp class, and it fails. In order to make it work, you will need to add an inject method in your `TestAppComponent`, to inject the overriden TestApp, so that it becomes: ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } fun inject(testApp: TestApp) } ``` The reason why this is required, is because Dagger is type based, and uses the type of each class to be injected/provided to determine how to generate the code at compile-time. In your case, when you try to inject the TestApp, dagger will inject its superclass (the App class), because it only know that it has to inject the App class. If you have a look at the AndroidInjector interface (that you use in your AppComponent), you will see that it is declared like: ``` public interface AndroidInjector<T> { void inject(T instance) .... } ``` This means that it will generate a method: ``` fun inject(app App) ``` in the AppComponent. And this is why @Inject works in your App class, but does not work in your TestApp class, unless you explicitly provided it in the TestAppComponent.
61,539,234
I'm trying to create Espresso tests and using a `mockWebServer` the thing is when I try to create my `mockWebServer` it calls the real api call and I want to intercept it and mock the response. My dagger organisation is : My App ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this) .inject(this) this.application = this } } ``` Then MyAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, RetrofitModule::class, RoomModule::class, AppFeaturesModule::class ] ) interface AppComponent : AndroidInjector<App> { @Component.Factory interface Factory { fun create(@BindsInstance application: App): AppComponent } } ``` Then I've created this TestApp ``` class TestApp : App() { override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { DaggerTestAppComponent.factory() .create(this) .inject(this) } } ``` And this is my TestAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } } ``` Note: Here I've created a new module, called `TestRetrofitModule` where the BASE\_URL is "<http://localhost:8080>", I don't know if I need something else. Also I've created the `TestRunner` ``` class TestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, TestApp::class.java.name, context) } } ``` And put it on the `testInstrumentationRunner` Problem 1 --------- I can not use ``` @Inject lateinit var okHttpClient: OkHttpClient ``` because it says that it's not initialised. Problem 2 (Solved thanks Skizo) ------------------------------- My mockWebServer is not dispatching the responses even-though is not pointing the real api call, is pointing the one that I've put to the TestRetrofitModule, the thing is that I have to link that mockWebServer and Retrofit.
2020/05/01
['https://Stackoverflow.com/questions/61539234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4329781/']
I had the same problem with `mockWebServer` recently, what you need to do is to put a breakpoint and see what's the error, in my case I put it on my `BaseRepository` where I was doing the call, and found that the exception was : ``` java.net.UnknownServiceException: CLEARTEXT communication to localhost not permitted by network security policy ``` What I did to solve the problem is add this on my `manifest.xml` ``` android:usesCleartextTraffic="true" ``` But you may have to use other approaches you can take a look on [android-8-cleartext-http-traffic-not-permitted](https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted).
How about `a dagger module` for your `Test Class` with a `ContributeAndroidInjector` in there and do `Inject` on a `@Before` method. Your `TestAppComponent`: ``` @Component(modules = [AndroidInjectionModule::class, TestAppModule::class]) interface TestAppComponent { fun inject(app: TestApp) @Component.Builder interface Builder { @BindsInstance fun application(application: TestApp): Builder fun build(): TestAppComponent } } ``` `TestAppModule` like: ``` @Module interface TestAppModule { @ContributesAndroidInjector(modules = [Provider::class]) fun activity(): MainActivity @Module object Provider { @Provides @JvmStatic fun provideString(): String = "This is test." } // Your other dependencies here } ``` And `@Before` method of `Test Class` you must be do: ``` @Before fun setUp() { val instrumentation = InstrumentationRegistry.getInstrumentation() val app = instrumentation.targetContext.applicationContext as TestApp DaggerTestAppComponent.builder().application(app).build().inject(app) // Some things other } ``` An important thing, you must be have (on `build.gradle` module `app`): ``` kaptAndroidTest "com.google.dagger:dagger-compiler:$version_dagger" kaptAndroidTest "com.google.dagger:dagger-android-processor:$version" ``` Now, when you launch an `Activity` like `MainActivity`, Dagger will inject `dependencies` from your `TestAppModule` instead of `AppModule` before. Moreover, If you want to `@Inject` to `Test Class`, you can add: ``` fun inject(testClass: TestClass) // On Your TestAppComponent ``` And then, you can call: ``` DaggerTestAppComponent.builder().application(app).build().inject(this) // This is on your TestClass ``` to Inject some dependencies to your `TestClass`. Hope this can help you!!
61,539,234
I'm trying to create Espresso tests and using a `mockWebServer` the thing is when I try to create my `mockWebServer` it calls the real api call and I want to intercept it and mock the response. My dagger organisation is : My App ``` open class App : Application(), HasAndroidInjector { lateinit var application: Application @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.factory() .create(this) .inject(this) this.application = this } } ``` Then MyAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, RetrofitModule::class, RoomModule::class, AppFeaturesModule::class ] ) interface AppComponent : AndroidInjector<App> { @Component.Factory interface Factory { fun create(@BindsInstance application: App): AppComponent } } ``` Then I've created this TestApp ``` class TestApp : App() { override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun onCreate() { DaggerTestAppComponent.factory() .create(this) .inject(this) } } ``` And this is my TestAppComponent ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } } ``` Note: Here I've created a new module, called `TestRetrofitModule` where the BASE\_URL is "<http://localhost:8080>", I don't know if I need something else. Also I've created the `TestRunner` ``` class TestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, TestApp::class.java.name, context) } } ``` And put it on the `testInstrumentationRunner` Problem 1 --------- I can not use ``` @Inject lateinit var okHttpClient: OkHttpClient ``` because it says that it's not initialised. Problem 2 (Solved thanks Skizo) ------------------------------- My mockWebServer is not dispatching the responses even-though is not pointing the real api call, is pointing the one that I've put to the TestRetrofitModule, the thing is that I have to link that mockWebServer and Retrofit.
2020/05/01
['https://Stackoverflow.com/questions/61539234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4329781/']
How about `a dagger module` for your `Test Class` with a `ContributeAndroidInjector` in there and do `Inject` on a `@Before` method. Your `TestAppComponent`: ``` @Component(modules = [AndroidInjectionModule::class, TestAppModule::class]) interface TestAppComponent { fun inject(app: TestApp) @Component.Builder interface Builder { @BindsInstance fun application(application: TestApp): Builder fun build(): TestAppComponent } } ``` `TestAppModule` like: ``` @Module interface TestAppModule { @ContributesAndroidInjector(modules = [Provider::class]) fun activity(): MainActivity @Module object Provider { @Provides @JvmStatic fun provideString(): String = "This is test." } // Your other dependencies here } ``` And `@Before` method of `Test Class` you must be do: ``` @Before fun setUp() { val instrumentation = InstrumentationRegistry.getInstrumentation() val app = instrumentation.targetContext.applicationContext as TestApp DaggerTestAppComponent.builder().application(app).build().inject(app) // Some things other } ``` An important thing, you must be have (on `build.gradle` module `app`): ``` kaptAndroidTest "com.google.dagger:dagger-compiler:$version_dagger" kaptAndroidTest "com.google.dagger:dagger-android-processor:$version" ``` Now, when you launch an `Activity` like `MainActivity`, Dagger will inject `dependencies` from your `TestAppModule` instead of `AppModule` before. Moreover, If you want to `@Inject` to `Test Class`, you can add: ``` fun inject(testClass: TestClass) // On Your TestAppComponent ``` And then, you can call: ``` DaggerTestAppComponent.builder().application(app).build().inject(this) // This is on your TestClass ``` to Inject some dependencies to your `TestClass`. Hope this can help you!!
I am presuming that you are trying to inject OkHttpClient: ``` @Inject lateinit var okHttpClient: OkHttpClient ``` in your TestApp class, and it fails. In order to make it work, you will need to add an inject method in your `TestAppComponent`, to inject the overriden TestApp, so that it becomes: ``` @Singleton @Component( modules = [ AndroidInjectionModule::class, AppModule::class, TestRetrofitModule::class, AppFeaturesModule::class, RoomModule::class] ) interface TestAppComponent : AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance application: App): TestAppComponent } fun inject(testApp: TestApp) } ``` The reason why this is required, is because Dagger is type based, and uses the type of each class to be injected/provided to determine how to generate the code at compile-time. In your case, when you try to inject the TestApp, dagger will inject its superclass (the App class), because it only know that it has to inject the App class. If you have a look at the AndroidInjector interface (that you use in your AppComponent), you will see that it is declared like: ``` public interface AndroidInjector<T> { void inject(T instance) .... } ``` This means that it will generate a method: ``` fun inject(app App) ``` in the AppComponent. And this is why @Inject works in your App class, but does not work in your TestApp class, unless you explicitly provided it in the TestAppComponent.
67,309,013
I'm trying to draw a rotated shape at a given point. To give an example, in the following image, the red rectangle is a non-rotated rectangle drawn at a point and then the blue rectangle is rotated and drawn at the same position. The blue rectangle is the outcome I'm aiming for. [![](https://i.stack.imgur.com/1gIYm.png)](https://i.stack.imgur.com/1gIYm.png) I've been experimenting and trying different methods. Currently, here is what I used for the image: ``` Point point = new Point(300, 300); Dimension dim = new Dimension(200, 100); double radians = Math.toRadians(30); g.setColor(new java.awt.Color(1f, 0f, 0f, .5f)); g.fillRect(point.x, point.y, dim.width, dim.height); translate(g, dim, radians); g.rotate(radians, point.getX(), point.getY()); g.setColor(new java.awt.Color(0f, 0f, 1f, .5f)); g.fillRect(point.x, point.y, dim.width, dim.height); private static void translate(Graphics2D g, Dimension dim, double radians) { if (radians > Math.toRadians(360)) { radians %= Math.toRadians(360); } int xOffsetX = 0; int xOffsetY = 0; int yOffsetX = 0; int yOffsetY = 0; if (radians > 0 && radians <= Math.toRadians(90)) { xOffsetY -= dim.getHeight(); } else if (radians > Math.toRadians(90) && radians <= Math.toRadians(180)) { xOffsetX -= dim.getWidth(); xOffsetY -= dim.getHeight(); yOffsetY -= dim.getHeight(); } else if (radians > Math.toRadians(180) && radians <= Math.toRadians(270)) { xOffsetX -= dim.getWidth(); yOffsetX -= dim.getWidth(); yOffsetY -= dim.getHeight(); } else { yOffsetX -= dim.getWidth(); } int x = rotateX(xOffsetX, xOffsetY, radians); int y = rotateY(yOffsetX, yOffsetY, radians); g.translate(x, y); } private static int rotateX(int x, int y, double radians) { if (x == 0 && y == 0) { return 0; } return (int) Math.round(x * Math.cos(radians) - y * Math.sin(radians)); } private static int rotateY(int x, int y, double radians) { if (x == 0 && y == 0) { return 0; } return (int) Math.round(x * Math.sin(radians) + y * Math.cos(radians)); } ``` This works for rectangles but doesn't work for other types of shapes. I'm trying to figure out if there is a way to accomplish this for every type of shape. Also note that the code is just for testing purposes and there are a lot of bad practices in it, like calling Math.toRadians so much.
2021/04/28
['https://Stackoverflow.com/questions/67309013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11235159/']
Something like this? [![enter image description here](https://i.stack.imgur.com/yzHpM.png)](https://i.stack.imgur.com/yzHpM.png) [![enter image description here](https://i.stack.imgur.com/CT9or.png)](https://i.stack.imgur.com/CT9or.png) [![enter image description here](https://i.stack.imgur.com/63oo5.png)](https://i.stack.imgur.com/63oo5.png) It can be achieved using a rotate transform first, then using the bounds of the rotated shape as a basis, the translate transform can be used to shift it back to meet the top most `y` and leftmost `x` values of the original rectangle. See the `getImage()` method for one implementation of that. ``` int a = angleModel.getNumber().intValue(); AffineTransform rotateTransform = AffineTransform.getRotateInstance((a*2*Math.PI)/360d); // rotate the original shape with no regard to the final bounds Shape rotatedShape = rotateTransform.createTransformedShape(rectangle); // get the bounds of the rotated shape Rectangle2D rotatedRect = rotatedShape.getBounds2D(); // calculate the x,y offset needed to shift it to top/left bounds of original rectangle double xOff = rectangle.getX()-rotatedRect.getX(); double yOff = rectangle.getY()-rotatedRect.getY(); AffineTransform translateTransform = AffineTransform.getTranslateInstance(xOff, yOff); // shift the new shape to the top left of original rectangle Shape rotateAndTranslateShape = translateTransform.createTransformedShape(rotatedShape); ``` Here is the complete source code: ``` import java.awt.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.EmptyBorder; public class TransformedShape { private JComponent ui = null; JLabel output = new JLabel(); JToolBar tools = new JToolBar("Tools"); ChangeListener changeListener = (ChangeEvent e) -> { refresh(); }; int pad = 5; Rectangle2D.Double rectangle = new Rectangle2D.Double(pad,pad,200,100); SpinnerNumberModel angleModel = new SpinnerNumberModel(30, 0, 90, 1); public TransformedShape() { initUI(); } private BufferedImage getImage() { int a = angleModel.getNumber().intValue(); AffineTransform rotateTransform = AffineTransform.getRotateInstance((a*2*Math.PI)/360d); Shape rotatedShape = rotateTransform.createTransformedShape(rectangle); Rectangle2D rotatedRect = rotatedShape.getBounds2D(); double xOff = rectangle.getX()-rotatedRect.getX(); double yOff = rectangle.getY()-rotatedRect.getY(); AffineTransform translateTransform = AffineTransform.getTranslateInstance(xOff, yOff); Shape rotateAndTranslateShape = translateTransform.createTransformedShape(rotatedShape); Area combinedShape = new Area(rotateAndTranslateShape); combinedShape.add(new Area(rectangle)); Rectangle2D r = combinedShape.getBounds2D(); BufferedImage bi = new BufferedImage((int)(r.getWidth()+(2*pad)), (int)(r.getHeight()+(2*pad)), BufferedImage.TYPE_INT_ARGB); Graphics2D g = bi.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(new Color(255,0,0,127)); g.fill(rectangle); g.setColor(new Color(0,0,255,127)); g.fill(rotateAndTranslateShape); g.dispose(); return bi; } private void addModelToToolbar(String label, SpinnerNumberModel model) { tools.add(new JLabel(label)); JSpinner spinner = new JSpinner(model); spinner.addChangeListener(changeListener); tools.add(spinner); } public final void initUI() { if (ui!=null) return; ui = new JPanel(new BorderLayout(4,4)); ui.setBorder(new EmptyBorder(4,4,4,4)); ui.add(output); ui.add(tools,BorderLayout.PAGE_START); addModelToToolbar("Angle", angleModel); refresh(); } private void refresh() { output.setIcon(new ImageIcon(getImage())); } public JComponent getUI() { return ui; } public static void main(String[] args) { Runnable r = () -> { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { ex.printStackTrace(); } TransformedShape o = new TransformedShape(); JFrame f = new JFrame(o.getClass().getSimpleName()); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setLocationByPlatform(true); f.setContentPane(o.getUI()); f.pack(); f.setMinimumSize(f.getSize()); f.setVisible(true); }; SwingUtilities.invokeLater(r); } } ```
You have a shape, any shape. You have a point `(px,py)` and you want to rotate the shape around this point and angle `ag` measured counter-clokwise. For each point of the shape the proccess has three steps: 1. Translate to `(px,py)` 2. Rotate 3. Translate back to `(0,0)` The translation is fully simple ``` xNew = xOld - px yNew = yOld - py ``` The rotation is a bit less simple ``` xRot = xNew * cos(ag) - yNew * sin(ag) yRot = xNew * sin(ag) + yNew * cos(ag) ``` Finally the translation back: ``` xDef = xRot + px yDef = yRot + py ``` A bit of explanation: Any transformation can be seen in two ways: 1) I move the shape 2) I move the axis-system. If you think about it, you'll find that the trasnsformation is relative: seen from the axis point of view or seen from the shape point of view. So, you can say "I want coordinates in the translated system", or you can also say "I want the coordinates of the translated shape". It doesn't matter what point of view you chose, the equations are the same. I'm explaining this so much, just to achieve you realize which is the positive direction of the angle: clockwise or counter-clockwise.
3,264,251
Let $G$ be a group with $y\in{G}$ and $n,r\in\mathbb{N}$. If $o(y)=n$, what is $o(y^r)$? My attempt: Let $$o(y^r)=a,$$ Then we have $$1\_G=(y^r)^a=(y)^{ra}.$$ So we have that $$n\mid ra,$$ So either $r$ or $a$ (or both) is a multiple of $n$. I'm not too sure where to go from here or if this is even the most effective approach.
2019/06/16
['https://math.stackexchange.com/questions/3264251', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/514050/']
No, take $\color{blue}{f(x)=1}$ and $\color{red}{g(x)=1-{1\over 2^x}}$ [![enter image description here](https://i.stack.imgur.com/VfsY1.png)](https://i.stack.imgur.com/VfsY1.png) --- If $f'(x)-g'(x)>0$ then this would be true.
Consider $f(x) = x+17$ and $g(x) = x.$ They increase at the same rate everywhere for any reasonable definition, yet $f > g.$
3,264,251
Let $G$ be a group with $y\in{G}$ and $n,r\in\mathbb{N}$. If $o(y)=n$, what is $o(y^r)$? My attempt: Let $$o(y^r)=a,$$ Then we have $$1\_G=(y^r)^a=(y)^{ra}.$$ So we have that $$n\mid ra,$$ So either $r$ or $a$ (or both) is a multiple of $n$. I'm not too sure where to go from here or if this is even the most effective approach.
2019/06/16
['https://math.stackexchange.com/questions/3264251', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/514050/']
No, take $\color{blue}{f(x)=1}$ and $\color{red}{g(x)=1-{1\over 2^x}}$ [![enter image description here](https://i.stack.imgur.com/VfsY1.png)](https://i.stack.imgur.com/VfsY1.png) --- If $f'(x)-g'(x)>0$ then this would be true.
Consider $g(x)=-e^{-x}$. That increases to $0$. Now take $f(x)=e^{-x}$. That decreases to $0$. Clearly $$f(x)>g(x)$$ Thus, knowing that $f$ is bigger than an increasing function $g$ doesn't even prove that $f$ is increasing.
3,264,251
Let $G$ be a group with $y\in{G}$ and $n,r\in\mathbb{N}$. If $o(y)=n$, what is $o(y^r)$? My attempt: Let $$o(y^r)=a,$$ Then we have $$1\_G=(y^r)^a=(y)^{ra}.$$ So we have that $$n\mid ra,$$ So either $r$ or $a$ (or both) is a multiple of $n$. I'm not too sure where to go from here or if this is even the most effective approach.
2019/06/16
['https://math.stackexchange.com/questions/3264251', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/514050/']
No, take $\color{blue}{f(x)=1}$ and $\color{red}{g(x)=1-{1\over 2^x}}$ [![enter image description here](https://i.stack.imgur.com/VfsY1.png)](https://i.stack.imgur.com/VfsY1.png) --- If $f'(x)-g'(x)>0$ then this would be true.
If $f$ increases more quickly than $g$, that simply means the function $f-g$ is increasing. So you want to show that $(f-g)'>0$ Your question therefore boils down to, is: $$f-g>0\implies (f-g)'>0$$ true? You can define $h(x)=f(x)-g(x)$ to give the statement: $$h(x)>0\implies h'(x)>0$$ f0r which I supply $h:\Bbb R^+ \mapsto \Bbb R: h(x)=\frac1x$ as an adequate counterexample.
3,264,251
Let $G$ be a group with $y\in{G}$ and $n,r\in\mathbb{N}$. If $o(y)=n$, what is $o(y^r)$? My attempt: Let $$o(y^r)=a,$$ Then we have $$1\_G=(y^r)^a=(y)^{ra}.$$ So we have that $$n\mid ra,$$ So either $r$ or $a$ (or both) is a multiple of $n$. I'm not too sure where to go from here or if this is even the most effective approach.
2019/06/16
['https://math.stackexchange.com/questions/3264251', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/514050/']
Consider $g(x)=-e^{-x}$. That increases to $0$. Now take $f(x)=e^{-x}$. That decreases to $0$. Clearly $$f(x)>g(x)$$ Thus, knowing that $f$ is bigger than an increasing function $g$ doesn't even prove that $f$ is increasing.
Consider $f(x) = x+17$ and $g(x) = x.$ They increase at the same rate everywhere for any reasonable definition, yet $f > g.$
3,264,251
Let $G$ be a group with $y\in{G}$ and $n,r\in\mathbb{N}$. If $o(y)=n$, what is $o(y^r)$? My attempt: Let $$o(y^r)=a,$$ Then we have $$1\_G=(y^r)^a=(y)^{ra}.$$ So we have that $$n\mid ra,$$ So either $r$ or $a$ (or both) is a multiple of $n$. I'm not too sure where to go from here or if this is even the most effective approach.
2019/06/16
['https://math.stackexchange.com/questions/3264251', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/514050/']
Consider $f(x) = x+17$ and $g(x) = x.$ They increase at the same rate everywhere for any reasonable definition, yet $f > g.$
If $f$ increases more quickly than $g$, that simply means the function $f-g$ is increasing. So you want to show that $(f-g)'>0$ Your question therefore boils down to, is: $$f-g>0\implies (f-g)'>0$$ true? You can define $h(x)=f(x)-g(x)$ to give the statement: $$h(x)>0\implies h'(x)>0$$ f0r which I supply $h:\Bbb R^+ \mapsto \Bbb R: h(x)=\frac1x$ as an adequate counterexample.
3,264,251
Let $G$ be a group with $y\in{G}$ and $n,r\in\mathbb{N}$. If $o(y)=n$, what is $o(y^r)$? My attempt: Let $$o(y^r)=a,$$ Then we have $$1\_G=(y^r)^a=(y)^{ra}.$$ So we have that $$n\mid ra,$$ So either $r$ or $a$ (or both) is a multiple of $n$. I'm not too sure where to go from here or if this is even the most effective approach.
2019/06/16
['https://math.stackexchange.com/questions/3264251', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/514050/']
Consider $g(x)=-e^{-x}$. That increases to $0$. Now take $f(x)=e^{-x}$. That decreases to $0$. Clearly $$f(x)>g(x)$$ Thus, knowing that $f$ is bigger than an increasing function $g$ doesn't even prove that $f$ is increasing.
If $f$ increases more quickly than $g$, that simply means the function $f-g$ is increasing. So you want to show that $(f-g)'>0$ Your question therefore boils down to, is: $$f-g>0\implies (f-g)'>0$$ true? You can define $h(x)=f(x)-g(x)$ to give the statement: $$h(x)>0\implies h'(x)>0$$ f0r which I supply $h:\Bbb R^+ \mapsto \Bbb R: h(x)=\frac1x$ as an adequate counterexample.
709,346
I'm working with a startup that's teaching kids to program. We've just obtained our first "fleet" of laptops - half a dozen refurbished thinkpads running Windows 7 - and I'm looking for the best way to administer and maintain them. I've already determined that it appears to make sense to buy a volume license key, so I can use reimaging rights and generate a single known good image I can write to all of them, and use to wipe out a computer whenever I need to. What I'm wondering about now is how best to manage them on an ongoing basis. The laptops will run on a variety of networks - none of them controlled by us - and we've got no central office or servers. We'd rather not acquire any. I'd like to be able to easily push out updates and new software to all the laptops, as well as doing things like remotely configuring administrator accounts, and managing patches to make sure the laptops are kept up to date. As a tiny startup, funds are limited, and money spent on software licenses is money we could have spent on more hardware, so expensive solutions are a bit of a no-go. Does anyone have any recommendations for how we can most easily do this?
2015/07/29
['https://serverfault.com/questions/709346', 'https://serverfault.com', 'https://serverfault.com/users/83562/']
This is the perfect use case for [Microsoft Intune](http://www.microsoft.com/en-us/server-cloud/products/microsoft-intune/). While it is primarily known as an MDM solution, it also has PC management capabilities as well, such as app deployment and patch management. It's also completely cloud-based and is licensed on a per-device per-month basis, so it can scale as you grow. If you're already managing internal devices with System a Center Configuration Manager, it has some neat integration. If not, it's perfectly functional as a standalone product as well.
It would be possible to automatically connect each laptop to a VPN network. All you would need is an VPN server / router. And some configuration for the laptop to connect to vpn on logon. After that you could simply RDP to it.
709,346
I'm working with a startup that's teaching kids to program. We've just obtained our first "fleet" of laptops - half a dozen refurbished thinkpads running Windows 7 - and I'm looking for the best way to administer and maintain them. I've already determined that it appears to make sense to buy a volume license key, so I can use reimaging rights and generate a single known good image I can write to all of them, and use to wipe out a computer whenever I need to. What I'm wondering about now is how best to manage them on an ongoing basis. The laptops will run on a variety of networks - none of them controlled by us - and we've got no central office or servers. We'd rather not acquire any. I'd like to be able to easily push out updates and new software to all the laptops, as well as doing things like remotely configuring administrator accounts, and managing patches to make sure the laptops are kept up to date. As a tiny startup, funds are limited, and money spent on software licenses is money we could have spent on more hardware, so expensive solutions are a bit of a no-go. Does anyone have any recommendations for how we can most easily do this?
2015/07/29
['https://serverfault.com/questions/709346', 'https://serverfault.com', 'https://serverfault.com/users/83562/']
This is the perfect use case for [Microsoft Intune](http://www.microsoft.com/en-us/server-cloud/products/microsoft-intune/). While it is primarily known as an MDM solution, it also has PC management capabilities as well, such as app deployment and patch management. It's also completely cloud-based and is licensed on a per-device per-month basis, so it can scale as you grow. If you're already managing internal devices with System a Center Configuration Manager, it has some neat integration. If not, it's perfectly functional as a standalone product as well.
Depending on your budget (which you haven't stated) I think a good solution for you could be that of a HP Microserver with some extra RAM as a domain controller? That way you have an extremely portable server with the ability to push out updates and lock down the laptops with group policy? For that amount of laptops the Microserver will easily be able to handle the load and you'll have everything you're wanting. The downside is of course the cost. You're probably looking at about £1300- maybe more to get a finished solution. However once it's setup it'll be low maintenance and you can add to it when and where you find the money with things like RAID and perhaps a small switch?
709,346
I'm working with a startup that's teaching kids to program. We've just obtained our first "fleet" of laptops - half a dozen refurbished thinkpads running Windows 7 - and I'm looking for the best way to administer and maintain them. I've already determined that it appears to make sense to buy a volume license key, so I can use reimaging rights and generate a single known good image I can write to all of them, and use to wipe out a computer whenever I need to. What I'm wondering about now is how best to manage them on an ongoing basis. The laptops will run on a variety of networks - none of them controlled by us - and we've got no central office or servers. We'd rather not acquire any. I'd like to be able to easily push out updates and new software to all the laptops, as well as doing things like remotely configuring administrator accounts, and managing patches to make sure the laptops are kept up to date. As a tiny startup, funds are limited, and money spent on software licenses is money we could have spent on more hardware, so expensive solutions are a bit of a no-go. Does anyone have any recommendations for how we can most easily do this?
2015/07/29
['https://serverfault.com/questions/709346', 'https://serverfault.com', 'https://serverfault.com/users/83562/']
This is the perfect use case for [Microsoft Intune](http://www.microsoft.com/en-us/server-cloud/products/microsoft-intune/). While it is primarily known as an MDM solution, it also has PC management capabilities as well, such as app deployment and patch management. It's also completely cloud-based and is licensed on a per-device per-month basis, so it can scale as you grow. If you're already managing internal devices with System a Center Configuration Manager, it has some neat integration. If not, it's perfectly functional as a standalone product as well.
I'm not sure if this will cover all you need but... At the place I am recently employed, company-issued laptops (which are running Windows) are required to be able to access the company VPN. Namely, VPN access is only allowed using company-issued laptops. Users are not admins on their local machine. Therefore, company IT personnel do all the administering, like setting Windows Update schedules, setting the schedules for anti-virus update, etc. At first glance, it seemed annoying to me as a user not to be able to admin a laptop I take home or install what I want, and it probably takes the IT group some resources to manage the laptop fleet, but I suspect this methodology reduces external threats that free-floating laptops might otherwise present. Good luck.
709,346
I'm working with a startup that's teaching kids to program. We've just obtained our first "fleet" of laptops - half a dozen refurbished thinkpads running Windows 7 - and I'm looking for the best way to administer and maintain them. I've already determined that it appears to make sense to buy a volume license key, so I can use reimaging rights and generate a single known good image I can write to all of them, and use to wipe out a computer whenever I need to. What I'm wondering about now is how best to manage them on an ongoing basis. The laptops will run on a variety of networks - none of them controlled by us - and we've got no central office or servers. We'd rather not acquire any. I'd like to be able to easily push out updates and new software to all the laptops, as well as doing things like remotely configuring administrator accounts, and managing patches to make sure the laptops are kept up to date. As a tiny startup, funds are limited, and money spent on software licenses is money we could have spent on more hardware, so expensive solutions are a bit of a no-go. Does anyone have any recommendations for how we can most easily do this?
2015/07/29
['https://serverfault.com/questions/709346', 'https://serverfault.com', 'https://serverfault.com/users/83562/']
This is the perfect use case for [Microsoft Intune](http://www.microsoft.com/en-us/server-cloud/products/microsoft-intune/). While it is primarily known as an MDM solution, it also has PC management capabilities as well, such as app deployment and patch management. It's also completely cloud-based and is licensed on a per-device per-month basis, so it can scale as you grow. If you're already managing internal devices with System a Center Configuration Manager, it has some neat integration. If not, it's perfectly functional as a standalone product as well.
I would recommend [Meraki Systems Manager](https://meraki.cisco.com/products/systems-manager). It's an entirely cloud-managed solution that's free for up to 100 devices. It's probably not as robust as Microsoft InTune or Systems Center Configuration Manager, but it may fit the bill for the price. My favorite feature is the VNC-based remote assistance.
15,152,058
I wanted to use `Collection` for only single threaded environment and I am using a `HashMap` that is synchronized. However, I still doubt if it is thread safe to have it synchronized or not.
2013/03/01
['https://Stackoverflow.com/questions/15152058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/891556/']
For your needs, use `ConcurrentHashMap`. It allows concurrent modification of the Map from several threads without the need to block them. `Collections.synchronizedMap(map)` creates a blocking Map which will degrade performance, albeit ensure consistency
The commonly used `Collection` classes, such as `java.util.ArrayList`, are not synchronized. However, if there's a chance that two threads could be altering a collection concurrently, you can generate a synchronized collection from it using the `synchronizedCollection()` method. Similar to the read-only methods, the thread-safe APIs let you generate a synchronized collection, list, set, or map. For instance, this is how you can generate a synchronized map from a `HashMap`: ``` Map map = Collections.synchronizedMap(new HashMap()); map.put(... ```
15,152,058
I wanted to use `Collection` for only single threaded environment and I am using a `HashMap` that is synchronized. However, I still doubt if it is thread safe to have it synchronized or not.
2013/03/01
['https://Stackoverflow.com/questions/15152058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/891556/']
For your needs, use `ConcurrentHashMap`. It allows concurrent modification of the Map from several threads without the need to block them. `Collections.synchronizedMap(map)` creates a blocking Map which will degrade performance, albeit ensure consistency
As its a single-threaded environment you can safely use HashMap.
15,152,058
I wanted to use `Collection` for only single threaded environment and I am using a `HashMap` that is synchronized. However, I still doubt if it is thread safe to have it synchronized or not.
2013/03/01
['https://Stackoverflow.com/questions/15152058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/891556/']
1. the standard java HashMap is not synchronized. 2. If you are in a single threaded environment you don't need to worry about synchronization.
The commonly used `Collection` classes, such as `java.util.ArrayList`, are not synchronized. However, if there's a chance that two threads could be altering a collection concurrently, you can generate a synchronized collection from it using the `synchronizedCollection()` method. Similar to the read-only methods, the thread-safe APIs let you generate a synchronized collection, list, set, or map. For instance, this is how you can generate a synchronized map from a `HashMap`: ``` Map map = Collections.synchronizedMap(new HashMap()); map.put(... ```
15,152,058
I wanted to use `Collection` for only single threaded environment and I am using a `HashMap` that is synchronized. However, I still doubt if it is thread safe to have it synchronized or not.
2013/03/01
['https://Stackoverflow.com/questions/15152058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/891556/']
If you're only using a single thread, you don't *need* a thread-safe collection - `HashMap` should be fine. You should be very careful to work out your requirements: * If you're really using a single thread, stick with `HashMap` (or consider `LinkedHashMap`) * If you're sharing the map, you need to work out what kind of safety you want: + If the map is fully populated before it's used by multiple threads, which just read, then `HashMap` is still fine. + `Collections.synchronizedMap` will only synchronize each individual operation; it still isn't safe to iterate in one thread and modify the map in another thread without synchronization. + `ConcurrentHashMap` is a more "thoroughly" thread-safe approach, and one I'd generally prefer over `synchronizedMap`. It allows for modification during iteration, but doesn't guarantee where such modifications will be seen while iterating. Also note that while `HashMap` allows null keys and values, `ConcurrentHashMap` doesn't.
The commonly used `Collection` classes, such as `java.util.ArrayList`, are not synchronized. However, if there's a chance that two threads could be altering a collection concurrently, you can generate a synchronized collection from it using the `synchronizedCollection()` method. Similar to the read-only methods, the thread-safe APIs let you generate a synchronized collection, list, set, or map. For instance, this is how you can generate a synchronized map from a `HashMap`: ``` Map map = Collections.synchronizedMap(new HashMap()); map.put(... ```
15,152,058
I wanted to use `Collection` for only single threaded environment and I am using a `HashMap` that is synchronized. However, I still doubt if it is thread safe to have it synchronized or not.
2013/03/01
['https://Stackoverflow.com/questions/15152058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/891556/']
1. the standard java HashMap is not synchronized. 2. If you are in a single threaded environment you don't need to worry about synchronization.
As its a single-threaded environment you can safely use HashMap.
15,152,058
I wanted to use `Collection` for only single threaded environment and I am using a `HashMap` that is synchronized. However, I still doubt if it is thread safe to have it synchronized or not.
2013/03/01
['https://Stackoverflow.com/questions/15152058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/891556/']
If you're only using a single thread, you don't *need* a thread-safe collection - `HashMap` should be fine. You should be very careful to work out your requirements: * If you're really using a single thread, stick with `HashMap` (or consider `LinkedHashMap`) * If you're sharing the map, you need to work out what kind of safety you want: + If the map is fully populated before it's used by multiple threads, which just read, then `HashMap` is still fine. + `Collections.synchronizedMap` will only synchronize each individual operation; it still isn't safe to iterate in one thread and modify the map in another thread without synchronization. + `ConcurrentHashMap` is a more "thoroughly" thread-safe approach, and one I'd generally prefer over `synchronizedMap`. It allows for modification during iteration, but doesn't guarantee where such modifications will be seen while iterating. Also note that while `HashMap` allows null keys and values, `ConcurrentHashMap` doesn't.
As its a single-threaded environment you can safely use HashMap.
5,713,437
i want to draw/add an image as a part of text in textbox in windows phone 7. I m not using Expression blend. So where i can find the drawing objects as well as paint events in silverlight?
2011/04/19
['https://Stackoverflow.com/questions/5713437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/665983/']
There is no way to add an image as part of a TextBox. Although I'm not entirely sure what you want to achieve. Do you really mean TextBox? If so, the only option will be to restyle it so it have the image included as well. Do you mean TextBlock? If so, and you're trying to include an image part way through a piece of text, you can wrap the image and the text either side of it in a WrapPanel.
You might want to override the template in order to define your own template. You can do this in the style: ``` <Style x:Key="textboxImage" TargetType="TextBox"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TextBox"> <Grid> <Grid.Background> <ImageBrush ImageSource="ApplicationIcon.png" /> </Grid.Background> <ContentControl x:Name="ContentElement" Foreground="{TemplateBinding Foreground}" Margin="{TemplateBinding Margin}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="Stretch"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> ``` You just need to set the style of your textbox to StaticResources textboxImage. I just tested and it works fine.
5,713,437
i want to draw/add an image as a part of text in textbox in windows phone 7. I m not using Expression blend. So where i can find the drawing objects as well as paint events in silverlight?
2011/04/19
['https://Stackoverflow.com/questions/5713437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/665983/']
You can apply a background image to a lot of Silverlight elements with the following: ``` <TextBox x:Name="SearchBox" Text="Search" Height="70" Width="390"> <TextBox.Background> <ImageBrush ImageSource="Images/MagnifyingGlass.png" Stretch="UniformToFill" /> </TextBox.Background> </TextBox> ```
You might want to override the template in order to define your own template. You can do this in the style: ``` <Style x:Key="textboxImage" TargetType="TextBox"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TextBox"> <Grid> <Grid.Background> <ImageBrush ImageSource="ApplicationIcon.png" /> </Grid.Background> <ContentControl x:Name="ContentElement" Foreground="{TemplateBinding Foreground}" Margin="{TemplateBinding Margin}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="Stretch"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> ``` You just need to set the style of your textbox to StaticResources textboxImage. I just tested and it works fine.
22,665,835
I am working in my asp.net project; when I run my program, it stops running and gives me this message: `A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)` `Server Error in '/Test2' Application.` ``` A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Source Error: Line 27: string cmdString = "Delete from tblSessionCart"; Line 28: SqlCommand cmd = new SqlCommand(cmdString, conn); Line 29: conn.Open(); Line 30: try Line 31: { Source File: c:\Users\mousa\Desktop\Test2\App_Code\clsSessionCart.cs Line: 29 Stack Trace: [SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4876455 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194 System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject) +354 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +90 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +401 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +225 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +4889331 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +431 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117 System.Data.SqlClient.SqlConnection.Open() +122 clsSessionCart.DeleteCart() in c:\Users\mousa\Desktop\Test2\App_Code\clsSessionCart.cs:29 ASP.global_asax.Session_Start(Object sender, EventArgs e) in c:\Users\mousa\Desktop\Test2\Global.asax:27 System.Web.SessionState.SessionStateModule.RaiseOnStart(EventArgs e) +8878884 System.Web.SessionState.SessionStateModule.CompleteAcquireState() +237 System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +504 System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +66 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 Version Information: Microsoft .NET Framework Version:2.0.50727.5477; ASP.NET Version:2.0.50727.5479 ```
2014/03/26
['https://Stackoverflow.com/questions/22665835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3464877/']
This problem is related to connection string, 1. Check instance server 2. Check user and password Connection string: > > > ``` > Server=YOUR_SQLSERVER_INSTANCE;Database=YOUR_DATABASE_NAME;User Id=sa;Password=YOUR_SA_PASSWORD; > > ``` > > If you have instance, make sure instance is specified in server, for example: Server=.\SQL2008
This exception throws when your sqlServer service is stopped or when your TCP port is changed, so check for that one.
22,665,835
I am working in my asp.net project; when I run my program, it stops running and gives me this message: `A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)` `Server Error in '/Test2' Application.` ``` A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Source Error: Line 27: string cmdString = "Delete from tblSessionCart"; Line 28: SqlCommand cmd = new SqlCommand(cmdString, conn); Line 29: conn.Open(); Line 30: try Line 31: { Source File: c:\Users\mousa\Desktop\Test2\App_Code\clsSessionCart.cs Line: 29 Stack Trace: [SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4876455 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194 System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject) +354 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +90 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +401 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +225 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +4889331 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +431 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117 System.Data.SqlClient.SqlConnection.Open() +122 clsSessionCart.DeleteCart() in c:\Users\mousa\Desktop\Test2\App_Code\clsSessionCart.cs:29 ASP.global_asax.Session_Start(Object sender, EventArgs e) in c:\Users\mousa\Desktop\Test2\Global.asax:27 System.Web.SessionState.SessionStateModule.RaiseOnStart(EventArgs e) +8878884 System.Web.SessionState.SessionStateModule.CompleteAcquireState() +237 System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +504 System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +66 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 Version Information: Microsoft .NET Framework Version:2.0.50727.5477; ASP.NET Version:2.0.50727.5479 ```
2014/03/26
['https://Stackoverflow.com/questions/22665835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3464877/']
This problem is related to connection string, 1. Check instance server 2. Check user and password Connection string: > > > ``` > Server=YOUR_SQLSERVER_INSTANCE;Database=YOUR_DATABASE_NAME;User Id=sa;Password=YOUR_SA_PASSWORD; > > ``` > > If you have instance, make sure instance is specified in server, for example: Server=.\SQL2008
We added the port info to our connection string which alleviated this error. For example: server=*servername*,*port#*;database=*databasename*;....
22,665,835
I am working in my asp.net project; when I run my program, it stops running and gives me this message: `A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)` `Server Error in '/Test2' Application.` ``` A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Source Error: Line 27: string cmdString = "Delete from tblSessionCart"; Line 28: SqlCommand cmd = new SqlCommand(cmdString, conn); Line 29: conn.Open(); Line 30: try Line 31: { Source File: c:\Users\mousa\Desktop\Test2\App_Code\clsSessionCart.cs Line: 29 Stack Trace: [SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4876455 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194 System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject) +354 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +90 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +401 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +225 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +4889331 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +431 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117 System.Data.SqlClient.SqlConnection.Open() +122 clsSessionCart.DeleteCart() in c:\Users\mousa\Desktop\Test2\App_Code\clsSessionCart.cs:29 ASP.global_asax.Session_Start(Object sender, EventArgs e) in c:\Users\mousa\Desktop\Test2\Global.asax:27 System.Web.SessionState.SessionStateModule.RaiseOnStart(EventArgs e) +8878884 System.Web.SessionState.SessionStateModule.CompleteAcquireState() +237 System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +504 System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +66 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 Version Information: Microsoft .NET Framework Version:2.0.50727.5477; ASP.NET Version:2.0.50727.5479 ```
2014/03/26
['https://Stackoverflow.com/questions/22665835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3464877/']
This problem is related to connection string, 1. Check instance server 2. Check user and password Connection string: > > > ``` > Server=YOUR_SQLSERVER_INSTANCE;Database=YOUR_DATABASE_NAME;User Id=sa;Password=YOUR_SA_PASSWORD; > > ``` > > If you have instance, make sure instance is specified in server, for example: Server=.\SQL2008
I got the error because my `DataSource` was named > > (localdb)\v11.0 > > > and in C# the backslash is interpreted as a special character so needs to be escaped as follows : the below lines will work! But single "\" fails. ``` String source = "Data Source=(localdb)" + "\\" + "v11.0;Initial Catalog=Northwind;Integrated Security=SSPI"; SqlConnection conn = new SqlConnection(source); conn.Open(); ```
22,665,835
I am working in my asp.net project; when I run my program, it stops running and gives me this message: `A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)` `Server Error in '/Test2' Application.` ``` A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Source Error: Line 27: string cmdString = "Delete from tblSessionCart"; Line 28: SqlCommand cmd = new SqlCommand(cmdString, conn); Line 29: conn.Open(); Line 30: try Line 31: { Source File: c:\Users\mousa\Desktop\Test2\App_Code\clsSessionCart.cs Line: 29 Stack Trace: [SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4876455 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194 System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject) +354 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +90 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +401 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +225 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +4889331 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +431 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117 System.Data.SqlClient.SqlConnection.Open() +122 clsSessionCart.DeleteCart() in c:\Users\mousa\Desktop\Test2\App_Code\clsSessionCart.cs:29 ASP.global_asax.Session_Start(Object sender, EventArgs e) in c:\Users\mousa\Desktop\Test2\Global.asax:27 System.Web.SessionState.SessionStateModule.RaiseOnStart(EventArgs e) +8878884 System.Web.SessionState.SessionStateModule.CompleteAcquireState() +237 System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +504 System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +66 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 Version Information: Microsoft .NET Framework Version:2.0.50727.5477; ASP.NET Version:2.0.50727.5479 ```
2014/03/26
['https://Stackoverflow.com/questions/22665835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3464877/']
This problem is related to connection string, 1. Check instance server 2. Check user and password Connection string: > > > ``` > Server=YOUR_SQLSERVER_INSTANCE;Database=YOUR_DATABASE_NAME;User Id=sa;Password=YOUR_SA_PASSWORD; > > ``` > > If you have instance, make sure instance is specified in server, for example: Server=.\SQL2008
I got the same error, and my connection string is correct. I try to use ip address of SQL Server instead of server name. Finally, this error has gone. I use this connection string ``` <add name="YourEntitiesName" connectionString="metadata=res://*/Model.SampleDatabaseModel.csdl|res://*/Model.SampleDatabaseModel.ssdl|res://*/Model.SampleDatabaseModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=10.123.60.12\SQLServerName;initial catalog=SampleDB;user id=sa;password=123456;MultipleActiveResultSets=True;Pooling=False;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> ``` instead of ``` <add name="YourEntitiesName" connectionString="metadata=res://*/Model.SampleDatabaseModel.csdl|res://*/Model.SampleDatabaseModel.ssdl|res://*/Model.SampleDatabaseModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=SERVER01\SQLServerName;initial catalog=SampleDB;user id=sa;password=123456;MultipleActiveResultSets=True;Pooling=False;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> ```
330,473
(QGIS 3.4) The image below will help explain my goal: I'm working out how to coalesce the attributes of the field "ID" if the field "X, Y" is a duplicate. I have highlighted some duplicate coordinates in red. My expression will create a new text field and chain all attributes in the "ID" field, delimited by a pipe (`|`). For example, where I have labelled features with blue text 1,2,3, the new field will write `Special Protection Areas | Scheudled Monuments | SSSI | AONB | Special Areas of Conservtion | Scheduled monuments | Scheduled Monuments | SSSI | AONB` I will omit duplicate values later in excel. [![enter image description here](https://i.stack.imgur.com/W6JnC.png)](https://i.stack.imgur.com/W6JnC.png) Here's what I have so far...`if( "X, Y" = "X, Y" , coalesce( "ID" ),' ')` but this just duplicates the "ID" field without any coalescing.
2019/07/30
['https://gis.stackexchange.com/questions/330473', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/93834/']
With credit to Vince, the correct expression to use in this case was: ``` concatenate( to_string( "ID" ),group_by:="X, Y", concatenator:='|') ```
In QGIS I can suggest using a [**"Virtual Layer"**](https://docs.qgis.org/3.10/en/docs/user_manual/managing_data_source/create_layers.html#creating-virtual-layers) through `Layer > Add Layer > Add/Edit Virtual Layer...` Let's assume there is a point layer with it's corresponding attribute table, see image below. [![input](https://i.stack.imgur.com/L1oUw.png)](https://i.stack.imgur.com/L1oUw.png) With the following query, it is possible to achieve the result. ```sql SELECT "X, Y", GROUP_CONCAT(info, ' | ') AS info_concat FROM "points" GROUP BY "X, Y" ``` The output Virtual Layer will look like as following [![result](https://i.stack.imgur.com/DgsTE.png)](https://i.stack.imgur.com/DgsTE.png) *Note:* Geometry is not included in the final output, otherwise extend the query with `geometry` parameter and to check how many points were grouped insert `COUNT()`, i.e. ```sql SELECT "X, Y", GROUP_CONCAT(info, ' | ') AS info_concat, geometry, COUNT("X, Y") AS pperloc FROM "points" GROUP BY "X, Y" ``` --- **References:** * [SQLite GROUP\_CONCAT](https://www.sqlitetutorial.net/sqlite-group_concat/) * [W3Schools | SQL COUNT(), AVG() and SUM() Functions](https://www.w3schools.com/sql/sql_count_avg_sum.asp)
4,127,256
I've seen many tutorials, but none of them have worked in my case, I think it is because I'm using a .jar instead of an .class and in that .jar, I have more than just one Java class. Anyone knows how to solve this? code: <http://dl.dropbox.com/u/1430071/code.txt>
2010/11/08
['https://Stackoverflow.com/questions/4127256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/501066/']
Ignore the DWR answers, they misunderstood your architecture. Applet code runs on client, not server. What error message do you get? Is the method you are trying to call public? The way you are calling the Java method, the method has to be in the applet class. Is it? It seems like your applet tag is missing the code attribute. It's required. Quoting an example from Oracle: ``` <applet codebase="http://java.sun.com/applets/NervousText/1.1" code="NervousText.class" width=400 height=75> <param name="text" value="Welcome to HotJava!"> <hr> If you were using a Java-enabled browser such as HotJava, you would see dancing text instead of this paragraph. <hr> </applet> ``` The code attribute must reference an applet class (a class that extends java.awt.Applet or javax.swing.JApplet) that can be found in one of the jars you've listed in the archive attribute. This has to be the full name of the class, something like: my.package.MyApplet (the .class at the end is optional).
Are you trying to call server side java from client side javascript? You would need to wire up a DWR call.
4,127,256
I've seen many tutorials, but none of them have worked in my case, I think it is because I'm using a .jar instead of an .class and in that .jar, I have more than just one Java class. Anyone knows how to solve this? code: <http://dl.dropbox.com/u/1430071/code.txt>
2010/11/08
['https://Stackoverflow.com/questions/4127256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/501066/']
Ignore the DWR answers, they misunderstood your architecture. Applet code runs on client, not server. What error message do you get? Is the method you are trying to call public? The way you are calling the Java method, the method has to be in the applet class. Is it? It seems like your applet tag is missing the code attribute. It's required. Quoting an example from Oracle: ``` <applet codebase="http://java.sun.com/applets/NervousText/1.1" code="NervousText.class" width=400 height=75> <param name="text" value="Welcome to HotJava!"> <hr> If you were using a Java-enabled browser such as HotJava, you would see dancing text instead of this paragraph. <hr> </applet> ``` The code attribute must reference an applet class (a class that extends java.awt.Applet or javax.swing.JApplet) that can be found in one of the jars you've listed in the archive attribute. This has to be the full name of the class, something like: my.package.MyApplet (the .class at the end is optional).
As Joe mentioned, DWR can help you here. Here a [link](http://directwebremoting.org/dwr/examples/index.html) to their tutorials.
44,212,729
I have a cordova plugin in my local. I can add it to my project without problems by typing: `cordova plugin add --link /Users/goforu/WorkSpace/MyProject/cordovaPlugins/cordova-plugin-IFlyspeech` But I can't remove it from my project: ``` cordova plugin remove cordova-plugin-xunfeiListenSpeaking ``` It always logs error > > Error: Plugin "cordova-plugin-xunfeiListenSpeaking" is not present in the project. See `cordova plugin list`. > > > When I type `cordova plugin list` I get this: > > cordova-plugin-console 1.0.5 "Console" > cordova-plugin-device 1.1.4 "Device" > cordova-plugin-splashscreen 4.0.3 "Splashscreen" > cordova-plugin-statusbar 2.2.1 "StatusBar" > cordova-plugin-whitelist > 1.3.1 "Whitelist" cordova-plugin-xunfeiListenSpeaking 0.0.1 "cordova-plugin-xunfeiListenSpeaking" > cordova-sqlite-storage 2.0.4 "Cordova sqlite storage plugin" > "Cordova sqlite storage plugin" ionic-plugin-keyboard 2.2.1 "Keyboard" > {} > > > And I also noticed that every time I remove and add android platform, this plugin will not get installed in project. Problem solved: As jcesarmobile said, maybe it's a bug. I solved this problem by getting rid of the '--link'. And now it works properly.
2017/05/27
['https://Stackoverflow.com/questions/44212729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3616815/']
It's a bug when using `--link`. I've already [reported it](https://issues.apache.org/jira/browse/CB-12840). Anyway, `--link` [is broken too](https://issues.apache.org/jira/browse/CB-12787), so don't use it. You don't really need it unless you are creating the plugin and want to have the changes on the original plugin folder when you edit it in your IDE.
Yes, it is showing on running command ``` cordova plugin remove/rm cordova-plugin-xunfeiListenSpeaking ``` Error: Plugin "cordova-plugin-xunfeiListenSpeaking" is not present in the project. See cordova plugin list. because, really there is no plugin existing in the plugins list but, the --link is broken as he said. So, there is a **workaround** for it.you can just remove the node modules directly or by using the command. it will solve because there are node modules with your plugin name. If still error permits, you can just remove and add platform android
10,548,777
I've created a .NET console application that gets some command line arguments. When I pass args with white spaces, I use quotes to embrace these arguments so that they are not splitted by cmd: ``` C:\MyAppDir> MyApp argument1 "argument 2" "the third argument" ``` If I execute the app in Windows XP it works fine: it gets 3 arguments: * argument1 * argument 2 * the third argument However, if i execute it in Windows Server 2008 it seems to ignore quotes: it gets 6 arguments: * argument1 * "argument * 2" * "the * third * argument" Any ideas why? NOTE: I printed arguments just when Main starts execution using this code: ``` Console.WriteLine("Command line arguments:"); foreach (string arg in args) { Console.WriteLine("# " + arg); } ```
2012/05/11
['https://Stackoverflow.com/questions/10548777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/150370/']
Make sure the character you are typing is indeed the double quote ". Maybe it's a character that looks like it. I know my Greek language settings produce a " but it's not read that way.
Please Try it. C:\MyAppDir> MyApp argument1 \"argument 2\" \"the third argument\"
10,548,777
I've created a .NET console application that gets some command line arguments. When I pass args with white spaces, I use quotes to embrace these arguments so that they are not splitted by cmd: ``` C:\MyAppDir> MyApp argument1 "argument 2" "the third argument" ``` If I execute the app in Windows XP it works fine: it gets 3 arguments: * argument1 * argument 2 * the third argument However, if i execute it in Windows Server 2008 it seems to ignore quotes: it gets 6 arguments: * argument1 * "argument * 2" * "the * third * argument" Any ideas why? NOTE: I printed arguments just when Main starts execution using this code: ``` Console.WriteLine("Command line arguments:"); foreach (string arg in args) { Console.WriteLine("# " + arg); } ```
2012/05/11
['https://Stackoverflow.com/questions/10548777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/150370/']
Make sure the character you are typing is indeed the double quote ". Maybe it's a character that looks like it. I know my Greek language settings produce a " but it's not read that way.
You can try, put each arguments between Quota"" and in the paths put double backslash for example like that: generadorPlantillasPDF.exe "C:\GDI\desarrollos\celula canales\proyectos\Progreso\curso xml\" generadorprogreso.xml C:\Temp\ BVI "C:\GDI\desarrollos\celula canales\proyectos\Progreso\plantilla\" "C:\GDI\desarrollos\celula canales\proyectos\Progreso\" "Formulario Progreso Version 2.0.docx" C:\Temp\
10,548,777
I've created a .NET console application that gets some command line arguments. When I pass args with white spaces, I use quotes to embrace these arguments so that they are not splitted by cmd: ``` C:\MyAppDir> MyApp argument1 "argument 2" "the third argument" ``` If I execute the app in Windows XP it works fine: it gets 3 arguments: * argument1 * argument 2 * the third argument However, if i execute it in Windows Server 2008 it seems to ignore quotes: it gets 6 arguments: * argument1 * "argument * 2" * "the * third * argument" Any ideas why? NOTE: I printed arguments just when Main starts execution using this code: ``` Console.WriteLine("Command line arguments:"); foreach (string arg in args) { Console.WriteLine("# " + arg); } ```
2012/05/11
['https://Stackoverflow.com/questions/10548777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/150370/']
Please Try it. C:\MyAppDir> MyApp argument1 \"argument 2\" \"the third argument\"
You can try, put each arguments between Quota"" and in the paths put double backslash for example like that: generadorPlantillasPDF.exe "C:\GDI\desarrollos\celula canales\proyectos\Progreso\curso xml\" generadorprogreso.xml C:\Temp\ BVI "C:\GDI\desarrollos\celula canales\proyectos\Progreso\plantilla\" "C:\GDI\desarrollos\celula canales\proyectos\Progreso\" "Formulario Progreso Version 2.0.docx" C:\Temp\
25,109,492
I use sass mixin and i want change my old code using regex for example i have the next scss code ``` margin-left:30px; margin-right:3em; padding-right:1rem; ``` to ``` @include margin-start(30px); @include margin-end(3em); @include padding-end(1rem); ```
2014/08/03
['https://Stackoverflow.com/questions/25109492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1901574/']
I dug into Directory class source code and found an inspiration. Here is a working solution which gives you list of all opened named pipes. My result does not contain \\.\pipe\ prefix as it can be seen in result of Directory.GetFiles. I tested my solution on WinXp SP3, Win 7, Win 8.1. ``` [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] struct WIN32_FIND_DATA { public uint dwFileAttributes; public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData); [DllImport("kernel32.dll", SetLastError = true)] static extern bool FindClose(IntPtr hFindFile); private static void Main(string[] args) { var namedPipes = new List<string>(); WIN32_FIND_DATA lpFindFileData; var ptr = FindFirstFile(@"\\.\pipe\*", out lpFindFileData); namedPipes.Add(lpFindFileData.cFileName); while (FindNextFile(ptr, out lpFindFileData)) { namedPipes.Add(lpFindFileData.cFileName); } FindClose(ptr); namedPipes.Sort(); foreach (var v in namedPipes) Console.WriteLine(v); Console.ReadLine(); } ```
Using one of the .NET 4 APIs returning `IEnumerable`, you can catch those exceptions: ``` static IEnumerable<string> EnumeratePipes() { bool MoveNextSafe(IEnumerator enumerator) { // Pipes might have illegal characters in path. Seen one from IAR containing < and >. // The FileSystemEnumerable.MoveNext source code indicates that another call to MoveNext will return // the next entry. // Pose a limit in case the underlying implementation changes somehow. This also means that no more than 10 // pipes with bad names may occur in sequence. const int Retries = 10; for (int i = 0; i < Retries; i++) { try { return enumerator.MoveNext(); } catch (ArgumentException) { } } Log.Warn("Pipe enumeration: Retry limit due to bad names reached."); return false; } using (var enumerator = Directory.EnumerateFiles(@"\\.\pipe\").GetEnumerator()) { while (MoveNextSafe(enumerator)) { yield return enumerator.Current; } } } ``` The badly named pipes are not enumerated in the end, of course. So, you cannot use this solution if you really want to list *all* of the pipes.
260,160
I found a [semi-related post](https://diy.stackexchange.com/questions/184406/barn-door-with-no-header) about this, but it doesn't really answer my question. It basically claims a horizontal, wall-mounted barn door could work in a space like below (see images). However, all horizontal, wall-mounted barn doors I have found seem to need to connect to the wall above the door when closed to keep it supported. In my case, there is no wall above the opening above the door. The options I am considering: * Add some sort of supporting wood board that connects to the wall on each side of the opening, then allows for a horizontal barn door to be connected to above the door when it's closed. The con to this is it will not look great. * I have also researched and found some ceiling hanging barn door options. This seems like a great option, however, I don't know if there are any drawbacks to hanging a door to the ceiling. I have never attempted anything like that. I am not sure what to consider there. [![enter image description here](https://i.stack.imgur.com/77AiL.jpg)](https://i.stack.imgur.com/77AiL.jpg)[![enter image description here](https://i.stack.imgur.com/zhLdL.jpg)](https://i.stack.imgur.com/zhLdL.jpg)[![enter image description here](https://i.stack.imgur.com/eh7Qb.jpg)](https://i.stack.imgur.com/eh7Qb.jpg) My question is: **Are there any other solutions or ideas I could or should consider for this space?** **The goal here is to stop sound from traveling up the stairwell, as it currently does**. Maybe there is a door type or covering I am not aware of that would work just as easily.
2022/11/08
['https://diy.stackexchange.com/questions/260160', 'https://diy.stackexchange.com', 'https://diy.stackexchange.com/users/158563/']
A few options come to mind: * A common swinging door. Easy to frame there. * A barn door, sliding right. Sliding left is probably prohibited and likely impractical because of the other door. * A pocket door in a faux wall on the right Additionally, or in lieu of the above, pad the stairs with carpet, pad the walls with decorative carpets, add (faux) curtain to the stairway window. I prefer a swinging door because they generally seal better when closed and make no noise when operated. A pocket door comes second. Barn doors still pass lots of noise. Barn or sliding door rail sound will transfer via rail, header and framing to upstairs. Closing the opening to fit a door, or installing a header to fit a rail should be no problem. Consider a glass-panelled or all-glass door for aesthetics and light. Plus the improved visibility helps prevent traffic conflicts. If you have framing questions after your decision, let us know. It is advisable to check the local building code, and also check the practicality of any kind of door or curtain at the bottom of stairs, e.g. handle reach from stairs etc... But at first glance it looks like you have sufficient landing before the door, so this might not be a practical issue.
Perhaps an accordion door (note: the accordion will not contribute to noise). [![enter image description here](https://i.stack.imgur.com/uYArV.png)](https://i.stack.imgur.com/uYArV.png)
260,160
I found a [semi-related post](https://diy.stackexchange.com/questions/184406/barn-door-with-no-header) about this, but it doesn't really answer my question. It basically claims a horizontal, wall-mounted barn door could work in a space like below (see images). However, all horizontal, wall-mounted barn doors I have found seem to need to connect to the wall above the door when closed to keep it supported. In my case, there is no wall above the opening above the door. The options I am considering: * Add some sort of supporting wood board that connects to the wall on each side of the opening, then allows for a horizontal barn door to be connected to above the door when it's closed. The con to this is it will not look great. * I have also researched and found some ceiling hanging barn door options. This seems like a great option, however, I don't know if there are any drawbacks to hanging a door to the ceiling. I have never attempted anything like that. I am not sure what to consider there. [![enter image description here](https://i.stack.imgur.com/77AiL.jpg)](https://i.stack.imgur.com/77AiL.jpg)[![enter image description here](https://i.stack.imgur.com/zhLdL.jpg)](https://i.stack.imgur.com/zhLdL.jpg)[![enter image description here](https://i.stack.imgur.com/eh7Qb.jpg)](https://i.stack.imgur.com/eh7Qb.jpg) My question is: **Are there any other solutions or ideas I could or should consider for this space?** **The goal here is to stop sound from traveling up the stairwell, as it currently does**. Maybe there is a door type or covering I am not aware of that would work just as easily.
2022/11/08
['https://diy.stackexchange.com/questions/260160', 'https://diy.stackexchange.com', 'https://diy.stackexchange.com/users/158563/']
A few options come to mind: * A common swinging door. Easy to frame there. * A barn door, sliding right. Sliding left is probably prohibited and likely impractical because of the other door. * A pocket door in a faux wall on the right Additionally, or in lieu of the above, pad the stairs with carpet, pad the walls with decorative carpets, add (faux) curtain to the stairway window. I prefer a swinging door because they generally seal better when closed and make no noise when operated. A pocket door comes second. Barn doors still pass lots of noise. Barn or sliding door rail sound will transfer via rail, header and framing to upstairs. Closing the opening to fit a door, or installing a header to fit a rail should be no problem. Consider a glass-panelled or all-glass door for aesthetics and light. Plus the improved visibility helps prevent traffic conflicts. If you have framing questions after your decision, let us know. It is advisable to check the local building code, and also check the practicality of any kind of door or curtain at the bottom of stairs, e.g. handle reach from stairs etc... But at first glance it looks like you have sufficient landing before the door, so this might not be a practical issue.
One option could be free-swinging **French doors**; while ideally you want more space between the bottom step and the door than you've got, French doors wouldn't feel like as much of an obstacle. Obviously, they would need to swing out into the room, away from the stairs. However, if the goal is to *reduce* noise, a better solution might be **sound baffles**. Empty stairs like that tend to collect and amplify noise; since there is nothing to absorb the sound inside, it bounces right back out just as loud as when it started. While there's not a lot you can do about the large window, the walls to the left and right could be draped with soft blankets or tapestries, or fitted with acoustic panels. You may even be able to fit the area over the stairs with something. Obviously, you could combine those with a door for even better sound-proofing.
260,160
I found a [semi-related post](https://diy.stackexchange.com/questions/184406/barn-door-with-no-header) about this, but it doesn't really answer my question. It basically claims a horizontal, wall-mounted barn door could work in a space like below (see images). However, all horizontal, wall-mounted barn doors I have found seem to need to connect to the wall above the door when closed to keep it supported. In my case, there is no wall above the opening above the door. The options I am considering: * Add some sort of supporting wood board that connects to the wall on each side of the opening, then allows for a horizontal barn door to be connected to above the door when it's closed. The con to this is it will not look great. * I have also researched and found some ceiling hanging barn door options. This seems like a great option, however, I don't know if there are any drawbacks to hanging a door to the ceiling. I have never attempted anything like that. I am not sure what to consider there. [![enter image description here](https://i.stack.imgur.com/77AiL.jpg)](https://i.stack.imgur.com/77AiL.jpg)[![enter image description here](https://i.stack.imgur.com/zhLdL.jpg)](https://i.stack.imgur.com/zhLdL.jpg)[![enter image description here](https://i.stack.imgur.com/eh7Qb.jpg)](https://i.stack.imgur.com/eh7Qb.jpg) My question is: **Are there any other solutions or ideas I could or should consider for this space?** **The goal here is to stop sound from traveling up the stairwell, as it currently does**. Maybe there is a door type or covering I am not aware of that would work just as easily.
2022/11/08
['https://diy.stackexchange.com/questions/260160', 'https://diy.stackexchange.com', 'https://diy.stackexchange.com/users/158563/']
The problem with a door here is that it will feel weird and cramped to people coming down the stairs. So you need enough space on the flat-floor to stand and open the door. Right now it looks about one stair-tread of depth, ideally you'd want triple that. I would suggest a curtain rail over the access, and hang a sound-absorbing curtain made from velvet or wool. You'd want a bi-pane curtain not a single-sided one, so that it opens from the center like a tent. There should be room beside so the open curtain does not narrow the width at all, so curtain would hang on the nearside of the wall, not in-line with the wall. Additionally, can anything be done at the top-end of the stairs? Anything that lowers the lintel will cause issues for people walking down the stairs. Don't make your house suitable only for short people. It already looks close to the forehead of stair-users. --- Your stairs are hard bare wood - that is an excellent sound reflector. Consider carpetting both the tread and the riser, and the landing. This will also reduce damage in the event of a fall. There's probably not a lot you can do for the walls. Some paints have noise-absorbing properties but its not great. Music studios minimise reflection with fabric/foam panels, but that takes depth and stairwells aren't that wide. Adding some framed unglazed pictures might help. Lastly, your window is also a hard flat surface that reflects sound like a mirror reflects light. Temporarily hang a sheet or blanket on it and see if it makes a perceptible difference. If so, consider a curtain there. If light is required, consider a lightweight net curtain in the alcove to fuzz and disrupt sound while adding privacy.
Perhaps an accordion door (note: the accordion will not contribute to noise). [![enter image description here](https://i.stack.imgur.com/uYArV.png)](https://i.stack.imgur.com/uYArV.png)
260,160
I found a [semi-related post](https://diy.stackexchange.com/questions/184406/barn-door-with-no-header) about this, but it doesn't really answer my question. It basically claims a horizontal, wall-mounted barn door could work in a space like below (see images). However, all horizontal, wall-mounted barn doors I have found seem to need to connect to the wall above the door when closed to keep it supported. In my case, there is no wall above the opening above the door. The options I am considering: * Add some sort of supporting wood board that connects to the wall on each side of the opening, then allows for a horizontal barn door to be connected to above the door when it's closed. The con to this is it will not look great. * I have also researched and found some ceiling hanging barn door options. This seems like a great option, however, I don't know if there are any drawbacks to hanging a door to the ceiling. I have never attempted anything like that. I am not sure what to consider there. [![enter image description here](https://i.stack.imgur.com/77AiL.jpg)](https://i.stack.imgur.com/77AiL.jpg)[![enter image description here](https://i.stack.imgur.com/zhLdL.jpg)](https://i.stack.imgur.com/zhLdL.jpg)[![enter image description here](https://i.stack.imgur.com/eh7Qb.jpg)](https://i.stack.imgur.com/eh7Qb.jpg) My question is: **Are there any other solutions or ideas I could or should consider for this space?** **The goal here is to stop sound from traveling up the stairwell, as it currently does**. Maybe there is a door type or covering I am not aware of that would work just as easily.
2022/11/08
['https://diy.stackexchange.com/questions/260160', 'https://diy.stackexchange.com', 'https://diy.stackexchange.com/users/158563/']
The problem with a door here is that it will feel weird and cramped to people coming down the stairs. So you need enough space on the flat-floor to stand and open the door. Right now it looks about one stair-tread of depth, ideally you'd want triple that. I would suggest a curtain rail over the access, and hang a sound-absorbing curtain made from velvet or wool. You'd want a bi-pane curtain not a single-sided one, so that it opens from the center like a tent. There should be room beside so the open curtain does not narrow the width at all, so curtain would hang on the nearside of the wall, not in-line with the wall. Additionally, can anything be done at the top-end of the stairs? Anything that lowers the lintel will cause issues for people walking down the stairs. Don't make your house suitable only for short people. It already looks close to the forehead of stair-users. --- Your stairs are hard bare wood - that is an excellent sound reflector. Consider carpetting both the tread and the riser, and the landing. This will also reduce damage in the event of a fall. There's probably not a lot you can do for the walls. Some paints have noise-absorbing properties but its not great. Music studios minimise reflection with fabric/foam panels, but that takes depth and stairwells aren't that wide. Adding some framed unglazed pictures might help. Lastly, your window is also a hard flat surface that reflects sound like a mirror reflects light. Temporarily hang a sheet or blanket on it and see if it makes a perceptible difference. If so, consider a curtain there. If light is required, consider a lightweight net curtain in the alcove to fuzz and disrupt sound while adding privacy.
One option could be free-swinging **French doors**; while ideally you want more space between the bottom step and the door than you've got, French doors wouldn't feel like as much of an obstacle. Obviously, they would need to swing out into the room, away from the stairs. However, if the goal is to *reduce* noise, a better solution might be **sound baffles**. Empty stairs like that tend to collect and amplify noise; since there is nothing to absorb the sound inside, it bounces right back out just as loud as when it started. While there's not a lot you can do about the large window, the walls to the left and right could be draped with soft blankets or tapestries, or fitted with acoustic panels. You may even be able to fit the area over the stairs with something. Obviously, you could combine those with a door for even better sound-proofing.
260,160
I found a [semi-related post](https://diy.stackexchange.com/questions/184406/barn-door-with-no-header) about this, but it doesn't really answer my question. It basically claims a horizontal, wall-mounted barn door could work in a space like below (see images). However, all horizontal, wall-mounted barn doors I have found seem to need to connect to the wall above the door when closed to keep it supported. In my case, there is no wall above the opening above the door. The options I am considering: * Add some sort of supporting wood board that connects to the wall on each side of the opening, then allows for a horizontal barn door to be connected to above the door when it's closed. The con to this is it will not look great. * I have also researched and found some ceiling hanging barn door options. This seems like a great option, however, I don't know if there are any drawbacks to hanging a door to the ceiling. I have never attempted anything like that. I am not sure what to consider there. [![enter image description here](https://i.stack.imgur.com/77AiL.jpg)](https://i.stack.imgur.com/77AiL.jpg)[![enter image description here](https://i.stack.imgur.com/zhLdL.jpg)](https://i.stack.imgur.com/zhLdL.jpg)[![enter image description here](https://i.stack.imgur.com/eh7Qb.jpg)](https://i.stack.imgur.com/eh7Qb.jpg) My question is: **Are there any other solutions or ideas I could or should consider for this space?** **The goal here is to stop sound from traveling up the stairwell, as it currently does**. Maybe there is a door type or covering I am not aware of that would work just as easily.
2022/11/08
['https://diy.stackexchange.com/questions/260160', 'https://diy.stackexchange.com', 'https://diy.stackexchange.com/users/158563/']
Perhaps an accordion door (note: the accordion will not contribute to noise). [![enter image description here](https://i.stack.imgur.com/uYArV.png)](https://i.stack.imgur.com/uYArV.png)
One option could be free-swinging **French doors**; while ideally you want more space between the bottom step and the door than you've got, French doors wouldn't feel like as much of an obstacle. Obviously, they would need to swing out into the room, away from the stairs. However, if the goal is to *reduce* noise, a better solution might be **sound baffles**. Empty stairs like that tend to collect and amplify noise; since there is nothing to absorb the sound inside, it bounces right back out just as loud as when it started. While there's not a lot you can do about the large window, the walls to the left and right could be draped with soft blankets or tapestries, or fitted with acoustic panels. You may even be able to fit the area over the stairs with something. Obviously, you could combine those with a door for even better sound-proofing.
73,359,708
I have a table with design ``` CREATE TABLE IF NOT EXISTS InsuranceContract ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `enquiryCode` VARCHAR(20) DEFAULT NULL, `contractCode` VARCHAR(20) DEFAULT NULL, `createdAt` DATETIME DEFAULT CURRENT_TIMESTAMP (), `updatedAt` DATETIME DEFAULT CURRENT_TIMESTAMP () ON UPDATE CURRENT_TIMESTAMP (), UNIQUE KEY (`enquiryCode`)) ENGINE=INNODB DEFAULT CHARSET=UTF8 COLLATE = UTF8_BIN; ``` Then I was created a procedure like this ``` DROP procedure IF EXISTS `sp_insurance_contract_get`; DELIMITER $$ CREATE PROCEDURE `sp_insurance_contract_get` (enquiryCode VARCHAR(20), contractCode VARCHAR(20)) BEGIN SET @t1 = "SELECT * FROM InsuranceContract WHERE InsuranceContract.enquiryCode = enquiryCode AND InsuranceContract.contractCode = contractCode;"; PREPARE param_stmt FROM @t1; EXECUTE param_stmt; DEALLOCATE PREPARE param_stmt; END$$ DELIMITER ; ``` And I was executed this procedure in MySQL Workbench by this command: ``` CALL sp_insurance_contract_get('EQ000000000014', '3001002'); ``` I expected I will receive 1 row result but it selected all records in this table. If I copy and create exactly this @t1 into plain SQL not using statement, it's correct. Please help me to fix this error. I'm using MySQL `8.0.19`
2022/08/15
['https://Stackoverflow.com/questions/73359708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12073199/']
You can use placehoders on prepare statements, this is why we use them to prevent sql injection One other thing never use column names as variables names, databases can not differentiate ``` DROP procedure IF EXISTS `sp_insurance_contract_get`; DELIMITER $$ CREATE PROCEDURE `sp_insurance_contract_get` (enquiryCode_ VARCHAR(20), contractCode_ VARCHAR(20)) BEGIN SET @t1 = "SELECT * FROM InsuranceContract WHERE enquiryCode = ? AND contractCode = ?;"; PREPARE param_stmt FROM @t1; SET @a = enquiryCode_; SET @b = contractCode_; EXECUTE param_stmt USING @a, @b; DEALLOCATE PREPARE param_stmt; END$$ DELIMITER ; ```
When you say ``` WHERE enquiryCode = enquiryCode ``` you compare that named column to itself. The result is true always (unless the column value is NULL). Change the names of your SP's parameters, so you can say something like ``` WHERE enquiryCode_param = enquiryCode ``` and things should work. Notice that you have no need of a MySql "prepared statement" here. In the MySql / MariaDb world prepared statements are used for dynamic SQL. That's for constructing statements within the server from text strings. You don't need to do that here.
45,320,053
I developed a website using Asp.Net MVC and Edmx database and I published this website on azure and my database is also on azure and I've a functionality on website that uploads excel record into database and that excel sheet contain almost 18000 records every time I upload that sheet it throw Timeout error after some time so what should I do. [![enter image description here](https://i.stack.imgur.com/n32VE.png)](https://i.stack.imgur.com/n32VE.png) Initially I was not using any command Timeout but after doing some research I'm using this in constructor ``` public ProfessionalServicesEntities() : base("name=ProfessionalServicesEntities") { this.Database.CommandTimeout = 10000; //this.Database.CommandTimeout = 0; //I tried this too. //((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 3600; } ``` Here is the code of function :- ``` public void SaveEquipments(IEnumerable<EquipSampleEntity> collection) { using (ProfessionalServicesEntities db = new ProfessionalServicesEntities()) { string modelXml = XmlSerialization.ListToXml(collection.Where(x=>x.Type == Model).ToList()); string accessoryXml = XmlSerialization.ListToXml(collection.Where(x => x.Type == Accessory).ToList()); db.ImportEquipmentFile(modelXml, accessoryXml); } } ``` here is context file code for SP:- ``` public virtual int ImportEquipmentFile(string modelXml, string accessoryXml) { var modelXmlParameter = modelXml != null ? new ObjectParameter("ModelXml", modelXml) : new ObjectParameter("ModelXml", typeof(string)); var accessoryXmlParameter = accessoryXml != null ? new ObjectParameter("AccessoryXml", accessoryXml) : new ObjectParameter("AccessoryXml", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("ImportEquipmentFile", modelXmlParameter, accessoryXmlParameter); } ```
2017/07/26
['https://Stackoverflow.com/questions/45320053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4207036/']
I actually Solved my problem. I did everything correct. But only thing I did not do is to map the hostname with the same ip in Route53. And instead of accessing the website with hostname, I was accessing it from IP. Now after accessing the website from hostname, I was able to access it :)
Seems like you posted [here and got your answer](https://github.com/nginxinc/kubernetes-ingress/issues/76). The solution is to deploy a different Ingress for each namespace. However, deploying 2 Ingresses complicates matters because one instance has to run on a non-standard port (eg. 8080, 8443). I think this is better solved using DNS. Create the CNAME records `cafe-qa.example.com` and `cafe-dev.example.com` both pointing to `cafe.example.com`. Update each Ingress manifest accordingly. Using DNS is somewhat the standard way to separate the Dev/QA/Prod environments.
45,320,053
I developed a website using Asp.Net MVC and Edmx database and I published this website on azure and my database is also on azure and I've a functionality on website that uploads excel record into database and that excel sheet contain almost 18000 records every time I upload that sheet it throw Timeout error after some time so what should I do. [![enter image description here](https://i.stack.imgur.com/n32VE.png)](https://i.stack.imgur.com/n32VE.png) Initially I was not using any command Timeout but after doing some research I'm using this in constructor ``` public ProfessionalServicesEntities() : base("name=ProfessionalServicesEntities") { this.Database.CommandTimeout = 10000; //this.Database.CommandTimeout = 0; //I tried this too. //((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 3600; } ``` Here is the code of function :- ``` public void SaveEquipments(IEnumerable<EquipSampleEntity> collection) { using (ProfessionalServicesEntities db = new ProfessionalServicesEntities()) { string modelXml = XmlSerialization.ListToXml(collection.Where(x=>x.Type == Model).ToList()); string accessoryXml = XmlSerialization.ListToXml(collection.Where(x => x.Type == Accessory).ToList()); db.ImportEquipmentFile(modelXml, accessoryXml); } } ``` here is context file code for SP:- ``` public virtual int ImportEquipmentFile(string modelXml, string accessoryXml) { var modelXmlParameter = modelXml != null ? new ObjectParameter("ModelXml", modelXml) : new ObjectParameter("ModelXml", typeof(string)); var accessoryXmlParameter = accessoryXml != null ? new ObjectParameter("AccessoryXml", accessoryXml) : new ObjectParameter("AccessoryXml", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("ImportEquipmentFile", modelXmlParameter, accessoryXmlParameter); } ```
2017/07/26
['https://Stackoverflow.com/questions/45320053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4207036/']
Seems like you posted [here and got your answer](https://github.com/nginxinc/kubernetes-ingress/issues/76). The solution is to deploy a different Ingress for each namespace. However, deploying 2 Ingresses complicates matters because one instance has to run on a non-standard port (eg. 8080, 8443). I think this is better solved using DNS. Create the CNAME records `cafe-qa.example.com` and `cafe-dev.example.com` both pointing to `cafe.example.com`. Update each Ingress manifest accordingly. Using DNS is somewhat the standard way to separate the Dev/QA/Prod environments.
You can create nginx ingress cotroller in kube-system namespace instead of creating it in QA namespace.
45,320,053
I developed a website using Asp.Net MVC and Edmx database and I published this website on azure and my database is also on azure and I've a functionality on website that uploads excel record into database and that excel sheet contain almost 18000 records every time I upload that sheet it throw Timeout error after some time so what should I do. [![enter image description here](https://i.stack.imgur.com/n32VE.png)](https://i.stack.imgur.com/n32VE.png) Initially I was not using any command Timeout but after doing some research I'm using this in constructor ``` public ProfessionalServicesEntities() : base("name=ProfessionalServicesEntities") { this.Database.CommandTimeout = 10000; //this.Database.CommandTimeout = 0; //I tried this too. //((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 3600; } ``` Here is the code of function :- ``` public void SaveEquipments(IEnumerable<EquipSampleEntity> collection) { using (ProfessionalServicesEntities db = new ProfessionalServicesEntities()) { string modelXml = XmlSerialization.ListToXml(collection.Where(x=>x.Type == Model).ToList()); string accessoryXml = XmlSerialization.ListToXml(collection.Where(x => x.Type == Accessory).ToList()); db.ImportEquipmentFile(modelXml, accessoryXml); } } ``` here is context file code for SP:- ``` public virtual int ImportEquipmentFile(string modelXml, string accessoryXml) { var modelXmlParameter = modelXml != null ? new ObjectParameter("ModelXml", modelXml) : new ObjectParameter("ModelXml", typeof(string)); var accessoryXmlParameter = accessoryXml != null ? new ObjectParameter("AccessoryXml", accessoryXml) : new ObjectParameter("AccessoryXml", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("ImportEquipmentFile", modelXmlParameter, accessoryXmlParameter); } ```
2017/07/26
['https://Stackoverflow.com/questions/45320053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4207036/']
Seems like you posted [here and got your answer](https://github.com/nginxinc/kubernetes-ingress/issues/76). The solution is to deploy a different Ingress for each namespace. However, deploying 2 Ingresses complicates matters because one instance has to run on a non-standard port (eg. 8080, 8443). I think this is better solved using DNS. Create the CNAME records `cafe-qa.example.com` and `cafe-dev.example.com` both pointing to `cafe.example.com`. Update each Ingress manifest accordingly. Using DNS is somewhat the standard way to separate the Dev/QA/Prod environments.
Had the same issue, found a way to resolve it: you just need to add the "**--watch-namespace**" argument to the ingress controller that sits under the ingress service that you've linked to your ingress resource. Then it will be bound only to the services within the same namespace as the ingress service and its pods belong to. ``` apiVersion: extensions/v1beta1 kind: Deployment metadata: namespace: my-namespace name: nginx-ingress-controller spec: replicas: 1 selector: matchLabels: name: nginx-ingress-lb template: metadata: labels: name: nginx-ingress-lb spec: serviceAccountName: ingress-account containers: - args: - /nginx-ingress-controller - "--default-backend-service=$(POD_NAMESPACE)/default-http-backend" - "--default-ssl-certificate=$(POD_NAMESPACE)/secret-tls" - "--watch-namespace=$(POD_NAMESPACE)" env: - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: POD_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace name: nginx-ingress-controller image: "quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.24.1" livenessProbe: httpGet: path: /healthz port: 10254 scheme: HTTP ports: - containerPort: 80 name: http protocol: TCP - containerPort: 443 name: https protocol: TCP --- apiVersion: v1 kind: Service metadata: namespace: my-namespace name: nginx-ingress spec: type: LoadBalancer ports: - name: https port: 443 targetPort: https selector: name: nginx-ingress-lb ```
45,320,053
I developed a website using Asp.Net MVC and Edmx database and I published this website on azure and my database is also on azure and I've a functionality on website that uploads excel record into database and that excel sheet contain almost 18000 records every time I upload that sheet it throw Timeout error after some time so what should I do. [![enter image description here](https://i.stack.imgur.com/n32VE.png)](https://i.stack.imgur.com/n32VE.png) Initially I was not using any command Timeout but after doing some research I'm using this in constructor ``` public ProfessionalServicesEntities() : base("name=ProfessionalServicesEntities") { this.Database.CommandTimeout = 10000; //this.Database.CommandTimeout = 0; //I tried this too. //((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 3600; } ``` Here is the code of function :- ``` public void SaveEquipments(IEnumerable<EquipSampleEntity> collection) { using (ProfessionalServicesEntities db = new ProfessionalServicesEntities()) { string modelXml = XmlSerialization.ListToXml(collection.Where(x=>x.Type == Model).ToList()); string accessoryXml = XmlSerialization.ListToXml(collection.Where(x => x.Type == Accessory).ToList()); db.ImportEquipmentFile(modelXml, accessoryXml); } } ``` here is context file code for SP:- ``` public virtual int ImportEquipmentFile(string modelXml, string accessoryXml) { var modelXmlParameter = modelXml != null ? new ObjectParameter("ModelXml", modelXml) : new ObjectParameter("ModelXml", typeof(string)); var accessoryXmlParameter = accessoryXml != null ? new ObjectParameter("AccessoryXml", accessoryXml) : new ObjectParameter("AccessoryXml", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("ImportEquipmentFile", modelXmlParameter, accessoryXmlParameter); } ```
2017/07/26
['https://Stackoverflow.com/questions/45320053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4207036/']
I actually Solved my problem. I did everything correct. But only thing I did not do is to map the hostname with the same ip in Route53. And instead of accessing the website with hostname, I was accessing it from IP. Now after accessing the website from hostname, I was able to access it :)
You can create nginx ingress cotroller in kube-system namespace instead of creating it in QA namespace.
45,320,053
I developed a website using Asp.Net MVC and Edmx database and I published this website on azure and my database is also on azure and I've a functionality on website that uploads excel record into database and that excel sheet contain almost 18000 records every time I upload that sheet it throw Timeout error after some time so what should I do. [![enter image description here](https://i.stack.imgur.com/n32VE.png)](https://i.stack.imgur.com/n32VE.png) Initially I was not using any command Timeout but after doing some research I'm using this in constructor ``` public ProfessionalServicesEntities() : base("name=ProfessionalServicesEntities") { this.Database.CommandTimeout = 10000; //this.Database.CommandTimeout = 0; //I tried this too. //((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 3600; } ``` Here is the code of function :- ``` public void SaveEquipments(IEnumerable<EquipSampleEntity> collection) { using (ProfessionalServicesEntities db = new ProfessionalServicesEntities()) { string modelXml = XmlSerialization.ListToXml(collection.Where(x=>x.Type == Model).ToList()); string accessoryXml = XmlSerialization.ListToXml(collection.Where(x => x.Type == Accessory).ToList()); db.ImportEquipmentFile(modelXml, accessoryXml); } } ``` here is context file code for SP:- ``` public virtual int ImportEquipmentFile(string modelXml, string accessoryXml) { var modelXmlParameter = modelXml != null ? new ObjectParameter("ModelXml", modelXml) : new ObjectParameter("ModelXml", typeof(string)); var accessoryXmlParameter = accessoryXml != null ? new ObjectParameter("AccessoryXml", accessoryXml) : new ObjectParameter("AccessoryXml", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("ImportEquipmentFile", modelXmlParameter, accessoryXmlParameter); } ```
2017/07/26
['https://Stackoverflow.com/questions/45320053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4207036/']
I actually Solved my problem. I did everything correct. But only thing I did not do is to map the hostname with the same ip in Route53. And instead of accessing the website with hostname, I was accessing it from IP. Now after accessing the website from hostname, I was able to access it :)
Had the same issue, found a way to resolve it: you just need to add the "**--watch-namespace**" argument to the ingress controller that sits under the ingress service that you've linked to your ingress resource. Then it will be bound only to the services within the same namespace as the ingress service and its pods belong to. ``` apiVersion: extensions/v1beta1 kind: Deployment metadata: namespace: my-namespace name: nginx-ingress-controller spec: replicas: 1 selector: matchLabels: name: nginx-ingress-lb template: metadata: labels: name: nginx-ingress-lb spec: serviceAccountName: ingress-account containers: - args: - /nginx-ingress-controller - "--default-backend-service=$(POD_NAMESPACE)/default-http-backend" - "--default-ssl-certificate=$(POD_NAMESPACE)/secret-tls" - "--watch-namespace=$(POD_NAMESPACE)" env: - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: POD_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace name: nginx-ingress-controller image: "quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.24.1" livenessProbe: httpGet: path: /healthz port: 10254 scheme: HTTP ports: - containerPort: 80 name: http protocol: TCP - containerPort: 443 name: https protocol: TCP --- apiVersion: v1 kind: Service metadata: namespace: my-namespace name: nginx-ingress spec: type: LoadBalancer ports: - name: https port: 443 targetPort: https selector: name: nginx-ingress-lb ```
45,320,053
I developed a website using Asp.Net MVC and Edmx database and I published this website on azure and my database is also on azure and I've a functionality on website that uploads excel record into database and that excel sheet contain almost 18000 records every time I upload that sheet it throw Timeout error after some time so what should I do. [![enter image description here](https://i.stack.imgur.com/n32VE.png)](https://i.stack.imgur.com/n32VE.png) Initially I was not using any command Timeout but after doing some research I'm using this in constructor ``` public ProfessionalServicesEntities() : base("name=ProfessionalServicesEntities") { this.Database.CommandTimeout = 10000; //this.Database.CommandTimeout = 0; //I tried this too. //((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 3600; } ``` Here is the code of function :- ``` public void SaveEquipments(IEnumerable<EquipSampleEntity> collection) { using (ProfessionalServicesEntities db = new ProfessionalServicesEntities()) { string modelXml = XmlSerialization.ListToXml(collection.Where(x=>x.Type == Model).ToList()); string accessoryXml = XmlSerialization.ListToXml(collection.Where(x => x.Type == Accessory).ToList()); db.ImportEquipmentFile(modelXml, accessoryXml); } } ``` here is context file code for SP:- ``` public virtual int ImportEquipmentFile(string modelXml, string accessoryXml) { var modelXmlParameter = modelXml != null ? new ObjectParameter("ModelXml", modelXml) : new ObjectParameter("ModelXml", typeof(string)); var accessoryXmlParameter = accessoryXml != null ? new ObjectParameter("AccessoryXml", accessoryXml) : new ObjectParameter("AccessoryXml", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("ImportEquipmentFile", modelXmlParameter, accessoryXmlParameter); } ```
2017/07/26
['https://Stackoverflow.com/questions/45320053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4207036/']
Had the same issue, found a way to resolve it: you just need to add the "**--watch-namespace**" argument to the ingress controller that sits under the ingress service that you've linked to your ingress resource. Then it will be bound only to the services within the same namespace as the ingress service and its pods belong to. ``` apiVersion: extensions/v1beta1 kind: Deployment metadata: namespace: my-namespace name: nginx-ingress-controller spec: replicas: 1 selector: matchLabels: name: nginx-ingress-lb template: metadata: labels: name: nginx-ingress-lb spec: serviceAccountName: ingress-account containers: - args: - /nginx-ingress-controller - "--default-backend-service=$(POD_NAMESPACE)/default-http-backend" - "--default-ssl-certificate=$(POD_NAMESPACE)/secret-tls" - "--watch-namespace=$(POD_NAMESPACE)" env: - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: POD_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace name: nginx-ingress-controller image: "quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.24.1" livenessProbe: httpGet: path: /healthz port: 10254 scheme: HTTP ports: - containerPort: 80 name: http protocol: TCP - containerPort: 443 name: https protocol: TCP --- apiVersion: v1 kind: Service metadata: namespace: my-namespace name: nginx-ingress spec: type: LoadBalancer ports: - name: https port: 443 targetPort: https selector: name: nginx-ingress-lb ```
You can create nginx ingress cotroller in kube-system namespace instead of creating it in QA namespace.
9,358,237
I got app with UITableView. There is UILabel in each UITableViewCell. I add labels in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //look at the upd } ``` But when i try to reload data in this table with some other information, old infromation (old labels) dont disappear, but still on cells. It's look like this: ... How should i organized adding UILabels? UPD I correct code in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Recent Dream"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; UILabel *textLabel = [[UILabel alloc] init]; textLabel.frame = CGRectMake(10, 0, self.view.frame.size.width -110, 48); textLabel.backgroundColor = [UIColor clearColor]; textLabel.font = [UIFont boldSystemFontOfSize:16]; [textLabel setTag:(int)indexPath]; [cell.contentView addSubview:textLabel]; } // Configure the cell... Dream *tempDream = [self.dreams objectAtIndex:indexPath.row]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MM/dd/yyyy"]; //Optionally for time zone converstions [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; NSString *stringFromDate = [formatter stringFromDate:tempDream.dateAdd]; UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bodyWrapper.png"]]; cell.contentView.backgroundColor = background; UILabel *textLabel = (UILabel *)[cell viewWithTag:(int)indexPath]; textLabel.text = tempDream.title; NSLog(@"%@",tempDream.title); NSLog(@"%@",textLabel.text); cell.textLabel.text = @""; cell.detailTextLabel.text = stringFromDate; return cell; } ``` And output look like this: ``` 2012-02-20 15:58:10.512 DreamerIOS[3037:10403] lllooooonggg dreeeeeeeaaaaammmm yeeeeeeah 2012-02-20 15:58:10.513 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] dream to end 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] adsfhadskgh dfagfadkuy gadyv dsfdfad fsdf a ghfncdhg hjfg f dfj ghf 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] (null) ``` So, NSLog(@"%@",tempDream.title); is OK, but NSLog(@"%@",textLabel.text); is null. Why?
2012/02/20
['https://Stackoverflow.com/questions/9358237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150441/']
it's not proper syntax use instead ``` case 's': case 'g': cout << "Finish"; break; ```
``` char o,t; cin >> o >> t; switch (o,t) { case 's': case 'g': cout << "Finish"; break; default: cout << "Nothing"; } ``` In switch when matched case is found, all operator after that are executed. That's why you should write `break;` operator after `case`-es to exit switch. So if you want to do the same in several cases you should just put them one after another.
9,358,237
I got app with UITableView. There is UILabel in each UITableViewCell. I add labels in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //look at the upd } ``` But when i try to reload data in this table with some other information, old infromation (old labels) dont disappear, but still on cells. It's look like this: ... How should i organized adding UILabels? UPD I correct code in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Recent Dream"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; UILabel *textLabel = [[UILabel alloc] init]; textLabel.frame = CGRectMake(10, 0, self.view.frame.size.width -110, 48); textLabel.backgroundColor = [UIColor clearColor]; textLabel.font = [UIFont boldSystemFontOfSize:16]; [textLabel setTag:(int)indexPath]; [cell.contentView addSubview:textLabel]; } // Configure the cell... Dream *tempDream = [self.dreams objectAtIndex:indexPath.row]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MM/dd/yyyy"]; //Optionally for time zone converstions [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; NSString *stringFromDate = [formatter stringFromDate:tempDream.dateAdd]; UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bodyWrapper.png"]]; cell.contentView.backgroundColor = background; UILabel *textLabel = (UILabel *)[cell viewWithTag:(int)indexPath]; textLabel.text = tempDream.title; NSLog(@"%@",tempDream.title); NSLog(@"%@",textLabel.text); cell.textLabel.text = @""; cell.detailTextLabel.text = stringFromDate; return cell; } ``` And output look like this: ``` 2012-02-20 15:58:10.512 DreamerIOS[3037:10403] lllooooonggg dreeeeeeeaaaaammmm yeeeeeeah 2012-02-20 15:58:10.513 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] dream to end 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] adsfhadskgh dfagfadkuy gadyv dsfdfad fsdf a ghfncdhg hjfg f dfj ghf 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] (null) ``` So, NSLog(@"%@",tempDream.title); is OK, but NSLog(@"%@",textLabel.text); is null. Why?
2012/02/20
['https://Stackoverflow.com/questions/9358237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150441/']
it's not proper syntax use instead ``` case 's': case 'g': cout << "Finish"; break; ```
You have some syntax error, the correct code is ``` char o,t; cin >> o >> t; switch (o) { case 's':case 'g': cout << "Finish"; break; default: cout << "Nothing"; } switch (t) { case 's':case 'g': cout << "Finish"; break; default: cout << "Nothing"; } ```
9,358,237
I got app with UITableView. There is UILabel in each UITableViewCell. I add labels in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //look at the upd } ``` But when i try to reload data in this table with some other information, old infromation (old labels) dont disappear, but still on cells. It's look like this: ... How should i organized adding UILabels? UPD I correct code in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Recent Dream"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; UILabel *textLabel = [[UILabel alloc] init]; textLabel.frame = CGRectMake(10, 0, self.view.frame.size.width -110, 48); textLabel.backgroundColor = [UIColor clearColor]; textLabel.font = [UIFont boldSystemFontOfSize:16]; [textLabel setTag:(int)indexPath]; [cell.contentView addSubview:textLabel]; } // Configure the cell... Dream *tempDream = [self.dreams objectAtIndex:indexPath.row]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MM/dd/yyyy"]; //Optionally for time zone converstions [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; NSString *stringFromDate = [formatter stringFromDate:tempDream.dateAdd]; UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bodyWrapper.png"]]; cell.contentView.backgroundColor = background; UILabel *textLabel = (UILabel *)[cell viewWithTag:(int)indexPath]; textLabel.text = tempDream.title; NSLog(@"%@",tempDream.title); NSLog(@"%@",textLabel.text); cell.textLabel.text = @""; cell.detailTextLabel.text = stringFromDate; return cell; } ``` And output look like this: ``` 2012-02-20 15:58:10.512 DreamerIOS[3037:10403] lllooooonggg dreeeeeeeaaaaammmm yeeeeeeah 2012-02-20 15:58:10.513 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] dream to end 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] adsfhadskgh dfagfadkuy gadyv dsfdfad fsdf a ghfncdhg hjfg f dfj ghf 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] (null) ``` So, NSLog(@"%@",tempDream.title); is OK, but NSLog(@"%@",textLabel.text); is null. Why?
2012/02/20
['https://Stackoverflow.com/questions/9358237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150441/']
it's not proper syntax use instead ``` case 's': case 'g': cout << "Finish"; break; ```
You can't `switch` on multiple values in C++. ``` switch (o,t) ``` uses the *comma operator* (it looks a lot like a pair would in some other languages, but it isn't). The comma operator evaluates its left operand (`o`), ignores the value of that, and then returns the value of its right operand (`t`). In other words, your `switch` only looks at `t`. There is no way around this. Your particular case is better written as ``` if (o == 's' && t == 'g') { cout << "Finish"; } else { cout << "Nothing"; } ```
9,358,237
I got app with UITableView. There is UILabel in each UITableViewCell. I add labels in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //look at the upd } ``` But when i try to reload data in this table with some other information, old infromation (old labels) dont disappear, but still on cells. It's look like this: ... How should i organized adding UILabels? UPD I correct code in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Recent Dream"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; UILabel *textLabel = [[UILabel alloc] init]; textLabel.frame = CGRectMake(10, 0, self.view.frame.size.width -110, 48); textLabel.backgroundColor = [UIColor clearColor]; textLabel.font = [UIFont boldSystemFontOfSize:16]; [textLabel setTag:(int)indexPath]; [cell.contentView addSubview:textLabel]; } // Configure the cell... Dream *tempDream = [self.dreams objectAtIndex:indexPath.row]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MM/dd/yyyy"]; //Optionally for time zone converstions [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; NSString *stringFromDate = [formatter stringFromDate:tempDream.dateAdd]; UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bodyWrapper.png"]]; cell.contentView.backgroundColor = background; UILabel *textLabel = (UILabel *)[cell viewWithTag:(int)indexPath]; textLabel.text = tempDream.title; NSLog(@"%@",tempDream.title); NSLog(@"%@",textLabel.text); cell.textLabel.text = @""; cell.detailTextLabel.text = stringFromDate; return cell; } ``` And output look like this: ``` 2012-02-20 15:58:10.512 DreamerIOS[3037:10403] lllooooonggg dreeeeeeeaaaaammmm yeeeeeeah 2012-02-20 15:58:10.513 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] dream to end 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] adsfhadskgh dfagfadkuy gadyv dsfdfad fsdf a ghfncdhg hjfg f dfj ghf 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] (null) ``` So, NSLog(@"%@",tempDream.title); is OK, but NSLog(@"%@",textLabel.text); is null. Why?
2012/02/20
['https://Stackoverflow.com/questions/9358237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150441/']
You cannot do switch for two expressions at the same time. The switch part only compiles because there is a comma operator (which simply evaluates to the second value, in this case `t`). Use plain old `if` statements.
``` char o,t; cin >> o >> t; switch (o,t) { case 's': case 'g': cout << "Finish"; break; default: cout << "Nothing"; } ``` In switch when matched case is found, all operator after that are executed. That's why you should write `break;` operator after `case`-es to exit switch. So if you want to do the same in several cases you should just put them one after another.
9,358,237
I got app with UITableView. There is UILabel in each UITableViewCell. I add labels in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //look at the upd } ``` But when i try to reload data in this table with some other information, old infromation (old labels) dont disappear, but still on cells. It's look like this: ... How should i organized adding UILabels? UPD I correct code in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Recent Dream"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; UILabel *textLabel = [[UILabel alloc] init]; textLabel.frame = CGRectMake(10, 0, self.view.frame.size.width -110, 48); textLabel.backgroundColor = [UIColor clearColor]; textLabel.font = [UIFont boldSystemFontOfSize:16]; [textLabel setTag:(int)indexPath]; [cell.contentView addSubview:textLabel]; } // Configure the cell... Dream *tempDream = [self.dreams objectAtIndex:indexPath.row]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MM/dd/yyyy"]; //Optionally for time zone converstions [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; NSString *stringFromDate = [formatter stringFromDate:tempDream.dateAdd]; UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bodyWrapper.png"]]; cell.contentView.backgroundColor = background; UILabel *textLabel = (UILabel *)[cell viewWithTag:(int)indexPath]; textLabel.text = tempDream.title; NSLog(@"%@",tempDream.title); NSLog(@"%@",textLabel.text); cell.textLabel.text = @""; cell.detailTextLabel.text = stringFromDate; return cell; } ``` And output look like this: ``` 2012-02-20 15:58:10.512 DreamerIOS[3037:10403] lllooooonggg dreeeeeeeaaaaammmm yeeeeeeah 2012-02-20 15:58:10.513 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] dream to end 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] adsfhadskgh dfagfadkuy gadyv dsfdfad fsdf a ghfncdhg hjfg f dfj ghf 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] (null) ``` So, NSLog(@"%@",tempDream.title); is OK, but NSLog(@"%@",textLabel.text); is null. Why?
2012/02/20
['https://Stackoverflow.com/questions/9358237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150441/']
``` char o,t; cin >> o >> t; switch (o,t) { case 's': case 'g': cout << "Finish"; break; default: cout << "Nothing"; } ``` In switch when matched case is found, all operator after that are executed. That's why you should write `break;` operator after `case`-es to exit switch. So if you want to do the same in several cases you should just put them one after another.
You have some syntax error, the correct code is ``` char o,t; cin >> o >> t; switch (o) { case 's':case 'g': cout << "Finish"; break; default: cout << "Nothing"; } switch (t) { case 's':case 'g': cout << "Finish"; break; default: cout << "Nothing"; } ```
9,358,237
I got app with UITableView. There is UILabel in each UITableViewCell. I add labels in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //look at the upd } ``` But when i try to reload data in this table with some other information, old infromation (old labels) dont disappear, but still on cells. It's look like this: ... How should i organized adding UILabels? UPD I correct code in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Recent Dream"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; UILabel *textLabel = [[UILabel alloc] init]; textLabel.frame = CGRectMake(10, 0, self.view.frame.size.width -110, 48); textLabel.backgroundColor = [UIColor clearColor]; textLabel.font = [UIFont boldSystemFontOfSize:16]; [textLabel setTag:(int)indexPath]; [cell.contentView addSubview:textLabel]; } // Configure the cell... Dream *tempDream = [self.dreams objectAtIndex:indexPath.row]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MM/dd/yyyy"]; //Optionally for time zone converstions [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; NSString *stringFromDate = [formatter stringFromDate:tempDream.dateAdd]; UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bodyWrapper.png"]]; cell.contentView.backgroundColor = background; UILabel *textLabel = (UILabel *)[cell viewWithTag:(int)indexPath]; textLabel.text = tempDream.title; NSLog(@"%@",tempDream.title); NSLog(@"%@",textLabel.text); cell.textLabel.text = @""; cell.detailTextLabel.text = stringFromDate; return cell; } ``` And output look like this: ``` 2012-02-20 15:58:10.512 DreamerIOS[3037:10403] lllooooonggg dreeeeeeeaaaaammmm yeeeeeeah 2012-02-20 15:58:10.513 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] dream to end 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] adsfhadskgh dfagfadkuy gadyv dsfdfad fsdf a ghfncdhg hjfg f dfj ghf 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] (null) ``` So, NSLog(@"%@",tempDream.title); is OK, but NSLog(@"%@",textLabel.text); is null. Why?
2012/02/20
['https://Stackoverflow.com/questions/9358237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150441/']
You cannot do switch for two expressions at the same time. The switch part only compiles because there is a comma operator (which simply evaluates to the second value, in this case `t`). Use plain old `if` statements.
You have some syntax error, the correct code is ``` char o,t; cin >> o >> t; switch (o) { case 's':case 'g': cout << "Finish"; break; default: cout << "Nothing"; } switch (t) { case 's':case 'g': cout << "Finish"; break; default: cout << "Nothing"; } ```
9,358,237
I got app with UITableView. There is UILabel in each UITableViewCell. I add labels in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //look at the upd } ``` But when i try to reload data in this table with some other information, old infromation (old labels) dont disappear, but still on cells. It's look like this: ... How should i organized adding UILabels? UPD I correct code in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Recent Dream"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; UILabel *textLabel = [[UILabel alloc] init]; textLabel.frame = CGRectMake(10, 0, self.view.frame.size.width -110, 48); textLabel.backgroundColor = [UIColor clearColor]; textLabel.font = [UIFont boldSystemFontOfSize:16]; [textLabel setTag:(int)indexPath]; [cell.contentView addSubview:textLabel]; } // Configure the cell... Dream *tempDream = [self.dreams objectAtIndex:indexPath.row]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MM/dd/yyyy"]; //Optionally for time zone converstions [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; NSString *stringFromDate = [formatter stringFromDate:tempDream.dateAdd]; UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bodyWrapper.png"]]; cell.contentView.backgroundColor = background; UILabel *textLabel = (UILabel *)[cell viewWithTag:(int)indexPath]; textLabel.text = tempDream.title; NSLog(@"%@",tempDream.title); NSLog(@"%@",textLabel.text); cell.textLabel.text = @""; cell.detailTextLabel.text = stringFromDate; return cell; } ``` And output look like this: ``` 2012-02-20 15:58:10.512 DreamerIOS[3037:10403] lllooooonggg dreeeeeeeaaaaammmm yeeeeeeah 2012-02-20 15:58:10.513 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] dream to end 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] adsfhadskgh dfagfadkuy gadyv dsfdfad fsdf a ghfncdhg hjfg f dfj ghf 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] (null) ``` So, NSLog(@"%@",tempDream.title); is OK, but NSLog(@"%@",textLabel.text); is null. Why?
2012/02/20
['https://Stackoverflow.com/questions/9358237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150441/']
You cannot do switch for two expressions at the same time. The switch part only compiles because there is a comma operator (which simply evaluates to the second value, in this case `t`). Use plain old `if` statements.
You can't `switch` on multiple values in C++. ``` switch (o,t) ``` uses the *comma operator* (it looks a lot like a pair would in some other languages, but it isn't). The comma operator evaluates its left operand (`o`), ignores the value of that, and then returns the value of its right operand (`t`). In other words, your `switch` only looks at `t`. There is no way around this. Your particular case is better written as ``` if (o == 's' && t == 'g') { cout << "Finish"; } else { cout << "Nothing"; } ```
9,358,237
I got app with UITableView. There is UILabel in each UITableViewCell. I add labels in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //look at the upd } ``` But when i try to reload data in this table with some other information, old infromation (old labels) dont disappear, but still on cells. It's look like this: ... How should i organized adding UILabels? UPD I correct code in this way: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Recent Dream"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; UILabel *textLabel = [[UILabel alloc] init]; textLabel.frame = CGRectMake(10, 0, self.view.frame.size.width -110, 48); textLabel.backgroundColor = [UIColor clearColor]; textLabel.font = [UIFont boldSystemFontOfSize:16]; [textLabel setTag:(int)indexPath]; [cell.contentView addSubview:textLabel]; } // Configure the cell... Dream *tempDream = [self.dreams objectAtIndex:indexPath.row]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MM/dd/yyyy"]; //Optionally for time zone converstions [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; NSString *stringFromDate = [formatter stringFromDate:tempDream.dateAdd]; UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bodyWrapper.png"]]; cell.contentView.backgroundColor = background; UILabel *textLabel = (UILabel *)[cell viewWithTag:(int)indexPath]; textLabel.text = tempDream.title; NSLog(@"%@",tempDream.title); NSLog(@"%@",textLabel.text); cell.textLabel.text = @""; cell.detailTextLabel.text = stringFromDate; return cell; } ``` And output look like this: ``` 2012-02-20 15:58:10.512 DreamerIOS[3037:10403] lllooooonggg dreeeeeeeaaaaammmm yeeeeeeah 2012-02-20 15:58:10.513 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] dream to end 2012-02-20 15:58:10.516 DreamerIOS[3037:10403] (null) 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] adsfhadskgh dfagfadkuy gadyv dsfdfad fsdf a ghfncdhg hjfg f dfj ghf 2012-02-20 15:58:10.519 DreamerIOS[3037:10403] (null) ``` So, NSLog(@"%@",tempDream.title); is OK, but NSLog(@"%@",textLabel.text); is null. Why?
2012/02/20
['https://Stackoverflow.com/questions/9358237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150441/']
You can't `switch` on multiple values in C++. ``` switch (o,t) ``` uses the *comma operator* (it looks a lot like a pair would in some other languages, but it isn't). The comma operator evaluates its left operand (`o`), ignores the value of that, and then returns the value of its right operand (`t`). In other words, your `switch` only looks at `t`. There is no way around this. Your particular case is better written as ``` if (o == 's' && t == 'g') { cout << "Finish"; } else { cout << "Nothing"; } ```
You have some syntax error, the correct code is ``` char o,t; cin >> o >> t; switch (o) { case 's':case 'g': cout << "Finish"; break; default: cout << "Nothing"; } switch (t) { case 's':case 'g': cout << "Finish"; break; default: cout << "Nothing"; } ```
60,176,340
I have a front-end application that sends a formData which contains arrays, so I'm using "object-to-formdata" to parse an the following object: ``` { "profileImage": { "name": "5574c060-853b-4999-ba39-1c66d5329704", "size": 364985, "mimetype": "image/png", "url": "uploads/5574c060-853b-4999-ba39-1c66d5329704" }, "skills": [], "lessonsFinished": [], "classes": [], "_id": "5e3c2f8c80776b12cc336fdf", "email": "[email protected]", "password": "$2b$10$iZ3/BuklZ1FCGlyQDPUyMOhcWAfei5yl.llYScbWIv12XWcsokrgS", "username": "adrian", "verified": false, "status": "student", "color": "blue", "verificationCode": "50SZWPCHDL685C", "__v": 0, "lastName": "Test", "name": "Test", } ``` The object contains objects and arrays, and when parsed and sent to the backend, which uses express, with bodyParser and "express-fileupload" as a file manager, I receive this object: ``` { 'profileImage[name]': '5574c060-853b-4999-ba39-1c66d5329704', 'profileImage[size]': '364985', 'profileImage[mimetype]': 'image/png', 'profileImage[url]': 'uploads/5574c060-853b-4999-ba39-1c66d5329704', 'skills[]': '', 'lessonsFinished[]': '', 'classes[]': '', _id: '5e3c2f8c80776b12cc336fdf', email: '[email protected]', password: '$2b$10$iZ3/BuklZ1FCGlyQDPUyMOhcWAfei5yl.llYScbWIv12XWcsokrgS', username: 'adrian', verified: 'false', status: 'student', color: 'blue', verificationCode: '50SZWPCHDL685C', __v: '0', lastName: 'Test', name: 'Test', } ``` I cannot seem to find a way of parsing this into a normal Object, since I need to use the full object as a query parameter for mongoose. My Express configuration goes as follows: ``` const bodyParser = require('body-parser'); const fileUpload = require('express-fileupload'); const express = require('express'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(fileUpload()) ``` Finally, I have the endpoint in which I am receiving the formData: ``` exports.create = function (model) { return async function (req, res, next) { try { let document = req.body; if (req.files) { Object.keys(req.files).forEach(key => { let file = req.files[key] file.mv(upload_dir + file.name, (err) => { if (err) return res.status(500).send(err); }); document[key] = { name: file.name, size: file.size, mimetype: file.mimetype, url: upload_dir + file.name } }) } const newDocument = await new model(req.body).save(); res.status(200).send(newDocument); } catch (err) { return next({ status: 500, message: err.message }) } } } ``` I receive the file just fine, and the rest of the data as well, but i cannot find a way of parsing the "encoded" (as in surrounded by brackets) object keys. I tried building a recursive function to decode them but after several hours I couldn't find a solution and I figured there must be another way already working. I tried the solutions presented in this thread: [How to convert FormData(HTML5 Object) to JSON](https://stackoverflow.com/questions/41431322/how-to-convert-formdatahtml5-object-to-json) but those just create an Object with the brackets included in the key... Thank you in advance for the help!
2020/02/11
['https://Stackoverflow.com/questions/60176340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11101440/']
If you have a small program that is going to exit quickly and you are running on a fully-featured modern desktop or server operating system, then probably you can rely on the operating system to clean up allocated heap memory when the process terminates; see [here](https://stackoverflow.com/questions/15882531/does-the-heap-get-freed-when-the-program-exits). Unless rsprintf\_s specifically tells you that you should free what it returns, I would not assume this is the case. It is possible that it has an implementation which does not even use heap memory (perhaps it uses statically allocated global memory, perhaps in a DATA section or something).
If you are on an operating system, where a misbehaving process can't really do much passive harm, then it is in practice fine. Active harm such as corrupting files is another thing, but leaving memory un-freed at program exit will not interact with those system APIs. So omitting memory free at program exit is, in a sense, always fine when program is running in such an operating system (such as any modern desktop OS). From a different viewpoint, it is never fine. The reasons why include, from the top of my head: * It's just not very smart to intentionally write non-portable code, when you don't *have to* for some reason. You never know what future brings. * Being sloppy with memory while not being sloppy with other things, that's a difficult mindset to maintain. Just don't be sloppy with your code. * What is now program exit might end up being just error handling function and resuming normal operation later, and then first of all it's easy to forget to fix the memory leak, and further you may have to do a lot of refactoring, when you suddenly need to have access to the pointer to be freed in a place where previously you had just thrown it away already. * When they see leaks, other programmers will think poorly of the whole program, and as an extension, of the programmer who wrote it. * In other languages, such as C++, freeing memory is coupled with calling cleanup code such as class destructor, and those in turn may for example flush buffers and close files, and not doing that can leave corrupt files etc. Better not develop bad habits with C, which you'd need to unlearn with different language.
60,176,340
I have a front-end application that sends a formData which contains arrays, so I'm using "object-to-formdata" to parse an the following object: ``` { "profileImage": { "name": "5574c060-853b-4999-ba39-1c66d5329704", "size": 364985, "mimetype": "image/png", "url": "uploads/5574c060-853b-4999-ba39-1c66d5329704" }, "skills": [], "lessonsFinished": [], "classes": [], "_id": "5e3c2f8c80776b12cc336fdf", "email": "[email protected]", "password": "$2b$10$iZ3/BuklZ1FCGlyQDPUyMOhcWAfei5yl.llYScbWIv12XWcsokrgS", "username": "adrian", "verified": false, "status": "student", "color": "blue", "verificationCode": "50SZWPCHDL685C", "__v": 0, "lastName": "Test", "name": "Test", } ``` The object contains objects and arrays, and when parsed and sent to the backend, which uses express, with bodyParser and "express-fileupload" as a file manager, I receive this object: ``` { 'profileImage[name]': '5574c060-853b-4999-ba39-1c66d5329704', 'profileImage[size]': '364985', 'profileImage[mimetype]': 'image/png', 'profileImage[url]': 'uploads/5574c060-853b-4999-ba39-1c66d5329704', 'skills[]': '', 'lessonsFinished[]': '', 'classes[]': '', _id: '5e3c2f8c80776b12cc336fdf', email: '[email protected]', password: '$2b$10$iZ3/BuklZ1FCGlyQDPUyMOhcWAfei5yl.llYScbWIv12XWcsokrgS', username: 'adrian', verified: 'false', status: 'student', color: 'blue', verificationCode: '50SZWPCHDL685C', __v: '0', lastName: 'Test', name: 'Test', } ``` I cannot seem to find a way of parsing this into a normal Object, since I need to use the full object as a query parameter for mongoose. My Express configuration goes as follows: ``` const bodyParser = require('body-parser'); const fileUpload = require('express-fileupload'); const express = require('express'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(fileUpload()) ``` Finally, I have the endpoint in which I am receiving the formData: ``` exports.create = function (model) { return async function (req, res, next) { try { let document = req.body; if (req.files) { Object.keys(req.files).forEach(key => { let file = req.files[key] file.mv(upload_dir + file.name, (err) => { if (err) return res.status(500).send(err); }); document[key] = { name: file.name, size: file.size, mimetype: file.mimetype, url: upload_dir + file.name } }) } const newDocument = await new model(req.body).save(); res.status(200).send(newDocument); } catch (err) { return next({ status: 500, message: err.message }) } } } ``` I receive the file just fine, and the rest of the data as well, but i cannot find a way of parsing the "encoded" (as in surrounded by brackets) object keys. I tried building a recursive function to decode them but after several hours I couldn't find a solution and I figured there must be another way already working. I tried the solutions presented in this thread: [How to convert FormData(HTML5 Object) to JSON](https://stackoverflow.com/questions/41431322/how-to-convert-formdatahtml5-object-to-json) but those just create an Object with the brackets included in the key... Thank you in advance for the help!
2020/02/11
['https://Stackoverflow.com/questions/60176340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11101440/']
> > I know, any dynamically allocated memory MUST be freed at the end of its use, with `free()`. > > > No. Not freeing has the result that less memory remains for your program to allocate for other purposes. It may (or may not) cause the program's memory footprint to be larger than it otherwise would be. In flagrant, extended, or extreme cases (as judged in an environment-dependent manner), it may mean that insufficient (virtual) memory is available to serve other applications, or to serve the leaky one itself. But none of those things mean you *must* free memory. You always have the alternative of accepting the consequences of not doing so. For the most part, the minor advantages attending wanton disregard for freeing allocated memory in no way balance the negative impact on the program and on the system on which it runs, but there are cases in which it does not cause any practical problem. All major operating systems in use today release processes' allocated memory at process termination. Therefore, small leaks in short-running programs are fairly inconsequential on most systems you're likely to meet, and whether one should free memory that one needs to use until just prior to program termination is a matter of style, not practicality. And that brings us directly to your example program. > > However, is it an idiomatic function? If it exists, is it then considered a minor problem not to free the memory in this style of case? > > > I think you meant "if it *exits*". As discussed above, there is substantially no difference in practical impact on the program or system between freeing manually just before exiting the top-level call to `main()` on one hand, and leaving it to the OS to clean up. > > I would like to know if such a function can be used without worrying about freeing the memory every time, although I doubt it. > > > You stand in grave danger of causing trouble for yourself and others if you neglect to free allocated memory without giving careful consideration to whether doing so will produce problems. You may under some circumstances go without freeing, but it would be foolish to do so without worrying about it, so to speak. Moreover, at your apparent level of experience, you may not yet be equipped to make good judgements in this area. I would actually put it the other way around, then: being sure to free allocated memory when you no longer need it is the worry-free alternative. Or at least worry-less. You can make that relatively easy by cultivating programming practices that support it.
If you are on an operating system, where a misbehaving process can't really do much passive harm, then it is in practice fine. Active harm such as corrupting files is another thing, but leaving memory un-freed at program exit will not interact with those system APIs. So omitting memory free at program exit is, in a sense, always fine when program is running in such an operating system (such as any modern desktop OS). From a different viewpoint, it is never fine. The reasons why include, from the top of my head: * It's just not very smart to intentionally write non-portable code, when you don't *have to* for some reason. You never know what future brings. * Being sloppy with memory while not being sloppy with other things, that's a difficult mindset to maintain. Just don't be sloppy with your code. * What is now program exit might end up being just error handling function and resuming normal operation later, and then first of all it's easy to forget to fix the memory leak, and further you may have to do a lot of refactoring, when you suddenly need to have access to the pointer to be freed in a place where previously you had just thrown it away already. * When they see leaks, other programmers will think poorly of the whole program, and as an extension, of the programmer who wrote it. * In other languages, such as C++, freeing memory is coupled with calling cleanup code such as class destructor, and those in turn may for example flush buffers and close files, and not doing that can leave corrupt files etc. Better not develop bad habits with C, which you'd need to unlearn with different language.
2,648,348
For ordinary differential equation, $$y'+y\sin(x) = \sin(2x) $$ where y=y(x) for real x. Is there any way that I can solve this question with eigenvalues and eigenvectors by changing above equation like X`=AX ? Thanks in advance
2018/02/13
['https://math.stackexchange.com/questions/2648348', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/530979/']
$$\frac{dy}{dx}+y\sin(x) = \sin(2x)=2\sin(x)\cos(x) $$ $$\frac{dy}{\sin(x)dx}+y =2\cos(x)$$ $$\frac{dy}{d(-\cos(x))}+y=2\cos(x) $$ Let $\quad X=\cos(x)$ $$-\frac{dy}{dX}+y=2X$$ This first order linear ODE is easy to solve : $\quad y=c\:e^X+2X+2$ $$y(x)=c\:e^{\cos(x)}+2\cos(x)+2$$
$$ y'+y\sin x=\sin (2x)\quad\Longleftrightarrow\quad \mathrm{e}^{-\cos x}(\,y'+y\sin x)=2 \sin x\cos x\,\mathrm{e}^{-\cos x} \\ \quad\Longleftrightarrow\quad \big(\mathrm{e}^{-\cos x}y\big)'=f(\cos x)\sin x=-\frac{d}{dx}F(\cos x), $$ where $$ f(w)=2 w\mathrm{e}^{-w}\quad\text{and}\quad F(w)=\int f(w)\,dw. $$ But $$ F(w)=\int 2 w\,\mathrm{e}^{-w}\,dw=-2(w+1)\mathrm{e}^{-w}+c $$ and hence $$ \big(\mathrm{e}^{-\cos x}y\big)'=-\frac{d}{dx}\left(-2(\cos x+1)\mathrm{e}^{-\cos x}\right) $$ and finally $$ \mathrm{e}^{-\cos x}y=2(\cos x+1)\mathrm{e}^{-\cos x}+c $$ or $$ y=2(\cos x+1)+c\,\mathrm{e}^{\cos x} $$ for some $c\in\mathbb R$.
592,278
I'm trying to prevent the ipmi kernel modules from loading on a server with a SuperMicro X8DTG-D motherboard running Ubuntu 14.04. My motivation for doing so is that the modules sometimes seem to take a very long time to unload when I attempt to reboot the machine. My understanding is that putting the following into a file in /etc/modprobe.d and regenerating the RAM disk used on boot should prevent the listed modules from loading; however, they still appear to be loaded when the machine is booted even though I confirmed that the file containing the below lines is included in the RAM disk: ``` alias ipmi_si off alias ipmi_devintf off alias ipmi_msghandler off ``` Any ideas as to how to disable loading of these modules?
2014/04/30
['https://serverfault.com/questions/592278', 'https://serverfault.com', 'https://serverfault.com/users/86482/']
I suggest to create a file /etc/modprobe.d/blacklist-ipmi.conf containing ``` blacklist ipmi_si blacklist ipmi_devintf blacklist ipmi_msghandler ```
If you have **ipmitool** package installed, comment your module in ``` /usr/lib/modules-load.d/ipmievd.conf ```
185,212
I want to make an AJAX request on every select value change to update the real value from database. I'm coding inside a shortcode on `functions.php`. I have a `select` element like this one below, ``` echo '<select name="changeValue" onchange="changeValue(' . $user->ID . ', this.options[this.selectedIndex])">' ``` At the end of the shortcode, I do: ``` ?> <script type="text/javascript"> function changeValue(id, valueElement) { jQuery.post( "<?php echo admin_url('admin-ajax.php'); ?>", { 'action': 'update_value', 'data': { user_id: id, value: valueElement.value } }, function(response){ console.log(response) } ); } </script> <? } add_shortcode('the_shortcode', 'the_shortcode'); function update_value() { $user_id = $_POST['data']['user_id']; $value= $_POST['data']['value']; echo $user_id . ' - ' . $empresa; //return update_user_meta($user_id , 'value', $value); wp_die(); } add_action( 'wp_ajax_update_value', 'update_value' ); add_action( 'wp_ajax_nopriv_update_value', 'update_value' ); ``` My code **works when I'm logged as Admin**. However if I'm logged as another user, `console.log(response)` returns the whole HTML page content. What am I doing wrong? EDIT: Another difference is that when logged as Admin, `admin-ajax.php` returns `200 OK`, whereas when logged as a user it returns `302 Found`.
2015/04/24
['https://wordpress.stackexchange.com/questions/185212', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/51091/']
What a type you work with response If you work with json ``` $.post( ajaxurl , data , function(res){ // your code },'json'); ``` Remove wp\_die() and replace with die()
When using `admin-ajax.php` the `admin_init` hook is fired, so many functions that run in the admin will also run when ajax is used. In this case there is some code locking non admin users out of the admin by redirecting them somewhere else. This could be part of your theme or coming from a plugin. When the redirect fires it 'returns' the html of the homepage to your ajax request, which is why you see html instead of the response you expect. The redirect would need to be modified to ignore ajax requests: ``` if ( ( ! current_user_can( 'level_5' ) ) && ( $_SERVER['PHP_SELF'] != '/wp- admin/admin-ajax.php' ) ) { wp_redirect( site_url() ); } ``` You could also use the REST API instead of ajax to avoid this issue.
62,573,604
I have an example here with a simple state called counter. In the componentDidMount, I am getting 0 instead of 3 during console.log and during unmount, I am getting the counter number from button click instead of 0. I am confused as to how does it really works? Here is the code: ``` import React, { Component } from 'react' class TestNumber extends Component { constructor(props) { super(props) this.state = {counter: 0} } componentDidMount() { console.log('Mount Called') this.setState({counter:3}) console.log(this.state.counter) } componentWillUnmount() { this.setState({counter:0}) console.log('Unmount Called') console.log(this.state.counter) } handleClick = () => { this.setState({counter: this.state.counter + 1}) } render() { return ( <div> <h2>{this.state.counter}</h2> <button onClick={this.handleClick}> Click me </button> </div> ) } } export default TestNumber ```
2020/06/25
['https://Stackoverflow.com/questions/62573604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9500607/']
In addition to posed answer. The problem here is not with life cycle methods but the problem is `state`. In react state can be asynchronous sometimes. React Doc: <https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous> Supporting article: <https://medium.com/@wereHamster/beware-react-setstate-is-asynchronous-ce87ef1a9cf3> In general we should assume that react `state` is asynchronous and should not rely on it immediately. Following code will print correct `console.log`. ``` this.setState({count: 3}, () => { console.log(this.state.counter) }); ``` Bottom line > > React state can be asynchronous > > >
It is not about how those two life-cycle methods work, it is about the `setState` being async in React, which means that the sate value won't be modified right after you call `setState` and that is why you get the old values from the console.log. [Why is setState in reactjs Async instead of Sync?](https://stackoverflow.com/q/36085726/5913039) The following example will give you the right results. ``` componentDidMount() { this.setState({counter:3}, () => { console.log(this.state.counter); }); console.log(this.state.counter) } componentWillUnmount() { this.setState({counter:0}, () => { console.log(this.state.counter); }); console.log('Unmount Called'); } ```
9,607
I have been working as a freelancer for a few months, providing R&D services for small companies. My preferred mode of collaboration is billing per project, which usually lasts a few weeks. It gives me the flexibility to solve the problems as a want and in the order that I prefer. The disadvantage is that I systematically under-estimate the time required for accomplishing a project, and consequently find myself underpaid. I have tried for about a month charging per week, but it seems to provoke the dynamics where I am more concerned with showing my client that I do work than focusing on getting good results. Specifically, I avoid the risks of trying new ways that may potentially take a lot of time without certain positive outcome, and I feel pressure from my client to report on the intermediate steps rather then on the final outcome. I am looking for suggestions on improving collaboration, as well as for the pros and cons of different modes of collaboration that I might not have considered.
2020/02/04
['https://freelancing.stackexchange.com/questions/9607', 'https://freelancing.stackexchange.com', 'https://freelancing.stackexchange.com/users/23884/']
I started my consultancy twenty years ago and struggled with this problem a lot in the past. I found that everyone is generally happier in the long run with hourly contracts billed weekly or monthly. If you are running into issues where customers want quantifiable proof that you are working on their projects as much as you say that you are, then you should utilize a time tracking solution that monitors your screen, mouse, and keyboard movements like [HubStaff](http://ssqt.co/m5fIOsy). I also bill on a per project basis, but I only do this when I am absolutely certain of how long it will take and how much it will cost in order to complete the project.
It depends on the scope of the project. If you think that after completion of project multiple revisions will be required and client can ask for multiple modifications, you need to go for the hourly payment method. If all the requirements are crystal clear and you are clear in your mind regarding the requirements and can estimate the time duration for the project, go for the project wise payment. As project wise payments are better when it comes to bigger projects.
9,607
I have been working as a freelancer for a few months, providing R&D services for small companies. My preferred mode of collaboration is billing per project, which usually lasts a few weeks. It gives me the flexibility to solve the problems as a want and in the order that I prefer. The disadvantage is that I systematically under-estimate the time required for accomplishing a project, and consequently find myself underpaid. I have tried for about a month charging per week, but it seems to provoke the dynamics where I am more concerned with showing my client that I do work than focusing on getting good results. Specifically, I avoid the risks of trying new ways that may potentially take a lot of time without certain positive outcome, and I feel pressure from my client to report on the intermediate steps rather then on the final outcome. I am looking for suggestions on improving collaboration, as well as for the pros and cons of different modes of collaboration that I might not have considered.
2020/02/04
['https://freelancing.stackexchange.com/questions/9607', 'https://freelancing.stackexchange.com', 'https://freelancing.stackexchange.com/users/23884/']
I started my consultancy twenty years ago and struggled with this problem a lot in the past. I found that everyone is generally happier in the long run with hourly contracts billed weekly or monthly. If you are running into issues where customers want quantifiable proof that you are working on their projects as much as you say that you are, then you should utilize a time tracking solution that monitors your screen, mouse, and keyboard movements like [HubStaff](http://ssqt.co/m5fIOsy). I also bill on a per project basis, but I only do this when I am absolutely certain of how long it will take and how much it will cost in order to complete the project.
I don't use any of those pricing models. I find [value-based pricing](https://www.priceintelligently.com/blog/value-based-pricing) not only more easily managed, but much more profitable.
17,548,265
I would like to set up a simple jQuery onClick event to make the UI dynamic on a handlebars template. I was wondering to addClass() after a specific click. consider the HTML (generated by handlebars) ``` {{#if hasButton}} <div id="container"> <button type="submit" class="myButton">Click me!</button> </div> {{/if}} ``` i.e: After a click within a button, its container will receive a loading class that will create the interaction using CSS. ``` $(".myButton").on("click", function(event){ $(this).parent().addClass("loading"); }); ``` This code should goes on my handlebars-template or should I rewrite it into a specific helper for it? Is there any examples that could be provided so I can study it then develop something similar? Thanks in advance!
2013/07/09
['https://Stackoverflow.com/questions/17548265', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1060155/']
You have to refresh your Jquery listeners AFTER the insertion of nodes into your DOM HTML. ``` var source = "<li><a href="{{uri}}">{{label}}</a></li>"; var template = Handlebars.compile(source); var context = {"uri":"http://example.com", "label":"my label"}; $("ul").append( template(context) ); // add your JQuery event listeners $("li").click(function(){ alert("success"); }); ```
I am not sure what your problem exactly is. It's correct like this if you keep your JavaScript in a \*.js file, `perhaps` using parent() instead on `prev()` in this specific case.
17,548,265
I would like to set up a simple jQuery onClick event to make the UI dynamic on a handlebars template. I was wondering to addClass() after a specific click. consider the HTML (generated by handlebars) ``` {{#if hasButton}} <div id="container"> <button type="submit" class="myButton">Click me!</button> </div> {{/if}} ``` i.e: After a click within a button, its container will receive a loading class that will create the interaction using CSS. ``` $(".myButton").on("click", function(event){ $(this).parent().addClass("loading"); }); ``` This code should goes on my handlebars-template or should I rewrite it into a specific helper for it? Is there any examples that could be provided so I can study it then develop something similar? Thanks in advance!
2013/07/09
['https://Stackoverflow.com/questions/17548265', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1060155/']
there is no need to reattach the event handler on every dynamic DOM update if you're defining them at document level: ``` $(document).on('click','li',function(){ alert( 'success' ); }); ``` Hope this helps! :-)
I am not sure what your problem exactly is. It's correct like this if you keep your JavaScript in a \*.js file, `perhaps` using parent() instead on `prev()` in this specific case.
3,458,590
I'm trying to add a 'Home' and 'Work' address my Person record. It seems only 1 shows up (the one added later. Is if possible to add multiple addresses to a Person and see them displayed in the UnknownPersonViewController? If so, how should I do this? Here's my code: ``` void multiValueAddDictionaryValueAndLabel(ABMultiValueRef multi, CFDictionaryRef values, CFStringRef label) { if (multi && values != NULL) { ABMultiValueAddValueAndLabel(multi, values, label, NULL); } } CFStringRef getValueForKey(CFDictionaryRef dict, CFStringRef key) { CFStringRef value = NULL; if (CFDictionaryContainsKey(dict, key)) { value = CFDictionaryGetValue(dict, key); } return value; } ABRecordRef createPerson(CFDictionaryRef dict) { ABRecordRef person = ABPersonCreate(); /* Add work address ... */ ABMultiValueRef workAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType); NSDictionary *values = [NSDictionary dictionaryWithObjectsAndKeys: (NSString *)getValueForKey(dict, CFSTR("d:street")), (NSString *)kABPersonAddressStreetKey, (NSString *)getValueForKey(dict, CFSTR("d:postalcode")), (NSString *)kABPersonAddressZIPKey, (NSString *)getValueForKey(dict, CFSTR("d:l")), (NSString *)kABPersonAddressCityKey, (NSString *)getValueForKey(dict, CFSTR("d:st")), (NSString *)kABPersonAddressCityKey, (NSString *)getValueForKey(dict, CFSTR("d:co")), (NSString *)kABPersonAddressCountryKey, nil]; multiValueAddDictionaryValueAndLabel(workAddress, (CFDictionaryRef)values, kABWorkLabel); ABRecordSetValue(person, kABPersonAddressProperty, workAddress, NULL); CFRelease(workAddress); /* Add home address ... */ ABMultiValueRef homeAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType); values = [NSDictionary dictionaryWithObjectsAndKeys: (NSString *)getValueForKey(dict, CFSTR("d:homeStreet")), (NSString *)kABPersonAddressStreetKey, (NSString *)getValueForKey(dict, CFSTR("d:homePostalCode")), (NSString *)kABPersonAddressZIPKey, (NSString *)getValueForKey(dict, CFSTR("d:homeCity")), (NSString *)kABPersonAddressCityKey, (NSString *)getValueForKey(dict, CFSTR("d:homeState")), (NSString *)kABPersonAddressCityKey, (NSString *)getValueForKey(dict, CFSTR("d:homeCountry")), (NSString *)kABPersonAddressCountryKey, nil]; multiValueAddDictionaryValueAndLabel(homeAddress, (CFDictionaryRef)values, kABHomeLabel); ABRecordSetValue(person, kABPersonAddressProperty, homeAddress, NULL); CFRelease(homeAddress); } ```
2010/08/11
['https://Stackoverflow.com/questions/3458590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/250164/']
What you want to do is use the same mutable ABMultiValueRef for both addresses: ``` ABMultiValueRef addresses = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType); // set up your 2 dictionaries here as you did in your question (though obviously with differing names) ABMultiValueAddDictionaryValueAndLabel(addresses, (CFDictionaryRef)workValues, kABWorkLabel); ABMultiValueAddDictionaryValueAndLabel(addresses, (CFDictionaryRef)homeValues, kABHomeLabel); ABRecordSetValue(person, kABPersonAddressProperty, homeAddress, NULL); CFRelease(addresses); ```
This code works: ``` ABMultiValueRef addresses = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType); values = [NSDictionary dictionaryWithObjectsAndKeys: (NSString *)getValueForKey(dict, CFSTR("d:street")), (NSString *)kABPersonAddressStreetKey, (NSString *)getValueForKey(dict, CFSTR("d:postalcode")), (NSString *)kABPersonAddressZIPKey, (NSString *)getValueForKey(dict, CFSTR("d:l")), (NSString *)kABPersonAddressCityKey, (NSString *)getValueForKey(dict, CFSTR("d:st")), (NSString *)kABPersonAddressCityKey, (NSString *)getValueForKey(dict, CFSTR("d:co")), (NSString *)kABPersonAddressCountryKey, nil]; multiValueAddDictionaryValueAndLabel(addresses, (CFDictionaryRef)values, kABWorkLabel); values = [NSDictionary dictionaryWithObjectsAndKeys: (NSString *)getValueForKey(dict, CFSTR("d:homeStreet")), (NSString *)kABPersonAddressStreetKey, (NSString *)getValueForKey(dict, CFSTR("d:homePostalCode")), (NSString *)kABPersonAddressZIPKey, (NSString *)getValueForKey(dict, CFSTR("d:homeCity")), (NSString *)kABPersonAddressCityKey, (NSString *)getValueForKey(dict, CFSTR("d:homeState")), (NSString *)kABPersonAddressCityKey, (NSString *)getValueForKey(dict, CFSTR("d:homeCountry")), (NSString *)kABPersonAddressCountryKey, nil]; multiValueAddDictionaryValueAndLabel(addresses, (CFDictionaryRef)values, kABHomeLabel); ABRecordSetValue(person, kABPersonAddressProperty, addresses, NULL); CFRelease(addresses); ```
48,527,248
Question: --------- Is it possible to use WampServer3 (Apache, PHP, MySQL) to work with my Application Load Balancer over port 443? If so how? Issue: ------ Currently my application load balancer is connected to my instance and I have 2 listeners, Port 80 and Port 443. The listener on port 443 has an SSL Certificate attached to it that was generated by the AWS Certificate Manager. * My target group that is listening on port 80 is healthy and working properly. * My target group that is listening on port 443 is unhealthy and timing out. I know that port 443 is failing due to the Apache settings but I am not sure how I am supposed to enable the port in Apache. Based on everything that I have read, Apache requires you to have the physical file and key for the SSL in order for it to allow requests through port 443. I have tried to follow the instructions without those two things but WampServer3 will not restart without them. I feel like there has to be a way to get this to work but I have hit a wall. Perhaps I am not searching for the right thing, or I am missing an additional module that needs to be used. **TLDR:** Because the SSL that is generated by the AWS Certificate Manager cannot be physically downloaded, how can I get it to work with Apache on Windows 10 without having the file or key? **EDIT** So to my understanding I need to not only put the Rewrite code below in my `<VirtualHost>` ``` RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} =http RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent] ``` I also need to put `X-Forwarded-Proto: https` at the top of my `healthcheck.php` page before the `<html>` tag? I'll keep reading about this since I don't fully understand it.
2018/01/30
['https://Stackoverflow.com/questions/48527248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2675902/']
You have a listener on both 80 and 443 on your load balancer. The listener on 443 has the ACM cert. You also say that you have one target group for each listener - one on 80 which is health, and one on 443 which is not. The simple answer is to use one target group for both listeners. That way the connection to your end user is secure if they come in on 443, and only internal traffic between your ALB and instances uses HTTP. That way the health check will succeed, and your users will be able to use the site. But that's not what most people really want - they want end-to-end security, and more than likely they want to redirect from port 80 to 443. To force everyone to use 443, you will need a redirect rule in your apache config that checks to see if the incoming connection was secure. Because SSL is terminated on the ALB, you will need to check one of the X-Forwarded header values (See [this](https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html)) and redirect if say X-Forward-Port is 80. To ensure that end-to-end traffic is secure, you can configure you listeners to listen on port 443 instead of port 80. You can use self-signed certificates for this, and I believe that some versions of Linux come with default certs. The ALB will not do certificate validation. Edit: In a comment, there was a question on where to put the rewrite code: ``` RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} =http RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent] ``` If you have a single entry then this should work. If you have separate entries for port 80 and 443 AND you're using self-signed certs with different listeners, then you would need to put it in the port 80 virtual host entry.
I ended up not using the AWS Certificate Manager at all due to the hurdles that one has to overcome in order to get it to work. Instead I found a great resource that provides SSL Certificates for free - [LetsEncrypt](https://letsencrypt.org/). I would highly recommend this solution for everyone due to the ease of use. Plus they seem to be backed by many reputable companies.
12,491,240
I'm developing an android app with phonegap and I have a table with some data. When clicking on a row it should go back to index and fire a function, so I turn each row into an html `a href` with a `onclick` property. The problem is that the `href` it's working and it goes back to the index but ti doesn't fire the function. Here's the code that generates the table and the code of the function: ``` function doLocalStorage(xyz) { alert(xyz); } <table id="hor-minimalist-b"><thead></thead><tbody></tbody></table> <script language="javascript"> var table = document.getElementById('hor-minimalist-b'); // get the table element var tableBody = table.childNodes[1]; // get the table body var tableHead = table.childNodes[0]; // get the table head var thead = document.createElement('th'); var row2 = document.createElement('tr'); // create a new row var headText = document.createTextNode('Dados'); thead.scope = "col"; thead.appendChild(headText); row2.appendChild(thead); tableHead.appendChild(row2); for (var i=0; i<len; i++) { var row = document.createElement('tr'); // create a new row var cell = document.createElement('td'); // create a new cell var a = document.createElement('a'); var cellText = document.createTextNode(localStorage.getItem('key' + i)); var xyz = localStorage.key(i); a.href = "index.html"; a.onclick = "doLocalStorage(xyz);"; a.appendChild(cellText); cell.appendChild(a); // append input to the new cell row.appendChild(cell); // append the new cell to the new row tableBody.appendChild(row); // append the row to table body } </script> ``` Thanks :)
2012/09/19
['https://Stackoverflow.com/questions/12491240', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/907577/']
One you should really be using jQuery as it will take care of browser inconsistencies for you. Two, you'll likely need to use onlick like this. ``` a.onclick = function() { doLocalStorage(xyz); }; ```
Try to delete a href attribute and handle a click event with redirection `window.location.href = ('url')`. It should help.
2,926,220
Can a python script on my server access the webcam and audio input of a user as easily and as well as a Flash plugin can?
2010/05/28
['https://Stackoverflow.com/questions/2926220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/301860/']
No: the "plugin" you mention runs in the user's **browser**, your server-side script (Python or otherwise) runs on the **server**, a completely different proposition. This relates to your other recent question about a server-side script accessing information on your desktop: your client machine tends to be very protected against possibly malicious server-side apps (never enough, but everybody keeps trying to make it more and more protected these days).
Server-side web scripts have no access to the client other than through requests. You need to use JavaScript, Java, or Flash to access devices that the browser (and consequently user) allows them to.
2,926,220
Can a python script on my server access the webcam and audio input of a user as easily and as well as a Flash plugin can?
2010/05/28
['https://Stackoverflow.com/questions/2926220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/301860/']
No: the "plugin" you mention runs in the user's **browser**, your server-side script (Python or otherwise) runs on the **server**, a completely different proposition. This relates to your other recent question about a server-side script accessing information on your desktop: your client machine tends to be very protected against possibly malicious server-side apps (never enough, but everybody keeps trying to make it more and more protected these days).
Not as easy, no. But there are extensions you can use. E.g. A Win32 Python Extension for Accessing Video Devices (e.g. a USB WebCam, a TV-Card, ...) <http://videocapture.sourceforge.net/> Tutorial: <http://technobabbler.com/?p=22>
74,487,746
I deployed kubernetes cluster in `minikube` which has one master node and one worker node. When I tried to see the kube-proxy with: ``` kubectl get pods -n kube-system ``` two kube-proxies apear ``` kube-proxy-6jxgq kube-proxy-sq58d ``` According to the refrence architecture [https://kubernetes.io/docs/concepts/overview/components/](https://www.stackoverflow.com/) kube-proxy is the component of worker node. I expect to see one kube-proxy not two. what is the reason?
2022/11/18
['https://Stackoverflow.com/questions/74487746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19664050/']
Update ------ So after seeing your photos, I believe this is what you are trying to achieve: ```css .collection-item-28 { margin-bottom: 14px; /* Adjust this to your liking */ } .text-block-19{ position: absolute; top: 100%; transform: translateY(-100%); width: 100%; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } ``` Preview: [![enter image description here](https://i.stack.imgur.com/X3fM1.png)](https://i.stack.imgur.com/X3fM1.png) Smaller: [![enter image description here](https://i.stack.imgur.com/ebz4v.png)](https://i.stack.imgur.com/ebz4v.png)
From what I have understood the thing that you need. I have created a small sandbox implementation for that. You can check just the index.css file and App.js to look for structure. <https://codesandbox.io/s/vigilant-roman-4dv820> Let me know if it helps or you need any clarification or a thing apart from that. Cheers :)
7,204,024
I have done it before, but it's not working this time. All I'm trying to do is delete an entry from a table, and as you can see, it is supposed to output "ok" if it succeeds, (and I *have* manually checked the querystring data and everything matches what its trying to delete, even all the conditions are also met), but it isn't deleting. ``` @{ var message = ""; try { var d = Database.Open("tgyytuyt"); var query = "DELETE FROM Cart WHERE OrderId = '" + Request.QueryString["Value"] + "' AND UserId = '" + Request.QueryString["SubValue"] + "' AND PartNumber = '" + Request.QueryString["Final"] + "'"; d.Execute(query); message = "ok"; //Response.Redirect("~/OSM/Default.cshtml"); } catch(Exception ex) { message = ex.Message; } } <p>@message</p> ``` Is there something that I'm doing wrong that could be causing the item to not be deleted?
2011/08/26
['https://Stackoverflow.com/questions/7204024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/908110/']
It looks fine. It will fail when you've *actually* a `rendered` attribute set on the link or one of its parents and the bean is in request scope. This should work if the bean is put in the view scope and you always return `null` or `void` from link actions which should return to the same view. This way the conditions for the `rendered` attribute will be preserved. JSF namely rechecks this condition during apply request values phase of the form submit as part of safeguard against hacked/tampered requests. ### See also: * [commandButton/commandLink/ajax action/listener method not invoked or input value not updated](https://stackoverflow.com/questions/2118656/hcommandlink-is-not-being-invoked) (lists all possible causes)
i think first command link should be inside h:form
12,523,146
> > **Possible Duplicate:** > > [How to remove all CSS classes using jQuery?](https://stackoverflow.com/questions/1424981/how-to-remove-all-css-classes-using-jquery) > > > I have the following: ``` <div id="abc"> </div> ``` Inside that div there can be one only of the following: ``` <p class="message"> <p class="message error"></p> <p class="message warning"></p> <p class="message success"></p> <p class="message loading"></p> ``` Is there a way that I can find and remove all classes from the `<p>` element?
2012/09/21
['https://Stackoverflow.com/questions/12523146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
> > If no class names are specified in the parameter, all classes will be removed. > > > [Source](http://api.jquery.com/removeClass/). Use `removeClass()` with no arguments.
You can use `removeAttr` method: ``` $('#abc p').removeAttr('class') ```
12,523,146
> > **Possible Duplicate:** > > [How to remove all CSS classes using jQuery?](https://stackoverflow.com/questions/1424981/how-to-remove-all-css-classes-using-jquery) > > > I have the following: ``` <div id="abc"> </div> ``` Inside that div there can be one only of the following: ``` <p class="message"> <p class="message error"></p> <p class="message warning"></p> <p class="message success"></p> <p class="message loading"></p> ``` Is there a way that I can find and remove all classes from the `<p>` element?
2012/09/21
['https://Stackoverflow.com/questions/12523146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
You can do this: ``` $("#abc p").attr("class", ""); ``` or ``` $("#abc p").removeClass(); ```
You can use `removeAttr` method: ``` $('#abc p').removeAttr('class') ```