Search is not available for this dataset
qid
int64
1
74.7M
question
stringlengths
1
70k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
0
60.5k
19,024,137
Iam very new in jquery. here is jquery from [smart wizard](https://github.com/mstratman/jQuery-Smart-Wizard/blob/master/README.md): ``` / Default Properties and Events $.fn.smartWizard.defaults = { selected: 0, // Selected Step, 0 = first step keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled) enableAllSteps: false, transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft contentURL:null, // content url, Enables Ajax content loading contentCache:true, // cache step contents, if false content is fetched always from ajax url cycleSteps: false, // cycle step navigation enableFinishButton: false, // make finish button enabled always hideButtonsOnDisabled: false, // when the previous/next/finish buttons are disabled, hide them instead? errorSteps:[], // Array Steps with errors labelNext:'Next', labelPrevious:'Previous', labelFinish:'Finish', noForwardJumping: false, ajaxType: "POST", onLeaveStep: null, // triggers when leaving a step onShowStep: null, // triggers when showing a step onFinish: null, // triggers when Finish button is clicked includeFinishButton : true // Add the finish button }; })(jQuery); <script type="text/javascript"> $(document).ready(function() { // Smart Wizard $('#wizard').smartWizard({ onLeaveStep: leaveAStepCallback, onFinish: onFinishCallback }); function leaveAStepCallback(obj, context) { debugger; alert("Leaving step " + context.fromStep + " to go to step " + context.toStep); return validateSteps(context.fromStep); // return false to stay on step and true to continue navigation } function onFinishCallback(objs, context) { debugger; if (validateAllSteps()) { $('form').submit(); } } // Your Step validation logic function validateSteps(stepnumber) { debugger; var isStepValid = true; // validate step 1 if (stepnumber == 1) { // Your step validation logic // set isStepValid = false if has errors } // ... } function validateAllSteps() { debugger; var isStepValid = true; // all step validation logic return isStepValid; } }); </script> ``` i need some functione for onFinish, where i can send request with many parameters. how to do it?
2013/09/26
[ "https://Stackoverflow.com/questions/19024137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291120/" ]
add your custom function like below. ``` onFinish: function () { alert("Finish Clicked!") }, // triggers when Finish button is clicked ```
// Changing Label of finish button $('#wizard').smartWizard.defaults.labelFinish = "confirm & Buy";
19,024,137
Iam very new in jquery. here is jquery from [smart wizard](https://github.com/mstratman/jQuery-Smart-Wizard/blob/master/README.md): ``` / Default Properties and Events $.fn.smartWizard.defaults = { selected: 0, // Selected Step, 0 = first step keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled) enableAllSteps: false, transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft contentURL:null, // content url, Enables Ajax content loading contentCache:true, // cache step contents, if false content is fetched always from ajax url cycleSteps: false, // cycle step navigation enableFinishButton: false, // make finish button enabled always hideButtonsOnDisabled: false, // when the previous/next/finish buttons are disabled, hide them instead? errorSteps:[], // Array Steps with errors labelNext:'Next', labelPrevious:'Previous', labelFinish:'Finish', noForwardJumping: false, ajaxType: "POST", onLeaveStep: null, // triggers when leaving a step onShowStep: null, // triggers when showing a step onFinish: null, // triggers when Finish button is clicked includeFinishButton : true // Add the finish button }; })(jQuery); <script type="text/javascript"> $(document).ready(function() { // Smart Wizard $('#wizard').smartWizard({ onLeaveStep: leaveAStepCallback, onFinish: onFinishCallback }); function leaveAStepCallback(obj, context) { debugger; alert("Leaving step " + context.fromStep + " to go to step " + context.toStep); return validateSteps(context.fromStep); // return false to stay on step and true to continue navigation } function onFinishCallback(objs, context) { debugger; if (validateAllSteps()) { $('form').submit(); } } // Your Step validation logic function validateSteps(stepnumber) { debugger; var isStepValid = true; // validate step 1 if (stepnumber == 1) { // Your step validation logic // set isStepValid = false if has errors } // ... } function validateAllSteps() { debugger; var isStepValid = true; // all step validation logic return isStepValid; } }); </script> ``` i need some functione for onFinish, where i can send request with many parameters. how to do it?
2013/09/26
[ "https://Stackoverflow.com/questions/19024137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291120/" ]
You can listen for an onclick event on the toolbar extra buttons. ``` // Toolbar extra buttons var btnFinish = $("<button></button>") .text("Finish") .addClass("btn btn-primary") .on("click", function () { alert("Finish Clicked"); }); var btnCancel = $("<button></button>") .text("Cancel") .addClass("btn btn-secondary") .on("click", function () { $("#wizard").smartWizard("reset"); }); // Initiate wizard $("#wizard").smartWizard({ selected: 0, theme: "default", autoAdjustHeight: true, transition: { animation: "slide-horizontal", }, toolbarSettings: { toolbarPosition: "bottom", toolbarExtraButtons: [btnFinish, btnCancel], }, }); ```
// Changing Label of finish button $('#wizard').smartWizard.defaults.labelFinish = "confirm & Buy";
19,024,137
Iam very new in jquery. here is jquery from [smart wizard](https://github.com/mstratman/jQuery-Smart-Wizard/blob/master/README.md): ``` / Default Properties and Events $.fn.smartWizard.defaults = { selected: 0, // Selected Step, 0 = first step keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled) enableAllSteps: false, transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft contentURL:null, // content url, Enables Ajax content loading contentCache:true, // cache step contents, if false content is fetched always from ajax url cycleSteps: false, // cycle step navigation enableFinishButton: false, // make finish button enabled always hideButtonsOnDisabled: false, // when the previous/next/finish buttons are disabled, hide them instead? errorSteps:[], // Array Steps with errors labelNext:'Next', labelPrevious:'Previous', labelFinish:'Finish', noForwardJumping: false, ajaxType: "POST", onLeaveStep: null, // triggers when leaving a step onShowStep: null, // triggers when showing a step onFinish: null, // triggers when Finish button is clicked includeFinishButton : true // Add the finish button }; })(jQuery); <script type="text/javascript"> $(document).ready(function() { // Smart Wizard $('#wizard').smartWizard({ onLeaveStep: leaveAStepCallback, onFinish: onFinishCallback }); function leaveAStepCallback(obj, context) { debugger; alert("Leaving step " + context.fromStep + " to go to step " + context.toStep); return validateSteps(context.fromStep); // return false to stay on step and true to continue navigation } function onFinishCallback(objs, context) { debugger; if (validateAllSteps()) { $('form').submit(); } } // Your Step validation logic function validateSteps(stepnumber) { debugger; var isStepValid = true; // validate step 1 if (stepnumber == 1) { // Your step validation logic // set isStepValid = false if has errors } // ... } function validateAllSteps() { debugger; var isStepValid = true; // all step validation logic return isStepValid; } }); </script> ``` i need some functione for onFinish, where i can send request with many parameters. how to do it?
2013/09/26
[ "https://Stackoverflow.com/questions/19024137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291120/" ]
add your custom function like below. ``` onFinish: function () { alert("Finish Clicked!") }, // triggers when Finish button is clicked ```
Use the following code, your form will be submitted. I hope this will help you. ``` var Myform=$('#saveForm'); $(document).on('click','.btn-finish',function(e){ $('#saveForm')[0].submit(); }); ```
19,024,137
Iam very new in jquery. here is jquery from [smart wizard](https://github.com/mstratman/jQuery-Smart-Wizard/blob/master/README.md): ``` / Default Properties and Events $.fn.smartWizard.defaults = { selected: 0, // Selected Step, 0 = first step keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled) enableAllSteps: false, transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft contentURL:null, // content url, Enables Ajax content loading contentCache:true, // cache step contents, if false content is fetched always from ajax url cycleSteps: false, // cycle step navigation enableFinishButton: false, // make finish button enabled always hideButtonsOnDisabled: false, // when the previous/next/finish buttons are disabled, hide them instead? errorSteps:[], // Array Steps with errors labelNext:'Next', labelPrevious:'Previous', labelFinish:'Finish', noForwardJumping: false, ajaxType: "POST", onLeaveStep: null, // triggers when leaving a step onShowStep: null, // triggers when showing a step onFinish: null, // triggers when Finish button is clicked includeFinishButton : true // Add the finish button }; })(jQuery); <script type="text/javascript"> $(document).ready(function() { // Smart Wizard $('#wizard').smartWizard({ onLeaveStep: leaveAStepCallback, onFinish: onFinishCallback }); function leaveAStepCallback(obj, context) { debugger; alert("Leaving step " + context.fromStep + " to go to step " + context.toStep); return validateSteps(context.fromStep); // return false to stay on step and true to continue navigation } function onFinishCallback(objs, context) { debugger; if (validateAllSteps()) { $('form').submit(); } } // Your Step validation logic function validateSteps(stepnumber) { debugger; var isStepValid = true; // validate step 1 if (stepnumber == 1) { // Your step validation logic // set isStepValid = false if has errors } // ... } function validateAllSteps() { debugger; var isStepValid = true; // all step validation logic return isStepValid; } }); </script> ``` i need some functione for onFinish, where i can send request with many parameters. how to do it?
2013/09/26
[ "https://Stackoverflow.com/questions/19024137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291120/" ]
You can listen for an onclick event on the toolbar extra buttons. ``` // Toolbar extra buttons var btnFinish = $("<button></button>") .text("Finish") .addClass("btn btn-primary") .on("click", function () { alert("Finish Clicked"); }); var btnCancel = $("<button></button>") .text("Cancel") .addClass("btn btn-secondary") .on("click", function () { $("#wizard").smartWizard("reset"); }); // Initiate wizard $("#wizard").smartWizard({ selected: 0, theme: "default", autoAdjustHeight: true, transition: { animation: "slide-horizontal", }, toolbarSettings: { toolbarPosition: "bottom", toolbarExtraButtons: [btnFinish, btnCancel], }, }); ```
Use the following code, your form will be submitted. I hope this will help you. ``` var Myform=$('#saveForm'); $(document).on('click','.btn-finish',function(e){ $('#saveForm')[0].submit(); }); ```
91,568
I am trying to understand the sentence "Tom loves Jane with his whole being" without involving the word "with". Does the sentence "Tom loves Jane with his whole being" have the exact same meaning as "Tom's whole being loves Jane"?
2016/06/01
[ "https://ell.stackexchange.com/questions/91568", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/34511/" ]
**with his whole being** is a metaphor meaning completely and without reservations. It is similar in meaning to [wholeheartedly](http://dictionary.cambridge.org/dictionary/english/wholehearted?q=wholeheartedly), which means with (someone's) whole heart. The heart is a metaphor for the emotions, so wholeheartedly means with all of one's emotions. [being](http://www.collinsdictionary.com/dictionary/english/being) is what defines a person- their essence, personality, spirit, soul: the part that goes away when somebody dies. **with his whole being** means with every part of his personality. The following sentence might be a suitable way of explaining your original sentence: > > Everything that Tom thinks, says or does reflects his love for Jane. > > >
The phrase "Tom loves Jane with his whole being" is slightly idiomatic - a bit like, for example, "Tom loves Jane with his heart". You wouldn't really say, "Tom's heart loves Jane". "...with his whole being" is suggesting complete or unfaltering love.
66,596,421
I have a parent entity called Player and two child entities called bat and ball. PK of Player entity is 'playerId', composite pk of ball is 'playerId(FK)' and 'ballColor', & composite pk of bat is 'playerId(FK)' and 'batColor' Note : player-to-bat is OneToOne and player-to-ball is OneToMany (unidirectional) ``` @Entity @Table(name = "player") public class Player implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "player_id") private Long playerId; @JsonManagedReference @OneToMany(mappedBy = "player", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @Fetch(value=FetchMode.SELECT) private List<Ball> balls; @OneToOne(mappedBy = "player", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JsonManagedReference private Bat bat; // getters and setters } @Entity @Table(name = "bat") public class Bat implements Serializable { private static final long serialVersionUID = -114046508592L; @EmbeddedId private BatEmbeddedId batEmbeddedId = new BatEmbeddedId(); @MapsId("playerId") @OneToOne @JoinColumn(name = "bat_id", insertable = false, updatable = false) @JsonBackReference private Player player; // getters and setters for player field } @Entity @Table(name = "ball") public class Ball implements Serializable { private static final long serialVersionUID = -1108592L; @EmbeddedId private BallEmbeddedId ballEmbeddedId = new BallEmbeddedId(); @MapsId("playerId") @ManyToOne @JoinColumn(name = "ball_id", insertable = false, updatable = false) @JsonBackReference private Player player; // getters and setters for player field } @Embeddable public class BatEmbeddedId implements Serializable{ private static final long serialVersionUID = -91976886L; @Column(name = "player_id") private Long playerId; @Column(name = "bat_color") private String batColor; public BatEmbeddedId() {} public BatEmbeddedId(Long playerId, String batColor) { super(); this.playerId= playerId; this.batColor= batColor; } // getters and setters for all fields } @Embeddable public class BallEmbeddedId implements Serializable{ private static final long serialVersionUID = -91976889990L; @Column(name = "player_id") private Long playerId; @Column(name = "ball_color") private String ballColor; public BatEmbeddedId() {} public BatEmbeddedId(Long playerId, String ballColor) { super(); this.playerId= playerId; this.ballColor= ballColor; } // getters and setters for all fields } public interface PlayerRepository extends JpaRepository<Player, Long>, JpaSpecificationExecutor<Player> { Player findByPlayerId(Long playerId); } @Service public class myService{ @Autowired PlayerRepository playerRepository; // Save logic for player Player player = new Player(); BatEmbeddedId batEmId = new BatEmbeddedId(); //note i can't set the playerId here coz its not yet generated batEmId.setBatColor("white"); Bat bat = new Bat(); bat.setBatEmbeddedId(batEmId); bat.setPlayer(player); player.setBat(bat); // added bat to player object List<Ball> balls = new ArrayList<>(); BallEmbeddedId ballEmId1 = new BallEmbeddedId(); BallEmbeddedId ballEmId2 = new BallEmbeddedId(); ballEmId1.setBallColor("white"); ballEmId2.setBallColor("red"); Ball b1 = new Ball(); Ball b2 = new Ball(); b1.setBallEmbeddedId(ballEmId1); b2.setBallEmbeddedId(ballEmId2); balls.add(b1); balls.add(b2); //adding balls to player object player.setBalls(balls); //finally calling a save playerRepository.save(player); } ``` After running the above code am getting the following error : `org.springframework.dao.DataIntegrityViolationException: A different object with the same identifier value was already associated with the session` Am I doing something wrong in the save logic of these related entities ? Many thanks in advance!!!
2021/03/12
[ "https://Stackoverflow.com/questions/66596421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11370275/" ]
Try to correct your mapping like below: ```java @Entity @Table(name = "bat") public class Bat implements Serializable { // ... @EmbeddedId private BatEmbeddedId batEmbeddedId = new BatEmbeddedId(); @MapsId("playerId") @OneToOne @JoinColumn(name = "player_id") @JsonBackReference private Player player; // getters and setters for player field } @Embeddable public class BatEmbeddedId implements Serializable{ // ... // @Column annotation will be ignored as you use @MapsId("playerId") // The column name will be taken from the @JoinColumn(name = "player_id") annotation // @Column(name = "player_id") private Long playerId; @Column(name = "bat_color") private String batColor; public BatEmbeddedId() {} public BatEmbeddedId(Long playerId, String batColor) { // super() is redundant // super(); this.playerId= playerId; this.batColor= batColor; } // getters and setters for all fields // The primary key class must define equals and hashCode methods, // consistent with equality for the underlying database types to which the primary key is mapped. // see https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#identifiers-composite @Override public boolean equals(Object o) { if ( this == o ) return true; if ( o == null || getClass() != o.getClass() ) return false; BatEmbeddedId pk = (BatEmbeddedId) o; return Objects.equals( playerId, pk.playerId ) && Objects.equals( batColor, pk.batColor ); } @Override public int hashCode() { return Objects.hash( playerId, batColor ); } } @Entity @Table(name = "ball") public class Ball implements Serializable { // ... @EmbeddedId private BallEmbeddedId ballEmbeddedId = new BallEmbeddedId(); @MapsId("playerId") @ManyToOne @JoinColumn(name = "player_id") @JsonBackReference private Player player; // getters and setters for player field } @Embeddable public class BallEmbeddedId implements Serializable{ // ... // @Column(name = "player_id") private Long playerId; @Column(name = "ball_color") private String ballColor; public BatEmbeddedId() {} public BatEmbeddedId(Long playerId, String ballColor) { this.playerId= playerId; this.ballColor= ballColor; } // getters and setters for all fields // equals and hashCode } ```
Did you try to remove the `insertable = false, updatable = false` from the player associations already? `@MapsId` should be able to handle without that. Also, you should mark the columns in the embeddable types as `nullable = false`. If the problem still persists, are you sure that you are not doing anything else within the same transaction? Are you using the latest Hibernate version 5.4.29? If so, and you still have the problem, please create an issue in the issue tracker(<https://hibernate.atlassian.net>) with a test case(<https://github.com/hibernate/hibernate-test-case-templates/blob/master/orm/hibernate-orm-5/src/test/java/org/hibernate/bugs/JPAUnitTestCase.java>) that reproduces the issue.
66,502,452
Recently i worked on one project, where Angular is used as the front end framework and springboot is backend. Now i moved to .NET projects .I understood that Blazor supports two hosting models, client side hosting model and server side hosting model. Now i am going to start .NET project with blazor. I have created REST API for the project.Now i have to use Blazor in that project.Here my doubt comes. 1)Blazor web assembly is for front end (or) back end ? 2)Blazor Server app is for front end (or) back end?
2021/03/06
[ "https://Stackoverflow.com/questions/66502452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14943292/" ]
Just a few words of explanation. In traditional web design, you have a server which assembles code using stuff the user's browser must not have access to: database searches, proprietary logic, files and so on. That's usually done with C#, PHP, etc. That's the back end. Front end is the stuff that can and IS done in the user's browser: changing text, collecting input, handling mouse events and so on. That's usually done with JavaScript. This is because JavaScript is safer to run on a browser-- it doesn't have access to your drives and so on. How web pages work is that you collect form information-- type in text, set the state of checkboxes, etc., then package ALL that information with a form submission to the server. The server then processes all that information, REBUILDS the entire page, and sends a whole, complete page back to the client's browser. It's a very big transaction. Blazor doesn't do that. Everything on a page can be individually updated at any time without sending large blocks of information back and forth. Every event on a page (button click and so on) can be sent as an individual event call to the server, and you can return either no changes (for example if you're just saving some info to a database), or by changing any or all the content on the page. In other words, there's not really a very meaningful distinction between front end anymore: the visible page is an expression of the current state of code, rather than a new object that gets rebuilt every time you click a button. And just to clarify, it's a very robust connection-- you can check the contents on a textbox in real time as you type each character, or you can send updates to the user while you grind through 20 file uploads: "Processing image 1/20" and so on.
WASM runs in the browser on the client. If your codes run only on browser (not dependents on server) you can use WASM. However you can suppose it as a front end app and use WebAPI to connect to the server. Blazor Server is front end and back end (both).
66,502,452
Recently i worked on one project, where Angular is used as the front end framework and springboot is backend. Now i moved to .NET projects .I understood that Blazor supports two hosting models, client side hosting model and server side hosting model. Now i am going to start .NET project with blazor. I have created REST API for the project.Now i have to use Blazor in that project.Here my doubt comes. 1)Blazor web assembly is for front end (or) back end ? 2)Blazor Server app is for front end (or) back end?
2021/03/06
[ "https://Stackoverflow.com/questions/66502452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14943292/" ]
Just a few words of explanation. In traditional web design, you have a server which assembles code using stuff the user's browser must not have access to: database searches, proprietary logic, files and so on. That's usually done with C#, PHP, etc. That's the back end. Front end is the stuff that can and IS done in the user's browser: changing text, collecting input, handling mouse events and so on. That's usually done with JavaScript. This is because JavaScript is safer to run on a browser-- it doesn't have access to your drives and so on. How web pages work is that you collect form information-- type in text, set the state of checkboxes, etc., then package ALL that information with a form submission to the server. The server then processes all that information, REBUILDS the entire page, and sends a whole, complete page back to the client's browser. It's a very big transaction. Blazor doesn't do that. Everything on a page can be individually updated at any time without sending large blocks of information back and forth. Every event on a page (button click and so on) can be sent as an individual event call to the server, and you can return either no changes (for example if you're just saving some info to a database), or by changing any or all the content on the page. In other words, there's not really a very meaningful distinction between front end anymore: the visible page is an expression of the current state of code, rather than a new object that gets rebuilt every time you click a button. And just to clarify, it's a very robust connection-- you can check the contents on a textbox in real time as you type each character, or you can send updates to the user while you grind through 20 file uploads: "Processing image 1/20" and so on.
in nutshell, Blazor web assembly WASM: it is a front end where you can use the C# instead of Javascript ( you can still use javascript and call js function), for that to call any function/ Web API you have to send an HTTP request to get the data from your endpoint. Blazor Server is an app that uses server resources, and all the interactions between the user and the server happen based on SingalR for real-time connection. so that means any kind of request will process on the server-side and respond to the user (Client Browser), so this means this type of application will use the traditional way (client-server app), all the layers of your apps are available in server-side, and your front end will render dynamically based on the requested contents.
65,608,535
I have an application that works as expected and I can insert/update the rows through application. But when I connect to my oracle database through SQL Developer and tried to run the UPDATE query, I get message that 1 row is updated. while the row is not updated. Also the user I used to connect oracle database is same for both Application and SQL Developer with having insert and update privileges. I feel a transparency Layer is implemented in oracle database that blocks the direct query execution. Can anyone knows how this feature is implemented or which oracle product is configured?
2021/01/07
[ "https://Stackoverflow.com/questions/65608535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8403256/" ]
In your template use the pre tag and json pipe, ```js <pre> {{ InstanceId | json }} </pre> ```
this.instanceId = JSON.parse(data); should do the trick
65,608,535
I have an application that works as expected and I can insert/update the rows through application. But when I connect to my oracle database through SQL Developer and tried to run the UPDATE query, I get message that 1 row is updated. while the row is not updated. Also the user I used to connect oracle database is same for both Application and SQL Developer with having insert and update privileges. I feel a transparency Layer is implemented in oracle database that blocks the direct query execution. Can anyone knows how this feature is implemented or which oracle product is configured?
2021/01/07
[ "https://Stackoverflow.com/questions/65608535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8403256/" ]
**1. Concatenate string and object in controller** You need to use comma instead of plus to log the object in the controller. ```js console.log("InstanceId is: ", InstanceId) ``` instead of ```js console.log("InstanceId is: " + InstanceId) ``` **2. Render object property in the template** The hyphen in the property must obfuscate for the template rendered to access it. You could use bracket notation instead of dot notation here. ```html <td>{{ Instance Id["case-id"]}}</td> ``` instead of ```html <td>{{ Instance Id.case-id}}</td> ```
this.instanceId = JSON.parse(data); should do the trick
35,440,204
``` public class saeidactivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.saeid); Button btn=(Button) findViewById(R.id.saeidbtn1); TextView str=(TextView) findViewById(R.id.saeidtxtv1); btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { str.setTextColor(0xFF00FF00); } }); } } ```
2016/02/16
[ "https://Stackoverflow.com/questions/35440204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5928886/" ]
You need to learn about OOP (Object Oriented Programming) in more detail. Perhaps search for Dependency Injection, or Exceptions. Also, you need to create a PHP script that accepts your ajax requests and calls the necessary functions or methods which should all be separated into their own files and in classes. This will separate the different data layers from each other (i.e. presentation, business logic, data). You should also invest some time in learning what MVC(Model View Controller) is about. This will help you understand the importance of the separation. For now, I will show you a quick solution to your problem. Lets imagine your file structure is all in the same directory as such: ``` |--- ajax_requests.php |--- Database.php |--- Functions.php |--- index.php ``` **index.php** is where your HTML /jQuery is located: ``` <!DOCTYPE html> <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <title>Admin check</title> <meta charset="UTF-8"> </head> <body> <script type='text/javascript'> $.ajax({ type: "post", url: "ajax_requests.php", data: {request: "get_grupy_json"}, success: function(result){ console.log(result); } }); </script> ``` Notice how we are using jQuery to make our Ajax request. We are making a `post` request to the file `ajax_requests.php` sending the `get_grupy_json` as our `request` parameter. No SQL queries should be present on your front-end views. **ajax\_requests.php** receives the request, gets the Database object and sends it to the Functions object, then it checks that the request exists as a method of the Functions class, if it does, it runs the method and turns the result as json (remember to add error checking on your own): ``` <?php if (!empty($_POST)) { $method = $_POST['request']; include 'Database.php'; include "Functions.php"; $db = new Database(); $functions = new Functions($db); if (method_exists($functions, $method)) { $data = $functions->$method(); header('Content-Type: application/json'); echo json_encode($data); } } ``` **Functions.php** ``` class Functions { private $db; public function __construct(Database $db) { $this->db = $db; } public function get_grupy_json() { $query = "SELECT * FROM `grupy`"; $result = $this->db->dataQuery($query); return $result->fetchAll(); } } ``` **Database.php** ``` class Database { private $conn = null; public function __construct() { try { $username = "root"; $password = "root"; $servername = "localhost"; $dbname = "test"; $this->conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { trigger_error("Error: " . $e->getMessage()); } } public function dataQuery($query, $params = array()) { try { $stmt = $this->conn->prepare($query); $stmt->execute($params); return $stmt; } catch (PDOException $e) { trigger_error("Error: " . $e->getMessage()); }; } } ``` This is a rough mockup of what i would do. I hope you get the idea of how it is all separated so that you can easily add features to your application as it grows.
AJAX does not work like this. Basically, product of PHP is a HTML page (with JS), that is rendered upon request in the browser. When user performs an action, that should result in displaying data retrieved by AJAX, the browser makes another request, possibly to different PHP script. Result of this request is not displayed to the user, as while performing the first request, rather it is passed to a function in JS of the currently displayed page (that is what makes it AJAX). This function can then process the data in any way it wants. Have a look at this: <http://www.w3schools.com/jquery/jquery_ajax_intro.asp>.
894,646
I do not understand improper integrals. Is $$ \int\_1^e \frac{ \mathrm{dx}}{x(\ln x)^{1/2}}$$ an improper integral? Is $$ \int\_0^2 \frac{\mathrm{dx}}{x^2+6x+8}$$ an improper integral? For both I need to evaluate the integral or show that it's divergent. I have no idea what to do and need serious help for math homework since we never covered this in our Calc 1 class.
2014/08/12
[ "https://math.stackexchange.com/questions/894646", "https://math.stackexchange.com", "https://math.stackexchange.com/users/169232/" ]
Improper integrals occur in primarily two ways: an bound that goes off to infinity or a bound where the function goes off to infinity (infinitely wide vs. infinitely tall). Clearly anything of the form$$\int\_0^\infty f(x)\mathrm{d}x$$ is improper and we have to really consider what happens as we *approach* infinity. Which should scream **limit**! So we set it up as follows: $$\lim\_{b\to\infty}\int\_0^b f(x)\mathrm{d}x$$ and perform the integration as normal, and *then* take the limit. The other possibility is when the function in the integral does funky things on our bounds (such as going off to infinity or dividing by zero, etc.) One example is this simple integral: $$\int\_0^1 \frac{\mathrm{d}x}{x-1}$$ This could potentially have an infinity area (look at the [graph](http://www.wolframalpha.com/input/?i=1%2F%281-x%29%20from%200%20to%201)) because as we get close to $x=1$ we are getting close to dividing by $0$. So we pull the same trick and we look at the integral $$\int\_0^{0.9} \frac{\mathrm{d}x}{x-1}$$ and then $$\int\_0^{0.99} \frac{\mathrm{d}x}{x-1}$$ and it doesn't take long to realize you're taking a limit. $$\lim\_{b\to1}\int\_0^b \frac{\mathrm{d}x}{x-1}$$ where this time $b$ approaches a finite value. --- Now, to visit your examples: neither of them have an infinite bound and so our first type of improper integral can be ruled out. Now we see if we divide by $0$ or take the $\log$ of $0$ or other math no-no's. (As Andre corrected me) The first one has the $\ln{1}=0$ in a denominator which is the same as trying to divide by $0$ and therefore, we have an improper integral. And we would want to solve: $$\lim\_{b\to 1^+}\int\_b^e \frac{\mathrm{d}x}{x\left(\ln{x}\right)^{1/2}}$$ and solve the integral first (in terms of a new variable $b$) and *then* take the limit, as if it had nothing to do with an integral. In the current state, it seems that the second integral has no such "funk" and therefore is not improper. I hope this helps clear up what an improper integral is! --- EDIT: I do want to point out that if the bounds on the second integral were this: $$\int\_{-2}^0\frac{\mathrm{d}x}{x^2+6x+8}$$ then we *would* have an improper integral because if we look at $x=-2$ we end up with $1/0$ and that's a no-no. So we, instead, consider: $$\lim\_{b\to -2^+}\int\_b^0\frac{\mathrm{d}x}{x^2+6x+8}$$ and solve the integral first (in terms of a new variable $b$) and *then* take the limit, as if it had nothing to do with an integral.
There are two types of improper integrals: In one type, at least one limit of integration is infinite ($\infty$ or $-\infty$); in the other type, the integrand has an infinite limit somewhere on the interval of integration. Your first integral is improper since the integrand 'blows up' as $x$ approaches 1 from the right. Your second integral is proper since the denominator is always positive (and never 0) on the interval of integration. You should be able to do the first integral with a $u$-substitution. The second integral can be done with a partial fraction decomposition.
12,208,336
Is it possible to apply a fade out effect on the jQuery UI modal dialog box overlay? The issue is that the overlay div is destroyed when the modal dialog box is closed preventing any kind of animation. This is the code I have that would work if the overlay div was not destroyed on close. ``` $("#edit-dialog-box").dialog( { autoOpen: false, modal: true, width: "30em", show: "fade", hide: "fade", open: function() { $(".ui-widget-overlay").hide().fadeIn(); }, close: function() { $(".ui-widget-overlay").fadeOut(); } }); ```
2012/08/31
[ "https://Stackoverflow.com/questions/12208336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078268/" ]
Demo: <http://jsfiddle.net/276Ft/2/> ``` $('#dialog').dialog({ autoOpen: true, modal: true, width: '100px', height: '100px', show: 'fade', hide: 'fade', open: function () { $('.ui-widget-overlay', this).hide().fadeIn(); $('.ui-icon-closethick').bind('click.close', function () { $('.ui-widget-overlay').fadeOut(function () { $('.ui-icon-closethick').unbind('click.close'); $('.ui-icon-closethick').trigger('click'); }); return false; }); } }); ``` ​
I advise not to bind the fadeOut of the overlay to the “closethick” close event. This solution will work in all cases, for example if you use a “Cancel” button, or if the dialog closes itself after doing anything else due to other buttons: ``` $('#dialog').dialog({ autoOpen: true, modal: true, width: '100px', height: '100px', show: 'fade', hide: 'fade', open: function () { $('.ui-widget-overlay', this).hide().fadeIn(); }, beforeClose: function(event, ui){ // Wait for the overlay to be faded out to try to close it again if($('.ui-widget-overlay').is(":visible")){ $('.ui-widget-overlay').fadeOut(function(){ $('.ui-widget-overlay').hide(); $('.ui-icon-closethick').trigger('click'); }); return false; // Avoid closing } } }); ```
38,874,837
I have a query that looks like the following: ``` SELECT time_start, some_count FROM foo WHERE user_id = 1 AND DATE(time_start) = '2016-07-27' ORDER BY some_count DESC, time_start DESC LIMIT 1; ``` What this does is return me one row, where some\_count is the highest count for `user_id = 1`. It also gives me the time stamp which is the most current for that `some_count`, as `some_count` could be the same for multiple `time_start` values and I want the most current one. Now I'm trying to do is run a query that will figure this out for every single `user_id` that occurred at least once for a specific date, in this case `2016-07-27`. Ultimately it's going to probably require a GROUP BY as I'm looking for a group maximum per `user_id` What's the best way to write a query of that nature?
2016/08/10
[ "https://Stackoverflow.com/questions/38874837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175836/" ]
I am sharing two of my approaches. **Approach #1 (scalable):** Using `MySQL user_defined variables` ``` SELECT t.user_id, t.time_start, t.time_stop, t.some_count FROM ( SELECT user_id, time_start, time_stop, some_count, IF(@sameUser = user_id, @rn := @rn + 1, IF(@sameUser := user_id, @rn := 1, @rn := 1) ) AS row_number FROM foo CROSS JOIN ( SELECT @sameUser := - 1, @rn := 1 ) var WHERE DATE(time_start) = '2016-07-27' ORDER BY user_id, some_count DESC, time_stop DESC ) AS t WHERE t.row_number <= 1 ORDER BY t.user_id; ``` Scalable because if you want latest n rows for each user then you just need to change this line : `... WHERE t.row_number <= n...` I can add explanation later if the query provides expected result --- **Approach #2:(Not scalable)** Using `INNER JOIN and GROUP BY` ``` SELECT F.user_id, F.some_count, F.time_start, MAX(F.time_stop) AS max_time_stop FROM foo F INNER JOIN ( SELECT user_id, MAX(some_count) AS max_some_count FROM foo WHERE DATE(time_start) = '2016-07-27' GROUP BY user_id ) AS t ON F.user_id = t.user_id AND F.some_count = t.max_some_count WHERE DATE(time_start) = '2016-07-27' GROUP BY F.user_id ```
I believe, you don't need to do anything fancy for the query. Just sort the table by **user\_id** in ascending order and **some\_count** and **time\_start** in a descending order and select expected fields from the ordered table GROUP BY **user\_id**. Its simple. Try and let me know if works. ``` SELECT user_id, some_count, time_start FROM (SELECT * FROM foo ORDER BY user_id ASC, some_count DESC, time_start DESC)sorted_foo WHERE DATE( time_start ) = '2016-07-27' GROUP BY user_id ```
38,874,837
I have a query that looks like the following: ``` SELECT time_start, some_count FROM foo WHERE user_id = 1 AND DATE(time_start) = '2016-07-27' ORDER BY some_count DESC, time_start DESC LIMIT 1; ``` What this does is return me one row, where some\_count is the highest count for `user_id = 1`. It also gives me the time stamp which is the most current for that `some_count`, as `some_count` could be the same for multiple `time_start` values and I want the most current one. Now I'm trying to do is run a query that will figure this out for every single `user_id` that occurred at least once for a specific date, in this case `2016-07-27`. Ultimately it's going to probably require a GROUP BY as I'm looking for a group maximum per `user_id` What's the best way to write a query of that nature?
2016/08/10
[ "https://Stackoverflow.com/questions/38874837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175836/" ]
You can use `NOT EXISTS()` : ``` SELECT * FROM foo t WHERE (DATE(time_start) = '2016-07-27' OR DATE(time_stop) = '2016-07-27') AND NOT EXISTS(SELECT 1 FROM foo s WHERE t.user_id = s.user_id AND (s.some_count > t.some_count OR (s.some_count = t.some_count AND s.time_stop > t.time_stop))) ``` The `NOT EXISTS()` will select only records that another record with a larger count or a another record with the same count but a newer `time_stop` doesn't exists for them.
``` SELECT c1.user_id, c1.some_count, MAX(c1.time_start) AS time_start FROM foo AS c1 JOIN ( SELECT user_id, MAX(some_count) AS some_count FROM foo WHERE time_start >= '2016-07-27' AND time_start < '2016-07-27' + INTERVAL 1 DAY GROUP BY user_id ) AS c2 USING (user_id, some_count) GROUP BY c1.user_id, c1.some_count ``` And, add these for better performance: ``` INDEX(user_id, some_count, time_start) INDEX(time_start) ``` The test for the `time_start` range was changed so that the second index could be used. This was loosely derived from by blog on [*groupwise max*](http://mysql.rjweb.org/doc.php/groupwise_max) .
38,874,837
I have a query that looks like the following: ``` SELECT time_start, some_count FROM foo WHERE user_id = 1 AND DATE(time_start) = '2016-07-27' ORDER BY some_count DESC, time_start DESC LIMIT 1; ``` What this does is return me one row, where some\_count is the highest count for `user_id = 1`. It also gives me the time stamp which is the most current for that `some_count`, as `some_count` could be the same for multiple `time_start` values and I want the most current one. Now I'm trying to do is run a query that will figure this out for every single `user_id` that occurred at least once for a specific date, in this case `2016-07-27`. Ultimately it's going to probably require a GROUP BY as I'm looking for a group maximum per `user_id` What's the best way to write a query of that nature?
2016/08/10
[ "https://Stackoverflow.com/questions/38874837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175836/" ]
I am sharing two of my approaches. **Approach #1 (scalable):** Using `MySQL user_defined variables` ``` SELECT t.user_id, t.time_start, t.time_stop, t.some_count FROM ( SELECT user_id, time_start, time_stop, some_count, IF(@sameUser = user_id, @rn := @rn + 1, IF(@sameUser := user_id, @rn := 1, @rn := 1) ) AS row_number FROM foo CROSS JOIN ( SELECT @sameUser := - 1, @rn := 1 ) var WHERE DATE(time_start) = '2016-07-27' ORDER BY user_id, some_count DESC, time_stop DESC ) AS t WHERE t.row_number <= 1 ORDER BY t.user_id; ``` Scalable because if you want latest n rows for each user then you just need to change this line : `... WHERE t.row_number <= n...` I can add explanation later if the query provides expected result --- **Approach #2:(Not scalable)** Using `INNER JOIN and GROUP BY` ``` SELECT F.user_id, F.some_count, F.time_start, MAX(F.time_stop) AS max_time_stop FROM foo F INNER JOIN ( SELECT user_id, MAX(some_count) AS max_some_count FROM foo WHERE DATE(time_start) = '2016-07-27' GROUP BY user_id ) AS t ON F.user_id = t.user_id AND F.some_count = t.max_some_count WHERE DATE(time_start) = '2016-07-27' GROUP BY F.user_id ```
**Strategy** In general it's more efficient to find maximum values rather than sorting groups of records. In this case, the ordering is on an integer (`some_count`) followed by a date/time (`time_start`) - so to find a single maximum row, we need to combine these in some way. A simple way of doing this is to combine the two into a string but there is the usual snag of string comparison valuing `"4"` as higher than `"12"` for example. This is easily overcome by using [`LPAD`](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#idm139935329305744) to add leading zeros so `4` becomes `"0000000004"`, which is lower than `"0000000012"` in a string comparison. Assuming `time_start` is a `DATETIME` field, it can simply be appended to this for a secondary ordering since its string conversion results in a sortable format (`yyyy-mm-dd hh:MM:ss`). **SQL** Using this strategy, we can restrict via a simple subselect: ``` SELECT time_start, some_count FROM foo f1 WHERE DATE(time_start) = '2016-07-27' AND CONCAT(LPAD(some_count, 10, '0'), time_start) = (SELECT MAX(CONCAT(LPAD(some_count, 10, '0'), time_start)) FROM foo f2 WHERE DATE(f2.time_start) = '2016-07-27' AND f2.user_id = f1.user_id); ``` **Demo** Rextester demo here: <http://rextester.com/HCGY1362>
38,874,837
I have a query that looks like the following: ``` SELECT time_start, some_count FROM foo WHERE user_id = 1 AND DATE(time_start) = '2016-07-27' ORDER BY some_count DESC, time_start DESC LIMIT 1; ``` What this does is return me one row, where some\_count is the highest count for `user_id = 1`. It also gives me the time stamp which is the most current for that `some_count`, as `some_count` could be the same for multiple `time_start` values and I want the most current one. Now I'm trying to do is run a query that will figure this out for every single `user_id` that occurred at least once for a specific date, in this case `2016-07-27`. Ultimately it's going to probably require a GROUP BY as I'm looking for a group maximum per `user_id` What's the best way to write a query of that nature?
2016/08/10
[ "https://Stackoverflow.com/questions/38874837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175836/" ]
You can use `NOT EXISTS()` : ``` SELECT * FROM foo t WHERE (DATE(time_start) = '2016-07-27' OR DATE(time_stop) = '2016-07-27') AND NOT EXISTS(SELECT 1 FROM foo s WHERE t.user_id = s.user_id AND (s.some_count > t.some_count OR (s.some_count = t.some_count AND s.time_stop > t.time_stop))) ``` The `NOT EXISTS()` will select only records that another record with a larger count or a another record with the same count but a newer `time_stop` doesn't exists for them.
I believe, you don't need to do anything fancy for the query. Just sort the table by **user\_id** in ascending order and **some\_count** and **time\_start** in a descending order and select expected fields from the ordered table GROUP BY **user\_id**. Its simple. Try and let me know if works. ``` SELECT user_id, some_count, time_start FROM (SELECT * FROM foo ORDER BY user_id ASC, some_count DESC, time_start DESC)sorted_foo WHERE DATE( time_start ) = '2016-07-27' GROUP BY user_id ```
38,874,837
I have a query that looks like the following: ``` SELECT time_start, some_count FROM foo WHERE user_id = 1 AND DATE(time_start) = '2016-07-27' ORDER BY some_count DESC, time_start DESC LIMIT 1; ``` What this does is return me one row, where some\_count is the highest count for `user_id = 1`. It also gives me the time stamp which is the most current for that `some_count`, as `some_count` could be the same for multiple `time_start` values and I want the most current one. Now I'm trying to do is run a query that will figure this out for every single `user_id` that occurred at least once for a specific date, in this case `2016-07-27`. Ultimately it's going to probably require a GROUP BY as I'm looking for a group maximum per `user_id` What's the best way to write a query of that nature?
2016/08/10
[ "https://Stackoverflow.com/questions/38874837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175836/" ]
``` SELECT user_id, some_count, max(time_start) AS time_start FROM (SELECT a.* FROM foo AS a INNER JOIN (SELECT user_id, max(some_count) AS some_count FROM foo WHERE DATE(time_start) = '2016-07-27' GROUP BY user_id) AS b ON a.user_id = b.user_id AND a.some_count = b.some_count) AS c GROUP BY user_id, some_count; ``` Explaining from inside out: The most inner table (b) will give you the max some\_count per user. this is not enough as you want the max for two columns - so I'm joining it with the full table (a) to get the records that has these max values (c), and from that I'm taking the max time\_start for each user/some\_count combination.
``` SELECT c1.user_id, c1.some_count, MAX(c1.time_start) AS time_start FROM foo AS c1 JOIN ( SELECT user_id, MAX(some_count) AS some_count FROM foo WHERE time_start >= '2016-07-27' AND time_start < '2016-07-27' + INTERVAL 1 DAY GROUP BY user_id ) AS c2 USING (user_id, some_count) GROUP BY c1.user_id, c1.some_count ``` And, add these for better performance: ``` INDEX(user_id, some_count, time_start) INDEX(time_start) ``` The test for the `time_start` range was changed so that the second index could be used. This was loosely derived from by blog on [*groupwise max*](http://mysql.rjweb.org/doc.php/groupwise_max) .
38,874,837
I have a query that looks like the following: ``` SELECT time_start, some_count FROM foo WHERE user_id = 1 AND DATE(time_start) = '2016-07-27' ORDER BY some_count DESC, time_start DESC LIMIT 1; ``` What this does is return me one row, where some\_count is the highest count for `user_id = 1`. It also gives me the time stamp which is the most current for that `some_count`, as `some_count` could be the same for multiple `time_start` values and I want the most current one. Now I'm trying to do is run a query that will figure this out for every single `user_id` that occurred at least once for a specific date, in this case `2016-07-27`. Ultimately it's going to probably require a GROUP BY as I'm looking for a group maximum per `user_id` What's the best way to write a query of that nature?
2016/08/10
[ "https://Stackoverflow.com/questions/38874837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175836/" ]
I am sharing two of my approaches. **Approach #1 (scalable):** Using `MySQL user_defined variables` ``` SELECT t.user_id, t.time_start, t.time_stop, t.some_count FROM ( SELECT user_id, time_start, time_stop, some_count, IF(@sameUser = user_id, @rn := @rn + 1, IF(@sameUser := user_id, @rn := 1, @rn := 1) ) AS row_number FROM foo CROSS JOIN ( SELECT @sameUser := - 1, @rn := 1 ) var WHERE DATE(time_start) = '2016-07-27' ORDER BY user_id, some_count DESC, time_stop DESC ) AS t WHERE t.row_number <= 1 ORDER BY t.user_id; ``` Scalable because if you want latest n rows for each user then you just need to change this line : `... WHERE t.row_number <= n...` I can add explanation later if the query provides expected result --- **Approach #2:(Not scalable)** Using `INNER JOIN and GROUP BY` ``` SELECT F.user_id, F.some_count, F.time_start, MAX(F.time_stop) AS max_time_stop FROM foo F INNER JOIN ( SELECT user_id, MAX(some_count) AS max_some_count FROM foo WHERE DATE(time_start) = '2016-07-27' GROUP BY user_id ) AS t ON F.user_id = t.user_id AND F.some_count = t.max_some_count WHERE DATE(time_start) = '2016-07-27' GROUP BY F.user_id ```
You can use your original query as a correlated subquery in the WHERE clause. ``` SELECT user_id, time_stop, some_count FROM foo f WHERE f.id = ( SELECT f1.id FROM foo f1 WHERE f1.user_id = f.user_id -- correlate AND DATE(f1.time_start) = '2016-07-27' ORDER BY f1.some_count DESC, f1.time_stop DESC LIMIT 1 ) ``` MySQL should be able to cache the result of the subquery for every distinct `user_id`. Another way is to use nested GROUP BY queries: ``` select f.user_id, f.some_count, max(f.time_stop) as time_stop from ( select f.user_id, max(f.some_count) as some_count from foo f where date(f.time_start) = '2016-07-27' group by f.user_id ) sub join foo f using(user_id, some_count) where date(f.time_start) = '2016-07-27' group by f.user_id, f.some_count ```
38,874,837
I have a query that looks like the following: ``` SELECT time_start, some_count FROM foo WHERE user_id = 1 AND DATE(time_start) = '2016-07-27' ORDER BY some_count DESC, time_start DESC LIMIT 1; ``` What this does is return me one row, where some\_count is the highest count for `user_id = 1`. It also gives me the time stamp which is the most current for that `some_count`, as `some_count` could be the same for multiple `time_start` values and I want the most current one. Now I'm trying to do is run a query that will figure this out for every single `user_id` that occurred at least once for a specific date, in this case `2016-07-27`. Ultimately it's going to probably require a GROUP BY as I'm looking for a group maximum per `user_id` What's the best way to write a query of that nature?
2016/08/10
[ "https://Stackoverflow.com/questions/38874837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175836/" ]
``` SELECT user_id, some_count, max(time_start) AS time_start FROM (SELECT a.* FROM foo AS a INNER JOIN (SELECT user_id, max(some_count) AS some_count FROM foo WHERE DATE(time_start) = '2016-07-27' GROUP BY user_id) AS b ON a.user_id = b.user_id AND a.some_count = b.some_count) AS c GROUP BY user_id, some_count; ``` Explaining from inside out: The most inner table (b) will give you the max some\_count per user. this is not enough as you want the max for two columns - so I'm joining it with the full table (a) to get the records that has these max values (c), and from that I'm taking the max time\_start for each user/some\_count combination.
Your problem could be solved with something called **window functions**, but MySQL has no support for this kind of feature. I have two solutions for you. One is simulating a window function and the other is the common way you'll write some queries to address these situations in MySQL. This is the first one, which I answered [this question](https://stackoverflow.com/questions/39239626/retrieve-last-non-null-record-of-every-column-for-each-record-id-in-mysql/39240623#39240623): ``` -- simulates the window function -- first_value(<col>) over(partition by user_id order by some_count DESC, time_start DESC) SELECT user_id, substring_index(group_concat(time_start ORDER BY some_count DESC, time_start DESC), ',', 1) time_start, substring_index(group_concat(some_count ORDER BY some_count DESC, time_start DESC), ',', 1) some_count FROM foo WHERE DATE(time_start) = '2016-07-27' GROUP BY user_id ; ``` Basically, you group your data by `user_id` and concatenates all values from a specified column using the `,` separator, ordered by the columns you want, for each group, and then substrings only the first ordered value. This is not an optimal approach... And that's the second one, which I answered [this question](https://stackoverflow.com/questions/39302650/using-max-and-sum-for-the-same-column-without-subquery-mysql/39302868#39302868): ``` SELECT user_id, some_count, MAX(time_start) time_start FROM foo outq WHERE 1=1 AND DATE(time_start) = '2016-07-27' AND NOT EXISTS ( SELECT 1 FROM foo WHERE 1=1 AND user_id = outq.user_id AND some_count > outq.some_count AND DATE(time_start) = DATE(outq.time_start) ) GROUP BY user_id, some_count ; ``` Basically, the subquery checks for each `user_id` if there are any `some_count` higher them the current one been checked on that date, as the main query expects it to `NOT EXISTS`. You'll left with all highest `some_count` per `user_id` in a date, but for a same highest value from a user may exists several different `time_start` in that date. Now things are simple. You can securely `GROUP BY` user and count, because they are already the data you want, and get from the group the maximum `time_start`. This kind of subquery is the common way of solving problems like that in MySQL. I recommend you to try both solutions, but choose the second one and remember the subquery sintax to solve any future problem. Also, in MySQL, an implicit `ORDER BY <columns>` is applied in all queries having a `GROUP BY <columns>`. If you don't bother with the result order, you can save some processing by declaring `ORDER BY NULL`, which will disable the implicit ordenation feature in your query.
38,874,837
I have a query that looks like the following: ``` SELECT time_start, some_count FROM foo WHERE user_id = 1 AND DATE(time_start) = '2016-07-27' ORDER BY some_count DESC, time_start DESC LIMIT 1; ``` What this does is return me one row, where some\_count is the highest count for `user_id = 1`. It also gives me the time stamp which is the most current for that `some_count`, as `some_count` could be the same for multiple `time_start` values and I want the most current one. Now I'm trying to do is run a query that will figure this out for every single `user_id` that occurred at least once for a specific date, in this case `2016-07-27`. Ultimately it's going to probably require a GROUP BY as I'm looking for a group maximum per `user_id` What's the best way to write a query of that nature?
2016/08/10
[ "https://Stackoverflow.com/questions/38874837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175836/" ]
You can use your original query as a correlated subquery in the WHERE clause. ``` SELECT user_id, time_stop, some_count FROM foo f WHERE f.id = ( SELECT f1.id FROM foo f1 WHERE f1.user_id = f.user_id -- correlate AND DATE(f1.time_start) = '2016-07-27' ORDER BY f1.some_count DESC, f1.time_stop DESC LIMIT 1 ) ``` MySQL should be able to cache the result of the subquery for every distinct `user_id`. Another way is to use nested GROUP BY queries: ``` select f.user_id, f.some_count, max(f.time_stop) as time_stop from ( select f.user_id, max(f.some_count) as some_count from foo f where date(f.time_start) = '2016-07-27' group by f.user_id ) sub join foo f using(user_id, some_count) where date(f.time_start) = '2016-07-27' group by f.user_id, f.some_count ```
Your problem could be solved with something called **window functions**, but MySQL has no support for this kind of feature. I have two solutions for you. One is simulating a window function and the other is the common way you'll write some queries to address these situations in MySQL. This is the first one, which I answered [this question](https://stackoverflow.com/questions/39239626/retrieve-last-non-null-record-of-every-column-for-each-record-id-in-mysql/39240623#39240623): ``` -- simulates the window function -- first_value(<col>) over(partition by user_id order by some_count DESC, time_start DESC) SELECT user_id, substring_index(group_concat(time_start ORDER BY some_count DESC, time_start DESC), ',', 1) time_start, substring_index(group_concat(some_count ORDER BY some_count DESC, time_start DESC), ',', 1) some_count FROM foo WHERE DATE(time_start) = '2016-07-27' GROUP BY user_id ; ``` Basically, you group your data by `user_id` and concatenates all values from a specified column using the `,` separator, ordered by the columns you want, for each group, and then substrings only the first ordered value. This is not an optimal approach... And that's the second one, which I answered [this question](https://stackoverflow.com/questions/39302650/using-max-and-sum-for-the-same-column-without-subquery-mysql/39302868#39302868): ``` SELECT user_id, some_count, MAX(time_start) time_start FROM foo outq WHERE 1=1 AND DATE(time_start) = '2016-07-27' AND NOT EXISTS ( SELECT 1 FROM foo WHERE 1=1 AND user_id = outq.user_id AND some_count > outq.some_count AND DATE(time_start) = DATE(outq.time_start) ) GROUP BY user_id, some_count ; ``` Basically, the subquery checks for each `user_id` if there are any `some_count` higher them the current one been checked on that date, as the main query expects it to `NOT EXISTS`. You'll left with all highest `some_count` per `user_id` in a date, but for a same highest value from a user may exists several different `time_start` in that date. Now things are simple. You can securely `GROUP BY` user and count, because they are already the data you want, and get from the group the maximum `time_start`. This kind of subquery is the common way of solving problems like that in MySQL. I recommend you to try both solutions, but choose the second one and remember the subquery sintax to solve any future problem. Also, in MySQL, an implicit `ORDER BY <columns>` is applied in all queries having a `GROUP BY <columns>`. If you don't bother with the result order, you can save some processing by declaring `ORDER BY NULL`, which will disable the implicit ordenation feature in your query.
38,874,837
I have a query that looks like the following: ``` SELECT time_start, some_count FROM foo WHERE user_id = 1 AND DATE(time_start) = '2016-07-27' ORDER BY some_count DESC, time_start DESC LIMIT 1; ``` What this does is return me one row, where some\_count is the highest count for `user_id = 1`. It also gives me the time stamp which is the most current for that `some_count`, as `some_count` could be the same for multiple `time_start` values and I want the most current one. Now I'm trying to do is run a query that will figure this out for every single `user_id` that occurred at least once for a specific date, in this case `2016-07-27`. Ultimately it's going to probably require a GROUP BY as I'm looking for a group maximum per `user_id` What's the best way to write a query of that nature?
2016/08/10
[ "https://Stackoverflow.com/questions/38874837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175836/" ]
You can use your original query as a correlated subquery in the WHERE clause. ``` SELECT user_id, time_stop, some_count FROM foo f WHERE f.id = ( SELECT f1.id FROM foo f1 WHERE f1.user_id = f.user_id -- correlate AND DATE(f1.time_start) = '2016-07-27' ORDER BY f1.some_count DESC, f1.time_stop DESC LIMIT 1 ) ``` MySQL should be able to cache the result of the subquery for every distinct `user_id`. Another way is to use nested GROUP BY queries: ``` select f.user_id, f.some_count, max(f.time_stop) as time_stop from ( select f.user_id, max(f.some_count) as some_count from foo f where date(f.time_start) = '2016-07-27' group by f.user_id ) sub join foo f using(user_id, some_count) where date(f.time_start) = '2016-07-27' group by f.user_id, f.some_count ```
``` SELECT c1.user_id, c1.some_count, MAX(c1.time_start) AS time_start FROM foo AS c1 JOIN ( SELECT user_id, MAX(some_count) AS some_count FROM foo WHERE time_start >= '2016-07-27' AND time_start < '2016-07-27' + INTERVAL 1 DAY GROUP BY user_id ) AS c2 USING (user_id, some_count) GROUP BY c1.user_id, c1.some_count ``` And, add these for better performance: ``` INDEX(user_id, some_count, time_start) INDEX(time_start) ``` The test for the `time_start` range was changed so that the second index could be used. This was loosely derived from by blog on [*groupwise max*](http://mysql.rjweb.org/doc.php/groupwise_max) .
38,874,837
I have a query that looks like the following: ``` SELECT time_start, some_count FROM foo WHERE user_id = 1 AND DATE(time_start) = '2016-07-27' ORDER BY some_count DESC, time_start DESC LIMIT 1; ``` What this does is return me one row, where some\_count is the highest count for `user_id = 1`. It also gives me the time stamp which is the most current for that `some_count`, as `some_count` could be the same for multiple `time_start` values and I want the most current one. Now I'm trying to do is run a query that will figure this out for every single `user_id` that occurred at least once for a specific date, in this case `2016-07-27`. Ultimately it's going to probably require a GROUP BY as I'm looking for a group maximum per `user_id` What's the best way to write a query of that nature?
2016/08/10
[ "https://Stackoverflow.com/questions/38874837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175836/" ]
I am sharing two of my approaches. **Approach #1 (scalable):** Using `MySQL user_defined variables` ``` SELECT t.user_id, t.time_start, t.time_stop, t.some_count FROM ( SELECT user_id, time_start, time_stop, some_count, IF(@sameUser = user_id, @rn := @rn + 1, IF(@sameUser := user_id, @rn := 1, @rn := 1) ) AS row_number FROM foo CROSS JOIN ( SELECT @sameUser := - 1, @rn := 1 ) var WHERE DATE(time_start) = '2016-07-27' ORDER BY user_id, some_count DESC, time_stop DESC ) AS t WHERE t.row_number <= 1 ORDER BY t.user_id; ``` Scalable because if you want latest n rows for each user then you just need to change this line : `... WHERE t.row_number <= n...` I can add explanation later if the query provides expected result --- **Approach #2:(Not scalable)** Using `INNER JOIN and GROUP BY` ``` SELECT F.user_id, F.some_count, F.time_start, MAX(F.time_stop) AS max_time_stop FROM foo F INNER JOIN ( SELECT user_id, MAX(some_count) AS max_some_count FROM foo WHERE DATE(time_start) = '2016-07-27' GROUP BY user_id ) AS t ON F.user_id = t.user_id AND F.some_count = t.max_some_count WHERE DATE(time_start) = '2016-07-27' GROUP BY F.user_id ```
You can use `NOT EXISTS()` : ``` SELECT * FROM foo t WHERE (DATE(time_start) = '2016-07-27' OR DATE(time_stop) = '2016-07-27') AND NOT EXISTS(SELECT 1 FROM foo s WHERE t.user_id = s.user_id AND (s.some_count > t.some_count OR (s.some_count = t.some_count AND s.time_stop > t.time_stop))) ``` The `NOT EXISTS()` will select only records that another record with a larger count or a another record with the same count but a newer `time_stop` doesn't exists for them.
14,355,712
> > **Possible Duplicate:** > > [How to add a JComboBox to a JTable cell?](https://stackoverflow.com/questions/2059229/how-to-add-a-jcombobox-to-a-jtable-cell) > > > I'm finding it difficult to add `JComboBox` to one of the cells of a `JTable`, I tried the code below but it's not working.. **How can I add jcombobox to a particular cell?** On pressing `enter` a new `jcombobox` should be added automatically to the desired column. ``` jTable1 = new javax.swing.JTable(); mod=new DefaultTableModel(); mod.addColumn("No"); mod.addColumn("Item ID"); mod.addColumn("Units"); mod.addColumn("Amount"); mod.addColumn("UOM"); mod.addColumn("Delivery Date"); mod.addColumn("Total Amount"); mod.addColumn("Notes"); mod.addColumn("Received"); mod.addRow(new Object [][] { {1, null, null, null, null, null, null, null, null} }); jTable1.setModel(mod); jTable1.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(generateBox())); jTable1.setColumnSelectionAllowed(true); Code to generate ComboBox private JComboBox generateBox() { JComboBox bx=null; Connection con=CPool.getConnection(); try { Statement st=con.createStatement(); String query="select distinct inid from inventory where company_code="+"'"+ims.MainWindow.cc+"'"; ResultSet rs=st.executeQuery(query); bx=new JComboBox(); while(rs.next()){ bx.addItem(rs.getString(1)); } CPool.closeConnection(con); CPool.closeStatement(st); CPool.closeResultSet(rs); }catch(Exception x) { System.out.println(x.getMessage()); } return bx; } ```
2013/01/16
[ "https://Stackoverflow.com/questions/14355712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1955017/" ]
Look at this link it will help you <http://docs.oracle.com/javase/tutorial/uiswing/components/table.html> ![enter image description here](https://i.stack.imgur.com/0CG6G.png) and the code : <http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableRenderDemoProject/src/components/TableRenderDemo.java>
`JComboBox` is added to `JTable` by extending DefaultCellEditor **Example:** ``` TableColumn comboCol1 = table.getColumnModel().getColumn(0); comboCol1.setCellEditor(new CustomComboBoxEditor()); /** Custom class for adding elements in the JComboBox. */ public class CustomComboBoxEditor extends DefaultCellEditor { // Declare a model that is used for adding the elements to the `Combo box` private DefaultComboBoxModel model; public CustomComboBoxEditor() { super(new JComboBox()); this.model = (DefaultComboBoxModel)((JComboBox)getComponent()).getModel(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { // Add the elements which you want to the model. // Here I am adding elements from the orderList(say) which you can pass via constructor to this class. model.addElement(orderList.get(i)); //finally return the component. return super.getTableCellEditorComponent(table, value, isSelected, row, column); } } ``` > > By using a custom class to create Components in JTable you can have > more control over the content which your are showing. > > >
26,994,020
Here is the Reddit widget code: I'd like for every clickable link in the reddit widget box to open up into a new tab. Any idea of how to do this? Thanks For all your help!
2014/11/18
[ "https://Stackoverflow.com/questions/26994020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4265442/" ]
So, for example, reddit generates this for you for a widget code. The problem is that it will open any links in the same window. `<script src="http://www.reddit.com/r/satire/hot/.embed?limit=5&t=all" type="text/javascript"></script>` You can make it open in a new tab/window (based on browser settings) by adding **&target=blank** : `<script src="http://www.reddit.com/r/satire/hot/.embed?limit=5&t=all&style=off&target=blank" type="text/javascript"></script>` Adding the bolded script seems to do the trick just fine.
You could try adding the target="\_blank" attribute to each link in the widget with jquery. ``` $(document).ready(function(){ $('.rembeddit a').each(function(){ $(this).attr('target', '_blank'); }); }); ```
24,367,854
I am writing a simple form at work using HTML and have added JavaScript to the page to allow users to add extra rows to a table. This table has input type="Text" tags and select tags. When the user clicks the button to add a row, the JavaScript adds a row, but clears the input and select tags. My script is ``` var x = x + 1; function another() { x = x + 1; y = y + 1; var bigTable = document.getElementById("bigTable"); bigTable.innerHTML += ("<TR><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><SELECT NAME=\"PO" + x + "\"><OPTION>Select</OPTION><OPTION>1234567890</OPTION></SELECT> </TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"SKU" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"modelNum" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"itemNum" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"qty" + x + "\" ID=\"qty"+x+"\" onBlur=\"total();\"></TD></TR>"); } ``` I'm not sure what the issue is here. Is the "+=" statement basically resetting my table like an = statement would? EDIT: I don't know how to get all of the code to appear, but what is displayed is not all of my code. I have a basic Table and using JavaScript use a += statement to add HTML to it. EDIT: My table is this: ``` <TABLE ID="bigTable"> <TR> <TH>P.O. #</TH> <TH>SKU #</TH> <TH>Model #</TH> <TH>Item #</TH> <TH>Quantity</TH> </TR> <TR> <TD CLASS="bigTable" ALIGN="Center"> <SELECT NAME="PO1"> <OPTION>Select</OPTION> <OPTION>1234567890</OPTION> </SELECT> </TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="SKU1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="modelNum1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="itemNum1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="qty1" ID="qty1" onBlur="total();"></TD> </TR> </TABLE> ``` My JavaScript Replicates everything between the tags. And I use the variable x to update the number in the names for the inputs and dropdowns. Variable Y is used to increment a calculation function.
2014/06/23
[ "https://Stackoverflow.com/questions/24367854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767679/" ]
When you edit the `innerHTML` of a HTML element, the entire DOM gets re-parsed. Since the input's values aren't actually stored in the input elements's HTML, they are cleared. An option would be to use DOM manipulation to add the row: ``` function another(){ x = x + 1; y = y + 1; var bigTable = document.getElementById("bigTable"); vat tr = document.createElement('tr'); tr.innerHTML = ("<td class='bigTable2' align='Center'><select name='PO" + x + "'><option>select</option><option>1234567890</option></select></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='SKU" + x + "'></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='modelNum" + x + "'></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='itemNum" + x + "'></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='qty" + x + "' ID='qty" + x + "' onBlur='total();'></td>"); bigTable.appendChild(tr); } ``` Notice how the string no longer contains a `<tr>` tag. This codes creates a `tr` element, then adds the rows to it, then adds that whole, (parsed), `tr` to the table. (I also changed the tags / attributes to lowercase and replaced all `\"` with `'` to make it more readable)
To be clear, `x += y` is the same as writing `x = x + y`. What's happening here is that you are overwriting the HTML with what you had plus the new row. This clears your inputs because their values are not stored in the HTML (when you type inside one of the input, it's "value" property is not updated in the actual HTML). So you are basically overwriting your HTML with what was there initially plus some added nodes. EDIT: Go for Cerbrus's solution. Much cleaner.
24,367,854
I am writing a simple form at work using HTML and have added JavaScript to the page to allow users to add extra rows to a table. This table has input type="Text" tags and select tags. When the user clicks the button to add a row, the JavaScript adds a row, but clears the input and select tags. My script is ``` var x = x + 1; function another() { x = x + 1; y = y + 1; var bigTable = document.getElementById("bigTable"); bigTable.innerHTML += ("<TR><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><SELECT NAME=\"PO" + x + "\"><OPTION>Select</OPTION><OPTION>1234567890</OPTION></SELECT> </TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"SKU" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"modelNum" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"itemNum" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"qty" + x + "\" ID=\"qty"+x+"\" onBlur=\"total();\"></TD></TR>"); } ``` I'm not sure what the issue is here. Is the "+=" statement basically resetting my table like an = statement would? EDIT: I don't know how to get all of the code to appear, but what is displayed is not all of my code. I have a basic Table and using JavaScript use a += statement to add HTML to it. EDIT: My table is this: ``` <TABLE ID="bigTable"> <TR> <TH>P.O. #</TH> <TH>SKU #</TH> <TH>Model #</TH> <TH>Item #</TH> <TH>Quantity</TH> </TR> <TR> <TD CLASS="bigTable" ALIGN="Center"> <SELECT NAME="PO1"> <OPTION>Select</OPTION> <OPTION>1234567890</OPTION> </SELECT> </TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="SKU1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="modelNum1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="itemNum1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="qty1" ID="qty1" onBlur="total();"></TD> </TR> </TABLE> ``` My JavaScript Replicates everything between the tags. And I use the variable x to update the number in the names for the inputs and dropdowns. Variable Y is used to increment a calculation function.
2014/06/23
[ "https://Stackoverflow.com/questions/24367854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767679/" ]
When you edit the `innerHTML` of a HTML element, the entire DOM gets re-parsed. Since the input's values aren't actually stored in the input elements's HTML, they are cleared. An option would be to use DOM manipulation to add the row: ``` function another(){ x = x + 1; y = y + 1; var bigTable = document.getElementById("bigTable"); vat tr = document.createElement('tr'); tr.innerHTML = ("<td class='bigTable2' align='Center'><select name='PO" + x + "'><option>select</option><option>1234567890</option></select></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='SKU" + x + "'></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='modelNum" + x + "'></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='itemNum" + x + "'></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='qty" + x + "' ID='qty" + x + "' onBlur='total();'></td>"); bigTable.appendChild(tr); } ``` Notice how the string no longer contains a `<tr>` tag. This codes creates a `tr` element, then adds the rows to it, then adds that whole, (parsed), `tr` to the table. (I also changed the tags / attributes to lowercase and replaced all `\"` with `'` to make it more readable)
What I ended up going with was a dynamic JavaScript code that would create a dynamic array and store values in each column of my current table. Then the code created a new row and the array was then accessed to repopulate the values.
24,367,854
I am writing a simple form at work using HTML and have added JavaScript to the page to allow users to add extra rows to a table. This table has input type="Text" tags and select tags. When the user clicks the button to add a row, the JavaScript adds a row, but clears the input and select tags. My script is ``` var x = x + 1; function another() { x = x + 1; y = y + 1; var bigTable = document.getElementById("bigTable"); bigTable.innerHTML += ("<TR><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><SELECT NAME=\"PO" + x + "\"><OPTION>Select</OPTION><OPTION>1234567890</OPTION></SELECT> </TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"SKU" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"modelNum" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"itemNum" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"qty" + x + "\" ID=\"qty"+x+"\" onBlur=\"total();\"></TD></TR>"); } ``` I'm not sure what the issue is here. Is the "+=" statement basically resetting my table like an = statement would? EDIT: I don't know how to get all of the code to appear, but what is displayed is not all of my code. I have a basic Table and using JavaScript use a += statement to add HTML to it. EDIT: My table is this: ``` <TABLE ID="bigTable"> <TR> <TH>P.O. #</TH> <TH>SKU #</TH> <TH>Model #</TH> <TH>Item #</TH> <TH>Quantity</TH> </TR> <TR> <TD CLASS="bigTable" ALIGN="Center"> <SELECT NAME="PO1"> <OPTION>Select</OPTION> <OPTION>1234567890</OPTION> </SELECT> </TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="SKU1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="modelNum1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="itemNum1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="qty1" ID="qty1" onBlur="total();"></TD> </TR> </TABLE> ``` My JavaScript Replicates everything between the tags. And I use the variable x to update the number in the names for the inputs and dropdowns. Variable Y is used to increment a calculation function.
2014/06/23
[ "https://Stackoverflow.com/questions/24367854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767679/" ]
To be clear, `x += y` is the same as writing `x = x + y`. What's happening here is that you are overwriting the HTML with what you had plus the new row. This clears your inputs because their values are not stored in the HTML (when you type inside one of the input, it's "value" property is not updated in the actual HTML). So you are basically overwriting your HTML with what was there initially plus some added nodes. EDIT: Go for Cerbrus's solution. Much cleaner.
What I ended up going with was a dynamic JavaScript code that would create a dynamic array and store values in each column of my current table. Then the code created a new row and the array was then accessed to repopulate the values.
61,226
I have MacBook Pro: ``` 13-inch, Late 2011 2.4 GHz Intel Core i5 4 GB 1333 MHz DDR3 Intel HD Graphics 3000 384MB OS X Lion 10.7.4 ``` When it plays a video, the CPU temperature goes over 90 degrees celsius and the fan makes loud noises. Is this normal? Or should I change speed of fan and make it faster for better cooling?
2012/08/19
[ "https://apple.stackexchange.com/questions/61226", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/27671/" ]
I believe that it is common for the CPU to reach 90°C under heavy load. However a simple video should not bump an i5 into that region. Depending on the footage and format you are playing back you might want to try a different player (vlc mplayerX). If you are playing back flash HD videos in your browser (especially multiple streams simultaneously), that behavior might be common (due to the bad flash performance on os x). So much for the software. Secondly you should take care of the outer temperature (e.g.is your computer in a very hot room) and even more importantly where your notebook is placed. e.g. does it sit on a carpet or any other good insulating soft cushiony surface that prevents heat from leaving your computer. Thirdly you might want to take a look in the activity monitor and see whats using your cpu. (Maybe some background application e.g. spotlight indexing new pdfs)
Try [SMCFanControl](http://www.macupdate.com/app/mac/23049/smcfancontrol), a free app for regulating fan speed. Your Mac only increases fan speed once core temperature hits a certain threshold. At this point, the mac is already hot, and the fan must work overtime to lower it. If you expect a high load, you can primitively increase fan speed, to avoid the sudden temperature spike.
61,226
I have MacBook Pro: ``` 13-inch, Late 2011 2.4 GHz Intel Core i5 4 GB 1333 MHz DDR3 Intel HD Graphics 3000 384MB OS X Lion 10.7.4 ``` When it plays a video, the CPU temperature goes over 90 degrees celsius and the fan makes loud noises. Is this normal? Or should I change speed of fan and make it faster for better cooling?
2012/08/19
[ "https://apple.stackexchange.com/questions/61226", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/27671/" ]
I believe that it is common for the CPU to reach 90°C under heavy load. However a simple video should not bump an i5 into that region. Depending on the footage and format you are playing back you might want to try a different player (vlc mplayerX). If you are playing back flash HD videos in your browser (especially multiple streams simultaneously), that behavior might be common (due to the bad flash performance on os x). So much for the software. Secondly you should take care of the outer temperature (e.g.is your computer in a very hot room) and even more importantly where your notebook is placed. e.g. does it sit on a carpet or any other good insulating soft cushiony surface that prevents heat from leaving your computer. Thirdly you might want to take a look in the activity monitor and see whats using your cpu. (Maybe some background application e.g. spotlight indexing new pdfs)
If youtube is giving you heat issues it's pretty likely that it's due to them using VP8/VP9 codecs by default, which your mac won't have hardware decoding for. If you use chrome you can install the plugin **h264ify**. You should be able to hardware decode youtube with that & take the load off your CPU.
61,226
I have MacBook Pro: ``` 13-inch, Late 2011 2.4 GHz Intel Core i5 4 GB 1333 MHz DDR3 Intel HD Graphics 3000 384MB OS X Lion 10.7.4 ``` When it plays a video, the CPU temperature goes over 90 degrees celsius and the fan makes loud noises. Is this normal? Or should I change speed of fan and make it faster for better cooling?
2012/08/19
[ "https://apple.stackexchange.com/questions/61226", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/27671/" ]
I have bought a Retina macbook Pro late 2013 13' and when i play civilization V my temps are 95/98, in idle they are 30/40..I think they're normal
Try [SMCFanControl](http://www.macupdate.com/app/mac/23049/smcfancontrol), a free app for regulating fan speed. Your Mac only increases fan speed once core temperature hits a certain threshold. At this point, the mac is already hot, and the fan must work overtime to lower it. If you expect a high load, you can primitively increase fan speed, to avoid the sudden temperature spike.
61,226
I have MacBook Pro: ``` 13-inch, Late 2011 2.4 GHz Intel Core i5 4 GB 1333 MHz DDR3 Intel HD Graphics 3000 384MB OS X Lion 10.7.4 ``` When it plays a video, the CPU temperature goes over 90 degrees celsius and the fan makes loud noises. Is this normal? Or should I change speed of fan and make it faster for better cooling?
2012/08/19
[ "https://apple.stackexchange.com/questions/61226", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/27671/" ]
After further clarification, it seems that you're getting this high temperature from running videos on YouTube's Flash Player. Flash Player is infamous for its overall crapiness, especially its resource usage (especially CPU usage). One solution to this problem is to find solutions for watching online video (such as off YouTube) without using their Flash Player. Here are the two applications I use: * [ClickToFlash](http://hoyois.github.com/safariextensions/clicktoflash/ClickToFlash.safariextz) is a free app that replaces Flash content with a gray placeholder, which only runs the Flash content if clicked on. It works on most YouTube videos, detects the video frame, and lets you play the video using the HTML5 video player, which uses almost no CPU at all. As a bonus, it prevents Flash ads from running (which can sometimes slip by AdBlock) * [HUDTube](http://hudtu.be) (it's accompanying Safari and Chrome extensions) allows you to open videos in an external player (much like QuickTime, but with a togglable ability to keep it on top of all other windows). It's useful to play the few videos ClickToFlash doesn't pick up.
Try [SMCFanControl](http://www.macupdate.com/app/mac/23049/smcfancontrol), a free app for regulating fan speed. Your Mac only increases fan speed once core temperature hits a certain threshold. At this point, the mac is already hot, and the fan must work overtime to lower it. If you expect a high load, you can primitively increase fan speed, to avoid the sudden temperature spike.
61,226
I have MacBook Pro: ``` 13-inch, Late 2011 2.4 GHz Intel Core i5 4 GB 1333 MHz DDR3 Intel HD Graphics 3000 384MB OS X Lion 10.7.4 ``` When it plays a video, the CPU temperature goes over 90 degrees celsius and the fan makes loud noises. Is this normal? Or should I change speed of fan and make it faster for better cooling?
2012/08/19
[ "https://apple.stackexchange.com/questions/61226", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/27671/" ]
After further clarification, it seems that you're getting this high temperature from running videos on YouTube's Flash Player. Flash Player is infamous for its overall crapiness, especially its resource usage (especially CPU usage). One solution to this problem is to find solutions for watching online video (such as off YouTube) without using their Flash Player. Here are the two applications I use: * [ClickToFlash](http://hoyois.github.com/safariextensions/clicktoflash/ClickToFlash.safariextz) is a free app that replaces Flash content with a gray placeholder, which only runs the Flash content if clicked on. It works on most YouTube videos, detects the video frame, and lets you play the video using the HTML5 video player, which uses almost no CPU at all. As a bonus, it prevents Flash ads from running (which can sometimes slip by AdBlock) * [HUDTube](http://hudtu.be) (it's accompanying Safari and Chrome extensions) allows you to open videos in an external player (much like QuickTime, but with a togglable ability to keep it on top of all other windows). It's useful to play the few videos ClickToFlash doesn't pick up.
If youtube is giving you heat issues it's pretty likely that it's due to them using VP8/VP9 codecs by default, which your mac won't have hardware decoding for. If you use chrome you can install the plugin **h264ify**. You should be able to hardware decode youtube with that & take the load off your CPU.
61,226
I have MacBook Pro: ``` 13-inch, Late 2011 2.4 GHz Intel Core i5 4 GB 1333 MHz DDR3 Intel HD Graphics 3000 384MB OS X Lion 10.7.4 ``` When it plays a video, the CPU temperature goes over 90 degrees celsius and the fan makes loud noises. Is this normal? Or should I change speed of fan and make it faster for better cooling?
2012/08/19
[ "https://apple.stackexchange.com/questions/61226", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/27671/" ]
After further clarification, it seems that you're getting this high temperature from running videos on YouTube's Flash Player. Flash Player is infamous for its overall crapiness, especially its resource usage (especially CPU usage). One solution to this problem is to find solutions for watching online video (such as off YouTube) without using their Flash Player. Here are the two applications I use: * [ClickToFlash](http://hoyois.github.com/safariextensions/clicktoflash/ClickToFlash.safariextz) is a free app that replaces Flash content with a gray placeholder, which only runs the Flash content if clicked on. It works on most YouTube videos, detects the video frame, and lets you play the video using the HTML5 video player, which uses almost no CPU at all. As a bonus, it prevents Flash ads from running (which can sometimes slip by AdBlock) * [HUDTube](http://hudtu.be) (it's accompanying Safari and Chrome extensions) allows you to open videos in an external player (much like QuickTime, but with a togglable ability to keep it on top of all other windows). It's useful to play the few videos ClickToFlash doesn't pick up.
In Safari, right click, copy url of the video and play it on VLC. It will solve 100% the problem ;)
61,226
I have MacBook Pro: ``` 13-inch, Late 2011 2.4 GHz Intel Core i5 4 GB 1333 MHz DDR3 Intel HD Graphics 3000 384MB OS X Lion 10.7.4 ``` When it plays a video, the CPU temperature goes over 90 degrees celsius and the fan makes loud noises. Is this normal? Or should I change speed of fan and make it faster for better cooling?
2012/08/19
[ "https://apple.stackexchange.com/questions/61226", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/27671/" ]
This problem can be easily solved First, download and run the Adobe Flash uninstaller Then restart the computer Second, place the power supply in a cool place In one minute the temperature reaches less than 70 degrees
In Safari, right click, copy url of the video and play it on VLC. It will solve 100% the problem ;)
61,226
I have MacBook Pro: ``` 13-inch, Late 2011 2.4 GHz Intel Core i5 4 GB 1333 MHz DDR3 Intel HD Graphics 3000 384MB OS X Lion 10.7.4 ``` When it plays a video, the CPU temperature goes over 90 degrees celsius and the fan makes loud noises. Is this normal? Or should I change speed of fan and make it faster for better cooling?
2012/08/19
[ "https://apple.stackexchange.com/questions/61226", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/27671/" ]
If youtube is giving you heat issues it's pretty likely that it's due to them using VP8/VP9 codecs by default, which your mac won't have hardware decoding for. If you use chrome you can install the plugin **h264ify**. You should be able to hardware decode youtube with that & take the load off your CPU.
In Safari, right click, copy url of the video and play it on VLC. It will solve 100% the problem ;)
61,226
I have MacBook Pro: ``` 13-inch, Late 2011 2.4 GHz Intel Core i5 4 GB 1333 MHz DDR3 Intel HD Graphics 3000 384MB OS X Lion 10.7.4 ``` When it plays a video, the CPU temperature goes over 90 degrees celsius and the fan makes loud noises. Is this normal? Or should I change speed of fan and make it faster for better cooling?
2012/08/19
[ "https://apple.stackexchange.com/questions/61226", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/27671/" ]
Try [SMCFanControl](http://www.macupdate.com/app/mac/23049/smcfancontrol), a free app for regulating fan speed. Your Mac only increases fan speed once core temperature hits a certain threshold. At this point, the mac is already hot, and the fan must work overtime to lower it. If you expect a high load, you can primitively increase fan speed, to avoid the sudden temperature spike.
In Safari, right click, copy url of the video and play it on VLC. It will solve 100% the problem ;)
61,226
I have MacBook Pro: ``` 13-inch, Late 2011 2.4 GHz Intel Core i5 4 GB 1333 MHz DDR3 Intel HD Graphics 3000 384MB OS X Lion 10.7.4 ``` When it plays a video, the CPU temperature goes over 90 degrees celsius and the fan makes loud noises. Is this normal? Or should I change speed of fan and make it faster for better cooling?
2012/08/19
[ "https://apple.stackexchange.com/questions/61226", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/27671/" ]
I have bought a Retina macbook Pro late 2013 13' and when i play civilization V my temps are 95/98, in idle they are 30/40..I think they're normal
If youtube is giving you heat issues it's pretty likely that it's due to them using VP8/VP9 codecs by default, which your mac won't have hardware decoding for. If you use chrome you can install the plugin **h264ify**. You should be able to hardware decode youtube with that & take the load off your CPU.
34,535,602
I've been using Highcharts on a Wordpress website for about 9 months without problems. Last week I updated to Wordpress 4.4 and soon after I noticed that my charts didn't render properly anymore (may be unrelated, not sure). In Chrome or Safari the div doesn't expand height-wise at all so the charts aren't legible. In Firefox, they initially displayed the same behavior as the other two browsers, but now just an empty div displays. I tried changing the order I list my scripts in my header.php file, but that didn't seem to have any effect. I also removed all other scripts except the highcharts script, but that didn't work either. I've also tried adjusting code in my function.php file using this method on CSS Tricks: <https://css-tricks.com/snippets/wordpress/include-jquery-in-wordpress-theme/> but no luck there either. Here's an example of a chart that's not rendering correctly: <http://siliconvalleyindicators.org/data/people/talent-flows-diversity/total-science-engineering-degrees-conferred/> Any advice is much appreciated.
2015/12/30
[ "https://Stackoverflow.com/questions/34535602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5731796/" ]
You have this element for holding chart: ``` <div style="width:100%; height:100%;" data-highcharts-chart="0" id="hc1"> ``` Replace heigh with some value with px, em etc. ``` style="width:100%; height:200px;" ``` This should fix your problem.
``` GET http://siliconvalleyindicators.org/data/people/talent-flows-diversity/total-science-engineering-degrees-conferred/js/functions.js ``` If you open your js console you will see that `js/functions.js` can't be found. Use an absolute link like this: `<?php bloginfo('template_directory')?>/js/functions.js`
19,291,499
How can I change the output directory in Google glog? I only found `google::SetLogDestination(google::LogSeverity, const char* path)` tried it with: ``` google::SetLogDestination(ERROR, "C:\\log\\error.log); google::InitGoogleLogging("Test"); LOG(ERROR) << "TEST"; ``` but nothing was written! Btw.: if you suggest another lightweight, easy to use and thread safe library please let me know! Thx for any help!
2013/10/10
[ "https://Stackoverflow.com/questions/19291499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384556/" ]
Here is the test what I did, you may try it, ``` #include <glog/logging.h> using namespace std; int main(int /*argc*/, char** argv) { FLAGS_logtostderr = true; google::SetLogDestination(google::GLOG_INFO,"c:/lovelyGoogle" ); google::InitGoogleLogging(argv[0]); LOG(INFO) << "This is INFO"; LOG(WARNING) << "This is WARNING"; LOG(ERROR) << "This is Error"; system("pause"); return 0; } ``` Tested under Visual studio 2012, google-glog 0.3.3 on Windows 7. It generated `lvoelyGoogle20131016-141423.5160` on my C driver. If you set `FLAGS_logtostderr = false`, the log file will not be generated, I believe you have already read [this](http://google-glog.googlecode.com/svn/trunk/doc/glog.html) (well, I have no comment on it) hope this helpful, good luck. --- PS: I have tested on QtCreator (Qt5.1) as well on Windows7, nothing output. I have no idea how to fix it now.
I use this: ``` fLS::FLAGS_log_dir = "c:/Documents/logs"; ```
19,291,499
How can I change the output directory in Google glog? I only found `google::SetLogDestination(google::LogSeverity, const char* path)` tried it with: ``` google::SetLogDestination(ERROR, "C:\\log\\error.log); google::InitGoogleLogging("Test"); LOG(ERROR) << "TEST"; ``` but nothing was written! Btw.: if you suggest another lightweight, easy to use and thread safe library please let me know! Thx for any help!
2013/10/10
[ "https://Stackoverflow.com/questions/19291499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384556/" ]
You can also do one of the following: Pass the log directory as a commandline argument as long as you have the GFlgas library installed: ``` ./your_application --log_dir=/some/log/directory ``` If you don't want to pass it in the commandline and instead set it in the source: ``` FLAGS_log_dir = "/some/log/directory"; ``` If the Google gflags library isn't installed you can set it as an environment variable: ``` GLOG_log_dir=/some/log/directory ./your_application ```
Here is the test what I did, you may try it, ``` #include <glog/logging.h> using namespace std; int main(int /*argc*/, char** argv) { FLAGS_logtostderr = true; google::SetLogDestination(google::GLOG_INFO,"c:/lovelyGoogle" ); google::InitGoogleLogging(argv[0]); LOG(INFO) << "This is INFO"; LOG(WARNING) << "This is WARNING"; LOG(ERROR) << "This is Error"; system("pause"); return 0; } ``` Tested under Visual studio 2012, google-glog 0.3.3 on Windows 7. It generated `lvoelyGoogle20131016-141423.5160` on my C driver. If you set `FLAGS_logtostderr = false`, the log file will not be generated, I believe you have already read [this](http://google-glog.googlecode.com/svn/trunk/doc/glog.html) (well, I have no comment on it) hope this helpful, good luck. --- PS: I have tested on QtCreator (Qt5.1) as well on Windows7, nothing output. I have no idea how to fix it now.
19,291,499
How can I change the output directory in Google glog? I only found `google::SetLogDestination(google::LogSeverity, const char* path)` tried it with: ``` google::SetLogDestination(ERROR, "C:\\log\\error.log); google::InitGoogleLogging("Test"); LOG(ERROR) << "TEST"; ``` but nothing was written! Btw.: if you suggest another lightweight, easy to use and thread safe library please let me know! Thx for any help!
2013/10/10
[ "https://Stackoverflow.com/questions/19291499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384556/" ]
Here is the test what I did, you may try it, ``` #include <glog/logging.h> using namespace std; int main(int /*argc*/, char** argv) { FLAGS_logtostderr = true; google::SetLogDestination(google::GLOG_INFO,"c:/lovelyGoogle" ); google::InitGoogleLogging(argv[0]); LOG(INFO) << "This is INFO"; LOG(WARNING) << "This is WARNING"; LOG(ERROR) << "This is Error"; system("pause"); return 0; } ``` Tested under Visual studio 2012, google-glog 0.3.3 on Windows 7. It generated `lvoelyGoogle20131016-141423.5160` on my C driver. If you set `FLAGS_logtostderr = false`, the log file will not be generated, I believe you have already read [this](http://google-glog.googlecode.com/svn/trunk/doc/glog.html) (well, I have no comment on it) hope this helpful, good luck. --- PS: I have tested on QtCreator (Qt5.1) as well on Windows7, nothing output. I have no idea how to fix it now.
In my terrifying experience with this library I came to see that this flag `FLAGS_log_dir` and this function `google::SetLogDestination()` compete with each other. Wonderful. I learned that you can use either but not both. **option 1: use flags** ``` FLAGS_log_dir=/path/to/your/logdir google::InitGoogleLogging(exec_name.c_str()); ``` and generate a bunch of files named `your_exec.some_number.machine_name.log.log_severity....` and their respective symbolic link inside the `/path/to/your/logdir`. A pair of files will be generated for each log\_severity you have used in your program (INFO, WARNING, ERROR, FATAL). Fun fact: INFO files contain everything, WARNING files contain everything from warning downwards, and so on. God knows why these symlinks are needed. **option 2: use file names** ``` std::string log_dir = "/path/to/log/dir"; for (int severity = 0; severity < google::NUM_SEVERITIES; ++severity) { std::string fpath = fs::path(fs::path(log_dir) / fs::path(exec_name).filename()); google::SetLogDestination(severity, fpath.c_str()); google::SetLogSymlink(severity, ""); } google::InitGoogleLogging(exec_name.c_str()); ``` where `fs` is the filesystem library of c++17. This is send all logs to the same file (just one, not many) and finally remove that annoying symbolic link.
19,291,499
How can I change the output directory in Google glog? I only found `google::SetLogDestination(google::LogSeverity, const char* path)` tried it with: ``` google::SetLogDestination(ERROR, "C:\\log\\error.log); google::InitGoogleLogging("Test"); LOG(ERROR) << "TEST"; ``` but nothing was written! Btw.: if you suggest another lightweight, easy to use and thread safe library please let me know! Thx for any help!
2013/10/10
[ "https://Stackoverflow.com/questions/19291499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384556/" ]
You can also do one of the following: Pass the log directory as a commandline argument as long as you have the GFlgas library installed: ``` ./your_application --log_dir=/some/log/directory ``` If you don't want to pass it in the commandline and instead set it in the source: ``` FLAGS_log_dir = "/some/log/directory"; ``` If the Google gflags library isn't installed you can set it as an environment variable: ``` GLOG_log_dir=/some/log/directory ./your_application ```
I use this: ``` fLS::FLAGS_log_dir = "c:/Documents/logs"; ```
19,291,499
How can I change the output directory in Google glog? I only found `google::SetLogDestination(google::LogSeverity, const char* path)` tried it with: ``` google::SetLogDestination(ERROR, "C:\\log\\error.log); google::InitGoogleLogging("Test"); LOG(ERROR) << "TEST"; ``` but nothing was written! Btw.: if you suggest another lightweight, easy to use and thread safe library please let me know! Thx for any help!
2013/10/10
[ "https://Stackoverflow.com/questions/19291499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384556/" ]
You can also do one of the following: Pass the log directory as a commandline argument as long as you have the GFlgas library installed: ``` ./your_application --log_dir=/some/log/directory ``` If you don't want to pass it in the commandline and instead set it in the source: ``` FLAGS_log_dir = "/some/log/directory"; ``` If the Google gflags library isn't installed you can set it as an environment variable: ``` GLOG_log_dir=/some/log/directory ./your_application ```
In my terrifying experience with this library I came to see that this flag `FLAGS_log_dir` and this function `google::SetLogDestination()` compete with each other. Wonderful. I learned that you can use either but not both. **option 1: use flags** ``` FLAGS_log_dir=/path/to/your/logdir google::InitGoogleLogging(exec_name.c_str()); ``` and generate a bunch of files named `your_exec.some_number.machine_name.log.log_severity....` and their respective symbolic link inside the `/path/to/your/logdir`. A pair of files will be generated for each log\_severity you have used in your program (INFO, WARNING, ERROR, FATAL). Fun fact: INFO files contain everything, WARNING files contain everything from warning downwards, and so on. God knows why these symlinks are needed. **option 2: use file names** ``` std::string log_dir = "/path/to/log/dir"; for (int severity = 0; severity < google::NUM_SEVERITIES; ++severity) { std::string fpath = fs::path(fs::path(log_dir) / fs::path(exec_name).filename()); google::SetLogDestination(severity, fpath.c_str()); google::SetLogSymlink(severity, ""); } google::InitGoogleLogging(exec_name.c_str()); ``` where `fs` is the filesystem library of c++17. This is send all logs to the same file (just one, not many) and finally remove that annoying symbolic link.
2,156,569
I have the following code to return the length of a cycle in a string: ``` module Main where import Data.List detec ys n | 2*n > (length ys) = error "no cycle" | t == h = (2*n - n) | otherwise = detec ys (n+1) where t = ys !! n h = if n == 0 then ys !! 1 else ys !! (n*2) f x = detec (show x) 0 answer = map f [1/x|x<-[1..100]] ``` But what I don't know how to do is make it ignore the `"no cycle"` exception so that the list produced only contains the lengths of the strings which are cyclic. How can I do this?
2010/01/28
[ "https://Stackoverflow.com/questions/2156569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150851/" ]
Please don't use `error` to implement logic where the "erroneous" result is expected to occur. Instead, why not return `Maybe n` instead of just `n`, then [use `catMaybes`](http://haskell.org/ghc/docs/latest/html/libraries/base-4.2.0.0/Data-Maybe.html#v%3AcatMaybes) to filter out the `Nothing`s? The changes are easy enough: ``` module Main where import Data.List import Data.Maybe detec ys n | 2*n > (length ys) = Nothing | t == h = Just (2*n - n) | otherwise = detec ys (n+1) where t = ys !! n h = if n == 0 then ys !! 1 else ys !! (n*2) f x = detec (show x) 0 answer = catMaybes $ map f [1/x|x<-[1..100]] ``` By the way, you're indexing past the end of the list; perhaps you meant to check `2*n + 1 > length ys`? Drifting slightly off topic, I'd like to mention that `!!` and `length` are, for the most part, both inefficient and non-idiomatic when applied to lists, especially in an iterating construct like this. The list type is basically a *cons cell list*, which is an intrinsically recursive data structure, and is emphatically *not* an array. Ideally you should avoid doing anything with a list that can't be easily expressed with pattern matching, e.g., `f (x:xs) = ...`.
You might use [`catch`](http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Control-Exception.html#5) from Control.Exception as in ``` import Prelude hiding (catch) import Control.Exception main = do print answer `catch` errorMessage where errorMessage :: SomeException -> IO () errorMessage = putStrLn . ("error: " ++) . show ``` Catching `SomeException` is sloppy, and the output is messy: ``` [error: No cycle ``` It got partway through printing an array but ran into the exception. Not very nice. Another answer has covered the fine approach of using the `Maybe` monad for representing computations that can fail. An even more general approach is `MonadError`: ``` {-# LANGUAGE FlexibleContexts #-} import Control.Applicative import Control.Monad.Error detec2 :: (MonadError String m, Eq a) => [a] -> Int -> m Int detec2 ys n | 2*n >= (length ys) = throwError "No cycle" | t == h = return (2*n - n) | otherwise = detec2 ys (n+1) where t = ys !! n h = if n == 0 then ys !! 1 else ys !! (n*2) ``` (Notice this also fixes the bug in your first guard that allows `!!` to throw exceptions.) This permits similar but more flexible use, for example: ``` answer2 = f2 <$> [1/x | x <- [1..100]] f2 x = detec2 (show x) 0 main = do forM_ answer2 $ \x -> case x of Left msg -> putStrLn $ "error: " ++ msg Right x -> print x ``` Now the first few lines of the output are ``` error: No cycle error: No cycle 2 error: No cycle error: No cycle 3 6 error: No cycle 2 ``` Keep in mind this is still a pure function: you don't have to run it inside `IO`. To ignore the no-cycle errors, you might use ``` cycles :: [Int] cycles = [x | Right x <- answer2] ``` If you don't care about errors messages at all, then don't generate them. A natural way to do this is with lists where you return the empty list for no cycles and condense the result with `concatMap`: ``` detec3 :: (Show a) => a -> [Int] detec3 x = go 0 where go :: Int -> [Int] go n | 2*n >= len = [] | t == h = [2*n - n] | otherwise = go (n+1) where t = ys !! n h | n == 0 = ys !! 1 | otherwise = ys !! (n*2) len = length ys ys = show x main = do print $ concatMap (detec3 . recip) [1..100] ``` Finally, you may be interested in reading [8 ways to report errors in Haskell](http://www.randomhacks.net/articles/2007/03/10/haskell-8-ways-to-report-errors).
2,156,569
I have the following code to return the length of a cycle in a string: ``` module Main where import Data.List detec ys n | 2*n > (length ys) = error "no cycle" | t == h = (2*n - n) | otherwise = detec ys (n+1) where t = ys !! n h = if n == 0 then ys !! 1 else ys !! (n*2) f x = detec (show x) 0 answer = map f [1/x|x<-[1..100]] ``` But what I don't know how to do is make it ignore the `"no cycle"` exception so that the list produced only contains the lengths of the strings which are cyclic. How can I do this?
2010/01/28
[ "https://Stackoverflow.com/questions/2156569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150851/" ]
Are you working on [Project Euler #26](http://projecteuler.net/index.php?section=problems&id=26)? Just because a certain digit repeats, doesn't mean you've found a cycle: for example, in 334/999=0.334334334…, the cycle isn't (3), it is (334). Also, it unwise to depend on floating point computation to give you enough accurate digits: the solution to #26 definitely goes beyond what floating-point will give you. In any case, there are easier ways to find cycles. This keeps a list of previously-seen elements as it walks down the list, and returns when it finds that the current element has already been seen. ``` findCycle :: Eq a => [a] -> Int findCycle = findCycle' [] where findCycle' _ [] = 0 findCycle' k (x:xs) = maybe (findCycle' (x:k) xs) succ $ elemIndex x k ``` Your [tortoise and hare](http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare) algorithm is incomplete: it may not always find the smallest cycle. That flaw is corrected here. ``` findCycle :: Eq a => [a] -> Int findCycle xs = findCycle' xs (tail xs) where findCycle' (x:xs) (y:_:ys) | x == y = fromJust (elemIndex x xs) + 1 | otherwise = findCycle' xs ys ``` This assumes that it'll never run off the end of the list. If you implement your own decimal expansion, you can easily ensure that is true.
You might use [`catch`](http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Control-Exception.html#5) from Control.Exception as in ``` import Prelude hiding (catch) import Control.Exception main = do print answer `catch` errorMessage where errorMessage :: SomeException -> IO () errorMessage = putStrLn . ("error: " ++) . show ``` Catching `SomeException` is sloppy, and the output is messy: ``` [error: No cycle ``` It got partway through printing an array but ran into the exception. Not very nice. Another answer has covered the fine approach of using the `Maybe` monad for representing computations that can fail. An even more general approach is `MonadError`: ``` {-# LANGUAGE FlexibleContexts #-} import Control.Applicative import Control.Monad.Error detec2 :: (MonadError String m, Eq a) => [a] -> Int -> m Int detec2 ys n | 2*n >= (length ys) = throwError "No cycle" | t == h = return (2*n - n) | otherwise = detec2 ys (n+1) where t = ys !! n h = if n == 0 then ys !! 1 else ys !! (n*2) ``` (Notice this also fixes the bug in your first guard that allows `!!` to throw exceptions.) This permits similar but more flexible use, for example: ``` answer2 = f2 <$> [1/x | x <- [1..100]] f2 x = detec2 (show x) 0 main = do forM_ answer2 $ \x -> case x of Left msg -> putStrLn $ "error: " ++ msg Right x -> print x ``` Now the first few lines of the output are ``` error: No cycle error: No cycle 2 error: No cycle error: No cycle 3 6 error: No cycle 2 ``` Keep in mind this is still a pure function: you don't have to run it inside `IO`. To ignore the no-cycle errors, you might use ``` cycles :: [Int] cycles = [x | Right x <- answer2] ``` If you don't care about errors messages at all, then don't generate them. A natural way to do this is with lists where you return the empty list for no cycles and condense the result with `concatMap`: ``` detec3 :: (Show a) => a -> [Int] detec3 x = go 0 where go :: Int -> [Int] go n | 2*n >= len = [] | t == h = [2*n - n] | otherwise = go (n+1) where t = ys !! n h | n == 0 = ys !! 1 | otherwise = ys !! (n*2) len = length ys ys = show x main = do print $ concatMap (detec3 . recip) [1..100] ``` Finally, you may be interested in reading [8 ways to report errors in Haskell](http://www.randomhacks.net/articles/2007/03/10/haskell-8-ways-to-report-errors).
2,156,569
I have the following code to return the length of a cycle in a string: ``` module Main where import Data.List detec ys n | 2*n > (length ys) = error "no cycle" | t == h = (2*n - n) | otherwise = detec ys (n+1) where t = ys !! n h = if n == 0 then ys !! 1 else ys !! (n*2) f x = detec (show x) 0 answer = map f [1/x|x<-[1..100]] ``` But what I don't know how to do is make it ignore the `"no cycle"` exception so that the list produced only contains the lengths of the strings which are cyclic. How can I do this?
2010/01/28
[ "https://Stackoverflow.com/questions/2156569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150851/" ]
Please don't use `error` to implement logic where the "erroneous" result is expected to occur. Instead, why not return `Maybe n` instead of just `n`, then [use `catMaybes`](http://haskell.org/ghc/docs/latest/html/libraries/base-4.2.0.0/Data-Maybe.html#v%3AcatMaybes) to filter out the `Nothing`s? The changes are easy enough: ``` module Main where import Data.List import Data.Maybe detec ys n | 2*n > (length ys) = Nothing | t == h = Just (2*n - n) | otherwise = detec ys (n+1) where t = ys !! n h = if n == 0 then ys !! 1 else ys !! (n*2) f x = detec (show x) 0 answer = catMaybes $ map f [1/x|x<-[1..100]] ``` By the way, you're indexing past the end of the list; perhaps you meant to check `2*n + 1 > length ys`? Drifting slightly off topic, I'd like to mention that `!!` and `length` are, for the most part, both inefficient and non-idiomatic when applied to lists, especially in an iterating construct like this. The list type is basically a *cons cell list*, which is an intrinsically recursive data structure, and is emphatically *not* an array. Ideally you should avoid doing anything with a list that can't be easily expressed with pattern matching, e.g., `f (x:xs) = ...`.
Are you working on [Project Euler #26](http://projecteuler.net/index.php?section=problems&id=26)? Just because a certain digit repeats, doesn't mean you've found a cycle: for example, in 334/999=0.334334334…, the cycle isn't (3), it is (334). Also, it unwise to depend on floating point computation to give you enough accurate digits: the solution to #26 definitely goes beyond what floating-point will give you. In any case, there are easier ways to find cycles. This keeps a list of previously-seen elements as it walks down the list, and returns when it finds that the current element has already been seen. ``` findCycle :: Eq a => [a] -> Int findCycle = findCycle' [] where findCycle' _ [] = 0 findCycle' k (x:xs) = maybe (findCycle' (x:k) xs) succ $ elemIndex x k ``` Your [tortoise and hare](http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare) algorithm is incomplete: it may not always find the smallest cycle. That flaw is corrected here. ``` findCycle :: Eq a => [a] -> Int findCycle xs = findCycle' xs (tail xs) where findCycle' (x:xs) (y:_:ys) | x == y = fromJust (elemIndex x xs) + 1 | otherwise = findCycle' xs ys ``` This assumes that it'll never run off the end of the list. If you implement your own decimal expansion, you can easily ensure that is true.
5,959
*Ce* and *ça* both mean the same thing (this) in French, so what is the difference between them? When would someone use one over the other?
2013/03/11
[ "https://french.stackexchange.com/questions/5959", "https://french.stackexchange.com", "https://french.stackexchange.com/users/1114/" ]
This answer will be about the pronouns, but note that *ce* (with variants *cet*, *cette*) is also a demonstrative adjective and as such will be followed by a noun and that *ça* should not be confused with *çà* which is an old synonym of *ici*. *Ça* is an alternative form of *cela*; they can replace each other in most if not all contexts, but *ça* tend to be used more often (but not exclusively) when speaking, while *cela* tend to be used more often (but not exclusively) in writing. One case where *cela* is used more often both orally and in writing is when it is opposed with *ceci*. *Ce*, *ceci*, *cela* and *ça* are the neutral demonstrative pronouns. They don't replace a noun (forms with *celui*, *celle*, *ceux*, *celles* are used in those cases) but something implied or (part of) a sentence. When they are opposed, *ceci* is used for the nearer (in space, in time or in the discourse), *cela* (or sometimes *ça*) for the further. Alone, *ceci* is for something quite near and *cela* or *ça* for something quite far, but *cela* is also used for things near, especially for part of sentences which precedes the pronoun. Usages of *ce* are more limited: * in *ce que*, *ce qui*, *ce dont*, ... then it stands for a thing (it used to be able to stand for a person, but that's rare nowadays) or a (part of) a sentence. * as subject of *être*, *ce* stands for what comes before (in that case it can be redundant and only used for emphasis), or the situation. * it is also sometimes used as the subject of *pouvoir* or *devoir*, when used as modal verbs (aka semi-auxiliaries). * there are some other usages, more or less literary (*ce me semble*), more or less fixed remnants of older structures (*Ce disant, ...*) and it is sometimes replaced with *ça* for emphasis.
« il / elle est » becomes « c’est » and « ils / elles sont » becomes « ce sont » IF - an article is followed by a modified noun. Example: * he is a boy = c’est un garçon. * they are boys. Ce sont les garçons. :) « Ça » is an informal use of this and that as I know of. :)
24,411,934
I have a small server and small client. The code has been extrapolated to focus on the problem at hand. I have a client that sends a POST request to the server. The server responds with a json object. I am unable to see the json response object from within the node.js client. However, if I make a curl request, I can see it... //SERVER ``` var restify = require('restify'), Logger = require('bunyan'), api = require('./routes/api'), util = require('util'), fs = require('fs'); //START SERVER var server = restify.createServer({ name: 'image-server', log: log }) server.listen(7000, function () { console.log('%s listening at %s', server.name, server.url) }) server.use(restify.fullResponse()); server.use(restify.bodyParser()); //change from github var user = {username: "usr", password: "pwd"}; //auth middleware server.use(function(req,res,next){ if(req.params.username==user.username && req.params.password == user.password){ return next(); }else{ res.send(401); } }); server.post('/doc/', function(req,res){ var objToJson = {"result" : "success", "user" : "simon", "location" : "someloc"}; console.log("saved new doc. res: " + util.inspect(objToJson)); res.send(objToJson); }); ``` //CLIENT ``` var formdata = require('form-data'); var request = require('request'); var util = require('util'); var fs = require('fs'); var form = new formdata(); form.append('username', 'usr'); form.append('password', 'pwd'); form.append('user', '[email protected]'); form.append('file', fs.createReadStream('/some/file.png')); form.append('filename', "roger123131.png"); form.submit('http://0.0.0.0:7000/doc', function(err, res) { console.log(res.statusCode); console.log(res.body); console.log( "here." + util.inspect(res)); process.exit(); }); ``` In the client, I use form-data module. I need to send over the file, though I'm not sure if this is related/pertinent to the problem at hand. //CURL REQUEST ``` curl -v --form username=usr --form password=pwd --form file=@/tmp/0000b.jpg --form user=someemail http://0.0.0.0:7000/doc ``` The output of the curl request works. My question is, why can i not see the json response when I dump the response object in my node.js client code, but I can when making a request using curl? I'm sure the answer is simple... EDIT: Here is the output of the node.js client, showing the response object with no evidence of the json object/string: ``` 200 undefined here.{ _readableState: { highWaterMark: 16384, buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: false, ended: false, endEmitted: false, reading: true, calledRead: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, objectMode: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: { end: [Function: responseOnEnd], readable: [Function] }, _maxListeners: 10, socket: { _connecting: false, _handle: { fd: 10, writeQueueSize: 0, owner: [Circular], onread: [Function: onread], reading: true }, _readableState: { highWaterMark: 16384, buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: false, ended: false, endEmitted: false, reading: true, calledRead: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, objectMode: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: { end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], free: [Function], close: [Object], agentRemove: [Function], drain: [Function: ondrain], error: [Function: socketErrorListener] }, _maxListeners: 10, _writableState: { highWaterMark: 16384, objectMode: false, needDrain: false, ending: false, ended: false, finished: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, sync: false, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, buffer: [], errorEmitted: false }, writable: true, allowHalfOpen: false, onend: [Function: socketOnEnd], destroyed: false, bytesRead: 587, _bytesDispatched: 23536, _pendingData: null, _pendingEncoding: '', parser: { _headers: [], _url: '', onHeaders: [Function: parserOnHeaders], onHeadersComplete: [Function: parserOnHeadersComplete], onBody: [Function: parserOnBody], onMessageComplete: [Function: parserOnMessageComplete], socket: [Circular], incoming: [Circular], maxHeaderPairs: 2000, onIncoming: [Function: parserOnIncomingClient] }, _httpMessage: { domain: null, _events: [Object], _maxListeners: 10, output: [], outputEncodings: [], writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: false, _headerSent: true, _header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n', _hasBody: true, _trailer: '', finished: true, _hangupClose: false, socket: [Circular], connection: [Circular], agent: [Object], socketPath: undefined, method: 'POST', path: '/doc', _headers: [Object], _headerNames: [Object], parser: [Object], res: [Circular] }, ondata: [Function: socketOnData] }, connection: { _connecting: false, _handle: { fd: 10, writeQueueSize: 0, owner: [Circular], onread: [Function: onread], reading: true }, _readableState: { highWaterMark: 16384, buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: false, ended: false, endEmitted: false, reading: true, calledRead: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, objectMode: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: { end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], free: [Function], close: [Object], agentRemove: [Function], drain: [Function: ondrain], error: [Function: socketErrorListener] }, _maxListeners: 10, _writableState: { highWaterMark: 16384, objectMode: false, needDrain: false, ending: false, ended: false, finished: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, sync: false, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, buffer: [], errorEmitted: false }, writable: true, allowHalfOpen: false, onend: [Function: socketOnEnd], destroyed: false, bytesRead: 587, _bytesDispatched: 23536, _pendingData: null, _pendingEncoding: '', parser: { _headers: [], _url: '', onHeaders: [Function: parserOnHeaders], onHeadersComplete: [Function: parserOnHeadersComplete], onBody: [Function: parserOnBody], onMessageComplete: [Function: parserOnMessageComplete], socket: [Circular], incoming: [Circular], maxHeaderPairs: 2000, onIncoming: [Function: parserOnIncomingClient] }, _httpMessage: { domain: null, _events: [Object], _maxListeners: 10, output: [], outputEncodings: [], writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: false, _headerSent: true, _header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n', _hasBody: true, _trailer: '', finished: true, _hangupClose: false, socket: [Circular], connection: [Circular], agent: [Object], socketPath: undefined, method: 'POST', path: '/doc', _headers: [Object], _headerNames: [Object], parser: [Object], res: [Circular] }, ondata: [Function: socketOnData] }, httpVersion: '1.1', complete: false, headers: { 'content-type': 'application/json', 'content-length': '56', 'access-control-allow-origin': '*', 'access-control-allow-headers': 'Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Api-Version, Response-Time', 'access-control-allow-methods': 'POST', 'access-control-expose-headers': 'Api-Version, Request-Id, Response-Time', connection: 'Keep-Alive', 'content-md5': '/HLlB0jKu9S+l17eGyJfxg==', date: 'Wed, 25 Jun 2014 15:40:00 GMT', server: 'image-server', 'request-id': 'f7ca8390-fc7e-11e3-aa4e-e9c4573d9f1d', 'response-time': '4' }, trailers: {}, _pendings: [], _pendingIndex: 0, url: '', method: null, statusCode: 200, client: { _connecting: false, _handle: { fd: 10, writeQueueSize: 0, owner: [Circular], onread: [Function: onread], reading: true }, _readableState: { highWaterMark: 16384, buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: false, ended: false, endEmitted: false, reading: true, calledRead: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, objectMode: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: { end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], free: [Function], close: [Object], agentRemove: [Function], drain: [Function: ondrain], error: [Function: socketErrorListener] }, _maxListeners: 10, _writableState: { highWaterMark: 16384, objectMode: false, needDrain: false, ending: false, ended: false, finished: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, sync: false, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, buffer: [], errorEmitted: false }, writable: true, allowHalfOpen: false, onend: [Function: socketOnEnd], destroyed: false, bytesRead: 587, _bytesDispatched: 23536, _pendingData: null, _pendingEncoding: '', parser: { _headers: [], _url: '', onHeaders: [Function: parserOnHeaders], onHeadersComplete: [Function: parserOnHeadersComplete], onBody: [Function: parserOnBody], onMessageComplete: [Function: parserOnMessageComplete], socket: [Circular], incoming: [Circular], maxHeaderPairs: 2000, onIncoming: [Function: parserOnIncomingClient] }, _httpMessage: { domain: null, _events: [Object], _maxListeners: 10, output: [], outputEncodings: [], writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: false, _headerSent: true, _header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n', _hasBody: true, _trailer: '', finished: true, _hangupClose: false, socket: [Circular], connection: [Circular], agent: [Object], socketPath: undefined, method: 'POST', path: '/doc', _headers: [Object], _headerNames: [Object], parser: [Object], res: [Circular] }, ondata: [Function: socketOnData] }, _consuming: true, _dumped: false, httpVersionMajor: 1, httpVersionMinor: 1, upgrade: false, req: { domain: null, _events: { error: [Object], response: [Function] }, _maxListeners: 10, output: [], outputEncodings: [], writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: false, _headerSent: true, _header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n', _hasBody: true, _trailer: '', finished: true, _hangupClose: false, socket: { _connecting: false, _handle: [Object], _readableState: [Object], readable: true, domain: null, _events: [Object], _maxListeners: 10, _writableState: [Object], writable: true, allowHalfOpen: false, onend: [Function: socketOnEnd], destroyed: false, bytesRead: 587, _bytesDispatched: 23536, _pendingData: null, _pendingEncoding: '', parser: [Object], _httpMessage: [Circular], ondata: [Function: socketOnData] }, connection: { _connecting: false, _handle: [Object], _readableState: [Object], readable: true, domain: null, _events: [Object], _maxListeners: 10, _writableState: [Object], writable: true, allowHalfOpen: false, onend: [Function: socketOnEnd], destroyed: false, bytesRead: 587, _bytesDispatched: 23536, _pendingData: null, _pendingEncoding: '', parser: [Object], _httpMessage: [Circular], ondata: [Function: socketOnData] }, agent: { domain: null, _events: [Object], _maxListeners: 10, options: {}, requests: {}, sockets: [Object], maxSockets: 5, createConnection: [Function] }, socketPath: undefined, method: 'POST', path: '/doc', _headers: { 'content-type': 'multipart/form-data; boundary=--------------------------994987473640480876924123', host: '0.0.0.0:7000', 'content-length': 23351 }, _headerNames: { 'content-type': 'content-type', host: 'Host', 'content-length': 'Content-Length' }, parser: { _headers: [], _url: '', onHeaders: [Function: parserOnHeaders], onHeadersComplete: [Function: parserOnHeadersComplete], onBody: [Function: parserOnBody], onMessageComplete: [Function: parserOnMessageComplete], socket: [Object], incoming: [Circular], maxHeaderPairs: 2000, onIncoming: [Function: parserOnIncomingClient] }, res: [Circular] }, pipe: [Function], addListener: [Function], on: [Function], pause: [Function], resume: [Function], read: [Function] } ```
2014/06/25
[ "https://Stackoverflow.com/questions/24411934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2263135/" ]
Look closely at this expression: ``` $('#searchResults').append(htmlifyResultsRow(data[i]), i) ``` You are passing `i` to `.append()`, not to `htmlifyResultsRow()`. This is why `i` is `undefined` in your `htmlifyResultsRow` function, because it is never passed a value for `i` in the first place. What you're probably looking to do is: ``` $('#searchResults').append(htmlifyResultsRow(data[i], i)) ```
this is the problem: ``` $('#searchResults').append(htmlifyResultsRow(data[i]), i) ``` it should be: ``` $('#searchResults').append(htmlifyResultsRow(data[i], i)) ```
60,007,527
e.g. ``` const char* my_func_string = "int func(){" " return 1; }"; //is there a way to do it automatically? int func(){ return 1; } ``` func could be of multiple lines. And I want my\_func\_string to capture the change whenever I change func. It'd be better if it's captured at compile time because the executables may not find the source code
2020/01/31
[ "https://Stackoverflow.com/questions/60007527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8984267/" ]
You could define the defaults within the function and use the [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals) to combine the two objects, which will override the defaults where applicable. ```js function search(filterOptions) { const defaults = { foo: 'foo', foo2: 'bar' }; filterOptions = {...defaults,...filterOptions}; console.log(filterOptions); } search({foo: 'something'}); ```
You can define the default variable with an `if` statement: ``` function search(arr) { if(arr.bar === undefined) { arr.bar = "bar1"; } //do whatever } ``` The use of **`===`** is to make sure that the `if` does not run if bar is set to `"undefined"` (a string).
60,007,527
e.g. ``` const char* my_func_string = "int func(){" " return 1; }"; //is there a way to do it automatically? int func(){ return 1; } ``` func could be of multiple lines. And I want my\_func\_string to capture the change whenever I change func. It'd be better if it's captured at compile time because the executables may not find the source code
2020/01/31
[ "https://Stackoverflow.com/questions/60007527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8984267/" ]
You can provide default values in the parameter list: ```js function search({ foo = "bar", foo2 = "bar2"} = {}) { console.log("foo is " + foo + ", foo2 is " + foo2); } console.log(search()); console.log(search({ foo: "broccoli" })); console.log(search({ foo: "my foo", foo2: "my foo2" })); ``` The `= {}` at the end is to handle the case when the function is called with no parameters.
You can define the default variable with an `if` statement: ``` function search(arr) { if(arr.bar === undefined) { arr.bar = "bar1"; } //do whatever } ``` The use of **`===`** is to make sure that the `if` does not run if bar is set to `"undefined"` (a string).
31,263,203
I want to encapsulate global variables in a single "data-manager-module". Access is only possible with functions to avoid all the ugly global variable problems ... So the content is completely hidden from the users. Are there any existing concepts? How could such an implementation look like? How should the values stored in the "data-manager-module"?
2015/07/07
[ "https://Stackoverflow.com/questions/31263203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5088471/" ]
A "data manager module" doesn't make any sense. Implementing one would merely be sweeping away a fundamentally poor program design underneath the carpet, hiding it instead of actually cleaning it up. The main problem with globals is not user-abuse, but that they create tight couplings between modules in your project, making it hard to read and maintain, and also increases the chance of bugs "escalating" outside the module where the bug was located. Every datum in your program belongs to a certain module, where a "module" consists of a h file and a corresponding c file. Call it module or class or ADT or whatever you like. Common sense and OO design both dictate that the variables need to be declared in the module where they actually belong, period. You can either do so by declaring the variable at file scope `static` and then implement setter/getter functions. This is "poor man's private encapsulation" and not thread-safe, but for embedded systems it will work just fine in most cases. This is the embedded industry de facto standard of declaring such variables. Or alternatively and more advanced, you can do true private encapsulation by declaring a struct as incomplete type in a h file, and define it in the C file. This is sometimes called "opaque type" and gives true encapsulation on object basis, meaning that you can declare multiple instances of the class. Opaque type can also be used to implement inheritance (though in rather burdensome ways).
Declare and define all the variables in a header file that is included into the manager's .c file but not into its .h That way they will be only visible for the manager's functions.
31,263,203
I want to encapsulate global variables in a single "data-manager-module". Access is only possible with functions to avoid all the ugly global variable problems ... So the content is completely hidden from the users. Are there any existing concepts? How could such an implementation look like? How should the values stored in the "data-manager-module"?
2015/07/07
[ "https://Stackoverflow.com/questions/31263203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5088471/" ]
A "data manager module" doesn't make any sense. Implementing one would merely be sweeping away a fundamentally poor program design underneath the carpet, hiding it instead of actually cleaning it up. The main problem with globals is not user-abuse, but that they create tight couplings between modules in your project, making it hard to read and maintain, and also increases the chance of bugs "escalating" outside the module where the bug was located. Every datum in your program belongs to a certain module, where a "module" consists of a h file and a corresponding c file. Call it module or class or ADT or whatever you like. Common sense and OO design both dictate that the variables need to be declared in the module where they actually belong, period. You can either do so by declaring the variable at file scope `static` and then implement setter/getter functions. This is "poor man's private encapsulation" and not thread-safe, but for embedded systems it will work just fine in most cases. This is the embedded industry de facto standard of declaring such variables. Or alternatively and more advanced, you can do true private encapsulation by declaring a struct as incomplete type in a h file, and define it in the C file. This is sometimes called "opaque type" and gives true encapsulation on object basis, meaning that you can declare multiple instances of the class. Opaque type can also be used to implement inheritance (though in rather burdensome ways).
You can keep all variables in a single source inside a struct with getters and setters ``` static struct all_globals{ long long myll; /* ... */ } all_globals; /* Not _really_ global*/ long long getmyll(void){ return all_globals.myll; } long long setmyll(long long value){ return all_globals.myll = value; } ``` similarly, you could use an internal header file that is not exported to the user API, then strip symbols from the resulting binary/library ``` /* globals.c */ struct all_globals{ long long myll; /* ... */ } all_globals; /* Not _really_ global*/ /* globals.h */ #define getmyll() all_globals.myll #define setmyll(value) all_globals.myll = (value) ``` This will still be technically visible to the end user with enough effort, but allows you to distinguish globals and keep them together.
58,743,518
I' fetching data from axios through my API but when I'm rendering the data of it so it shows me blank template. So kindly let me know if I'm doing any mistake. I pasted my code with api response. Thanks console.log => response.data ``` Data Array [ Object { "ID": 2466, "ItemName": "WWE2K20" } ] ``` My Component ``` import React, { Component } from 'react'; import { Container, Header, Content, Card, CardItem, Body, Text } from 'native-base'; import { View, StyleSheet, FlatList, Image } from 'react-native'; import axios from 'axios'; export default class HomeScreen extends Component { constructor() { super() this.state = { itemList: [] } } async componentDidMount() { await axios.get('myapiuri') .then((response) => { this.setState({ itemList: response.data }); console.log("Data", this.state.itemList) }) .catch(error=>console.log(error)) } render() { return ( <Container> <Content> <FlatList data={this.state.itemList} renderItem={(item) => { return( <Text>{item.ItemName}</Text> ); }} keyExtractor={(item) => item.ID} /> </Content> </Container> ); } } ```
2019/11/07
[ "https://Stackoverflow.com/questions/58743518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8923126/" ]
There are a few problems I see. First you need to use ({item}) in renderItem as stated in comments. Second, you are mixing async/await with then block. In this case there is no need to async/await. So your code must be: ``` export default class HomeScreen extends Component { constructor() { super(); this.state = { itemList: [] }; } componentDidMount() { axios .get("myapiuri") .then(response => { this.setState({ itemList: response.data }); console.log("Data", this.state.itemList); }) .catch(error => console.log(error)); } render() { return ( <Container> <Content> <FlatList data={this.state.itemList} renderItem={({ item }) => { return <Text>{item.ItemName}</Text>; }} keyExtractor={item => item.ID} /> </Content> </Container> ); } } ``` If you still having problems, please look at this example: <https://snack.expo.io/@suleymansah/c0e4e5>
``` <FlatList data={this.state.itemList} renderItem={**(item)** => { return( <Text>{item.ItemName}</Text> ); }} keyExtractor={(item) => item.ID} /> ``` in here "item" is a object , it has , ID and ItemName. when you call like this item is not recognize as a object that is why nothing show , **({ item })** you should change above call as this. then item recognize as a object and you can call its attributes as , item.Id or item.ItemName i think you got my point why your code is not working. please learn react-native life cycle. componentDidMount didnt want async, after component render componentDidMount will call and componentWillMount call at one time when component loading.componentWillReceiveProps call when any state of the component change.
49,924,634
``` data = pd.read_csv("file.csv") As = data.groupby('A') for name, group in As: current_column = group.iloc[:, i] current_column.iloc[0] = np.NAN ``` The problem: 'data' stays the same after this loop, even though I'm trying to set values to np.NAN .
2018/04/19
[ "https://Stackoverflow.com/questions/49924634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1525654/" ]
The simple answer is that, as indicated in the above quote from the mongo documenation, "different drivers might vary". In this case the default for mongolite is 5 minutes, found in [this](https://github.com/jeroen/mongolite/issues/34) github issue, I'm guessing it's related to the C drivers. > > The default socket timeout for connections is 5 minutes. This means > that if your MongoDB server dies or becomes unavailable it will take 5 > minutes to detect this. You can change this by providing > sockettimeoutms= in your connection URI. > > > Also noted in the github issue is a solution which is to increase the `sockettimeoutms` in the URI. At the end of the connection URI you should add `?sockettimeoutms=1200000` as an option to increase the length of time (20 minutes in this case) before a socket timeout. Modifying the original example code: ``` library(mongolite) mongo <- mongo(collection,url = paste0("mongodb://", user,":",pass, "@", mongo_host, ":", port,"/",db,"?sockettimeoutms=1200000")) mongo$find(fields = '{"sample_id":1,"_id":0}') ```
Laravel: in your database.php `'sockettimeoutms' => '1200000'`, add this and enjoy the ride
58,859,720
i need to send email when the ticket saves but am getting the error am guessing am supposed to put the values in array is my syntax okay? **ErrorException Undefined variable: userName** This is the store function ``` public function store(Request $request) { // Create Ticket $ticket=new Ticket; $ticket->userName= $request->input('userName'); $ticket->userEmail= $request->input('userEmail'); $ticket->phoneNumber= $request->input('phoneNumber'); $ticket->regular_quantity= $request->input('regular_quantity'); $ticket->vip_quantity= $request->input('vip_quantity'); $ticket->event_id=$request->route('id'); $ticket->total= $request->input('regular_quantity') + $request->input('vip_quantity'); $event = Event::find($ticket->event_id); if ($ticket->regular_quantity < $event->regular_attendies && $ticket->vip_quantity < $event->vip_attendies) { if($event->regular_attendies>0 && $event->vip_attendies>0){ DB::table('events')->decrement('regular_attendies', $ticket->regular_quantity); DB::table('events')->decrement('vip_attendies', $ticket->vip_quantity); $ticket->save(); $to_name = '$userName'; $to_email = '$userEmail'; $data = array('name'=>"$userName", "body" => "Test mail"); Mail::send('layouts.mail', $data, function($message) use ($to_name,$to_email){ $message->to('$userEmail'); $message->subject('Ticket success'); $message->from('[email protected]','kisila'); }); echo "Email sent"; } else{ echo"no available space"; } return redirect('/'); } } ```
2019/11/14
[ "https://Stackoverflow.com/questions/58859720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Not sure what you're trying to do here. ``` $to_name = '$userName'; $to_email = '$userEmail'; ``` Setting `$to_name` to `'$userName'` will result in the string `'$userName'`, which seems pointless. Also, you're getting an error in this line: ``` $data = array('name'=>"$userName", "body" => "Test mail"); ``` When you wrap a variable in `" "`, it tries to parse it, but you don't have a variable `$username`. An easier way to accomplish this is to ignore setting these values and simply pass the newly created `$ticket` to your email, and reference the correct parameters: ``` $data = array("name" => $ticket->userName, "body" => "Test mail"); Mail::send("layouts.mail", $data, function($message) use ($ticket){ $message->to($ticket->userEmail); $message->subject("Ticket success"); $message->from('[email protected]','kisila'); }); ```
You never define the variable $userName (and the same mistake for $userEmail). Use ``` $to_name = $request->input('userName'); $to_email = $request->input('userEmail'); ``` and then also ``` $data = array('name'=> $to_name, "body" => "Test mail"); ``` You also have an error in your Mail:: send function ``` $message->to($userEmail); ``` should be ``` $message->to($to_email); ``` You will also need to define
68,230,934
I have a script that constantly adds data to a dictionary(cannot be changed meaning no lists or to stop adding the data). It can easily reach over 1000 different keys within it. I require each key and value but don't want to reset the dictionary `foo`. ```py foo = {"369610": "a", "109122": "a", "907897": "a", "333291":"a", "381819": "a", "387583": "a", "677430": "a", "660221": "a", "118095":"a", "612172": "a"} print(len(foo)) # At 10 foo["223533"] = "a" # Replaces 369610 in the dictionary foo["601336"] = "a" # Replaces 109122 in the dictionary print(len(foo)) # Should be 10 ``` If I was to add more keys to the dictionary, it would replace 907897 then 333291 then 381819 and then 387583. Once it reaches the limit of 10 any more added would replace the first index 223533. I still want to access each value of each key as to why this is a dictionary and not a list. I have thought to iterate over the dictionary then get each entry and overwrite that one with: ```py del foo[index] foo[random.randint(5000,100000)] = "a" ``` But I feel like this is an inefficient solution.
2021/07/02
[ "https://Stackoverflow.com/questions/68230934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11603043/" ]
``` from collections import OrderedDict class FooDict(OrderedDict): def __init__(self, maxsize=5, /, *args, **kwds): self.maxsize = maxsize super().__init__(*args, **kwds) def __getitem__(self, key): value = super().__getitem__(key) return value def __setitem__(self, key, value): super().__setitem__(key, value) if len(self) > self.maxsize: oldest = next(iter(self)) del self[oldest] ``` ``` foo = FooDict() for i in range(10): foo[random.randint(5000,100000)] = "a" print(foo) FooDict([(82596, 'a')]) FooDict([(82596, 'a'), (67860, 'a')]) FooDict([(82596, 'a'), (67860, 'a'), (13232, 'a')]) FooDict([(82596, 'a'), (67860, 'a'), (13232, 'a'), (45835, 'a')]) FooDict([(82596, 'a'), (67860, 'a'), (13232, 'a'), (45835, 'a'), (15591, 'a')]) FooDict([(67860, 'a'), (13232, 'a'), (45835, 'a'), (15591, 'a'), (36689, 'a')]) FooDict([(13232, 'a'), (45835, 'a'), (15591, 'a'), (36689, 'a'), (60175, 'a')]) FooDict([(45835, 'a'), (15591, 'a'), (36689, 'a'), (60175, 'a'), (87882, 'a')]) FooDict([(15591, 'a'), (36689, 'a'), (60175, 'a'), (87882, 'a'), (59414, 'a')]) FooDict([(36689, 'a'), (60175, 'a'), (87882, 'a'), (59414, 'a'), (87218, 'a')]) ```
Well, if anyone comes here looking for a dictionary which does not allow rewriting of keys nor their deletion (only insertion and lookup), then this is my solution: ``` class CircularBuffer: def __init__(self, size): self.maxsize = size self.array = [None] * size self.ptr = 0 self.get_ordered = self.GOpartial self.add = self.ADDpartial self.len = self.LENpartial def __getitem__(self, item): return self.array[item] def LENpartial(self): return self.ptr def LENfull(self): return self.maxsize def ADDpartial(self, item): self.array[self.ptr] = item self.ptr = self.ptr + 1 if self.ptr == self.maxsize: self.add = self.ADDfull self.get_ordered = self.GOfull self.len = self.LENfull self.ptr = 0 return None def ADDfull(self, item): ret = self.array[self.ptr] self.array[self.ptr] = item self.ptr = (self.ptr + 1) % self.maxsize return ret def GOpartial(self): return self.array[:self.ptr] def GOfull(self): return self.array[self.ptr:] + self.array[0: self.ptr] def __repr__(self): return self.array.__repr__() def __len__(self): return self.len() class CircularBufferDict: def __init__(self, size): self.keys = CircularBuffer(size) self.mapping = {} def add(self, k, v): if k in self.mapping: raise KeyError(f"Key {k} already exists in the dictionary.") rewritten = self.keys.add(k) if rewritten is not None: del self.mapping[rewritten] self.mapping[k] = v def get(self, k): return self.mapping[k] ``` After the maximum size is reached, it keeps a constant amount of elements. Every operation time belongs to `O(1)` (amortized on hash lookup). Deletion (and therefore overwriting) is inefficient when using this structure (defragmenting the array would take linear time).
1,665,208
I have a partial view with a dropdown (with `Paid and unpaid` as options) and a button. I am loading this partial view using jquery load, when the user click `Paid/Unpaid List link` in the sub menu of a page. When i select Paid in dropdown and click the button, it shows the list of paid customers in the jquery dialog and if i select Unpaid and click button, it shows unpaid customers in the jquery dialog. I am writing the following code for the dialog: ``` $('#customers').dialog({ bgiframe: true, autoOpen: false, open: function(event, ui) { //populate table var p_option = $('#d_PaidUnPaid option:selected').val(); if (p_option == 'PAID') { $("#customercontent").html(''); //$("#customercontent").load("/Customer/Paid"); } else if (p_option == 'UNPAID') { $("#customercontent").html(''); //$("#customercontent").load("/Customer/Unpaid"); } }, close: function(event, ui) { //do nothing }, height: 500, width: 550, modal: true }); ``` For the first time, i am getting the list correctly in the jquery dialog, but when i click the `Paid/Unpaid List link` again and select Unpaid in the dropdown and click the button, it shows the previos loaded content in the jquery dialog. What am i doing wrong here?
2009/11/03
[ "https://Stackoverflow.com/questions/1665208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
Try adding no-caching option to jQuery AJAX. I had problems with the load() function (and IE) where cached results would always be shown. To change the setting for all jQuery AJAX requests do ``` $.ajaxSetup({cache: false}); ```
Try add this after open: ``` $('#customers').empty().remove(); ``` Example: ``` open: function(event, ui) { //populate table var p_option = $('#d_PaidUnPaid option:selected').val(); if (p_option == 'PAID') { $("#customercontent").html(''); //$("#customercontent").load("/Customer/Paid"); } else if (p_option == 'UNPAID') { $("#customercontent").html(''); //$("#customercontent").load("/Customer/Unpaid"); } $('#customers').empty().remove(); }, ```
1,665,208
I have a partial view with a dropdown (with `Paid and unpaid` as options) and a button. I am loading this partial view using jquery load, when the user click `Paid/Unpaid List link` in the sub menu of a page. When i select Paid in dropdown and click the button, it shows the list of paid customers in the jquery dialog and if i select Unpaid and click button, it shows unpaid customers in the jquery dialog. I am writing the following code for the dialog: ``` $('#customers').dialog({ bgiframe: true, autoOpen: false, open: function(event, ui) { //populate table var p_option = $('#d_PaidUnPaid option:selected').val(); if (p_option == 'PAID') { $("#customercontent").html(''); //$("#customercontent").load("/Customer/Paid"); } else if (p_option == 'UNPAID') { $("#customercontent").html(''); //$("#customercontent").load("/Customer/Unpaid"); } }, close: function(event, ui) { //do nothing }, height: 500, width: 550, modal: true }); ``` For the first time, i am getting the list correctly in the jquery dialog, but when i click the `Paid/Unpaid List link` again and select Unpaid in the dropdown and click the button, it shows the previos loaded content in the jquery dialog. What am i doing wrong here?
2009/11/03
[ "https://Stackoverflow.com/questions/1665208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
I hope Im not too late to come up with correct answer. I had the same problem and I solved it with following ajax settings. ``` open: function () { jQuery.ajaxSetup({ cache: false }); //populate table or do what you want... } ```
Try add this after open: ``` $('#customers').empty().remove(); ``` Example: ``` open: function(event, ui) { //populate table var p_option = $('#d_PaidUnPaid option:selected').val(); if (p_option == 'PAID') { $("#customercontent").html(''); //$("#customercontent").load("/Customer/Paid"); } else if (p_option == 'UNPAID') { $("#customercontent").html(''); //$("#customercontent").load("/Customer/Unpaid"); } $('#customers').empty().remove(); }, ```
4,697,088
How does php access a variable passed by JQuery? I have the following code: ``` $.post("getLatLong.php", { latitude: 500000}, function(data){ alert("Data Loaded: " + data); }); ``` but I don't understand how to access this value using php. I've tried ``` $userLat=$_GET["latitude"]; ``` and ``` $userLat=$_GET[latitude]; ``` and then I try to print out the value (to check that it worked) using: `echo $userLat;` but it does not return anything. I can't figure out how to access what is being passed to it.
2011/01/14
[ "https://Stackoverflow.com/questions/4697088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258755/" ]
$\_GET is for url variables (?latitude=bla), what you want is .. ``` $_POST['latitude'] ```
use $\_POST['latitude'] instead of $\_GET. the reason of course is that your jQuery call is to $.post, which transfers your latitude via the post method.
4,697,088
How does php access a variable passed by JQuery? I have the following code: ``` $.post("getLatLong.php", { latitude: 500000}, function(data){ alert("Data Loaded: " + data); }); ``` but I don't understand how to access this value using php. I've tried ``` $userLat=$_GET["latitude"]; ``` and ``` $userLat=$_GET[latitude]; ``` and then I try to print out the value (to check that it worked) using: `echo $userLat;` but it does not return anything. I can't figure out how to access what is being passed to it.
2011/01/14
[ "https://Stackoverflow.com/questions/4697088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258755/" ]
$\_GET is for url variables (?latitude=bla), what you want is .. ``` $_POST['latitude'] ```
You're using `$.post`. That means it will be in the $\_POST superglobal in PHP. If you were using `$.get`, it would be sent to PHP in the query string, and be in the $\_GET superglobal array. If you want to access it without worrying which HTTP method you used in jQuery, use $\_REQUEST. Try `var_dump($_REQUEST);` or `var_dump($_POST);` in your PHP page, and look at the data that comes back using Firebug or the webkit Inspector.
5,159
I have taken a look at the [list of recently migrated Arduino questions](https://electronics.stackexchange.com/search?tab=newest&q=arduino%20migrated%3ayes). I thought we had reached the consensus that questions regarding Arduino that involve a good deal of electronics are fine on this site. But I still see many questions migrated. * [ATMega328P-PU and 328P-AU](https://electronics.stackexchange.com/posts/158962/revisions) about differences between ATMega chips, not specifically in Arduinos * [What bytes do I send to the MAX7221 to light an LED (in an led Matrix)?](https://electronics.stackexchange.com/posts/158868/revisions) about interfacing a non-Arduino chip, which happens to be done with an Arduino * [Arduino - millis()](https://electronics.stackexchange.com/posts/158323/revisions) about C, which happens to be about a function from the Arduino libraries but also applies in many other cases * [Arduino/C++ byte manipulation](https://electronics.stackexchange.com/posts/160146/revisions) has nothing to do with Arduino: simple C - if anywhere, it should've been migrated to SO I would like to do a **general suggestion** that if the **community agrees** according to vote counts on this question and its answers, **this type of questions be no longer migrated** or only if there seems to be support from the community (other than only from one or two). As a moderator you're still part of the community and there is no reason to migrate away the questions you don't like if there's no support for this within the community. Update ====== This question, [Operate Arduino Nano using variable voltage](https://electronics.stackexchange.com/q/160323/17592), was first migrated to Arduino. I had to flag it there to get it migrated back here. Such moving around of posts isn't be beneficial to anyone. **NB**: (without sufficient rep?) you won't see this in the post history, but it's really true. I flagged the post on Arduino.SE and asked for a migration back. Related: [Can we stop the random migrating?](https://electronics.meta.stackexchange.com/q/5149/17592); +22/-5; not a duplicate since this is a general request (which the other was as well actually, but this was massively misunderstood, even after emphasising that aspect of the question).
2015/03/15
[ "https://electronics.meta.stackexchange.com/questions/5159", "https://electronics.meta.stackexchange.com", "https://electronics.meta.stackexchange.com/users/-1/" ]
You seem to be the primary agitator on this topic, and you also seem to still not understand the fundamental difference between Arduino users on one hand, and electronics hobbyists and student/professional EEs on the other. This difference has already been discussed extensively in your other questions. Yes, there's a considerable overlap in topics between the two groups, but Arduino users need answers that are specific to the Arduino hardware/software environment, and they're not likely to get those answers from EEs who are not very familiar with that environment. It's all about *context*, and the way that SE deals with context in general is to have separate sites. We've already discussed how the use of "meta-tags" to provide that context is not appropriate on SE. There's nothing wrong with EEs who *are* interested in Arduino belonging to both EE.SE and Arduino.SE and answering questions on each site as they see fit. And there's nothing wrong with directing Arduino users who show up here to a site where they'll feel more at home and get better (for them) answers. And if there are some who decide that they want to learn more about the underlying engineering issues, then they can belong to both sites, too.
For me, there are a few issues that come into play here. The first is that plenty of arduino-tagged questions find a home here. <https://electronics.stackexchange.com/questions/tagged/arduino?sort=newest&pageSize=50> shows all the closed, migrated, and still open (and some yet to be closed) questions. Clearly, there is a line, and there is some disagreement on where it should be set, but I don't think that it's too far off from where it needs to be. You've red-flagged three migrations in ten days that you didn't like. Is it safe to assume that you're happy with the remainders, and all the Arduino-tagged that haven't migrated? If so, we're not talking about a huge proportion of Arduino questions here. A second point is that your arguments that this line isn't where it needs to be would be boosted big time if you took them one step further -- i.e., if you can go on to say "This question was migrated, and I don't think that the question got good answers at the Arduino SE." If the asker got the answer needed there, I don't see a problem. We're not hurting for good questions over here that badly yet. If the question got poor answers, but would have gotten fine answers here, then that's a compelling argument that perhaps migration was a mistake. The next issue comes from a mod at the Arduino site, who asked us to not migrate junk: <https://electronics.meta.stackexchange.com/a/5106/11684>. For me, I think that if its a question that requires specific knowledge of the Arduino platform or libraries, even if the question is pure gold, migration is not unreasonable -- especially if there's some subtext that makes it feel like the asker might appreciate an answer in the language of the Arduino community. The mods there would probably welcome some good questions migrated in that direction, and I hope that this cross exchange between the two sites can keep a user base with some real expertise engaged over there. Lastly, I can't say I know the ins and outs of migration, but the review tools certainly make it look like the mods at Arduino are perfectly free to turn down the migration. FWIW, for me, of the three you point out, I think the MAX7221 question could have comfortably stayed here, and might have gotten migrated simply because it says 'loop' instead of 'while (1)' in main. That said, maybe someone who is more familiar with the Arduino SPI.h can phrase the answer better for this particular asker. If not, the world is still turning
5,159
I have taken a look at the [list of recently migrated Arduino questions](https://electronics.stackexchange.com/search?tab=newest&q=arduino%20migrated%3ayes). I thought we had reached the consensus that questions regarding Arduino that involve a good deal of electronics are fine on this site. But I still see many questions migrated. * [ATMega328P-PU and 328P-AU](https://electronics.stackexchange.com/posts/158962/revisions) about differences between ATMega chips, not specifically in Arduinos * [What bytes do I send to the MAX7221 to light an LED (in an led Matrix)?](https://electronics.stackexchange.com/posts/158868/revisions) about interfacing a non-Arduino chip, which happens to be done with an Arduino * [Arduino - millis()](https://electronics.stackexchange.com/posts/158323/revisions) about C, which happens to be about a function from the Arduino libraries but also applies in many other cases * [Arduino/C++ byte manipulation](https://electronics.stackexchange.com/posts/160146/revisions) has nothing to do with Arduino: simple C - if anywhere, it should've been migrated to SO I would like to do a **general suggestion** that if the **community agrees** according to vote counts on this question and its answers, **this type of questions be no longer migrated** or only if there seems to be support from the community (other than only from one or two). As a moderator you're still part of the community and there is no reason to migrate away the questions you don't like if there's no support for this within the community. Update ====== This question, [Operate Arduino Nano using variable voltage](https://electronics.stackexchange.com/q/160323/17592), was first migrated to Arduino. I had to flag it there to get it migrated back here. Such moving around of posts isn't be beneficial to anyone. **NB**: (without sufficient rep?) you won't see this in the post history, but it's really true. I flagged the post on Arduino.SE and asked for a migration back. Related: [Can we stop the random migrating?](https://electronics.meta.stackexchange.com/q/5149/17592); +22/-5; not a duplicate since this is a general request (which the other was as well actually, but this was massively misunderstood, even after emphasising that aspect of the question).
2015/03/15
[ "https://electronics.meta.stackexchange.com/questions/5159", "https://electronics.meta.stackexchange.com", "https://electronics.meta.stackexchange.com/users/-1/" ]
Part of the reason why (I think) migrations are so frustrating from a community perspective is that there is no recourse if the community disagrees with the migration. In fact, the only way to undo a migration is to coordinate with the moderators of the target site to close the question, and then it can be "bounced back" to the original site. This makes migrations an unchangeable moderator action, instead of a normal close vote. I started asking myself *"How many bad migrations are we getting?"*, as that really sets the tone of this discussion. Here are some numbers to bring facts into the discussion. In the last 90 days, 78 questions have been migrated to Arduino.SE. Of those 78 questions, 4 have been rejected. While that sounds like a good number, it's worth noting that there are some different dynamics on Arduino.SE in the sense that they are a smaller beta site and don't quite have the numbers required to close questions by community. This is part of the reason why migrations to relatively new sites is discouraged - they don't have as much capability to deal with bad questions. Below is a list of questions migrated to Arduino.se in the last 90 days or so. This is not all of them as I seem to have missed some, but it's most of them (and I didn't intentionally omit questions). Some of them are deleted. From the perspective of migrating solid EE questions with a hint of Arduino, it doesn't seem so bad at first glance. <https://electronics.stackexchange.com/questions/160389/saving-arduino-output-to-a-text-file-in-append-mode?noredirect=1> <https://electronics.stackexchange.com/questions/160412/gsm-modem-with-max232-to-arduino-serial?noredirect=1> <https://electronics.stackexchange.com/questions/160255/how-to-do-serial-monitor-with-arduino-yun?noredirect=1> <https://electronics.stackexchange.com/questions/160269/seeedstudio-wifi-shield-v1-1-not-working-with-arduino-mega-2560?noredirect=1> <https://electronics.stackexchange.com/questions/160146/arduino-c-byte-manipulation?noredirect=1> <https://electronics.stackexchange.com/questions/159998/anakog-input-not-going-zero?noredirect=1> <https://electronics.stackexchange.com/questions/160005/ethernet-shield-not-getting-ip?noredirect=1> <https://electronics.stackexchange.com/questions/159960/arduino-unstable-analog-reading-when-using-power-supply?noredirect=1> <https://electronics.stackexchange.com/questions/159910/operate-arduino-nano-using-variable-voltage?noredirect=1> <https://electronics.stackexchange.com/questions/159789/using-an-arduino-uno-to-program-a-standalone-atmega2560?noredirect=1> <https://electronics.stackexchange.com/questions/159761/arduino-mega-number-of-simultaneous-pulse-inputs?noredirect=1> <https://electronics.stackexchange.com/questions/157859/is-it-possible-to-connect-many-arduino-uno-in-one-pc?noredirect=1> <https://electronics.stackexchange.com/questions/158962/atmega328p-pu-and-328p-au?noredirect=1> <https://electronics.stackexchange.com/questions/158940/arduino-sainsmart-uno-communication-problem?noredirect=1> <https://electronics.stackexchange.com/questions/158868/what-bytes-do-i-send-to-the-max7221-to-light-an-led-in-an-led-matrix?noredirect=1> <https://electronics.stackexchange.com/questions/158323/arduino-millis?noredirect=1> <https://electronics.stackexchange.com/questions/157919/arduino-how-to-accept-user-input-array-variables?noredirect=1> <https://electronics.stackexchange.com/questions/156885/how-best-to-power-down-an-arduino-for-5-minutes-at-a-time?noredirect=1> <https://electronics.stackexchange.com/questions/157704/stepper-motor-controller-using-leonardo-pro-micro?noredirect=1> <https://electronics.stackexchange.com/questions/157370/arduino-based-solid-state-drive?noredirect=1> <https://electronics.stackexchange.com/questions/157306/need-help-with-on-off-switch-to-power-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/157029/which-components-to-built-remapping-keyboard-via-usb-in-out-remapped?noredirect=1> <https://electronics.stackexchange.com/questions/156741/gps-skm53-arduino-not-worcking?noredirect=1> <https://electronics.stackexchange.com/questions/156558/arduino-dimmer-shield-schematics-interpretation?noredirect=1> <https://electronics.stackexchange.com/questions/156360/programing-other-atmel-arm-chips-using-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/155797/arduino-like-boards-with-other-microcontrollers?noredirect=1> --- Most questions have been automatically deleted at this point (about 30 days) --- <https://electronics.stackexchange.com/questions/149276/arduino-based-home-automation-system?noredirect=1> <https://electronics.stackexchange.com/questions/154173/error-code-10-for-arduino-device-driver?noredirect=1> <https://electronics.stackexchange.com/questions/154138/how-can-i-connect-the-canon-printer-8-pin-wifi-connector-to-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/154078/should-i-use-an-arduino-or-not?noredirect=1> <https://electronics.stackexchange.com/questions/153435/two-arduinos-send-data-via-analog-pin?noredirect=1> <https://electronics.stackexchange.com/questions/153161/one-ftdi-on-three-atmega?noredirect=1> <https://electronics.stackexchange.com/questions/153073/servo-buzz-millis?noredirect=1> <https://electronics.stackexchange.com/questions/153023/which-arduino-to-choose-nano-micro-or-micro-pro?noredirect=1> <https://electronics.stackexchange.com/questions/152417/how-do-i-write-a-debugger-for-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/152402/set-arduino-digitalread-reference-voltage?noredirect=1> <https://electronics.stackexchange.com/questions/151410/nrf24l01with-arduino-and-multiple-servos?noredirect=1> <https://electronics.stackexchange.com/questions/151062/how-can-i-make-pinmode-calls-faster?noredirect=1> <https://electronics.stackexchange.com/questions/150898/how-to-remove-adafruit-pro-trinket-bootloader-flashing-startup-sequence?noredirect=1> <https://electronics.stackexchange.com/questions/150755/how-do-i-replace-a-burnt-atmega328-with-a-new-atmega328bootloaded-in-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150475/arduino-uno-r3-not-recognized-by-computer-tx-and-rx-not-blinking-neither-are-l?noredirect=1> <https://electronics.stackexchange.com/questions/150417/connecting-relay-to-arduino-another-issue?noredirect=1> <https://electronics.stackexchange.com/questions/150313/how-are-arduinos-osh-if-atmel-avr-is-proprietary?noredirect=1> <https://electronics.stackexchange.com/questions/150290/replacing-the-voltage-regulator-of-a-fried-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150207/how-to-implement-an-arduiono-prototype?noredirect=1> <https://electronics.stackexchange.com/questions/150239/is-this-bluetooth-module-cool-for-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150163/arduino-cannot-communicate-with-pc-after-running-servo?noredirect=1> <https://electronics.stackexchange.com/questions/149961/program-read-93lc46b-with-an-arduino-with-bit-banging?noredirect=1> <https://electronics.stackexchange.com/questions/149890/turn-arduino-into-a-bootstrap-loader-for-msp430-programming?noredirect=1> <https://electronics.stackexchange.com/questions/149839/driving-conveyor-belts-using-arduino-unos?noredirect=1> <https://electronics.stackexchange.com/questions/149862/arduino-serial-hex-values?noredirect=1> <https://electronics.stackexchange.com/questions/149862/arduino-serial-hex-values?noredirect=1> <https://electronics.stackexchange.com/questions/149819/why-doesnt-this-motor-turn?noredirect=1> <https://electronics.stackexchange.com/questions/149295/dhcpaddressprinter-example-has-no-output-in-serial-monitor?noredirect=1> <https://electronics.stackexchange.com/questions/148090/arduino-two-ethernet-shields?noredirect=1> <https://electronics.stackexchange.com/questions/146752/are-there-any-kl03-arduinos?noredirect=1> <https://electronics.stackexchange.com/questions/146205/how-to-connect-gsm-with-arduino-and-dialling-number-from-hex-kepad?noredirect=1> <https://electronics.stackexchange.com/questions/146116/light-led-when-2-others-are-disconnected?noredirect=1> <https://electronics.stackexchange.com/questions/145971/arduino-power-consumption-issues?noredirect=1> <https://electronics.stackexchange.com/questions/145850/help-with-parts-identification-from-arduino-starter-kit-from-aliexpress?noredirect=1> <https://electronics.stackexchange.com/questions/145488/powering-arduino-from-a-shield?noredirect=1> <https://electronics.stackexchange.com/questions/145463/arduino-wifi-shield-not-present-error?noredirect=1> <https://electronics.stackexchange.com/questions/145330/can-an-arduino-micro-recieve-commands-from-another-microcontroller-when-hardwire?noredirect=1> <https://electronics.stackexchange.com/questions/145258/raspberry-pi-with-arduino-serial-connection-stops-working?noredirect=1> <https://electronics.stackexchange.com/questions/145023/controlling-arduino-from-raspberry-pi?noredirect=1>
You seem to be the primary agitator on this topic, and you also seem to still not understand the fundamental difference between Arduino users on one hand, and electronics hobbyists and student/professional EEs on the other. This difference has already been discussed extensively in your other questions. Yes, there's a considerable overlap in topics between the two groups, but Arduino users need answers that are specific to the Arduino hardware/software environment, and they're not likely to get those answers from EEs who are not very familiar with that environment. It's all about *context*, and the way that SE deals with context in general is to have separate sites. We've already discussed how the use of "meta-tags" to provide that context is not appropriate on SE. There's nothing wrong with EEs who *are* interested in Arduino belonging to both EE.SE and Arduino.SE and answering questions on each site as they see fit. And there's nothing wrong with directing Arduino users who show up here to a site where they'll feel more at home and get better (for them) answers. And if there are some who decide that they want to learn more about the underlying engineering issues, then they can belong to both sites, too.
5,159
I have taken a look at the [list of recently migrated Arduino questions](https://electronics.stackexchange.com/search?tab=newest&q=arduino%20migrated%3ayes). I thought we had reached the consensus that questions regarding Arduino that involve a good deal of electronics are fine on this site. But I still see many questions migrated. * [ATMega328P-PU and 328P-AU](https://electronics.stackexchange.com/posts/158962/revisions) about differences between ATMega chips, not specifically in Arduinos * [What bytes do I send to the MAX7221 to light an LED (in an led Matrix)?](https://electronics.stackexchange.com/posts/158868/revisions) about interfacing a non-Arduino chip, which happens to be done with an Arduino * [Arduino - millis()](https://electronics.stackexchange.com/posts/158323/revisions) about C, which happens to be about a function from the Arduino libraries but also applies in many other cases * [Arduino/C++ byte manipulation](https://electronics.stackexchange.com/posts/160146/revisions) has nothing to do with Arduino: simple C - if anywhere, it should've been migrated to SO I would like to do a **general suggestion** that if the **community agrees** according to vote counts on this question and its answers, **this type of questions be no longer migrated** or only if there seems to be support from the community (other than only from one or two). As a moderator you're still part of the community and there is no reason to migrate away the questions you don't like if there's no support for this within the community. Update ====== This question, [Operate Arduino Nano using variable voltage](https://electronics.stackexchange.com/q/160323/17592), was first migrated to Arduino. I had to flag it there to get it migrated back here. Such moving around of posts isn't be beneficial to anyone. **NB**: (without sufficient rep?) you won't see this in the post history, but it's really true. I flagged the post on Arduino.SE and asked for a migration back. Related: [Can we stop the random migrating?](https://electronics.meta.stackexchange.com/q/5149/17592); +22/-5; not a duplicate since this is a general request (which the other was as well actually, but this was massively misunderstood, even after emphasising that aspect of the question).
2015/03/15
[ "https://electronics.meta.stackexchange.com/questions/5159", "https://electronics.meta.stackexchange.com", "https://electronics.meta.stackexchange.com/users/-1/" ]
OK, so what's your opinion on [this question](https://electronics.stackexchange.com/questions/159998/anakog-input-not-going-zero)? A user has flagged it for migration, and three moderators have looked at it so far without taking action. And despite being our Arduino evangelist, you haven't answered or commented on it, either.
For me, there are a few issues that come into play here. The first is that plenty of arduino-tagged questions find a home here. <https://electronics.stackexchange.com/questions/tagged/arduino?sort=newest&pageSize=50> shows all the closed, migrated, and still open (and some yet to be closed) questions. Clearly, there is a line, and there is some disagreement on where it should be set, but I don't think that it's too far off from where it needs to be. You've red-flagged three migrations in ten days that you didn't like. Is it safe to assume that you're happy with the remainders, and all the Arduino-tagged that haven't migrated? If so, we're not talking about a huge proportion of Arduino questions here. A second point is that your arguments that this line isn't where it needs to be would be boosted big time if you took them one step further -- i.e., if you can go on to say "This question was migrated, and I don't think that the question got good answers at the Arduino SE." If the asker got the answer needed there, I don't see a problem. We're not hurting for good questions over here that badly yet. If the question got poor answers, but would have gotten fine answers here, then that's a compelling argument that perhaps migration was a mistake. The next issue comes from a mod at the Arduino site, who asked us to not migrate junk: <https://electronics.meta.stackexchange.com/a/5106/11684>. For me, I think that if its a question that requires specific knowledge of the Arduino platform or libraries, even if the question is pure gold, migration is not unreasonable -- especially if there's some subtext that makes it feel like the asker might appreciate an answer in the language of the Arduino community. The mods there would probably welcome some good questions migrated in that direction, and I hope that this cross exchange between the two sites can keep a user base with some real expertise engaged over there. Lastly, I can't say I know the ins and outs of migration, but the review tools certainly make it look like the mods at Arduino are perfectly free to turn down the migration. FWIW, for me, of the three you point out, I think the MAX7221 question could have comfortably stayed here, and might have gotten migrated simply because it says 'loop' instead of 'while (1)' in main. That said, maybe someone who is more familiar with the Arduino SPI.h can phrase the answer better for this particular asker. If not, the world is still turning
5,159
I have taken a look at the [list of recently migrated Arduino questions](https://electronics.stackexchange.com/search?tab=newest&q=arduino%20migrated%3ayes). I thought we had reached the consensus that questions regarding Arduino that involve a good deal of electronics are fine on this site. But I still see many questions migrated. * [ATMega328P-PU and 328P-AU](https://electronics.stackexchange.com/posts/158962/revisions) about differences between ATMega chips, not specifically in Arduinos * [What bytes do I send to the MAX7221 to light an LED (in an led Matrix)?](https://electronics.stackexchange.com/posts/158868/revisions) about interfacing a non-Arduino chip, which happens to be done with an Arduino * [Arduino - millis()](https://electronics.stackexchange.com/posts/158323/revisions) about C, which happens to be about a function from the Arduino libraries but also applies in many other cases * [Arduino/C++ byte manipulation](https://electronics.stackexchange.com/posts/160146/revisions) has nothing to do with Arduino: simple C - if anywhere, it should've been migrated to SO I would like to do a **general suggestion** that if the **community agrees** according to vote counts on this question and its answers, **this type of questions be no longer migrated** or only if there seems to be support from the community (other than only from one or two). As a moderator you're still part of the community and there is no reason to migrate away the questions you don't like if there's no support for this within the community. Update ====== This question, [Operate Arduino Nano using variable voltage](https://electronics.stackexchange.com/q/160323/17592), was first migrated to Arduino. I had to flag it there to get it migrated back here. Such moving around of posts isn't be beneficial to anyone. **NB**: (without sufficient rep?) you won't see this in the post history, but it's really true. I flagged the post on Arduino.SE and asked for a migration back. Related: [Can we stop the random migrating?](https://electronics.meta.stackexchange.com/q/5149/17592); +22/-5; not a duplicate since this is a general request (which the other was as well actually, but this was massively misunderstood, even after emphasising that aspect of the question).
2015/03/15
[ "https://electronics.meta.stackexchange.com/questions/5159", "https://electronics.meta.stackexchange.com", "https://electronics.meta.stackexchange.com/users/-1/" ]
Part of the reason why (I think) migrations are so frustrating from a community perspective is that there is no recourse if the community disagrees with the migration. In fact, the only way to undo a migration is to coordinate with the moderators of the target site to close the question, and then it can be "bounced back" to the original site. This makes migrations an unchangeable moderator action, instead of a normal close vote. I started asking myself *"How many bad migrations are we getting?"*, as that really sets the tone of this discussion. Here are some numbers to bring facts into the discussion. In the last 90 days, 78 questions have been migrated to Arduino.SE. Of those 78 questions, 4 have been rejected. While that sounds like a good number, it's worth noting that there are some different dynamics on Arduino.SE in the sense that they are a smaller beta site and don't quite have the numbers required to close questions by community. This is part of the reason why migrations to relatively new sites is discouraged - they don't have as much capability to deal with bad questions. Below is a list of questions migrated to Arduino.se in the last 90 days or so. This is not all of them as I seem to have missed some, but it's most of them (and I didn't intentionally omit questions). Some of them are deleted. From the perspective of migrating solid EE questions with a hint of Arduino, it doesn't seem so bad at first glance. <https://electronics.stackexchange.com/questions/160389/saving-arduino-output-to-a-text-file-in-append-mode?noredirect=1> <https://electronics.stackexchange.com/questions/160412/gsm-modem-with-max232-to-arduino-serial?noredirect=1> <https://electronics.stackexchange.com/questions/160255/how-to-do-serial-monitor-with-arduino-yun?noredirect=1> <https://electronics.stackexchange.com/questions/160269/seeedstudio-wifi-shield-v1-1-not-working-with-arduino-mega-2560?noredirect=1> <https://electronics.stackexchange.com/questions/160146/arduino-c-byte-manipulation?noredirect=1> <https://electronics.stackexchange.com/questions/159998/anakog-input-not-going-zero?noredirect=1> <https://electronics.stackexchange.com/questions/160005/ethernet-shield-not-getting-ip?noredirect=1> <https://electronics.stackexchange.com/questions/159960/arduino-unstable-analog-reading-when-using-power-supply?noredirect=1> <https://electronics.stackexchange.com/questions/159910/operate-arduino-nano-using-variable-voltage?noredirect=1> <https://electronics.stackexchange.com/questions/159789/using-an-arduino-uno-to-program-a-standalone-atmega2560?noredirect=1> <https://electronics.stackexchange.com/questions/159761/arduino-mega-number-of-simultaneous-pulse-inputs?noredirect=1> <https://electronics.stackexchange.com/questions/157859/is-it-possible-to-connect-many-arduino-uno-in-one-pc?noredirect=1> <https://electronics.stackexchange.com/questions/158962/atmega328p-pu-and-328p-au?noredirect=1> <https://electronics.stackexchange.com/questions/158940/arduino-sainsmart-uno-communication-problem?noredirect=1> <https://electronics.stackexchange.com/questions/158868/what-bytes-do-i-send-to-the-max7221-to-light-an-led-in-an-led-matrix?noredirect=1> <https://electronics.stackexchange.com/questions/158323/arduino-millis?noredirect=1> <https://electronics.stackexchange.com/questions/157919/arduino-how-to-accept-user-input-array-variables?noredirect=1> <https://electronics.stackexchange.com/questions/156885/how-best-to-power-down-an-arduino-for-5-minutes-at-a-time?noredirect=1> <https://electronics.stackexchange.com/questions/157704/stepper-motor-controller-using-leonardo-pro-micro?noredirect=1> <https://electronics.stackexchange.com/questions/157370/arduino-based-solid-state-drive?noredirect=1> <https://electronics.stackexchange.com/questions/157306/need-help-with-on-off-switch-to-power-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/157029/which-components-to-built-remapping-keyboard-via-usb-in-out-remapped?noredirect=1> <https://electronics.stackexchange.com/questions/156741/gps-skm53-arduino-not-worcking?noredirect=1> <https://electronics.stackexchange.com/questions/156558/arduino-dimmer-shield-schematics-interpretation?noredirect=1> <https://electronics.stackexchange.com/questions/156360/programing-other-atmel-arm-chips-using-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/155797/arduino-like-boards-with-other-microcontrollers?noredirect=1> --- Most questions have been automatically deleted at this point (about 30 days) --- <https://electronics.stackexchange.com/questions/149276/arduino-based-home-automation-system?noredirect=1> <https://electronics.stackexchange.com/questions/154173/error-code-10-for-arduino-device-driver?noredirect=1> <https://electronics.stackexchange.com/questions/154138/how-can-i-connect-the-canon-printer-8-pin-wifi-connector-to-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/154078/should-i-use-an-arduino-or-not?noredirect=1> <https://electronics.stackexchange.com/questions/153435/two-arduinos-send-data-via-analog-pin?noredirect=1> <https://electronics.stackexchange.com/questions/153161/one-ftdi-on-three-atmega?noredirect=1> <https://electronics.stackexchange.com/questions/153073/servo-buzz-millis?noredirect=1> <https://electronics.stackexchange.com/questions/153023/which-arduino-to-choose-nano-micro-or-micro-pro?noredirect=1> <https://electronics.stackexchange.com/questions/152417/how-do-i-write-a-debugger-for-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/152402/set-arduino-digitalread-reference-voltage?noredirect=1> <https://electronics.stackexchange.com/questions/151410/nrf24l01with-arduino-and-multiple-servos?noredirect=1> <https://electronics.stackexchange.com/questions/151062/how-can-i-make-pinmode-calls-faster?noredirect=1> <https://electronics.stackexchange.com/questions/150898/how-to-remove-adafruit-pro-trinket-bootloader-flashing-startup-sequence?noredirect=1> <https://electronics.stackexchange.com/questions/150755/how-do-i-replace-a-burnt-atmega328-with-a-new-atmega328bootloaded-in-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150475/arduino-uno-r3-not-recognized-by-computer-tx-and-rx-not-blinking-neither-are-l?noredirect=1> <https://electronics.stackexchange.com/questions/150417/connecting-relay-to-arduino-another-issue?noredirect=1> <https://electronics.stackexchange.com/questions/150313/how-are-arduinos-osh-if-atmel-avr-is-proprietary?noredirect=1> <https://electronics.stackexchange.com/questions/150290/replacing-the-voltage-regulator-of-a-fried-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150207/how-to-implement-an-arduiono-prototype?noredirect=1> <https://electronics.stackexchange.com/questions/150239/is-this-bluetooth-module-cool-for-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150163/arduino-cannot-communicate-with-pc-after-running-servo?noredirect=1> <https://electronics.stackexchange.com/questions/149961/program-read-93lc46b-with-an-arduino-with-bit-banging?noredirect=1> <https://electronics.stackexchange.com/questions/149890/turn-arduino-into-a-bootstrap-loader-for-msp430-programming?noredirect=1> <https://electronics.stackexchange.com/questions/149839/driving-conveyor-belts-using-arduino-unos?noredirect=1> <https://electronics.stackexchange.com/questions/149862/arduino-serial-hex-values?noredirect=1> <https://electronics.stackexchange.com/questions/149862/arduino-serial-hex-values?noredirect=1> <https://electronics.stackexchange.com/questions/149819/why-doesnt-this-motor-turn?noredirect=1> <https://electronics.stackexchange.com/questions/149295/dhcpaddressprinter-example-has-no-output-in-serial-monitor?noredirect=1> <https://electronics.stackexchange.com/questions/148090/arduino-two-ethernet-shields?noredirect=1> <https://electronics.stackexchange.com/questions/146752/are-there-any-kl03-arduinos?noredirect=1> <https://electronics.stackexchange.com/questions/146205/how-to-connect-gsm-with-arduino-and-dialling-number-from-hex-kepad?noredirect=1> <https://electronics.stackexchange.com/questions/146116/light-led-when-2-others-are-disconnected?noredirect=1> <https://electronics.stackexchange.com/questions/145971/arduino-power-consumption-issues?noredirect=1> <https://electronics.stackexchange.com/questions/145850/help-with-parts-identification-from-arduino-starter-kit-from-aliexpress?noredirect=1> <https://electronics.stackexchange.com/questions/145488/powering-arduino-from-a-shield?noredirect=1> <https://electronics.stackexchange.com/questions/145463/arduino-wifi-shield-not-present-error?noredirect=1> <https://electronics.stackexchange.com/questions/145330/can-an-arduino-micro-recieve-commands-from-another-microcontroller-when-hardwire?noredirect=1> <https://electronics.stackexchange.com/questions/145258/raspberry-pi-with-arduino-serial-connection-stops-working?noredirect=1> <https://electronics.stackexchange.com/questions/145023/controlling-arduino-from-raspberry-pi?noredirect=1>
OK, so what's your opinion on [this question](https://electronics.stackexchange.com/questions/159998/anakog-input-not-going-zero)? A user has flagged it for migration, and three moderators have looked at it so far without taking action. And despite being our Arduino evangelist, you haven't answered or commented on it, either.
5,159
I have taken a look at the [list of recently migrated Arduino questions](https://electronics.stackexchange.com/search?tab=newest&q=arduino%20migrated%3ayes). I thought we had reached the consensus that questions regarding Arduino that involve a good deal of electronics are fine on this site. But I still see many questions migrated. * [ATMega328P-PU and 328P-AU](https://electronics.stackexchange.com/posts/158962/revisions) about differences between ATMega chips, not specifically in Arduinos * [What bytes do I send to the MAX7221 to light an LED (in an led Matrix)?](https://electronics.stackexchange.com/posts/158868/revisions) about interfacing a non-Arduino chip, which happens to be done with an Arduino * [Arduino - millis()](https://electronics.stackexchange.com/posts/158323/revisions) about C, which happens to be about a function from the Arduino libraries but also applies in many other cases * [Arduino/C++ byte manipulation](https://electronics.stackexchange.com/posts/160146/revisions) has nothing to do with Arduino: simple C - if anywhere, it should've been migrated to SO I would like to do a **general suggestion** that if the **community agrees** according to vote counts on this question and its answers, **this type of questions be no longer migrated** or only if there seems to be support from the community (other than only from one or two). As a moderator you're still part of the community and there is no reason to migrate away the questions you don't like if there's no support for this within the community. Update ====== This question, [Operate Arduino Nano using variable voltage](https://electronics.stackexchange.com/q/160323/17592), was first migrated to Arduino. I had to flag it there to get it migrated back here. Such moving around of posts isn't be beneficial to anyone. **NB**: (without sufficient rep?) you won't see this in the post history, but it's really true. I flagged the post on Arduino.SE and asked for a migration back. Related: [Can we stop the random migrating?](https://electronics.meta.stackexchange.com/q/5149/17592); +22/-5; not a duplicate since this is a general request (which the other was as well actually, but this was massively misunderstood, even after emphasising that aspect of the question).
2015/03/15
[ "https://electronics.meta.stackexchange.com/questions/5159", "https://electronics.meta.stackexchange.com", "https://electronics.meta.stackexchange.com/users/-1/" ]
Part of the reason why (I think) migrations are so frustrating from a community perspective is that there is no recourse if the community disagrees with the migration. In fact, the only way to undo a migration is to coordinate with the moderators of the target site to close the question, and then it can be "bounced back" to the original site. This makes migrations an unchangeable moderator action, instead of a normal close vote. I started asking myself *"How many bad migrations are we getting?"*, as that really sets the tone of this discussion. Here are some numbers to bring facts into the discussion. In the last 90 days, 78 questions have been migrated to Arduino.SE. Of those 78 questions, 4 have been rejected. While that sounds like a good number, it's worth noting that there are some different dynamics on Arduino.SE in the sense that they are a smaller beta site and don't quite have the numbers required to close questions by community. This is part of the reason why migrations to relatively new sites is discouraged - they don't have as much capability to deal with bad questions. Below is a list of questions migrated to Arduino.se in the last 90 days or so. This is not all of them as I seem to have missed some, but it's most of them (and I didn't intentionally omit questions). Some of them are deleted. From the perspective of migrating solid EE questions with a hint of Arduino, it doesn't seem so bad at first glance. <https://electronics.stackexchange.com/questions/160389/saving-arduino-output-to-a-text-file-in-append-mode?noredirect=1> <https://electronics.stackexchange.com/questions/160412/gsm-modem-with-max232-to-arduino-serial?noredirect=1> <https://electronics.stackexchange.com/questions/160255/how-to-do-serial-monitor-with-arduino-yun?noredirect=1> <https://electronics.stackexchange.com/questions/160269/seeedstudio-wifi-shield-v1-1-not-working-with-arduino-mega-2560?noredirect=1> <https://electronics.stackexchange.com/questions/160146/arduino-c-byte-manipulation?noredirect=1> <https://electronics.stackexchange.com/questions/159998/anakog-input-not-going-zero?noredirect=1> <https://electronics.stackexchange.com/questions/160005/ethernet-shield-not-getting-ip?noredirect=1> <https://electronics.stackexchange.com/questions/159960/arduino-unstable-analog-reading-when-using-power-supply?noredirect=1> <https://electronics.stackexchange.com/questions/159910/operate-arduino-nano-using-variable-voltage?noredirect=1> <https://electronics.stackexchange.com/questions/159789/using-an-arduino-uno-to-program-a-standalone-atmega2560?noredirect=1> <https://electronics.stackexchange.com/questions/159761/arduino-mega-number-of-simultaneous-pulse-inputs?noredirect=1> <https://electronics.stackexchange.com/questions/157859/is-it-possible-to-connect-many-arduino-uno-in-one-pc?noredirect=1> <https://electronics.stackexchange.com/questions/158962/atmega328p-pu-and-328p-au?noredirect=1> <https://electronics.stackexchange.com/questions/158940/arduino-sainsmart-uno-communication-problem?noredirect=1> <https://electronics.stackexchange.com/questions/158868/what-bytes-do-i-send-to-the-max7221-to-light-an-led-in-an-led-matrix?noredirect=1> <https://electronics.stackexchange.com/questions/158323/arduino-millis?noredirect=1> <https://electronics.stackexchange.com/questions/157919/arduino-how-to-accept-user-input-array-variables?noredirect=1> <https://electronics.stackexchange.com/questions/156885/how-best-to-power-down-an-arduino-for-5-minutes-at-a-time?noredirect=1> <https://electronics.stackexchange.com/questions/157704/stepper-motor-controller-using-leonardo-pro-micro?noredirect=1> <https://electronics.stackexchange.com/questions/157370/arduino-based-solid-state-drive?noredirect=1> <https://electronics.stackexchange.com/questions/157306/need-help-with-on-off-switch-to-power-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/157029/which-components-to-built-remapping-keyboard-via-usb-in-out-remapped?noredirect=1> <https://electronics.stackexchange.com/questions/156741/gps-skm53-arduino-not-worcking?noredirect=1> <https://electronics.stackexchange.com/questions/156558/arduino-dimmer-shield-schematics-interpretation?noredirect=1> <https://electronics.stackexchange.com/questions/156360/programing-other-atmel-arm-chips-using-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/155797/arduino-like-boards-with-other-microcontrollers?noredirect=1> --- Most questions have been automatically deleted at this point (about 30 days) --- <https://electronics.stackexchange.com/questions/149276/arduino-based-home-automation-system?noredirect=1> <https://electronics.stackexchange.com/questions/154173/error-code-10-for-arduino-device-driver?noredirect=1> <https://electronics.stackexchange.com/questions/154138/how-can-i-connect-the-canon-printer-8-pin-wifi-connector-to-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/154078/should-i-use-an-arduino-or-not?noredirect=1> <https://electronics.stackexchange.com/questions/153435/two-arduinos-send-data-via-analog-pin?noredirect=1> <https://electronics.stackexchange.com/questions/153161/one-ftdi-on-three-atmega?noredirect=1> <https://electronics.stackexchange.com/questions/153073/servo-buzz-millis?noredirect=1> <https://electronics.stackexchange.com/questions/153023/which-arduino-to-choose-nano-micro-or-micro-pro?noredirect=1> <https://electronics.stackexchange.com/questions/152417/how-do-i-write-a-debugger-for-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/152402/set-arduino-digitalread-reference-voltage?noredirect=1> <https://electronics.stackexchange.com/questions/151410/nrf24l01with-arduino-and-multiple-servos?noredirect=1> <https://electronics.stackexchange.com/questions/151062/how-can-i-make-pinmode-calls-faster?noredirect=1> <https://electronics.stackexchange.com/questions/150898/how-to-remove-adafruit-pro-trinket-bootloader-flashing-startup-sequence?noredirect=1> <https://electronics.stackexchange.com/questions/150755/how-do-i-replace-a-burnt-atmega328-with-a-new-atmega328bootloaded-in-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150475/arduino-uno-r3-not-recognized-by-computer-tx-and-rx-not-blinking-neither-are-l?noredirect=1> <https://electronics.stackexchange.com/questions/150417/connecting-relay-to-arduino-another-issue?noredirect=1> <https://electronics.stackexchange.com/questions/150313/how-are-arduinos-osh-if-atmel-avr-is-proprietary?noredirect=1> <https://electronics.stackexchange.com/questions/150290/replacing-the-voltage-regulator-of-a-fried-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150207/how-to-implement-an-arduiono-prototype?noredirect=1> <https://electronics.stackexchange.com/questions/150239/is-this-bluetooth-module-cool-for-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150163/arduino-cannot-communicate-with-pc-after-running-servo?noredirect=1> <https://electronics.stackexchange.com/questions/149961/program-read-93lc46b-with-an-arduino-with-bit-banging?noredirect=1> <https://electronics.stackexchange.com/questions/149890/turn-arduino-into-a-bootstrap-loader-for-msp430-programming?noredirect=1> <https://electronics.stackexchange.com/questions/149839/driving-conveyor-belts-using-arduino-unos?noredirect=1> <https://electronics.stackexchange.com/questions/149862/arduino-serial-hex-values?noredirect=1> <https://electronics.stackexchange.com/questions/149862/arduino-serial-hex-values?noredirect=1> <https://electronics.stackexchange.com/questions/149819/why-doesnt-this-motor-turn?noredirect=1> <https://electronics.stackexchange.com/questions/149295/dhcpaddressprinter-example-has-no-output-in-serial-monitor?noredirect=1> <https://electronics.stackexchange.com/questions/148090/arduino-two-ethernet-shields?noredirect=1> <https://electronics.stackexchange.com/questions/146752/are-there-any-kl03-arduinos?noredirect=1> <https://electronics.stackexchange.com/questions/146205/how-to-connect-gsm-with-arduino-and-dialling-number-from-hex-kepad?noredirect=1> <https://electronics.stackexchange.com/questions/146116/light-led-when-2-others-are-disconnected?noredirect=1> <https://electronics.stackexchange.com/questions/145971/arduino-power-consumption-issues?noredirect=1> <https://electronics.stackexchange.com/questions/145850/help-with-parts-identification-from-arduino-starter-kit-from-aliexpress?noredirect=1> <https://electronics.stackexchange.com/questions/145488/powering-arduino-from-a-shield?noredirect=1> <https://electronics.stackexchange.com/questions/145463/arduino-wifi-shield-not-present-error?noredirect=1> <https://electronics.stackexchange.com/questions/145330/can-an-arduino-micro-recieve-commands-from-another-microcontroller-when-hardwire?noredirect=1> <https://electronics.stackexchange.com/questions/145258/raspberry-pi-with-arduino-serial-connection-stops-working?noredirect=1> <https://electronics.stackexchange.com/questions/145023/controlling-arduino-from-raspberry-pi?noredirect=1>
For me, there are a few issues that come into play here. The first is that plenty of arduino-tagged questions find a home here. <https://electronics.stackexchange.com/questions/tagged/arduino?sort=newest&pageSize=50> shows all the closed, migrated, and still open (and some yet to be closed) questions. Clearly, there is a line, and there is some disagreement on where it should be set, but I don't think that it's too far off from where it needs to be. You've red-flagged three migrations in ten days that you didn't like. Is it safe to assume that you're happy with the remainders, and all the Arduino-tagged that haven't migrated? If so, we're not talking about a huge proportion of Arduino questions here. A second point is that your arguments that this line isn't where it needs to be would be boosted big time if you took them one step further -- i.e., if you can go on to say "This question was migrated, and I don't think that the question got good answers at the Arduino SE." If the asker got the answer needed there, I don't see a problem. We're not hurting for good questions over here that badly yet. If the question got poor answers, but would have gotten fine answers here, then that's a compelling argument that perhaps migration was a mistake. The next issue comes from a mod at the Arduino site, who asked us to not migrate junk: <https://electronics.meta.stackexchange.com/a/5106/11684>. For me, I think that if its a question that requires specific knowledge of the Arduino platform or libraries, even if the question is pure gold, migration is not unreasonable -- especially if there's some subtext that makes it feel like the asker might appreciate an answer in the language of the Arduino community. The mods there would probably welcome some good questions migrated in that direction, and I hope that this cross exchange between the two sites can keep a user base with some real expertise engaged over there. Lastly, I can't say I know the ins and outs of migration, but the review tools certainly make it look like the mods at Arduino are perfectly free to turn down the migration. FWIW, for me, of the three you point out, I think the MAX7221 question could have comfortably stayed here, and might have gotten migrated simply because it says 'loop' instead of 'while (1)' in main. That said, maybe someone who is more familiar with the Arduino SPI.h can phrase the answer better for this particular asker. If not, the world is still turning
52,670,062
I am using Gradle 4.1 with Gradle-Android plugin 3.0.1 on Android Studio 3.2 I have 2 flavors 'production' and 'staging' and I am unable to build my project as a library with different build variants. **app build.gradle:** ``` apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' android { ... productFlavors { production { } staging { } } defaultPublishConfig "productionRelease" publishNonDefault true } if( android.productFlavors.size() > 0 ) { android.libraryVariants.all { variant -> if( android.publishNonDefault && variant.name == android.defaultPublishConfig ) { def bundleTask = tasks["bundle${name.capitalize()}"] artifacts { archives(bundleTask.archivePath) { classifier name.replace('-' + variant.name, '') builtBy bundleTask name name.replace('-' + variant.name, '') } } } ``` ... Then I run: ./gradlew clean install, errors I got is: Execution failed for task ‘:app:install’. > > Could not publish configuration ‘archives’ > A POM cannot have multiple artifacts with the same type and classifier. Already have MavenArtifact app:aar:aar:null, trying to add MavenArtifact app:aar:aar:null. > > > And to get this code to compile, I need to swap **android.publishNonDefault** with **true**, otherwise I will get an error of: `Cannot get the value of write-only property 'publishNonDefault'` Any suggestions or hint would be really helpful, the aim is to build the library module on jitpack, where we can import it in project with build variants. thanks!
2018/10/05
[ "https://Stackoverflow.com/questions/52670062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2099298/" ]
After digging into this for 2 days, and emailing Jitpack support, the issue is because the lib has updated and **publishNonDefault** is deprecated. you just need to change your app build.gradle to: ``` apply plugin: 'com.github.dcendents.android-maven' dependencies {...} group = 'com.github.your-group' if (android.productFlavors.size() > 0) { android.libraryVariants.all { variant -> if (variant.name.toLowerCase().contains("debug")) { return } def bundleTask = tasks["bundle${variant.name.capitalize()}"] artifacts { archives(bundleTask.archivePath) { classifier variant.flavorName builtBy bundleTask name = project.name } } } } ```
problem was to create multiple flavors using jitpack so what I do is, create a variable which stores the flavor name, after that loop through the available variant, pass the `flavorBuild` to `artifact` so when u push the code to GitHub and create artifact via jitpack then jitpack create the required implementation based on your build flavor and then u can use it. You need to just change build flavor ``` publishing { publications { def flavorBuild ='production' android.libraryVariants.all { variant -> "maven${variant.name.capitalize()}Aar"(MavenPublication) { from components.findByName("android${variant.name.capitalize()}") groupId = 'com.examplesdk' artifactId = 'examplesdk' version "1.0.0-${variant.name}" artifact "$buildDir/outputs/aar/examplesdk-${flavorBuild}-release.aar" pom.withXml { def dependenciesNode = asNode().appendNode('dependencies') configurations.api.allDependencies.each { dependency -> def dependencyNode = dependenciesNode.appendNode('dependency') dependencyNode.appendNode('groupId', dependency.group) dependencyNode.appendNode('artifactId', dependency.name) dependencyNode.appendNode('version', dependency.version) } } } } } repositories{ maven { url "$buildDir/repo" } } } ```
901,190
I'm trying to enable Windows Hyper-V replication over WAN. I have (finally!) been able to achieve this in a test environment over LAN using the certificate-based authentication method (rather than Kerberos) and have been able to successfully get two servers to replicate using the hostname. My confusion now is that I do not know how to get them to communicate over the WAN for the purpose of replication. In production, I currently have one server (Win 2012 R2) sat in a datacentre and the intention is to spin up another server to take the replication, but this will be in another datacentre, connected only via the internet using external IP addresses. There is no active directory in place, they are just in a workgroup. I'd rather not set up AD or DC just for this (unless I really have to). I already have an A record pointing towards the server (via our domain names provider), so it has an entry in the form of server1.domain.com. So I have server1.domain.com pointing to external IP address, which reaches the server correctly. In a test environment, this is what I have done so far. Both servers are Windows 2012 R2. Server 1 is the main host server with a number of VM's, it's named SERVER1 (Computer Name) Server 2 has been spun up to take the replication of the VM's from server 1, it's named SERVER2. They are currently connected internally only via internal network and internal IP addresses. As mentioned above, I have successfully achieved replication between SERVER1 and SERVER2 using certificate-based authentication and it works correctly, but this is using the computer name SERVER2 as a destination replication server. Obviously once this is in a production environment, this method will not be possible. My question is, how do I set this up so that SERVER1 can see SERVER2 across a WAN (for the purpose of Hyper-V replica) where there is no active directory. How will they resolve? Do I make an entry on the HOSTS file? If so, what should I enter? Is it as easy as SERVER1 External IP address of SERVER1 SERVER2 External IP address of SERVER2 Or do I point it to the FQDN (which is created as an A record) in the format: SERVER1 SERVER1.domain.com SERVER2 SERVER2.domain.com I'd appreciate any assistance on this as I'm currently a bit stuck and as I'm currently unable to test this is a live production environment I'd rather go in with as much knowledge as possible. Thank you.
2018/03/12
[ "https://serverfault.com/questions/901190", "https://serverfault.com", "https://serverfault.com/users/197330/" ]
I am afraid this not an answer to what you currently have. What you should be running for your configuration, (ie no AD, no shared storage)is a shared nothing configuration supported on Windows Server 2016. <https://social.technet.microsoft.com/Forums/windows/en-US/e14e7171-d8fb-418c-9e9e-b3883f4c4ea3/windows-2016-2node-shared-nothing-stretched-cluster-with-storage-replicas?forum=winserverClustering> <https://www.starwindsoftware.com/blog/part-2-storage-replica-with-microsoft-failover-cluster-and-scale-out-file-server-role-windows-server-technical-preview>
So after a bit of playing around I was able to resolve this by entering the hostname of the Replica server in the Host server and making an entry in the HOSTS file that points the hostname to the IP address. It wasn't that difficult in the end.
41,366,113
i made a query that shows the result i want (close enough)... but it's not perfect as should be. I'm counting the number of registers per user.. The SQL: ``` SELECT us.name, _reg FROM tb_user AS us LEFT JOIN tb_register as rg ON rg.iduser = us.iduser INNER JOIN (select rg.iduser, count(*) FROM tb_register AS rg group by rg.iduser) AS _reg ON rg.iduser = _reg.iduser GROUP BY us.name, _reg ``` The result i get is something like... ``` +-----------+-----------------+ | name | _reg | +-----------+-----------------+ | example_A | (id_A, count_A) | +-----------+-----------------+ | example_B | (id_B, count_B) | +-----------+-----------------+ ``` But what i really want is just name and the row count.. I'm using in the subquery "rg.iduser" to reference in this INNER JOIN, but because of that, i get the "iduser" in the result. **Is there a better way to do that to show what i want.. or a way to hide the "iduser" in the result of this query?** Thanks..
2016/12/28
[ "https://Stackoverflow.com/questions/41366113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6226487/" ]
Gordon's answer shows you a better way to do the query. But I'd like to explain *why* you are seeing both columns in the output: You are using the alias for the derived table `_reg` in the select list, which means you are retrieving every row from that derived table as an anonymous record. If you just want the count, then give that column a proper alias and reference the *column* in the outer select, not the *row*: Also the `group by` in the outer select seems useless: ``` SELECT us.name, **\_reg.cnt** --<< HERE FROM tb_user AS us LEFT JOIN tb_register as rg ON rg.iduser = us.iduser JOIN ( select rg.iduser, count(*) **as cnt** --<< HERE FROM tb_register AS rg group by rg.iduser ) AS _reg ON rg.iduser = _reg.iduser; ```
Just select the column you want. The query, though, is more simply written as: ``` SELECT us.name, COUNT(rg.iduser) FROM tb_user us LEFT JOIN tb_register rg ON rg.iduser = us.iduser GROUP BY us.name; ``` Given what you want in the result set, there is no need for a subquery. Note: I am assuming that a given name is unique and does not span multiple `iduser`s. Or, if it does, then you want the total count. Based on your question and sample data, this seems reasonable.
33,645
When looking at the [Gee Bee](https://en.wikipedia.org/wiki/Gee_Bee_Model_R): [![enter image description here](https://i.stack.imgur.com/AaprL.jpg)](https://i.stack.imgur.com/AaprL.jpg) [Source](http://photo.net/learn/airshow/GeeBee.html) I wonder what the pilot is actually able to see, when rolling on the runway, when flying level, or trying to locate a possible emergency landing place. It seems this aircraft puts the pilot and the people on the ground at risk. Wouldn't a mirror improve safety, or is there a hole in the bottom of the fuselage? How could such an aircraft be allowed to fly at the time? Did flying it only require to hold a recreational private pilot license or additional qualifications? Would it be allowed today in Europe, or in the US, based on existing regulation?
2016/12/04
[ "https://aviation.stackexchange.com/questions/33645", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/3201/" ]
At least it has a forward looking windshield. [![enter image description here](https://i.stack.imgur.com/3YuVf.jpg)](https://i.stack.imgur.com/3YuVf.jpg) ([Source](http://images.fineartamerica.com/images-medium-large/charles-lindbergh-flying-his-plane-everett.jpg)) *[Spirit of St. Louis](https://en.wikipedia.org/wiki/Spirit_of_St._Louis) that was flown solo by Charles Lindbergh on May 20–21, 1927, on the first solo non-stop transatlantic flight from Long Island, New York, to Paris, France.* [![enter image description here](https://i.stack.imgur.com/bNHUs.png)](https://i.stack.imgur.com/bNHUs.png) ([Source](http://www.charleslindbergh.com/plane/plane.gif)) [![enter image description here](https://i.stack.imgur.com/aT0yO.jpg)](https://i.stack.imgur.com/aT0yO.jpg) ([Source](https://aviation.stackexchange.com/a/26052)) *A 777-300 [needs a camera](https://aviation.stackexchange.com/a/26052) too to make cornering easier.* Like all tail-draggers, the pilot can be guided by a wing-sitter, or by taxiing in an S-shape. For landing, a little cross-control to crab will allow a side view of what's ahead. Above methods were/are very common for WWII-era planes with huge noses and a tail-dragger undercarriage. [![enter image description here](https://i.stack.imgur.com/e3i31m.png)](https://i.stack.imgur.com/e3i31.png) [![enter image description here](https://i.stack.imgur.com/Y3V6Km.jpg)](https://i.stack.imgur.com/Y3V6K.jpg) ([Left](http://www.354thpmfg.com/aircraft_p47thunderbolt.html), [right](https://i.pinimg.com/originals/51/dc/9a/51dc9a2af09949d3e03d7cd5ea42cff6.jpg)) Taxiing with wing-sitter assistance. Landing on big grass-fields makes it easier too. > > Would the Gee Bee be allowed to fly today? > > > The [Gee Bee](https://en.wikipedia.org/wiki/Gee_Bee_Model_R) was still flying airshows until 2002, so the answer is yes. [![enter image description here](https://i.stack.imgur.com/YmBlh.jpg)](https://i.stack.imgur.com/YmBlh.jpg) ([Source](https://en.wikipedia.org/wiki/File:GeeBee_R2_Oshkosh.jpg)) *Gee Bee R2 flown by Delmar Benjamin at Oshkosh 2001. Benjamin flew an aerobatic routine in this aircraft at numerous airshows until he retired the aircraft in 2002.*
This YouTube video shows the view from an RC model of the plane.
33,645
When looking at the [Gee Bee](https://en.wikipedia.org/wiki/Gee_Bee_Model_R): [![enter image description here](https://i.stack.imgur.com/AaprL.jpg)](https://i.stack.imgur.com/AaprL.jpg) [Source](http://photo.net/learn/airshow/GeeBee.html) I wonder what the pilot is actually able to see, when rolling on the runway, when flying level, or trying to locate a possible emergency landing place. It seems this aircraft puts the pilot and the people on the ground at risk. Wouldn't a mirror improve safety, or is there a hole in the bottom of the fuselage? How could such an aircraft be allowed to fly at the time? Did flying it only require to hold a recreational private pilot license or additional qualifications? Would it be allowed today in Europe, or in the US, based on existing regulation?
2016/12/04
[ "https://aviation.stackexchange.com/questions/33645", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/3201/" ]
The reasons such aircraft (including Spirit of St.Louis as pointed out by @ymb) were allowed to fly are explained in [another answer](https://aviation.stackexchange.com/a/7877/9731). Quoting from it: > > You don't need a panoramic view to land, ... Navigation is easy enough through side windows ... and you can just yaw the plane left and right for the times you do want to line up with something. > > > Even today, tail draggers have basically zero forward visibility on the ground so they taxi by watching the edge of the pavement with the occasional sharp s-turn to check ahead. > > > As for certification requirements, you can get an experimental certificate and fly it. FAA [issues experimental certificates for racing aircraft](http://www.ecfr.gov/cgi-bin/text-idx?node=pt14.1.21&rgn=div5#se14.1.21_1191): > > §21.191 Experimental certificates. > > > Experimental certificates are issued for the following purposes: > > > (e) Air racing. Participating in air races, including (for such participants) practicing for such air races and flying to and from racing events. > > > GeeBee R2 was flying as recently as 2001 (not *that* recent, i know), so I'm pretty sure someone can fly it if they are upto it. FAA [requires special pilot authorization](https://www.faa.gov/licenses_certificates/vintage_experimental/guidance/) for this kind of aircraft: > > What type of experimental aircraft requires an FAA issued authorization? > > > This information applies to pilots of aircraft to which the FAA has issued Special Airworthiness Certificates for the purpose of Experimental under Title 14 CFR section 21.191 and are one of the following: > > > * "Large" aircraft (more than 12,500 pounds), > * Turbojet powered, or > * Airplanes that have a VNE (never exceed speed) in excess of 250 KIAS and more than 800 HP. > > >
This YouTube video shows the view from an RC model of the plane.
52,430,353
``` using System; class MainClass { public static void Main (string[] args) { bool loop1 = true; while(loop1) { Console.WriteLine("\nEnter the base length"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); continue; } Console.WriteLine("\nEnter the perpendicular height"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); } Console.WriteLine(area(length,height)); } } static int area(int length, int height) { return length * height/2; } } ``` I get the error > > exit status 1 > main.cs(28,40): error CS0103: The name `length' does not exist in the current context > main.cs(28,47): error CS0103: The name`height' does not exist in the current context > Compilation failed: 2 error(s), 0 warnings > > >
2018/09/20
[ "https://Stackoverflow.com/questions/52430353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10392786/" ]
You are declaring your variables inside the try, you need to move the declaration outside the try statement. I think this will fix it. Plus your declaring length twice, I think that was a typo and should have been height. ``` using System; class MainClass { public static void Main (string[] args) { int length = 0; int height = 0; bool loop1 = true; while(loop1) { Console.WriteLine("\nEnter the base length"); try { length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); continue; } Console.WriteLine("\nEnter the perpendicular height"); try { height = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); } Console.WriteLine(area(length,height)); }// end while }// end main static int area(int length, int height) { return length * height/2; } }// end calss ```
The reason for this error is your defined variable `int length` is scoped inside curly braces `{ }`. So the variable is only available inside the brace it is defined. To be able to access the variable as you want, you have to define length at the start outside try block.
52,430,353
``` using System; class MainClass { public static void Main (string[] args) { bool loop1 = true; while(loop1) { Console.WriteLine("\nEnter the base length"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); continue; } Console.WriteLine("\nEnter the perpendicular height"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); } Console.WriteLine(area(length,height)); } } static int area(int length, int height) { return length * height/2; } } ``` I get the error > > exit status 1 > main.cs(28,40): error CS0103: The name `length' does not exist in the current context > main.cs(28,47): error CS0103: The name`height' does not exist in the current context > Compilation failed: 2 error(s), 0 warnings > > >
2018/09/20
[ "https://Stackoverflow.com/questions/52430353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10392786/" ]
You are declaring your variables inside the try, you need to move the declaration outside the try statement. I think this will fix it. Plus your declaring length twice, I think that was a typo and should have been height. ``` using System; class MainClass { public static void Main (string[] args) { int length = 0; int height = 0; bool loop1 = true; while(loop1) { Console.WriteLine("\nEnter the base length"); try { length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); continue; } Console.WriteLine("\nEnter the perpendicular height"); try { height = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); } Console.WriteLine(area(length,height)); }// end while }// end main static int area(int length, int height) { return length * height/2; } }// end calss ```
Specifically addressing the "Use of unassigned local variable 'height'" message... This normally happens if you try to reference a variable that has never been assigned a value. Something like the following will trigger this error message: ``` int x; Console.WriteLine(x); ``` Does the "Use of unassigned local variable 'height'" message happen when you enter invalid input that can't be cast as an integer? Entering something like "x" or "1.5" for length will cause the `Convert.ToInt32()` call to throw an exception, meaning that your `length` variable will not have anything assigned to it when the call to `Console.WriteLine(area(length,height));` happens later. You can fix/prevent this by initializing your variable when they are declared: ``` int length = 0; int height = 0; ``` Now the variables are initialized and you won't see the "Use of unassigned local variable 'height'" message. You'll probably get `0` as your calculated area, but that's a different issue entirely. :) I'm making assumptions about your input, but that's the only way I can think of to replicate the error you're seeing.
52,430,353
``` using System; class MainClass { public static void Main (string[] args) { bool loop1 = true; while(loop1) { Console.WriteLine("\nEnter the base length"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); continue; } Console.WriteLine("\nEnter the perpendicular height"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); } Console.WriteLine(area(length,height)); } } static int area(int length, int height) { return length * height/2; } } ``` I get the error > > exit status 1 > main.cs(28,40): error CS0103: The name `length' does not exist in the current context > main.cs(28,47): error CS0103: The name`height' does not exist in the current context > Compilation failed: 2 error(s), 0 warnings > > >
2018/09/20
[ "https://Stackoverflow.com/questions/52430353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10392786/" ]
You're declaring the local variables `length` inside your try blocks; they only exist in that scope. Once execution leaves the try block, it doesn't exist anymore. See <https://msdn.microsoft.com/en-us/library/ms973875.aspx> for more information about how scoping works in C#. More specifically, when you call `Console.WriteLine(area(length,height));`, the variables `length` and `height` that you are trying to pass into the method do not exist in that scope. Declare them in that scope, rather than inside the try blocks.
The reason for this error is your defined variable `int length` is scoped inside curly braces `{ }`. So the variable is only available inside the brace it is defined. To be able to access the variable as you want, you have to define length at the start outside try block.
52,430,353
``` using System; class MainClass { public static void Main (string[] args) { bool loop1 = true; while(loop1) { Console.WriteLine("\nEnter the base length"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); continue; } Console.WriteLine("\nEnter the perpendicular height"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); } Console.WriteLine(area(length,height)); } } static int area(int length, int height) { return length * height/2; } } ``` I get the error > > exit status 1 > main.cs(28,40): error CS0103: The name `length' does not exist in the current context > main.cs(28,47): error CS0103: The name`height' does not exist in the current context > Compilation failed: 2 error(s), 0 warnings > > >
2018/09/20
[ "https://Stackoverflow.com/questions/52430353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10392786/" ]
You're declaring the local variables `length` inside your try blocks; they only exist in that scope. Once execution leaves the try block, it doesn't exist anymore. See <https://msdn.microsoft.com/en-us/library/ms973875.aspx> for more information about how scoping works in C#. More specifically, when you call `Console.WriteLine(area(length,height));`, the variables `length` and `height` that you are trying to pass into the method do not exist in that scope. Declare them in that scope, rather than inside the try blocks.
Specifically addressing the "Use of unassigned local variable 'height'" message... This normally happens if you try to reference a variable that has never been assigned a value. Something like the following will trigger this error message: ``` int x; Console.WriteLine(x); ``` Does the "Use of unassigned local variable 'height'" message happen when you enter invalid input that can't be cast as an integer? Entering something like "x" or "1.5" for length will cause the `Convert.ToInt32()` call to throw an exception, meaning that your `length` variable will not have anything assigned to it when the call to `Console.WriteLine(area(length,height));` happens later. You can fix/prevent this by initializing your variable when they are declared: ``` int length = 0; int height = 0; ``` Now the variables are initialized and you won't see the "Use of unassigned local variable 'height'" message. You'll probably get `0` as your calculated area, but that's a different issue entirely. :) I'm making assumptions about your input, but that's the only way I can think of to replicate the error you're seeing.
52,430,353
``` using System; class MainClass { public static void Main (string[] args) { bool loop1 = true; while(loop1) { Console.WriteLine("\nEnter the base length"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); continue; } Console.WriteLine("\nEnter the perpendicular height"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); } Console.WriteLine(area(length,height)); } } static int area(int length, int height) { return length * height/2; } } ``` I get the error > > exit status 1 > main.cs(28,40): error CS0103: The name `length' does not exist in the current context > main.cs(28,47): error CS0103: The name`height' does not exist in the current context > Compilation failed: 2 error(s), 0 warnings > > >
2018/09/20
[ "https://Stackoverflow.com/questions/52430353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10392786/" ]
The reason for this error is your defined variable `int length` is scoped inside curly braces `{ }`. So the variable is only available inside the brace it is defined. To be able to access the variable as you want, you have to define length at the start outside try block.
Specifically addressing the "Use of unassigned local variable 'height'" message... This normally happens if you try to reference a variable that has never been assigned a value. Something like the following will trigger this error message: ``` int x; Console.WriteLine(x); ``` Does the "Use of unassigned local variable 'height'" message happen when you enter invalid input that can't be cast as an integer? Entering something like "x" or "1.5" for length will cause the `Convert.ToInt32()` call to throw an exception, meaning that your `length` variable will not have anything assigned to it when the call to `Console.WriteLine(area(length,height));` happens later. You can fix/prevent this by initializing your variable when they are declared: ``` int length = 0; int height = 0; ``` Now the variables are initialized and you won't see the "Use of unassigned local variable 'height'" message. You'll probably get `0` as your calculated area, but that's a different issue entirely. :) I'm making assumptions about your input, but that's the only way I can think of to replicate the error you're seeing.
50,174,204
I have [consul](https://hub.docker.com/_/consul/) and [registrator](http://gliderlabs.github.io/registrator/latest/) running. I can start services in docker containers: ``` docker run -d -P --name=redis redis ``` And `registrator` is, as expected, able to register the services in `consul`: ``` http http://localhost:8500/v1/catalog/service/redis HTTP/1.1 200 OK Content-Encoding: gzip Content-Length: 308 Content-Type: application/json Date: Fri, 04 May 2018 11:33:50 GMT Vary: Accept-Encoding X-Consul-Effective-Consistency: leader X-Consul-Index: 34 X-Consul-Knownleader: true X-Consul-Lastcontact: 0 [ { "Address": "127.0.0.1", "CreateIndex": 34, "Datacenter": "dc1", "ID": "48b6c821-3b93-dbf4-394e-5024123ea7df", "ModifyIndex": 34, "Node": "863e97e527c3", "NodeMeta": { "consul-network-segment": "" }, "ServiceAddress": "", "ServiceEnableTagOverride": false, "ServiceID": "polyphemus.wavilon.net:redis:6379", "ServiceMeta": {}, "ServiceName": "redis", "ServicePort": 32769, "ServiceTags": [], "TaggedAddresses": { "lan": "127.0.0.1", "wan": "127.0.0.1" } } ] ``` I can then use `consul` DNS services: ``` » dig @127.0.0.1 -p 8600 redis.service.consul ; <<>> DiG 9.10.3-P4-Ubuntu <<>> @127.0.0.1 -p 8600 redis.service.consul ; (1 server found) ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 62382 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; WARNING: recursion requested but not available ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4096 ;; QUESTION SECTION: ;redis.service.consul. IN A ;; ANSWER SECTION: redis.service.consul. 0 IN A 127.0.0.1 ;; Query time: 0 msec ;; SERVER: 127.0.0.1#8600(127.0.0.1) ;; WHEN: Fri May 04 13:31:21 CEST 2018 ;; MSG SIZE rcvd: 65 ``` This is all fine. This basically means that I can start using consul to locate my services, so that something like this: ``` curl -X GET http://myservice.service.consul ``` Would work from inside my container. But ... there is one piece missing here: `registrator` is aware of the IP **and** the port where the service is running. I can check this via a special dns `SRV` request: ``` » dig @127.0.0.1 -p 8600 redis.service.consul SRV ; <<>> DiG 9.10.3-P4-Ubuntu <<>> @127.0.0.1 -p 8600 redis.service.consul SRV ; (1 server found) ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 52758 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 3 ;; WARNING: recursion requested but not available ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4096 ;; QUESTION SECTION: ;redis.service.consul. IN SRV ;; ANSWER SECTION: redis.service.consul. 0 IN SRV 1 1 32769 863e97e527c3.node.dc1.consul. ;; ADDITIONAL SECTION: 863e97e527c3.node.dc1.consul. 0 IN A 127.0.0.1 863e97e527c3.node.dc1.consul. 0 IN TXT "consul-network-segment=" ;; Query time: 0 msec ;; SERVER: 127.0.0.1#8600(127.0.0.1) ;; WHEN: Fri May 04 13:36:02 CEST 2018 ;; MSG SIZE rcvd: 149 ``` My question is: how do I integrate this in my application? Let's say I am writing a `python` application using `requests`. How would DNS resolution locate and use the port that is being exposed by the service? To be clear: the information is properly registered in `consul`, how do I use this information from the application? I see different options: * implement a "consul DNS resolution" layer in my application (as a library), which makes `SRV` DNS (or API) requests to consul in order to locate IP and port. * force the containers to always expose port `80` (I am doing http REST services), so that DNS resolution does not need to care about the port. The first option implies some refactoring of the application, which I would like to avoid. The second option implies that I need to fiddle with all services configuration. Is there a better alternative? Is there a transparent way of integrating `SRV` DNS requests when doing name resolution, and automatically making use of the port instead of using port `80` (or `443`)? I do not see how this would be feasible at all with `python` `requests`, or with `curl`, or with any other tool: we always need to manually specify the port when using those libraries / tools. And a related question: when / how are `SRV` DNS requests used? It seems those provide exactly the information that I need, but normal DNS resolution does not make use of it: clients are always making assumptions about the port where the service is running (`80` for `http`, `443` for `https` and so on) instead of asking the DNS server, which has the information.
2018/05/04
[ "https://Stackoverflow.com/questions/50174204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647991/" ]
Few ways in which we handled this problem: * Use a docker overlay network for container to container communication. In this case, your ports can be static (at the container level) and you can assume the port number while making connections * Use "consul-template" to generate a config file with IP and port info read from consul. This consul-template command will typically run as your docker entry point and will in turn launch your actual app. Whenever there is a change in consul, consul-template will regenerate the file and can be configured to reload/restart your app Thanks, Arul
There is no alternative within the constraints of DNS or using the Consul API directly, as you've already alluded to above; as it says [here](https://www.hashicorp.com/blog/load-balancing-strategies-for-consul#Cons): > > ...In this mode, applications and services talk directly to Consul each time they want to find other services in the datacenter....[Cons] Requires using the HTTP API directly in the application OR making DNS > queries and assuming port OR making two DNS queries to find the > address and port > > > That same link however, does offer up some alternatives, which always involve an intermediary. In the case of *Fabio*, effectively straight DNS is used, with association from the app to the port through a consul service tag, rather than any direct reference from the application to a [service] port.
68,496,205
I’m developing a new application in which I have to generate a unique custom serial number for each new invoice and I must have a counter for all of the invoices in the system. The format of the serial number is CCBBBYYYYNNNNNN. Where: * C = First two letters of the Company name * B = First three letters of the branch name * Y = Year No * N = Serial number from 000001 to 999999 I need your help to come up with a solution that will avoid any discrepancy in the serial numbers and can support multiple users at the same time. In addition, I need to create and save a counter for each newly-created invoice. How can I achieve this? What is the best way to do it through the database side or the application side? I also need to reset the serial number counter to zero at the beginning of every year.
2021/07/23
[ "https://Stackoverflow.com/questions/68496205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3885917/" ]
There is nothing special with array\_push in loop (You are using while loop) and initilizing values to an array (`$arr[] = $element`). The only differene is you are pushing value into the array through while loop and declaring initially using assignment operator. In your case, you have initilized $element to the array ``` $arr[] = "123"; //Lets say 123 is $element $arr[] = "NAME"; //Same way, you can repeat in next line as well $arr[] = "45"; echo '<pre>'; print_r($arr); // And the output was Array ( [0] => 123 [1] => NAME [2] => 45 ) ``` And the next statement was ``` while ($row = $result->fetch_assoc()) { $ids[] = $row['id'];// Lets say 123 is $row['id']; $names[] = $row['name']; //Lets say NAME is $row['name']; $ages[] = $row['age']; //Lets say 45 is $row['age']; } //The output will be same if only one row exist in the loop Array ( [0] => 123 [1] => NAME [2] => 45 .................. // Based on while loop rows ) ``` The symbol **[]** will push value into array because you didn't mention any key in between bracket.
``` $ids[] = $row['id']; ``` Here we group the returned `id` element (from the SQL query) into one array. Thus finally, the `ids` array will store all the `id` elements from the SQL query; likewise for the other arrays. The syntax `$id [] = $value` means we are pushing the `$value` element into the array.
34,525,650
I'm new to web front-end programming and am teaching myself AngularJS. I have created a very simple webapp that just lets users login and logout. I am running it locally on my Mac OSX. Below is my `index.html` file. Although it works, I'm not sure if I'm doing it right. I need to know how and where to import the angular.js files and the bootstrap.js files. My questions are as follows. I haven't been able to figure this stuff out by googling. I need someone to explain this stuff to me please. 1. I'm currently importing the `angular.js` file from `https://ajax.googleapis.com`. Is that correct? Or should I download it and store that file in the same directory as `index.html`? Why? When should I use the non-minified file? What is the benefit of using non-minified? 2. I'm currently not importing any bootstrap file(s). Which file(s) should I import? Should I import it/them as a URL or as a file from the same directory as `index.html` 3. For both Bootstrap and AngularJS, please tell me which line numbers I should put the `script src` lines in my HTML. 4. Should I check the Angular and Bootstrap files into my Github repository? index.html: ``` <html ng-app="app"> <head> </head> <body ng-controller="Main as main"> <input type="text" ng-model="main.username" placeholder="username"> <br> <input type="password" ng-model="main.password" placeholder="password"> <br> <br> <button ng-click="main.login()" ng-hide="main.isAuthed()">Login</button> <button ng-click="main.logout()" ng-show="main.isAuthed()">Logout</button> <br/> {{main.message}} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script> <script src="app.js"></script> </body> </html> ```
2015/12/30
[ "https://Stackoverflow.com/questions/34525650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1742777/" ]
Normally, you add CSS stylesheets and JS scripts in the `<head>`(between lines 2 and 3) area of your html. You can either link files with URLs like the example below or just download the whole Angular.js or Bootstrap.css file (both of them aren't that big) and put them in the same folder as your `index.html` file. URL/CDN example: ``` <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script> </head> ``` Local folder example: ``` <head> <link rel="stylesheet" href="bootstrap.min.css"> <script type="text/javascript" src="angular.min.js"></script> </head> ``` Minified files (`angular.js` vs `angular.min.js`) will both run the same way. The only difference is the `.min.` file has the code all squished without any spaces, tabs, and new lines. This makes it load faster for computers, but if you're going to customize your angular or bootstrap in the future, you will find the squished format impossible to read. You don't need to be too concerned with doing everything 'the perfect way' if you're just starting out. I used to include the angular.js and bootstrap.css files along with my index.html in my project when I pushed it to Github. After a while though you might find it cleaner to leave them out and just use the URL-format. Some people will say you should put all your JS files and links at the bottom of your webpage (just before the `</body>` tag), but again this is just another optimization towards 'perfect' that you shouldn't worry too much about.
This is advise for beginners, if you are an expert this may not apply to you: 1. I would advice you to have the files locally while you are developing, then your website will work w/o internet, and it will respond faster if you disable cashing (which you should when you are developing)! * You should disable cashing in your browser when you are developing, otherwise when you change your css and js files it will take minus before the browser detects the files have changed * the minimized versions are smaller but unreadable, I would use the none minimized versions while developing so I can understand error messages, and then switch to the minimized version either a) never or b) when speed becomes important 2. see 1 3. as a beginner you should but it in the head tag ie between line 2 and 3. sometimes people put it after the body tag to first load the webpage and then the scripts, this is fine also, but as a beginner I think it is advantageous for your webpage to fully work as soon as you can see it. 4. good question, I would do it out of laziness, alternative you could have a script called get\_dependencies.sh where you have lines as "wget stuff"
34,525,650
I'm new to web front-end programming and am teaching myself AngularJS. I have created a very simple webapp that just lets users login and logout. I am running it locally on my Mac OSX. Below is my `index.html` file. Although it works, I'm not sure if I'm doing it right. I need to know how and where to import the angular.js files and the bootstrap.js files. My questions are as follows. I haven't been able to figure this stuff out by googling. I need someone to explain this stuff to me please. 1. I'm currently importing the `angular.js` file from `https://ajax.googleapis.com`. Is that correct? Or should I download it and store that file in the same directory as `index.html`? Why? When should I use the non-minified file? What is the benefit of using non-minified? 2. I'm currently not importing any bootstrap file(s). Which file(s) should I import? Should I import it/them as a URL or as a file from the same directory as `index.html` 3. For both Bootstrap and AngularJS, please tell me which line numbers I should put the `script src` lines in my HTML. 4. Should I check the Angular and Bootstrap files into my Github repository? index.html: ``` <html ng-app="app"> <head> </head> <body ng-controller="Main as main"> <input type="text" ng-model="main.username" placeholder="username"> <br> <input type="password" ng-model="main.password" placeholder="password"> <br> <br> <button ng-click="main.login()" ng-hide="main.isAuthed()">Login</button> <button ng-click="main.logout()" ng-show="main.isAuthed()">Logout</button> <br/> {{main.message}} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script> <script src="app.js"></script> </body> </html> ```
2015/12/30
[ "https://Stackoverflow.com/questions/34525650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1742777/" ]
Normally, you add CSS stylesheets and JS scripts in the `<head>`(between lines 2 and 3) area of your html. You can either link files with URLs like the example below or just download the whole Angular.js or Bootstrap.css file (both of them aren't that big) and put them in the same folder as your `index.html` file. URL/CDN example: ``` <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script> </head> ``` Local folder example: ``` <head> <link rel="stylesheet" href="bootstrap.min.css"> <script type="text/javascript" src="angular.min.js"></script> </head> ``` Minified files (`angular.js` vs `angular.min.js`) will both run the same way. The only difference is the `.min.` file has the code all squished without any spaces, tabs, and new lines. This makes it load faster for computers, but if you're going to customize your angular or bootstrap in the future, you will find the squished format impossible to read. You don't need to be too concerned with doing everything 'the perfect way' if you're just starting out. I used to include the angular.js and bootstrap.css files along with my index.html in my project when I pushed it to Github. After a while though you might find it cleaner to leave them out and just use the URL-format. Some people will say you should put all your JS files and links at the bottom of your webpage (just before the `</body>` tag), but again this is just another optimization towards 'perfect' that you shouldn't worry too much about.
The usual convention is to put the CSS files in link tags inside your `<head>` tag (2-3), so that they are rendered before the html and the styles will apply when the content is loaded, so that the user will begin to see the page building up even before it is fully loaded, instead of seeing some not styled elements beforehand. more on that:[What's the difference if I put css file inside <head> or <body>?](https://stackoverflow.com/questions/1642212/whats-the-difference-if-i-put-css-file-inside-head-or-body) now, the scripts should be loaded at the end of the body(where they are now), for the following reasons: 1. if they will be rendered before most the html, they will delay the page from rendering until the whole script is loaded, and that's a UX hit. 2. most scripts are supposed to run anyway when the document is fully loaded, sometimes developers will use something like DOMContentLoaded to ensure that, but sometimes they don't and then a script will run without the corresponding html loaded. more on that :[Where should I put <script> tags in HTML markup?](https://stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup) you asked about minification: minification is supposed to make your files downloaded faster since they are compressed and have less weight. it is ideal for production, but bad for development since you can't debug them well. that's why you should enable minification only on production. (and because you use angular, also use $compileProvider.debugInfoEnabled(false), look for it.) as for using files in your project (download them) or from cdn (<https://ajax.googleapis.com>): a good convention for development is to use files on your project, so that you can develop without caring about your internet connection, and the distance the content need to go between their servers and your machine. however, on production, a good convention would be using the cdn in your page, since many other web pages may include the libraries you want to fetch(angular and bootstrap are quite common) so the file has a good chance to be already stored in your browser cache, and not need to be loaded again. and yet, you should define a fallback in your page such that if the cdn's are some why unavailable, the user will get the files from your project server. [here's an example](http://www.hanselman.com/blog/CDNsFailButYourScriptsDontHaveToFallbackFromCDNToLocalJQuery.aspx) for the last question: you can put them in some "Libraryscripts" directory, so that's it's clear they are just dependancies
53,682,098
I have opened an Android Studio project which was created some time ago and the IDE says that a gradle plugin for Kotlin supports a Kotlin version 1.2.51 or higher. I would like to set it to the latest version but I have to go to the Kotlin website on which it's not easy to find out this information. Is it possible to find out the latest version of Kotlin in Android Studio?
2018/12/08
[ "https://Stackoverflow.com/questions/53682098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1180728/" ]
If you are on windows do the following: FILE > SETTINGS > LANGUAGE AND FRAMEWORK > KOTLIN UPDATES [![enter image description here](https://i.stack.imgur.com/I97f8.jpg)](https://i.stack.imgur.com/I97f8.jpg) then click on check and then if there was a newer version press install
On Mac OS Preferences -> Languages & Frameworks -> Kotlin
11,914
Some people appear to be born with muscle\*. I know lots of people who don't work out at all, have an office job where they sit around all day, and still they have a muscular body with strong (looking) arms, big chest etc. Me, I'm naturally slim, and however hard I work out, I seem unable to make a big change in my physical appearance. Yes, I do get stronger and more fit, but I look (almost) the same after a year of intense training: thin. What can I do? Several years ago I did dumbell exercises from Bill Pearl's "Getting Stronger" and supplemented my diet with a meat based protein shake. After a year this made me look more toned, but the effect was minor. I stopped this routine when doing lunges with weights caused knee pain. At the moment I follow Mark Verstegen's "Core Performance" (the book), but have only been at it for a few months. I did not change my diet again except eat more soy products and nuts. The time is too short for any visible effects, of course. I'll very likely stop this routine also, because I'm experiencing shoulder pain from raining weights above shoulder height. I don't mean to imply that these routines don't work for me, I just describe what I did to give you an idea of the status quo - and of the fact that I easily self-hurt myself, if I work with weights. I don't want to go to a gym (for reasons that are irrelevant here but definite), so I cannot work out using machines. --- \*Obviously people are not literally "born with muscle". There is a genetic influence and, as has been found, the muscles that children use around 5 to 6 years of age develop in the adult individual. Both influences cannot be changed by a post-adolescent adult, so "born with muscle" is a good short description of the situation.
2013/03/14
[ "https://fitness.stackexchange.com/questions/11914", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/-1/" ]
Very few people are "born with muscle" to a degree that matters; they are possibly born with larger bone structures, or born with genes that make muscle gaining easier. One such gene would be the feeling of fullness -- some people have to eat more to feel full, and some less. However, if you've done a lot of heavy lifting via chores/physical tasks while growing up and still eat a lot, you will (slowly and inefficiently, but still surely) gain muscle. The unaccounted-for factor here is your diet. Lifting heavy, eating to calorie surplus, and eating large amounts of protein (try your body weight in grams, just to be sure) will make sure you make muscle gains. However, lifting heavy is not enough either: to stimulate hypertrophy (the growth of muscles), you should be lifting in the 8-12 rep range. Adjust weight (more or less) until you get there. To increase strength (absolute pounds lifted), lift in the 5-6 rep range.
I have a similar build and I have an idea to test, but I'm at a point in my life where I am not that motivated to test my idea so why don't you test it for me ;-) It isn't actually my idea, I got it from Tim Ferris and you can read about it on [his web site here](http://www.fourhourworkweek.com/blog/2007/04/29/from-geek-to-freak-how-i-gained-34-lbs-of-muscle-in-4-weeks/) or in his book, [The 4-Hour Body](http://rads.stackoverflow.com/amzn/click/030746363X). Generally speaking, your workouts would consist of one set of a relatively small number of exercises, performed until **complete** failure 1 or, at most, 2 times per week. This is failure like you have never pushed yourself to experience before. As I recall, Tim does basic strength training exercises like dead lifts, squats, etc. but I have some friends doing this on machines and it is probably safer to do this way, though perhaps not quite as effective. It amounts to a shockingly small amount of time in the gym followed by a lot of recovery time. Your diet consists of large amounts of protein. I could go on, but Tim Ferris can fill in the details with much more authority :-)
20,746,940
I have floats like these, ``` 0.0 , 50.0 ... ``` How do I convert them to: ``` 0 , 50 ... ``` I need the meaningful numbers in the decimal part stay intact; so `13.59` must remain `13.59`. EDIT : my question is way different from that duplicate of yours; if only you read through it you would know it.
2013/12/23
[ "https://Stackoverflow.com/questions/20746940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080376/" ]
Command `find_package` has two modes: `Module` mode and `Config` mode. You are trying to use `Module` mode when you actually need `Config` mode. ### Module mode `Find<package>.cmake` file located **within** your project. Something like this: ``` CMakeLists.txt cmake/FindFoo.cmake cmake/FindBoo.cmake ``` `CMakeLists.txt` content: ``` list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake") find_package(Foo REQUIRED) # FOO_INCLUDE_DIR, FOO_LIBRARIES find_package(Boo REQUIRED) # BOO_INCLUDE_DIR, BOO_LIBRARIES include_directories("${FOO_INCLUDE_DIR}") include_directories("${BOO_INCLUDE_DIR}") add_executable(Bar Bar.hpp Bar.cpp) target_link_libraries(Bar ${FOO_LIBRARIES} ${BOO_LIBRARIES}) ``` Note that `CMAKE_MODULE_PATH` has high priority and may be usefull when you need to rewrite standard `Find<package>.cmake` file. ### Config mode (install) `<package>Config.cmake` file located **outside** and produced by `install` command of other project (`Foo` for example). `foo` library: ``` > cat CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(Foo) add_library(foo Foo.hpp Foo.cpp) install(FILES Foo.hpp DESTINATION include) install(TARGETS foo DESTINATION lib) install(FILES FooConfig.cmake DESTINATION lib/cmake/Foo) ``` Simplified version of config file: ``` > cat FooConfig.cmake add_library(foo STATIC IMPORTED) find_library(FOO_LIBRARY_PATH foo HINTS "${CMAKE_CURRENT_LIST_DIR}/../../") set_target_properties(foo PROPERTIES IMPORTED_LOCATION "${FOO_LIBRARY_PATH}") ``` By default project installed in `CMAKE_INSTALL_PREFIX` directory: ``` > cmake -H. -B_builds > cmake --build _builds --target install -- Install configuration: "" -- Installing: /usr/local/include/Foo.hpp -- Installing: /usr/local/lib/libfoo.a -- Installing: /usr/local/lib/cmake/Foo/FooConfig.cmake ``` ### Config mode (use) Use `find_package(... CONFIG)` to include `FooConfig.cmake` with imported target `foo`: ``` > cat CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(Boo) # import library target `foo` find_package(Foo CONFIG REQUIRED) add_executable(boo Boo.cpp Boo.hpp) target_link_libraries(boo foo) > cmake -H. -B_builds -DCMAKE_VERBOSE_MAKEFILE=ON > cmake --build _builds Linking CXX executable Boo /usr/bin/c++ ... -o Boo /usr/local/lib/libfoo.a ``` Note that imported target is **highly** configurable. See my [answer](https://stackoverflow.com/a/20838147/2288008). **Update** * [Example](https://github.com/forexample/package-example)
You don't *need* to specify the module path per se. CMake ships with its own set of built-in find\_package scripts, and their location is in the default CMAKE\_MODULE\_PATH. The more normal use case for dependent projects that have been CMakeified would be to use CMake's external\_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE\_MODULE\_PATH in order to find the subproject at the system level.
20,746,940
I have floats like these, ``` 0.0 , 50.0 ... ``` How do I convert them to: ``` 0 , 50 ... ``` I need the meaningful numbers in the decimal part stay intact; so `13.59` must remain `13.59`. EDIT : my question is way different from that duplicate of yours; if only you read through it you would know it.
2013/12/23
[ "https://Stackoverflow.com/questions/20746940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080376/" ]
> > How is this usually done? Should I copy the `cmake/` directory of SomeLib into my project and set the CMAKE\_MODULE\_PATH relatively? > > > If you don't trust CMake to have that module, then - **yes, do that - sort of:** Copy the `find_SomeLib.cmake` and its dependencies into your `cmake/` directory. That's what I do as a fallback. It's an ugly solution though. Note that the `FindFoo.cmake` modules are each a sort of a bridge between platform-dependence and platform-independence - they look in various platform-specific places to obtain paths in variables whose names is platform-independent.
You don't *need* to specify the module path per se. CMake ships with its own set of built-in find\_package scripts, and their location is in the default CMAKE\_MODULE\_PATH. The more normal use case for dependent projects that have been CMakeified would be to use CMake's external\_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE\_MODULE\_PATH in order to find the subproject at the system level.
20,746,940
I have floats like these, ``` 0.0 , 50.0 ... ``` How do I convert them to: ``` 0 , 50 ... ``` I need the meaningful numbers in the decimal part stay intact; so `13.59` must remain `13.59`. EDIT : my question is way different from that duplicate of yours; if only you read through it you would know it.
2013/12/23
[ "https://Stackoverflow.com/questions/20746940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080376/" ]
If you are running `cmake` to generate `SomeLib` yourself (say as part of a superbuild), consider using the [User Package Registry](https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html#user-package-registry). This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the `CONFIG` mode of the [find\_packages()](https://cmake.org/cmake/help/latest/command/find_package.html?highlight=find_package) command, you'll see that the User Package Registry is one of elements. **Brief how-to** Associate the targets of `SomeLib` that you need outside of that external project by adding them to an export set in the `CMakeLists.txt` files where they are created: ``` add_library(thingInSomeLib ...) install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib) ``` Create a `XXXConfig.cmake` file for `SomeLib` in its `${CMAKE_CURRENT_BUILD_DIR}` and store this location in the User Package Registry by adding two calls to [export()](https://cmake.org/cmake/help/latest/command/export.html?highlight=export) to the `CMakeLists.txt` associated with `SomeLib`: ``` export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake export(PACKAGE SomeLib) # Store location of SomeLibConfig.cmake ``` Issue your `find_package(SomeLib REQUIRED)` commmand in the `CMakeLists.txt` file of the project that depends on `SomeLib` without the "non-cross-platform hard coded paths" tinkering with the `CMAKE_MODULE_PATH`. **When it might be the right approach** This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary. But if you're never actually installing `SomeLib` in your workflow, calling `EXPORT(PACKAGE <name>)` allows you to avoid the hard-coded path. And, of course, if you are installing `SomeLib`, you probably know your platform, `CMAKE_MODULE_PATH`, etc, so @user2288008's excellent answer will have you covered.
You don't *need* to specify the module path per se. CMake ships with its own set of built-in find\_package scripts, and their location is in the default CMAKE\_MODULE\_PATH. The more normal use case for dependent projects that have been CMakeified would be to use CMake's external\_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE\_MODULE\_PATH in order to find the subproject at the system level.
20,746,940
I have floats like these, ``` 0.0 , 50.0 ... ``` How do I convert them to: ``` 0 , 50 ... ``` I need the meaningful numbers in the decimal part stay intact; so `13.59` must remain `13.59`. EDIT : my question is way different from that duplicate of yours; if only you read through it you would know it.
2013/12/23
[ "https://Stackoverflow.com/questions/20746940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080376/" ]
Command `find_package` has two modes: `Module` mode and `Config` mode. You are trying to use `Module` mode when you actually need `Config` mode. ### Module mode `Find<package>.cmake` file located **within** your project. Something like this: ``` CMakeLists.txt cmake/FindFoo.cmake cmake/FindBoo.cmake ``` `CMakeLists.txt` content: ``` list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake") find_package(Foo REQUIRED) # FOO_INCLUDE_DIR, FOO_LIBRARIES find_package(Boo REQUIRED) # BOO_INCLUDE_DIR, BOO_LIBRARIES include_directories("${FOO_INCLUDE_DIR}") include_directories("${BOO_INCLUDE_DIR}") add_executable(Bar Bar.hpp Bar.cpp) target_link_libraries(Bar ${FOO_LIBRARIES} ${BOO_LIBRARIES}) ``` Note that `CMAKE_MODULE_PATH` has high priority and may be usefull when you need to rewrite standard `Find<package>.cmake` file. ### Config mode (install) `<package>Config.cmake` file located **outside** and produced by `install` command of other project (`Foo` for example). `foo` library: ``` > cat CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(Foo) add_library(foo Foo.hpp Foo.cpp) install(FILES Foo.hpp DESTINATION include) install(TARGETS foo DESTINATION lib) install(FILES FooConfig.cmake DESTINATION lib/cmake/Foo) ``` Simplified version of config file: ``` > cat FooConfig.cmake add_library(foo STATIC IMPORTED) find_library(FOO_LIBRARY_PATH foo HINTS "${CMAKE_CURRENT_LIST_DIR}/../../") set_target_properties(foo PROPERTIES IMPORTED_LOCATION "${FOO_LIBRARY_PATH}") ``` By default project installed in `CMAKE_INSTALL_PREFIX` directory: ``` > cmake -H. -B_builds > cmake --build _builds --target install -- Install configuration: "" -- Installing: /usr/local/include/Foo.hpp -- Installing: /usr/local/lib/libfoo.a -- Installing: /usr/local/lib/cmake/Foo/FooConfig.cmake ``` ### Config mode (use) Use `find_package(... CONFIG)` to include `FooConfig.cmake` with imported target `foo`: ``` > cat CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(Boo) # import library target `foo` find_package(Foo CONFIG REQUIRED) add_executable(boo Boo.cpp Boo.hpp) target_link_libraries(boo foo) > cmake -H. -B_builds -DCMAKE_VERBOSE_MAKEFILE=ON > cmake --build _builds Linking CXX executable Boo /usr/bin/c++ ... -o Boo /usr/local/lib/libfoo.a ``` Note that imported target is **highly** configurable. See my [answer](https://stackoverflow.com/a/20838147/2288008). **Update** * [Example](https://github.com/forexample/package-example)
> > How is this usually done? Should I copy the `cmake/` directory of SomeLib into my project and set the CMAKE\_MODULE\_PATH relatively? > > > If you don't trust CMake to have that module, then - **yes, do that - sort of:** Copy the `find_SomeLib.cmake` and its dependencies into your `cmake/` directory. That's what I do as a fallback. It's an ugly solution though. Note that the `FindFoo.cmake` modules are each a sort of a bridge between platform-dependence and platform-independence - they look in various platform-specific places to obtain paths in variables whose names is platform-independent.
20,746,940
I have floats like these, ``` 0.0 , 50.0 ... ``` How do I convert them to: ``` 0 , 50 ... ``` I need the meaningful numbers in the decimal part stay intact; so `13.59` must remain `13.59`. EDIT : my question is way different from that duplicate of yours; if only you read through it you would know it.
2013/12/23
[ "https://Stackoverflow.com/questions/20746940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080376/" ]
Command `find_package` has two modes: `Module` mode and `Config` mode. You are trying to use `Module` mode when you actually need `Config` mode. ### Module mode `Find<package>.cmake` file located **within** your project. Something like this: ``` CMakeLists.txt cmake/FindFoo.cmake cmake/FindBoo.cmake ``` `CMakeLists.txt` content: ``` list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake") find_package(Foo REQUIRED) # FOO_INCLUDE_DIR, FOO_LIBRARIES find_package(Boo REQUIRED) # BOO_INCLUDE_DIR, BOO_LIBRARIES include_directories("${FOO_INCLUDE_DIR}") include_directories("${BOO_INCLUDE_DIR}") add_executable(Bar Bar.hpp Bar.cpp) target_link_libraries(Bar ${FOO_LIBRARIES} ${BOO_LIBRARIES}) ``` Note that `CMAKE_MODULE_PATH` has high priority and may be usefull when you need to rewrite standard `Find<package>.cmake` file. ### Config mode (install) `<package>Config.cmake` file located **outside** and produced by `install` command of other project (`Foo` for example). `foo` library: ``` > cat CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(Foo) add_library(foo Foo.hpp Foo.cpp) install(FILES Foo.hpp DESTINATION include) install(TARGETS foo DESTINATION lib) install(FILES FooConfig.cmake DESTINATION lib/cmake/Foo) ``` Simplified version of config file: ``` > cat FooConfig.cmake add_library(foo STATIC IMPORTED) find_library(FOO_LIBRARY_PATH foo HINTS "${CMAKE_CURRENT_LIST_DIR}/../../") set_target_properties(foo PROPERTIES IMPORTED_LOCATION "${FOO_LIBRARY_PATH}") ``` By default project installed in `CMAKE_INSTALL_PREFIX` directory: ``` > cmake -H. -B_builds > cmake --build _builds --target install -- Install configuration: "" -- Installing: /usr/local/include/Foo.hpp -- Installing: /usr/local/lib/libfoo.a -- Installing: /usr/local/lib/cmake/Foo/FooConfig.cmake ``` ### Config mode (use) Use `find_package(... CONFIG)` to include `FooConfig.cmake` with imported target `foo`: ``` > cat CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(Boo) # import library target `foo` find_package(Foo CONFIG REQUIRED) add_executable(boo Boo.cpp Boo.hpp) target_link_libraries(boo foo) > cmake -H. -B_builds -DCMAKE_VERBOSE_MAKEFILE=ON > cmake --build _builds Linking CXX executable Boo /usr/bin/c++ ... -o Boo /usr/local/lib/libfoo.a ``` Note that imported target is **highly** configurable. See my [answer](https://stackoverflow.com/a/20838147/2288008). **Update** * [Example](https://github.com/forexample/package-example)
If you are running `cmake` to generate `SomeLib` yourself (say as part of a superbuild), consider using the [User Package Registry](https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html#user-package-registry). This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the `CONFIG` mode of the [find\_packages()](https://cmake.org/cmake/help/latest/command/find_package.html?highlight=find_package) command, you'll see that the User Package Registry is one of elements. **Brief how-to** Associate the targets of `SomeLib` that you need outside of that external project by adding them to an export set in the `CMakeLists.txt` files where they are created: ``` add_library(thingInSomeLib ...) install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib) ``` Create a `XXXConfig.cmake` file for `SomeLib` in its `${CMAKE_CURRENT_BUILD_DIR}` and store this location in the User Package Registry by adding two calls to [export()](https://cmake.org/cmake/help/latest/command/export.html?highlight=export) to the `CMakeLists.txt` associated with `SomeLib`: ``` export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake export(PACKAGE SomeLib) # Store location of SomeLibConfig.cmake ``` Issue your `find_package(SomeLib REQUIRED)` commmand in the `CMakeLists.txt` file of the project that depends on `SomeLib` without the "non-cross-platform hard coded paths" tinkering with the `CMAKE_MODULE_PATH`. **When it might be the right approach** This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary. But if you're never actually installing `SomeLib` in your workflow, calling `EXPORT(PACKAGE <name>)` allows you to avoid the hard-coded path. And, of course, if you are installing `SomeLib`, you probably know your platform, `CMAKE_MODULE_PATH`, etc, so @user2288008's excellent answer will have you covered.
20,746,940
I have floats like these, ``` 0.0 , 50.0 ... ``` How do I convert them to: ``` 0 , 50 ... ``` I need the meaningful numbers in the decimal part stay intact; so `13.59` must remain `13.59`. EDIT : my question is way different from that duplicate of yours; if only you read through it you would know it.
2013/12/23
[ "https://Stackoverflow.com/questions/20746940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080376/" ]
If you are running `cmake` to generate `SomeLib` yourself (say as part of a superbuild), consider using the [User Package Registry](https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html#user-package-registry). This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the `CONFIG` mode of the [find\_packages()](https://cmake.org/cmake/help/latest/command/find_package.html?highlight=find_package) command, you'll see that the User Package Registry is one of elements. **Brief how-to** Associate the targets of `SomeLib` that you need outside of that external project by adding them to an export set in the `CMakeLists.txt` files where they are created: ``` add_library(thingInSomeLib ...) install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib) ``` Create a `XXXConfig.cmake` file for `SomeLib` in its `${CMAKE_CURRENT_BUILD_DIR}` and store this location in the User Package Registry by adding two calls to [export()](https://cmake.org/cmake/help/latest/command/export.html?highlight=export) to the `CMakeLists.txt` associated with `SomeLib`: ``` export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake export(PACKAGE SomeLib) # Store location of SomeLibConfig.cmake ``` Issue your `find_package(SomeLib REQUIRED)` commmand in the `CMakeLists.txt` file of the project that depends on `SomeLib` without the "non-cross-platform hard coded paths" tinkering with the `CMAKE_MODULE_PATH`. **When it might be the right approach** This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary. But if you're never actually installing `SomeLib` in your workflow, calling `EXPORT(PACKAGE <name>)` allows you to avoid the hard-coded path. And, of course, if you are installing `SomeLib`, you probably know your platform, `CMAKE_MODULE_PATH`, etc, so @user2288008's excellent answer will have you covered.
> > How is this usually done? Should I copy the `cmake/` directory of SomeLib into my project and set the CMAKE\_MODULE\_PATH relatively? > > > If you don't trust CMake to have that module, then - **yes, do that - sort of:** Copy the `find_SomeLib.cmake` and its dependencies into your `cmake/` directory. That's what I do as a fallback. It's an ugly solution though. Note that the `FindFoo.cmake` modules are each a sort of a bridge between platform-dependence and platform-independence - they look in various platform-specific places to obtain paths in variables whose names is platform-independent.
71,709,360
I am following the NestJS fundamentals course and I am getting stuck with the "[Use transactions](https://learn.nestjs.com/courses/591712/lectures/23193771)" section: First of all, it seems to me that the course contains a typo in the import: ``` // ... other imports import { Entity } from '../events/entities/event.entity'; ``` Should be: `import { Event } ...` But then, after having completed the section, I realize that I have this compilation error: > > [Nest] 507493 - 04/01/2022, 5:13:17 PM ERROR [ExceptionHandler] No > repository for "Event" was found. Looks like this entity is not > registered in current "default" connection? RepositoryNotFoundError: > No repository for "Event" was found. Looks like this entity is not > registered in current "default" connection? > at RepositoryNotFoundError.TypeORMError [as constructor] (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/error/TypeORMError.ts:7:9) > at new RepositoryNotFoundError (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/error/RepositoryNotFoundError.ts:10:9) > at EntityManager.getRepository (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/entity-manager/EntityManager.ts:964:19) > at Connection.getRepository (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/connection/Connection.ts:354:29) > at InstanceWrapper.useFactory [as metatype] (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/typeorm/dist/typeorm.providers.js:17:30) > at Injector.instantiateClass (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:333:55) > at callback (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:48:41) > at processTicksAndRejections (node:internal/process/task\_queues:96:5) > at Injector.resolveConstructorParams (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:122:24) > at Injector.loadInstance (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:52:9) > > > The code is available here: <https://github.com/vmalep/nestJSCourse/tree/useTransacionError> I have tried different solution, but to no avail and the course does not give any contact to get support (despite the fact that we have to pay for it...). So I am asking for help in this forum. It will be highly appreciated! Best regards, Pierre
2022/04/01
[ "https://Stackoverflow.com/questions/71709360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2865385/" ]
here's a 1 liner for this purpose using the Counter function from collections library: ``` from collections import Counter l = ['dog', 'bird', 'bird', 'cat', 'dog', 'fish', 'cat', 'cat', 'dog', 'cat', 'bird', 'dog'] print(Counter(l)) ```
A native implementation, would be to go through the array and count the amount of repeated elements but verifying that they do not exist before in the dictionary, if so, then increase the counter, in a super simple way, you have something like this ```py l = ['dog', 'bird', 'bird', 'cat', 'dog', 'fish', 'cat', 'cat', 'dog', 'cat', 'bird', 'dog'] l_dict = {} for i in l: if i in l_dict: l_dict[i] += 1 else: l_dict[i] = 1 print(l_dict) ```
71,709,360
I am following the NestJS fundamentals course and I am getting stuck with the "[Use transactions](https://learn.nestjs.com/courses/591712/lectures/23193771)" section: First of all, it seems to me that the course contains a typo in the import: ``` // ... other imports import { Entity } from '../events/entities/event.entity'; ``` Should be: `import { Event } ...` But then, after having completed the section, I realize that I have this compilation error: > > [Nest] 507493 - 04/01/2022, 5:13:17 PM ERROR [ExceptionHandler] No > repository for "Event" was found. Looks like this entity is not > registered in current "default" connection? RepositoryNotFoundError: > No repository for "Event" was found. Looks like this entity is not > registered in current "default" connection? > at RepositoryNotFoundError.TypeORMError [as constructor] (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/error/TypeORMError.ts:7:9) > at new RepositoryNotFoundError (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/error/RepositoryNotFoundError.ts:10:9) > at EntityManager.getRepository (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/entity-manager/EntityManager.ts:964:19) > at Connection.getRepository (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/connection/Connection.ts:354:29) > at InstanceWrapper.useFactory [as metatype] (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/typeorm/dist/typeorm.providers.js:17:30) > at Injector.instantiateClass (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:333:55) > at callback (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:48:41) > at processTicksAndRejections (node:internal/process/task\_queues:96:5) > at Injector.resolveConstructorParams (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:122:24) > at Injector.loadInstance (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:52:9) > > > The code is available here: <https://github.com/vmalep/nestJSCourse/tree/useTransacionError> I have tried different solution, but to no avail and the course does not give any contact to get support (despite the fact that we have to pay for it...). So I am asking for help in this forum. It will be highly appreciated! Best regards, Pierre
2022/04/01
[ "https://Stackoverflow.com/questions/71709360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2865385/" ]
here's a 1 liner for this purpose using the Counter function from collections library: ``` from collections import Counter l = ['dog', 'bird', 'bird', 'cat', 'dog', 'fish', 'cat', 'cat', 'dog', 'cat', 'bird', 'dog'] print(Counter(l)) ```
The solution suggested by gil is good. The following solution also work : ```py l_dict = {key: l.count(key) for key in set(l)} ``` Using counter is more effective for large lists, but dict comprehension is better for shorter lists. We can verify it with timeit : ```py from timeit import timeit from collection import Counter # declare your list here def with_comprehension(): return {key: l.count(key) for key in set(l)} def with_counter(): return Counter(l) ``` With your example (12 elements), dict comprehension is better : ```py >>> timeit(with_comprehension) 0.9273126000771299 >>> timeit(with_counter) 1.1477947999956086 ``` But when you have 100 elements, counter become more effective : ```py >>> timeit(with_comprehension) 3.6719840000150725 >>> timeit(with_counter) 2.85686399997212 ```
593,092
I want to protect only certain numbers that are displayed after each request. There are about 30 such numbers. I was planning to have images generated in the place of those numerbers, but if the image is not warped as with captcha, wont scripts be able to decipher the number anyway? Also, how much of a performance hit would loading images be vs text?
2009/02/27
[ "https://Stackoverflow.com/questions/593092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49632/" ]
Generate an image containing those numbers and display the image. :-)
Don't output the numbers, i.e. prefix ``` echo $secretNumber; ``` with `//`.
593,092
I want to protect only certain numbers that are displayed after each request. There are about 30 such numbers. I was planning to have images generated in the place of those numerbers, but if the image is not warped as with captcha, wont scripts be able to decipher the number anyway? Also, how much of a performance hit would loading images be vs text?
2009/02/27
[ "https://Stackoverflow.com/questions/593092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49632/" ]
It's not possible. * You use javascript and encrypt the page, using document.write() calls after decrypting. I either scrape from the browser's display or feed the page through a JS engine to get the output. * You use Flash. I can poke into the flash file and get the values. You encrypt them in the flash and I can just run it then grab the output from the interpreter's display as a sequence of images. * You use images and I can just feed them through an OCR. You're in an arms race. What you need to do is make your information so useful and your pages so easy to use that you become the authority source. It's also handy to change your output formats regularly to keep up, but screen scrapers can handle that unless you make fairly radical changes. Radical changes drive users away because the page is continually unfamiliar to them. Your image solution wont' help much, and images are far less efficient. A number is usually only a few bytes long in HTML encoding. Images start at a few hundred bytes and expand to a 1k or more depending on how large you want. Images also will not render in the font the user has selected for their browser window, and are useless to people who use assisted computing devices (visually impaired people).
The only way to make sure bad-guys don't get your data is not to share it with anyone. Any other solution is essentially entering an arms race with the screen-scrapers. At one point or another, one of you will find the arms-race too costly to continue. If the data you are sharing has any perceptible value, then probably the screen-scrapers will be very determined.
593,092
I want to protect only certain numbers that are displayed after each request. There are about 30 such numbers. I was planning to have images generated in the place of those numerbers, but if the image is not warped as with captcha, wont scripts be able to decipher the number anyway? Also, how much of a performance hit would loading images be vs text?
2009/02/27
[ "https://Stackoverflow.com/questions/593092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49632/" ]
Javascript would probably be the easiest to implement, but you could get really creative and have large blocks of numbers with certain ones being viewable by placing layers on top of the invalid numbers, blending the wrong numbers into the background, or making them invisible via css and semi-randomly generated class names.
For all those that recommend using Javascript, or CSS to obfuscate the numbers, well there's probably a way around it. Firefox has a plugin called abduction. Basically what it does is saves the page to a file as an image. You could probably modify this plugin to save the image, and then analyze the image to find out the secret number that is trying to be hidden. Basically, if there's enough incentive behind scraping these numbers from the page, then it will be done. Otherwise, just post a regular number, and make it easier on your users so they won't have to worry so much about not being able to copy and paste the number, or other such problems the result from this trickery.
593,092
I want to protect only certain numbers that are displayed after each request. There are about 30 such numbers. I was planning to have images generated in the place of those numerbers, but if the image is not warped as with captcha, wont scripts be able to decipher the number anyway? Also, how much of a performance hit would loading images be vs text?
2009/02/27
[ "https://Stackoverflow.com/questions/593092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49632/" ]
I think you guys are being too reactive with these solutions. Javascript, Capcha, even litigation and the DMCA process don't address the complex adaptive nature of web scraping and data theft. Don't you think the "ideal" solution to prevent malicious bots and website scraping would be something working in a real-time proactive mitigation strategy? Very similar to a Content Protection Network. Just say'n. Examples: IBM - [IBM ISS Data Security Services](http://www-01.ibm.com/common/ssi/cgi-bin/ssialias?subtype=ca&infotype=an&appname=iSource&supplier=897&letternum=ENUS610-003&open&cm_mmc=6210-_-n-_-vrm_newsletter-_-10207_145074&cmibm_em=dm:0:16661896) DISTIL - [www.distil.it](http://www.distil.it)
I don't think this is possible, you can make their job harder (use images as some suggested here) but this is all you can do, you can't stop a determined person from getting the data, if you don't want them to scrape your data, don't publish it, as simple as that ...
593,092
I want to protect only certain numbers that are displayed after each request. There are about 30 such numbers. I was planning to have images generated in the place of those numerbers, but if the image is not warped as with captcha, wont scripts be able to decipher the number anyway? Also, how much of a performance hit would loading images be vs text?
2009/02/27
[ "https://Stackoverflow.com/questions/593092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49632/" ]
Generate an image containing those numbers and display the image. :-)
For all those that recommend using Javascript, or CSS to obfuscate the numbers, well there's probably a way around it. Firefox has a plugin called abduction. Basically what it does is saves the page to a file as an image. You could probably modify this plugin to save the image, and then analyze the image to find out the secret number that is trying to be hidden. Basically, if there's enough incentive behind scraping these numbers from the page, then it will be done. Otherwise, just post a regular number, and make it easier on your users so they won't have to worry so much about not being able to copy and paste the number, or other such problems the result from this trickery.
593,092
I want to protect only certain numbers that are displayed after each request. There are about 30 such numbers. I was planning to have images generated in the place of those numerbers, but if the image is not warped as with captcha, wont scripts be able to decipher the number anyway? Also, how much of a performance hit would loading images be vs text?
2009/02/27
[ "https://Stackoverflow.com/questions/593092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49632/" ]
It's not possible. * You use javascript and encrypt the page, using document.write() calls after decrypting. I either scrape from the browser's display or feed the page through a JS engine to get the output. * You use Flash. I can poke into the flash file and get the values. You encrypt them in the flash and I can just run it then grab the output from the interpreter's display as a sequence of images. * You use images and I can just feed them through an OCR. You're in an arms race. What you need to do is make your information so useful and your pages so easy to use that you become the authority source. It's also handy to change your output formats regularly to keep up, but screen scrapers can handle that unless you make fairly radical changes. Radical changes drive users away because the page is continually unfamiliar to them. Your image solution wont' help much, and images are far less efficient. A number is usually only a few bytes long in HTML encoding. Images start at a few hundred bytes and expand to a 1k or more depending on how large you want. Images also will not render in the font the user has selected for their browser window, and are useless to people who use assisted computing devices (visually impaired people).
What about posting a lot of dummy numbers and showing the right ones with external CSS? Just as long the scraper doesn't start to parse the external CSS.
593,092
I want to protect only certain numbers that are displayed after each request. There are about 30 such numbers. I was planning to have images generated in the place of those numerbers, but if the image is not warped as with captcha, wont scripts be able to decipher the number anyway? Also, how much of a performance hit would loading images be vs text?
2009/02/27
[ "https://Stackoverflow.com/questions/593092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49632/" ]
I think you guys are being too reactive with these solutions. Javascript, Capcha, even litigation and the DMCA process don't address the complex adaptive nature of web scraping and data theft. Don't you think the "ideal" solution to prevent malicious bots and website scraping would be something working in a real-time proactive mitigation strategy? Very similar to a Content Protection Network. Just say'n. Examples: IBM - [IBM ISS Data Security Services](http://www-01.ibm.com/common/ssi/cgi-bin/ssialias?subtype=ca&infotype=an&appname=iSource&supplier=897&letternum=ENUS610-003&open&cm_mmc=6210-_-n-_-vrm_newsletter-_-10207_145074&cmibm_em=dm:0:16661896) DISTIL - [www.distil.it](http://www.distil.it)
just do something unexpected and weird (different every time) w/ CSS box model. Force them to actually use a browser backed screenscraper.
593,092
I want to protect only certain numbers that are displayed after each request. There are about 30 such numbers. I was planning to have images generated in the place of those numerbers, but if the image is not warped as with captcha, wont scripts be able to decipher the number anyway? Also, how much of a performance hit would loading images be vs text?
2009/02/27
[ "https://Stackoverflow.com/questions/593092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49632/" ]
Javascript would probably be the easiest to implement, but you could get really creative and have large blocks of numbers with certain ones being viewable by placing layers on top of the invalid numbers, blending the wrong numbers into the background, or making them invisible via css and semi-randomly generated class names.
I don't think this is possible, you can make their job harder (use images as some suggested here) but this is all you can do, you can't stop a determined person from getting the data, if you don't want them to scrape your data, don't publish it, as simple as that ...
593,092
I want to protect only certain numbers that are displayed after each request. There are about 30 such numbers. I was planning to have images generated in the place of those numerbers, but if the image is not warped as with captcha, wont scripts be able to decipher the number anyway? Also, how much of a performance hit would loading images be vs text?
2009/02/27
[ "https://Stackoverflow.com/questions/593092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49632/" ]
It's not possible. * You use javascript and encrypt the page, using document.write() calls after decrypting. I either scrape from the browser's display or feed the page through a JS engine to get the output. * You use Flash. I can poke into the flash file and get the values. You encrypt them in the flash and I can just run it then grab the output from the interpreter's display as a sequence of images. * You use images and I can just feed them through an OCR. You're in an arms race. What you need to do is make your information so useful and your pages so easy to use that you become the authority source. It's also handy to change your output formats regularly to keep up, but screen scrapers can handle that unless you make fairly radical changes. Radical changes drive users away because the page is continually unfamiliar to them. Your image solution wont' help much, and images are far less efficient. A number is usually only a few bytes long in HTML encoding. Images start at a few hundred bytes and expand to a 1k or more depending on how large you want. Images also will not render in the font the user has selected for their browser window, and are useless to people who use assisted computing devices (visually impaired people).
I can't believe I'm promoting a common malware scripting tactic, but... You could encode the numbers as encoded Javascript that gets rendered at runtime.
593,092
I want to protect only certain numbers that are displayed after each request. There are about 30 such numbers. I was planning to have images generated in the place of those numerbers, but if the image is not warped as with captcha, wont scripts be able to decipher the number anyway? Also, how much of a performance hit would loading images be vs text?
2009/02/27
[ "https://Stackoverflow.com/questions/593092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49632/" ]
I think you guys are being too reactive with these solutions. Javascript, Capcha, even litigation and the DMCA process don't address the complex adaptive nature of web scraping and data theft. Don't you think the "ideal" solution to prevent malicious bots and website scraping would be something working in a real-time proactive mitigation strategy? Very similar to a Content Protection Network. Just say'n. Examples: IBM - [IBM ISS Data Security Services](http://www-01.ibm.com/common/ssi/cgi-bin/ssialias?subtype=ca&infotype=an&appname=iSource&supplier=897&letternum=ENUS610-003&open&cm_mmc=6210-_-n-_-vrm_newsletter-_-10207_145074&cmibm_em=dm:0:16661896) DISTIL - [www.distil.it](http://www.distil.it)
Assuming these numbers are updated often (if they aren't then protecting them is completely moot as a human can just transcribe them by hand) you can limit automated scraping via throttling. An automated script would have to hit your site often to check for updates, if you can limit these checks you win, without resorting to obfuscation. For pointers on throttling see [this question](https://stackoverflow.com/questions/450835/how-do-you-stop-scripters-from-slamming-your-website-hundreds-of-times-a-second).