qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
2,634,657
I am wondering if there is a function I could use in the standard libary. Do I need another library (BTW, I am developing for unix).
2010/04/14
[ "https://Stackoverflow.com/questions/2634657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302206/" ]
Use `scanf()` Format: `int scanf ( const char * format, ... );` `Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string.` Example: ``` #include <stdio.h> int main(void) { int n; printf("Enter the value to be stored in n: "); scanf("%d",&n); printf("n= %d",n); } ``` However have a look at **[this.](http://c-faq.com/stdio/scanfprobs.html)**
'Tis interesting - two answers so far both suggest `scanf()`; I wouldn't. When everything goes right, `scanf()` is OK. When things go wrong, recovery tends to be hard. I would normally use `fgets()` to read the user information for one line into a buffer (character array) first. I would then use `sscanf()` to collect information from the buffer into the target variables. The big advantage is that if the user types '12Z' when you wanted them to type two numbers, you can tell them what you saw and why it is not what you wanted much better. With `scanf()`, you can't do that.
966,841
Installed Ubuntu 17.10 today, menubar, launcher and the bar which indicates time/date/network connection status are missing. I am using the secondary display and connecting the laptop to the secondary. Even without the secondary display, the top bar on the screen and launcher are missing. When secondary is enabled and laptop display is disabled,there is no menu bar, launcher and bar at the screen top are also missing. In Ubuntu 17.04 if we disable built-in-display and enable secondary display it works fine. How can I fix it in Ubuntu 17.10?
2017/10/20
[ "https://askubuntu.com/questions/966841", "https://askubuntu.com", "https://askubuntu.com/users/360871/" ]
I have the same problem. So far I was able to enable the launcher on every screen. To do that you need to go to Settings -> Dock and pick "All displays" for "Show on" setting.
Have you tried setting the secondary display as your main one? The top panel only shows on the main display by default in Gnome 3. Unfortunately multi monitor support in Gnome 3 is not really polished in my opinion. Hopefully things will get better now that Ubuntu is using it.
966,841
Installed Ubuntu 17.10 today, menubar, launcher and the bar which indicates time/date/network connection status are missing. I am using the secondary display and connecting the laptop to the secondary. Even without the secondary display, the top bar on the screen and launcher are missing. When secondary is enabled and laptop display is disabled,there is no menu bar, launcher and bar at the screen top are also missing. In Ubuntu 17.04 if we disable built-in-display and enable secondary display it works fine. How can I fix it in Ubuntu 17.10?
2017/10/20
[ "https://askubuntu.com/questions/966841", "https://askubuntu.com", "https://askubuntu.com/users/360871/" ]
I think its simpler than that. Just set "show on" to "All displays" in the Dock settings on Ubuntu 17.10: [![screen](https://i.stack.imgur.com/v8FN1.png)](https://i.stack.imgur.com/v8FN1.png)
I am not entirely sure if what I will suggest is helpful for the very specific question, but I hope it is helpful to other users. After upgrading some pcs from Ubuntu Gnome 17.04 to Ubuntu 17.10 with dual monitors, it occurred to me that the monitor order and the primary monitor gets changed from the first monitor to the second. This configuration can be found in the new Ubuntu in Settings, Devices, Displays: [![Ubuntu 17.10 Monitor settings](https://i.stack.imgur.com/OweKL.png)](https://i.stack.imgur.com/OweKL.png) You can drag-drop to reorder the displays, and there is a small area below labelled 'Primary Display' which is not very obvious that is clickable.
966,841
Installed Ubuntu 17.10 today, menubar, launcher and the bar which indicates time/date/network connection status are missing. I am using the secondary display and connecting the laptop to the secondary. Even without the secondary display, the top bar on the screen and launcher are missing. When secondary is enabled and laptop display is disabled,there is no menu bar, launcher and bar at the screen top are also missing. In Ubuntu 17.04 if we disable built-in-display and enable secondary display it works fine. How can I fix it in Ubuntu 17.10?
2017/10/20
[ "https://askubuntu.com/questions/966841", "https://askubuntu.com", "https://askubuntu.com/users/360871/" ]
I am not entirely sure if what I will suggest is helpful for the very specific question, but I hope it is helpful to other users. After upgrading some pcs from Ubuntu Gnome 17.04 to Ubuntu 17.10 with dual monitors, it occurred to me that the monitor order and the primary monitor gets changed from the first monitor to the second. This configuration can be found in the new Ubuntu in Settings, Devices, Displays: [![Ubuntu 17.10 Monitor settings](https://i.stack.imgur.com/OweKL.png)](https://i.stack.imgur.com/OweKL.png) You can drag-drop to reorder the displays, and there is a small area below labelled 'Primary Display' which is not very obvious that is clickable.
Have you tried setting the secondary display as your main one? The top panel only shows on the main display by default in Gnome 3. Unfortunately multi monitor support in Gnome 3 is not really polished in my opinion. Hopefully things will get better now that Ubuntu is using it.
966,841
Installed Ubuntu 17.10 today, menubar, launcher and the bar which indicates time/date/network connection status are missing. I am using the secondary display and connecting the laptop to the secondary. Even without the secondary display, the top bar on the screen and launcher are missing. When secondary is enabled and laptop display is disabled,there is no menu bar, launcher and bar at the screen top are also missing. In Ubuntu 17.04 if we disable built-in-display and enable secondary display it works fine. How can I fix it in Ubuntu 17.10?
2017/10/20
[ "https://askubuntu.com/questions/966841", "https://askubuntu.com", "https://askubuntu.com/users/360871/" ]
Install the Gnome Tweak Tool: ``` sudo apt install gnome-tweak-tool ``` Then launch it ``` gnome-tweak-tool ``` Or get to it by searching for "tweak" in the "Show Applications" area. Bottom left will be a "workspaces" tab where you can tweak your workspaces. I found what I was looking for there. [![enter image description here](https://i.stack.imgur.com/eIAJU.png)](https://i.stack.imgur.com/eIAJU.png)
Have you tried setting the secondary display as your main one? The top panel only shows on the main display by default in Gnome 3. Unfortunately multi monitor support in Gnome 3 is not really polished in my opinion. Hopefully things will get better now that Ubuntu is using it.
966,841
Installed Ubuntu 17.10 today, menubar, launcher and the bar which indicates time/date/network connection status are missing. I am using the secondary display and connecting the laptop to the secondary. Even without the secondary display, the top bar on the screen and launcher are missing. When secondary is enabled and laptop display is disabled,there is no menu bar, launcher and bar at the screen top are also missing. In Ubuntu 17.04 if we disable built-in-display and enable secondary display it works fine. How can I fix it in Ubuntu 17.10?
2017/10/20
[ "https://askubuntu.com/questions/966841", "https://askubuntu.com", "https://askubuntu.com/users/360871/" ]
I think its simpler than that. Just set "show on" to "All displays" in the Dock settings on Ubuntu 17.10: [![screen](https://i.stack.imgur.com/v8FN1.png)](https://i.stack.imgur.com/v8FN1.png)
I have the same problem. So far I was able to enable the launcher on every screen. To do that you need to go to Settings -> Dock and pick "All displays" for "Show on" setting.
966,841
Installed Ubuntu 17.10 today, menubar, launcher and the bar which indicates time/date/network connection status are missing. I am using the secondary display and connecting the laptop to the secondary. Even without the secondary display, the top bar on the screen and launcher are missing. When secondary is enabled and laptop display is disabled,there is no menu bar, launcher and bar at the screen top are also missing. In Ubuntu 17.04 if we disable built-in-display and enable secondary display it works fine. How can I fix it in Ubuntu 17.10?
2017/10/20
[ "https://askubuntu.com/questions/966841", "https://askubuntu.com", "https://askubuntu.com/users/360871/" ]
You might try enabling the "multi-monitors-add-on". Follow the directions given here: <https://www.maketecheasier.com/extend-gnome-3-panel-dual-monitors/>, Reproduced Here for convenience: ``` git clone https://github.com/spin83/multi-monitors-add-on.git cd multi-monitors-add-on cp -r multi-monitors-add-on@spin83 ~/.local/share/gnome-shell/extensions ``` Relaunch Gnome Shell by typing "Alt+F2", then typing "r" and pressing enter Make sure you have gnome-tweak-tool ``` sudo apt install gnome-tweak-tool ``` Then open "tweaks" (gnome-tweak-tool), click on the "extensions", and then enable "Multi monitors add-on" NB this Also works for Ubuntu 18.04...
I have the same problem. So far I was able to enable the launcher on every screen. To do that you need to go to Settings -> Dock and pick "All displays" for "Show on" setting.
966,841
Installed Ubuntu 17.10 today, menubar, launcher and the bar which indicates time/date/network connection status are missing. I am using the secondary display and connecting the laptop to the secondary. Even without the secondary display, the top bar on the screen and launcher are missing. When secondary is enabled and laptop display is disabled,there is no menu bar, launcher and bar at the screen top are also missing. In Ubuntu 17.04 if we disable built-in-display and enable secondary display it works fine. How can I fix it in Ubuntu 17.10?
2017/10/20
[ "https://askubuntu.com/questions/966841", "https://askubuntu.com", "https://askubuntu.com/users/360871/" ]
I think its simpler than that. Just set "show on" to "All displays" in the Dock settings on Ubuntu 17.10: [![screen](https://i.stack.imgur.com/v8FN1.png)](https://i.stack.imgur.com/v8FN1.png)
Have you tried setting the secondary display as your main one? The top panel only shows on the main display by default in Gnome 3. Unfortunately multi monitor support in Gnome 3 is not really polished in my opinion. Hopefully things will get better now that Ubuntu is using it.
966,841
Installed Ubuntu 17.10 today, menubar, launcher and the bar which indicates time/date/network connection status are missing. I am using the secondary display and connecting the laptop to the secondary. Even without the secondary display, the top bar on the screen and launcher are missing. When secondary is enabled and laptop display is disabled,there is no menu bar, launcher and bar at the screen top are also missing. In Ubuntu 17.04 if we disable built-in-display and enable secondary display it works fine. How can I fix it in Ubuntu 17.10?
2017/10/20
[ "https://askubuntu.com/questions/966841", "https://askubuntu.com", "https://askubuntu.com/users/360871/" ]
You might try enabling the "multi-monitors-add-on". Follow the directions given here: <https://www.maketecheasier.com/extend-gnome-3-panel-dual-monitors/>, Reproduced Here for convenience: ``` git clone https://github.com/spin83/multi-monitors-add-on.git cd multi-monitors-add-on cp -r multi-monitors-add-on@spin83 ~/.local/share/gnome-shell/extensions ``` Relaunch Gnome Shell by typing "Alt+F2", then typing "r" and pressing enter Make sure you have gnome-tweak-tool ``` sudo apt install gnome-tweak-tool ``` Then open "tweaks" (gnome-tweak-tool), click on the "extensions", and then enable "Multi monitors add-on" NB this Also works for Ubuntu 18.04...
I am not entirely sure if what I will suggest is helpful for the very specific question, but I hope it is helpful to other users. After upgrading some pcs from Ubuntu Gnome 17.04 to Ubuntu 17.10 with dual monitors, it occurred to me that the monitor order and the primary monitor gets changed from the first monitor to the second. This configuration can be found in the new Ubuntu in Settings, Devices, Displays: [![Ubuntu 17.10 Monitor settings](https://i.stack.imgur.com/OweKL.png)](https://i.stack.imgur.com/OweKL.png) You can drag-drop to reorder the displays, and there is a small area below labelled 'Primary Display' which is not very obvious that is clickable.
966,841
Installed Ubuntu 17.10 today, menubar, launcher and the bar which indicates time/date/network connection status are missing. I am using the secondary display and connecting the laptop to the secondary. Even without the secondary display, the top bar on the screen and launcher are missing. When secondary is enabled and laptop display is disabled,there is no menu bar, launcher and bar at the screen top are also missing. In Ubuntu 17.04 if we disable built-in-display and enable secondary display it works fine. How can I fix it in Ubuntu 17.10?
2017/10/20
[ "https://askubuntu.com/questions/966841", "https://askubuntu.com", "https://askubuntu.com/users/360871/" ]
You might try enabling the "multi-monitors-add-on". Follow the directions given here: <https://www.maketecheasier.com/extend-gnome-3-panel-dual-monitors/>, Reproduced Here for convenience: ``` git clone https://github.com/spin83/multi-monitors-add-on.git cd multi-monitors-add-on cp -r multi-monitors-add-on@spin83 ~/.local/share/gnome-shell/extensions ``` Relaunch Gnome Shell by typing "Alt+F2", then typing "r" and pressing enter Make sure you have gnome-tweak-tool ``` sudo apt install gnome-tweak-tool ``` Then open "tweaks" (gnome-tweak-tool), click on the "extensions", and then enable "Multi monitors add-on" NB this Also works for Ubuntu 18.04...
Have you tried setting the secondary display as your main one? The top panel only shows on the main display by default in Gnome 3. Unfortunately multi monitor support in Gnome 3 is not really polished in my opinion. Hopefully things will get better now that Ubuntu is using it.
966,841
Installed Ubuntu 17.10 today, menubar, launcher and the bar which indicates time/date/network connection status are missing. I am using the secondary display and connecting the laptop to the secondary. Even without the secondary display, the top bar on the screen and launcher are missing. When secondary is enabled and laptop display is disabled,there is no menu bar, launcher and bar at the screen top are also missing. In Ubuntu 17.04 if we disable built-in-display and enable secondary display it works fine. How can I fix it in Ubuntu 17.10?
2017/10/20
[ "https://askubuntu.com/questions/966841", "https://askubuntu.com", "https://askubuntu.com/users/360871/" ]
I think its simpler than that. Just set "show on" to "All displays" in the Dock settings on Ubuntu 17.10: [![screen](https://i.stack.imgur.com/v8FN1.png)](https://i.stack.imgur.com/v8FN1.png)
You might try enabling the "multi-monitors-add-on". Follow the directions given here: <https://www.maketecheasier.com/extend-gnome-3-panel-dual-monitors/>, Reproduced Here for convenience: ``` git clone https://github.com/spin83/multi-monitors-add-on.git cd multi-monitors-add-on cp -r multi-monitors-add-on@spin83 ~/.local/share/gnome-shell/extensions ``` Relaunch Gnome Shell by typing "Alt+F2", then typing "r" and pressing enter Make sure you have gnome-tweak-tool ``` sudo apt install gnome-tweak-tool ``` Then open "tweaks" (gnome-tweak-tool), click on the "extensions", and then enable "Multi monitors add-on" NB this Also works for Ubuntu 18.04...
32,122,794
I'm just starting with Meteor. In an app which is to be localized, I want to set the document title. I am following the [advice given by Bernát](https://stackoverflow.com/a/19010848/1927589) In my barebones version, I have just 2 documents: head.html ``` <head> <meta charset="utf-8"> <title>{{localizedTitle}}</title> </head> ``` ui.js ``` UI.registerHelper("localizedTitle", function() { var title = "Localized Title" document.title = title; }); ``` When the app loads, the document title is "{{localizedTitle}}". If I call `UI._globalHelpers.localizedTitle()` from the console, the correct title is shown. What do I have to do to get the localized title to show when the page is loaded? --- EDIT: This works for me, but it seems to be a bit of a hack. The `title` template does nothing but get itself rendered, which actually adds nothing to the interface. body.html ``` <body> {{> title}} </body> <template name="title"> </template> ``` title.js ``` Template.title.onRendered(function () { document.title = getLocalizedString() function getLocalizedString() { return "Title : in English" } }) ```
2015/08/20
[ "https://Stackoverflow.com/questions/32122794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1927589/" ]
Following Bernát's answer, your global helper should not be called in the head's `<title>` tag, but within the `<template>` tag of the template where you wish to have a given title. In Meteor, `<head>` does not count as a template, therefore you cannot use Spacebars notation in it: it will just be considered as simple text. Also, keep in mind that your helper will not return (i.e. print) anything to the page. `document.title = "something"` directly assigns "something" to your ` tag. So no need to call your helper inside it! So, say you want to have the "Localized Title" title for a page using the `localized` template : ``` <template name="localized"> <h1>This is the localized page</h1> {{localizedTitle}} </template> ``` Here, your trick should work.
I've found it convenient to set the title in *onAfterAction* in my iron-router routes: ``` onAfterAction: function(){ document.title = 'foo'; // ex: your site's name var routeName = Router.current().route.getName(); if ( routeName ) document.title = document.title + ': ' + routeName; } ```
32,122,794
I'm just starting with Meteor. In an app which is to be localized, I want to set the document title. I am following the [advice given by Bernát](https://stackoverflow.com/a/19010848/1927589) In my barebones version, I have just 2 documents: head.html ``` <head> <meta charset="utf-8"> <title>{{localizedTitle}}</title> </head> ``` ui.js ``` UI.registerHelper("localizedTitle", function() { var title = "Localized Title" document.title = title; }); ``` When the app loads, the document title is "{{localizedTitle}}". If I call `UI._globalHelpers.localizedTitle()` from the console, the correct title is shown. What do I have to do to get the localized title to show when the page is loaded? --- EDIT: This works for me, but it seems to be a bit of a hack. The `title` template does nothing but get itself rendered, which actually adds nothing to the interface. body.html ``` <body> {{> title}} </body> <template name="title"> </template> ``` title.js ``` Template.title.onRendered(function () { document.title = getLocalizedString() function getLocalizedString() { return "Title : in English" } }) ```
2015/08/20
[ "https://Stackoverflow.com/questions/32122794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1927589/" ]
Following Bernát's answer, your global helper should not be called in the head's `<title>` tag, but within the `<template>` tag of the template where you wish to have a given title. In Meteor, `<head>` does not count as a template, therefore you cannot use Spacebars notation in it: it will just be considered as simple text. Also, keep in mind that your helper will not return (i.e. print) anything to the page. `document.title = "something"` directly assigns "something" to your ` tag. So no need to call your helper inside it! So, say you want to have the "Localized Title" title for a page using the `localized` template : ``` <template name="localized"> <h1>This is the localized page</h1> {{localizedTitle}} </template> ``` Here, your trick should work.
I think a more elegant solution is to make the title reactive and set it via a Session variable (other reactive data sources are of course also OK). Like that: ``` Template.body.onRendered(function() { this.autorun(function() { document.title = Session.get('documentTitle'); }); }); ``` Now every time you set the 'documentTitle' variable with ``` Session.set('documentTitle', 'Awesome title'); ``` the page title will change. No need for hacks and you can do this anywhere in your client code.
32,122,794
I'm just starting with Meteor. In an app which is to be localized, I want to set the document title. I am following the [advice given by Bernát](https://stackoverflow.com/a/19010848/1927589) In my barebones version, I have just 2 documents: head.html ``` <head> <meta charset="utf-8"> <title>{{localizedTitle}}</title> </head> ``` ui.js ``` UI.registerHelper("localizedTitle", function() { var title = "Localized Title" document.title = title; }); ``` When the app loads, the document title is "{{localizedTitle}}". If I call `UI._globalHelpers.localizedTitle()` from the console, the correct title is shown. What do I have to do to get the localized title to show when the page is loaded? --- EDIT: This works for me, but it seems to be a bit of a hack. The `title` template does nothing but get itself rendered, which actually adds nothing to the interface. body.html ``` <body> {{> title}} </body> <template name="title"> </template> ``` title.js ``` Template.title.onRendered(function () { document.title = getLocalizedString() function getLocalizedString() { return "Title : in English" } }) ```
2015/08/20
[ "https://Stackoverflow.com/questions/32122794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1927589/" ]
Following Bernát's answer, your global helper should not be called in the head's `<title>` tag, but within the `<template>` tag of the template where you wish to have a given title. In Meteor, `<head>` does not count as a template, therefore you cannot use Spacebars notation in it: it will just be considered as simple text. Also, keep in mind that your helper will not return (i.e. print) anything to the page. `document.title = "something"` directly assigns "something" to your ` tag. So no need to call your helper inside it! So, say you want to have the "Localized Title" title for a page using the `localized` template : ``` <template name="localized"> <h1>This is the localized page</h1> {{localizedTitle}} </template> ``` Here, your trick should work.
Try this instead: ``` UI.registerHelper('title', function() { return 'LocalizedTitle' }); ``` we can use title where ever you want you can use like this `{{title}}`
68,622,993
How would I transform the array in imageCollection to get the array in carouselPhotos? (See code below). ``` export default class HomeScreen extends Component { state = { imageCollection: [ { name: "Pictures of birds" image1: "http://127.0.0.1:8000/media/image1A.jpg", image2: "http://127.0.0.1:8000/media/image2A.jpg", image3: "http://127.0.0.1:8000/media/image3A.jpg"} ], carouselPhotos: [ { image: "http://127.0.0.1:8000/media/image1A.jpg", }, { image: "http://127.0.0.1:8000/media/image2A.jpg", }, { image: "http://127.0.0.1:8000/media/image3A.jpg", }, ], }; ``` I am using the react-native-snap-carousel, which renders 1 carousel card per object, so each image must be its own object. It is also important that the data in carouselPhotos is labeled as 'image', and it must be loaded for when the page opens. Any help would be greatly appreciated! Clarifications: imageCollection has many objects, but I will just pick one object for the carouselPhoto. There are three image properties names imageX, but there are also other properties such as "name"
2021/08/02
[ "https://Stackoverflow.com/questions/68622993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16372363/" ]
You can simply retrieve the values from your `imageCollection` object, then map them to the desired format. ``` Object.values(state.imageCollection[0]).map(imgUrl => ({ image: imgUrl })); ``` ### EDIT Since the object in your `imageCollection` array contains keys that should be ignored, we can first filter them out before mapping to the transformed result. We filter out keys that do not begin with the string "image", using [`Array.prototype.startsWith()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith). This means we also need to gather the keys from the object along with the values, so we use [`Object.entries()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries): ``` Object.entries(state.imageCollection[0]).filter(([key, val]) => key.startsWith("image")).map(([key, val]) => ({ image: val})); ``` Try it out: ```js state = { imageCollection: [ { name: "Pictures of birds", image1: "http://127.0.0.1:8000/media/image1A.jpg", image2: "http://127.0.0.1:8000/media/image2A.jpg", image3: "http://127.0.0.1:8000/media/image3A.jpg" } ] } const result = Object.entries(state.imageCollection[0]) .filter( ([key, val]) => key.startsWith("image")) .map( ([key, val]) => ({ image: val})); console.log(result); state.carouselPhotos = result; console.log(state); ```
You can use `reduce` & inside the callback iterate the current object and create a new object for each image and push it to the accumulator array ```js const imageCollection = [{ image1: "http://127.0.0.1:8000/media/image1A.jpg", image2: "http://127.0.0.1:8000/media/image2A.jpg", image3: "http://127.0.0.1:8000/media/image3A.jpg" }] const carouselData = imageCollection.reduce((acc, curr) => { for (let keys in curr) { acc.push({ image: curr[keys] }) } return acc; }, []); console.log(carouselData) ```
18,739,354
I have some authentication requried to hit a particular url. In browser I need to login only once, as for other related urls which can use the session id from the cookie need not required to go to the login page. Similarly, can I use the cookie generated in the cookie file using `--cookies-file=cookies.txt` in the commandline in phantomjs to open other page which requires the same cookie detail. Please suggest.
2013/09/11
[ "https://Stackoverflow.com/questions/18739354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/934913/" ]
Phantom JS and cookies ====================== `--cookies-file=cookies.txt` will only store non-session cookies in the cookie jar. Login and authentication is more commonly based on session cookies. ### What about session cookies? To save these is quite simple, but you should consider that they will likely expire quickly. You need to write your program logic to consider this. For example 1. Load cookies from the cookiejar 2. Hit a URL to check if the user is logged in 3. If not logged in Log in, Save cookies to cookiejar 4. continue with processing Example ------- ``` var fs = require('fs'); var CookieJar = "cookiejar.json"; var pageResponses = {}; page.onResourceReceived = function(response) { pageResponses[response.url] = response.status; fs.write(CookieJar, JSON.stringify(phantom.cookies), "w"); }; if(fs.isFile(CookieJar)) Array.prototype.forEach.call(JSON.parse(fs.read(CookieJar)), function(x){ phantom.addCookie(x); }); page.open(LoginCheckURL, function(status){ // this assumes that when you are not logged in, the server replies with a 303 if(pageResponses[LoginCheckURL] == 303) { //attempt login //assuming a resourceRequested event is fired the cookies will be written to the jar and on your next load of the script they will be found and used } }); ```
The file created by the option `--cookies-file=cookies.txt` is serialized from CookieJar: there are extra characters and it's sometimes difficult to parse. It may looks like: ``` [General] cookies="@Variant(\0\0\0\x7f\0\0\0\x16QList<QNetworkCookie>\0\0\0\0\x1\0\0\0\v\0\0\0{__cfduid=da7fda1ef6dd8b38450c6ad5632... ``` I used in the past [phantom.cookies](http://phantomjs.org/api/phantom/property/cookies.html). This array will be pre-populated by any existing Cookie data stored in the cookie file specified in the PhantomJS startup config/command-line options, if any. But you can also add dynamic cookie by using [phantom.addCookie](http://phantomjs.org/api/phantom/method/add-cookie.html). A basic example is ```js phantom.addCookie({ 'name': 'Valid-Cookie-Name', /* required property */ 'value': 'Valid-Cookie-Value', /* required property */ 'domain': 'localhost', /* required property */ 'path': '/foo', 'httponly': true, 'secure': false, 'expires': (new Date()).getTime() + (1000 * 60 * 60) /* <-- expires in 1 hour */ }); ``` With these methods, it's not so difficult to implement your own cookie management logic.
33,100,504
I am trying to use android arsenal libraries. i found a library here: <https://android-arsenal.com/details/1/1615> , and i downloaded a .zip file. i want to use it in my project.i have followed the instruction to add the library and add this code to the gradle ``` dependencies { compile 'com.github.chenupt:SpringIndicator:1.0.2' } ``` .but it still didn't work well. How do i add it to my project with Android Studio ?
2015/10/13
[ "https://Stackoverflow.com/questions/33100504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3505951/" ]
Look what you have added to your gradle dependecies, and what is in a tutorial. And you don't need any zip file, gradle will download the dependecies for you. It should be like this: ``` dependencies { compile 'com.github.chenupt.android:springindicator:1.0.2@aar' } ```
According to Java [docs](https://docs.gradle.org/current/userguide/java_plugin.html) `compile` is deprecated. > > ~~compile~~ (Deprecated) > > > Compile time dependencies. Superseded by implementation. > > > It should be like this: ``` dependencies { implementation 'com.github.chenupt.android:springindicator:1.0.2@aar' } ```
5,884,402
I wanted to find out what more efficient (if even) in the following code **Value type** ``` ForEach(string s in strings) { string t = s; } // or string t; ForEach(string s in strings) { t = s; } ``` and is there a different with reference types.
2011/05/04
[ "https://Stackoverflow.com/questions/5884402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544716/" ]
The two code snippets produce *exactly* the same IL. Here's the C# code I used to test with: ``` public string[] strings = new string[5]; public void TestOne() { foreach (string s in strings) { string t = s; } } public void TestTwo() { string t; foreach (string s in strings) { t = s; } } ``` And here's the resulting IL for both methods after compiling with optimizations enabled: ``` .method public hidebysig instance void TestOne() cil managed { // Code size 26 (0x1a) .maxstack 2 .locals init ([0] string s, [1] string[] CS$6$0000, [2] int32 CS$7$0001) IL_0000: ldarg.0 IL_0001: ldfld string[] strings IL_0006: stloc.1 IL_0007: ldc.i4.0 IL_0008: stloc.2 IL_0009: br.s IL_0013 IL_000b: ldloc.1 IL_000c: ldloc.2 IL_000d: ldelem.ref IL_000e: stloc.0 IL_000f: ldloc.2 IL_0010: ldc.i4.1 IL_0011: add IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldloc.1 IL_0015: ldlen IL_0016: conv.i4 IL_0017: blt.s IL_000b IL_0019: ret } // end of method TestOne .method public hidebysig instance void TestTwo() cil managed { // Code size 26 (0x1a) .maxstack 2 .locals init ([0] string s, [1] string[] CS$6$0000, [2] int32 CS$7$0001) IL_0000: ldarg.0 IL_0001: ldfld string[] strings IL_0006: stloc.1 IL_0007: ldc.i4.0 IL_0008: stloc.2 IL_0009: br.s IL_0013 IL_000b: ldloc.1 IL_000c: ldloc.2 IL_000d: ldelem.ref IL_000e: stloc.0 IL_000f: ldloc.2 IL_0010: ldc.i4.1 IL_0011: add IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldloc.1 IL_0015: ldlen IL_0016: conv.i4 IL_0017: blt.s IL_000b IL_0019: ret } // end of method TestTwo ``` As usual, the rule is the same: **trust your compiler**. Let it handle these optimizations for you, rather than trying to worry about it as you write the code. Just write the code that makes sense and is readable. Most importantly, ignore all the people who argue that one of them is "theoretically" better than the other. That's pure nonsense. There's no theory that's relevant until after the code is compiled. And since it compiles down to the exact same thing, it's guaranteed to be completely identical in performance. But if you still don't believe my urgings to trust your compiler (some of us are stubborn, I know because even I still am sometimes), at least you now know how to answer these types of questions on your own. Write some sample code that demonstrates both variations, compile it in "Release" mode, then open up the assembly in [ILDASM.exe](http://msdn.microsoft.com/en-us/library/f7dy01k1.aspx) and compare the resulting IL code for yourself. Things like this are so easy to test, there's never a reason to guess.
You don't need to do this at all. Just use `s`. Also, `string` in C#/BCL is a reference type.
5,884,402
I wanted to find out what more efficient (if even) in the following code **Value type** ``` ForEach(string s in strings) { string t = s; } // or string t; ForEach(string s in strings) { t = s; } ``` and is there a different with reference types.
2011/05/04
[ "https://Stackoverflow.com/questions/5884402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544716/" ]
Well neither of those will compile (I guess that you want to use `foreach` instead of `ForEach`?), but if they did they should compile down to the same IL after optimizations and so there would be no difference.
strings are *immutable reference types*. So the code ``` string t; foreach(string s in strings) { t = s; } ``` creates a new string instance for each step in the enumerator anyway (it doesn't "reuse" the instance `t`). There is no practical difference between the two code examples you posted.
5,884,402
I wanted to find out what more efficient (if even) in the following code **Value type** ``` ForEach(string s in strings) { string t = s; } // or string t; ForEach(string s in strings) { t = s; } ``` and is there a different with reference types.
2011/05/04
[ "https://Stackoverflow.com/questions/5884402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544716/" ]
The two code snippets produce *exactly* the same IL. Here's the C# code I used to test with: ``` public string[] strings = new string[5]; public void TestOne() { foreach (string s in strings) { string t = s; } } public void TestTwo() { string t; foreach (string s in strings) { t = s; } } ``` And here's the resulting IL for both methods after compiling with optimizations enabled: ``` .method public hidebysig instance void TestOne() cil managed { // Code size 26 (0x1a) .maxstack 2 .locals init ([0] string s, [1] string[] CS$6$0000, [2] int32 CS$7$0001) IL_0000: ldarg.0 IL_0001: ldfld string[] strings IL_0006: stloc.1 IL_0007: ldc.i4.0 IL_0008: stloc.2 IL_0009: br.s IL_0013 IL_000b: ldloc.1 IL_000c: ldloc.2 IL_000d: ldelem.ref IL_000e: stloc.0 IL_000f: ldloc.2 IL_0010: ldc.i4.1 IL_0011: add IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldloc.1 IL_0015: ldlen IL_0016: conv.i4 IL_0017: blt.s IL_000b IL_0019: ret } // end of method TestOne .method public hidebysig instance void TestTwo() cil managed { // Code size 26 (0x1a) .maxstack 2 .locals init ([0] string s, [1] string[] CS$6$0000, [2] int32 CS$7$0001) IL_0000: ldarg.0 IL_0001: ldfld string[] strings IL_0006: stloc.1 IL_0007: ldc.i4.0 IL_0008: stloc.2 IL_0009: br.s IL_0013 IL_000b: ldloc.1 IL_000c: ldloc.2 IL_000d: ldelem.ref IL_000e: stloc.0 IL_000f: ldloc.2 IL_0010: ldc.i4.1 IL_0011: add IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldloc.1 IL_0015: ldlen IL_0016: conv.i4 IL_0017: blt.s IL_000b IL_0019: ret } // end of method TestTwo ``` As usual, the rule is the same: **trust your compiler**. Let it handle these optimizations for you, rather than trying to worry about it as you write the code. Just write the code that makes sense and is readable. Most importantly, ignore all the people who argue that one of them is "theoretically" better than the other. That's pure nonsense. There's no theory that's relevant until after the code is compiled. And since it compiles down to the exact same thing, it's guaranteed to be completely identical in performance. But if you still don't believe my urgings to trust your compiler (some of us are stubborn, I know because even I still am sometimes), at least you now know how to answer these types of questions on your own. Write some sample code that demonstrates both variations, compile it in "Release" mode, then open up the assembly in [ILDASM.exe](http://msdn.microsoft.com/en-us/library/f7dy01k1.aspx) and compare the resulting IL code for yourself. Things like this are so easy to test, there's never a reason to guess.
I would bet that the compiler is intelligent enough to build them in exactly the same way. I don't think there is any difference, go on readability.
5,884,402
I wanted to find out what more efficient (if even) in the following code **Value type** ``` ForEach(string s in strings) { string t = s; } // or string t; ForEach(string s in strings) { t = s; } ``` and is there a different with reference types.
2011/05/04
[ "https://Stackoverflow.com/questions/5884402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544716/" ]
Theoretically speaking, the second one should be more efficient because the memory allocation is performed only once before the loop starts, while the first one should try to allocate memory at every iteration. However i do not know if there is any optimization performed by the compiler based on how the variable is used inside and outside the loop (in the second case the variable could be used in other parts of the code, not only in the loop).
This is the same code, only the declaration is at another place. You should always try to declare the variables next to their use, using the smallest possible scope. Note that `foreach` is written lowercase like all keywords in c#.
5,884,402
I wanted to find out what more efficient (if even) in the following code **Value type** ``` ForEach(string s in strings) { string t = s; } // or string t; ForEach(string s in strings) { t = s; } ``` and is there a different with reference types.
2011/05/04
[ "https://Stackoverflow.com/questions/5884402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544716/" ]
Well neither of those will compile (I guess that you want to use `foreach` instead of `ForEach`?), but if they did they should compile down to the same IL after optimizations and so there would be no difference.
You don't need to do this at all. Just use `s`. Also, `string` in C#/BCL is a reference type.
5,884,402
I wanted to find out what more efficient (if even) in the following code **Value type** ``` ForEach(string s in strings) { string t = s; } // or string t; ForEach(string s in strings) { t = s; } ``` and is there a different with reference types.
2011/05/04
[ "https://Stackoverflow.com/questions/5884402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544716/" ]
strings are *immutable reference types*. So the code ``` string t; foreach(string s in strings) { t = s; } ``` creates a new string instance for each step in the enumerator anyway (it doesn't "reuse" the instance `t`). There is no practical difference between the two code examples you posted.
I would bet that the compiler is intelligent enough to build them in exactly the same way. I don't think there is any difference, go on readability.
5,884,402
I wanted to find out what more efficient (if even) in the following code **Value type** ``` ForEach(string s in strings) { string t = s; } // or string t; ForEach(string s in strings) { t = s; } ``` and is there a different with reference types.
2011/05/04
[ "https://Stackoverflow.com/questions/5884402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544716/" ]
You don't need to do this at all. Just use `s`. Also, `string` in C#/BCL is a reference type.
strings are *immutable reference types*. So the code ``` string t; foreach(string s in strings) { t = s; } ``` creates a new string instance for each step in the enumerator anyway (it doesn't "reuse" the instance `t`). There is no practical difference between the two code examples you posted.
5,884,402
I wanted to find out what more efficient (if even) in the following code **Value type** ``` ForEach(string s in strings) { string t = s; } // or string t; ForEach(string s in strings) { t = s; } ``` and is there a different with reference types.
2011/05/04
[ "https://Stackoverflow.com/questions/5884402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544716/" ]
You don't need to do this at all. Just use `s`. Also, `string` in C#/BCL is a reference type.
They're both the same for memory effiency, because behind the scenes they all point to the same string. This is a semantic used by .NET/Java, and the reason why strings are immutable.
5,884,402
I wanted to find out what more efficient (if even) in the following code **Value type** ``` ForEach(string s in strings) { string t = s; } // or string t; ForEach(string s in strings) { t = s; } ``` and is there a different with reference types.
2011/05/04
[ "https://Stackoverflow.com/questions/5884402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544716/" ]
Theoretically speaking, the second one should be more efficient because the memory allocation is performed only once before the loop starts, while the first one should try to allocate memory at every iteration. However i do not know if there is any optimization performed by the compiler based on how the variable is used inside and outside the loop (in the second case the variable could be used in other parts of the code, not only in the loop).
I would bet that the compiler is intelligent enough to build them in exactly the same way. I don't think there is any difference, go on readability.
5,884,402
I wanted to find out what more efficient (if even) in the following code **Value type** ``` ForEach(string s in strings) { string t = s; } // or string t; ForEach(string s in strings) { t = s; } ``` and is there a different with reference types.
2011/05/04
[ "https://Stackoverflow.com/questions/5884402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544716/" ]
You don't need to do this at all. Just use `s`. Also, `string` in C#/BCL is a reference type.
Theoretically speaking, the second one should be more efficient because the memory allocation is performed only once before the loop starts, while the first one should try to allocate memory at every iteration. However i do not know if there is any optimization performed by the compiler based on how the variable is used inside and outside the loop (in the second case the variable could be used in other parts of the code, not only in the loop).
1,954,971
I recently needed to configure [CocoaHttpServer](http://code.google.com/p/cocoahttpserver/), which we're using in our application with success, to handle HTTPS connections coming from a client application (running on Android devices). This is fine - there is copious sample code which allows for this, and we were able to enable the secure server without issue. In practice we were seeing incredibly long SSL negotiation phases while the client was doing its handshaking with our server - upwards of 70 seconds. Through a long series of searches, I found that the delay was because of the calculation of Diffie-Hellman parameters used by default when SSL is enabled in CFSocket. This [thread](http://lists.apple.com/archives/Apple-cdsa/2008/Oct/msg00004.html) is where I first started to find the answer to my issue. To match what our Windows server was doing (using a less-secure SSL cipher) I needed to set the cipher explicitly on the Mac, which isn't easy when using AsyncSocket as a wrapper for the socket communications. Our Windows server was using: TLS\_RSA\_WITH\_RC4\_128\_MD5 )(0x04) RC4 128 bits MD5 RSA Our Macintosh server was using: TLS\_DHE\_RSA\_WITH\_AES\_256\_CBC\_SHA (0x039) AES 256 bits SHA-1 Ephemeral Diffie-Hellman key exchange using RSA certificate The difference in "security" is large, but likely not worth the effort/computation/delay that we were seeing. Security Theater?
2009/12/23
[ "https://Stackoverflow.com/questions/1954971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84727/" ]
*Please note that there are different ciphers that can be chosen - I chose to use the same one as our Windows implementation for consistency.* With information from [another question](http://lists.apple.com/archives/Apple-cdsa/2008/Oct/msg00004.html) mentioned above, I figured out how to set the cipher for CFSocket to use the same as Windows, and the code appears to be now quite a bit better - like it really works! CFSocket isn't directly exposing the SecureTransport support, which makes this kind of hard, but defining a particular key makes it work nicely. For posterity, here's the code I've added to -onSocketWillConnect: in our HTTPConnection class: ``` // define this value; it isn't exposed by CFSocketStream.h const extern CFStringRef kCFStreamPropertySocketSSLContext; ``` ... ``` CFReadStreamRef stream = [sock getCFReadStream]; CFDataRef data = (CFDataRef) CFReadStreamCopyProperty(stream, kCFStreamPropertySocketSSLContext); // Extract the SSLContextRef from the CFData SSLContextRef sslContext; CFDataGetBytes(data, CFRangeMake(0, sizeof(SSLContextRef)), (UInt8*)&sslContext); SSLCipherSuite *ciphers = (SSLCipherSuite *)malloc(1 * sizeof(SSLCipherSuite)); ciphers[0] = SSL_RSA_WITH_RC4_128_MD5; // Basic cipher - not Diffie-Hellman SSLSetEnabledCiphers(sslContext, ciphers, 1); ``` I hope this helps anyone working through the same issue as I - I'd be happy to share some more code and advice if needed.
For what it's worth, I contributed a [patch](http://code.google.com/p/cocoaasyncsocket/issues/detail?id=37) to CocoaAsyncSocket about a week before you had this issue. Sorry that I didn't notice your question back then. :-)
29,312,670
I get some errors. I need pass a member to a **const** member with operator =. I don't know what is error, my function declaration is: ``` template<class I> forceinline void OverweightValues<I>::init(int t, SharedArray<int>& elements0, SharedArray<int>& weights0, I& i) { {..} //both are declared as 'const SharedArray<int> elements, weights;' //but elements0 and weights0 not is const elements = elements0; weights = weights0; ``` When I compile get the error: ``` In line(16): no operator "=" matches these operands operand types are: const SharedArray<int> = SharedArray<int> In line(17): no operator "=" matches these operands operand types are: const SharedArray<int> = SharedArray<int> ``` How can I fix this?
2015/03/28
[ "https://Stackoverflow.com/questions/29312670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1334923/" ]
`const` members can only be set during creation. You'll need to use the constructor initializer list rather than two-phase construction. (Even the constructor body cannot assign them)
As @Ben Voigt mentioned, you can only initialize a const in the constructor initialization list. This is because, by the time the control reaches the constructor body all the class members are already created by the compiler using the default constructor. Hence, member initialization within the constructor body will actually invoke the assignment constructor which cannot be done for constants, references or objects for which default constructor is not available.
37,092,352
[![enter image description here](https://i.stack.imgur.com/fUjQU.png)](https://i.stack.imgur.com/fUjQU.png) As shown in the image, there are two circles connected by a line, I can animate the circle position by `createjs.Tween.get(circleOne).to({x: someCoord, y:anotherCoord},1000)`. I would like to update the line end points the similar way so that when the circles animate and move their ways the line end points stay attached to the circles. The line is made by `line.graphics.beginStroke("red").setStrokeStyle(2).moveTo(20,20)`. Thanks!!
2016/05/07
[ "https://Stackoverflow.com/questions/37092352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1500384/" ]
There is a better way to do this than what @tiago suggested: [Graphic Commands](http://blog.createjs.com/new-command-approach-to-easeljs-graphics/). You can update the values of commands that Graphics use any time by storing off the `command`. Here is a quick demo, where I tween 2 circles, and on the "update" event of the first tween, I update the line command values to the circle coordinates. <http://jsfiddle.net/lannymcnie/2xoL08bx/> **Example:** ``` var cmd = shape.graphics.lineTo(10,10).command; cmd.x = 20; // Changes the x of the lineTo command that is stored off. ``` You can also tween a command's properties: ``` createjs.Tween.get(cmd).to({x: 100, y:100}, 1000); ``` When a command's values change, they will draw with the new values the next time the stage is updated. You can see a list of the commands and their values in the [EaselJS docs](http://www.createjs.com/docs/easeljs/classes/Graphics.LineTo.html).
Every time the circles move you'll need to redraw the line by clearing the old graphics instructions and creating a new one in place, without TweenJS. Notice that this will be very expensive since you'll not gain any benefits from caching. Here's a line from coordinates `{x: 20, y: 20}` to `{x: 40, y: 40}`: ``` line.graphics.beginStroke("red").setStrokeStyle(2).moveTo(20,20).lineTo(40, 40); ``` Now if you want to change the end points to `{x: 10, y: 10}` to `{x: 50, y: 50}` you'll need to use: ``` line.graphics.clear(); line.graphics.beginStroke("red").setStrokeStyle(2).moveTo(10,10).lineTo(50, 50); ``` Remember that using `line.cache(x, y, w, h);` after the movement is highly recommended because it'll save the processor from drawing that line every frame unnecessarily.
6,198,994
I have two fields in my database for storing starttime and endtime. they are of datetime. I pick time from them using tostring("hh:mm tt"). Now I want to update only the time part of the date. I have dropdownlist to select hour and minutes and AM/PM. How can I update the time of date stored in sql server using Entity framework / LINQ in MVC3 application. Please suggest
2011/06/01
[ "https://Stackoverflow.com/questions/6198994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/634710/" ]
If I get this right, you want to look into using [foreign keys](http://www.postgresql.org/docs/9.0/static/tutorial-fk.html) and [triggers](http://www.postgresql.org/docs/9.0/static/plpgsql-trigger.html).
If it's a 1:1 relationship, could you not just combine the tables?
7,242,804
I Have a json array like ``` [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}] ``` How can i pass(to the backend) and store(in db) that javascript object with asp.net?? **EDIT:** OK to make it clearer, in some page, i got a javascript object ``` var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]; ``` , how can i pass it to some handler (like using ``` `$.post({url:"handler.ashx", data:array}) ``` ??), then in backend how can i save it into database or load this array later?? **OR**: I'll appreciate it if u teach me how to convert ``` var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]; ``` into: ``` var arraystring = '[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]'; ``` **EDIT2**: Now i use the string-solution (traversal the array and add some '"' ':' ',' '{}' manually) as i mentioned just above, is there any potential problems??
2011/08/30
[ "https://Stackoverflow.com/questions/7242804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342366/" ]
You have several options when dealing with JSON on .NET * You can simply keep the array as is in the DB and retrieve it as is and use it * You can parse it into an Object using [JSON.NET Library](http://json.codeplex.com/) for example on the 2nd case you simple use the JSON.NET method: ``` Newtonsoft.Json.Converters.KeyValuePairConverter ``` Or be fancy and use a [Custom Deserialize](http://james.newtonking.com/projects/json/help/) as it's really easy to pass to and from JSON. --- Let's imagine that you are posting something like this: ``` $.post("myForm.aspx", [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}], function() { // all done. }); ``` This will be converted to `A,B,C` when requesting the data using `Request.Form["name"]` or simply `Request["name"]` so you should change all the naming convention first and then you can simple use `Request["nameA"]`, `Request["nameB"]`, etc...
You would store it just like any other string you wanted to store in the database. If you want to re-instantiate it later in JavaScript you use the eval() function on the string to convert it back into an object.
7,242,804
I Have a json array like ``` [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}] ``` How can i pass(to the backend) and store(in db) that javascript object with asp.net?? **EDIT:** OK to make it clearer, in some page, i got a javascript object ``` var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]; ``` , how can i pass it to some handler (like using ``` `$.post({url:"handler.ashx", data:array}) ``` ??), then in backend how can i save it into database or load this array later?? **OR**: I'll appreciate it if u teach me how to convert ``` var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]; ``` into: ``` var arraystring = '[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]'; ``` **EDIT2**: Now i use the string-solution (traversal the array and add some '"' ':' ',' '{}' manually) as i mentioned just above, is there any potential problems??
2011/08/30
[ "https://Stackoverflow.com/questions/7242804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342366/" ]
You have several options when dealing with JSON on .NET * You can simply keep the array as is in the DB and retrieve it as is and use it * You can parse it into an Object using [JSON.NET Library](http://json.codeplex.com/) for example on the 2nd case you simple use the JSON.NET method: ``` Newtonsoft.Json.Converters.KeyValuePairConverter ``` Or be fancy and use a [Custom Deserialize](http://james.newtonking.com/projects/json/help/) as it's really easy to pass to and from JSON. --- Let's imagine that you are posting something like this: ``` $.post("myForm.aspx", [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}], function() { // all done. }); ``` This will be converted to `A,B,C` when requesting the data using `Request.Form["name"]` or simply `Request["name"]` so you should change all the naming convention first and then you can simple use `Request["nameA"]`, `Request["nameB"]`, etc...
The best way to do this is to de-serialize the json into object and save it to db as records. Check JSON.NET library <http://json.codeplex.com/> ``` public class MyObj { public string name{get;set;} public string value{get;set;} } void Main() { string json ="[{\"name\":\"A\",\"value\":\"A\"},{\"name\":\"B\",\"value\":\"B\"},{\"name\":\"C\",\"value\":\"C\"}]"; IList<MyObj> arr = JsonConvert.DeserializeObject<IList<MyObj>>(json); foreach(MyObj o in arr) { //add each object to db... Console.WriteLine(o.name+":"+o.value); } } ```
7,242,804
I Have a json array like ``` [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}] ``` How can i pass(to the backend) and store(in db) that javascript object with asp.net?? **EDIT:** OK to make it clearer, in some page, i got a javascript object ``` var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]; ``` , how can i pass it to some handler (like using ``` `$.post({url:"handler.ashx", data:array}) ``` ??), then in backend how can i save it into database or load this array later?? **OR**: I'll appreciate it if u teach me how to convert ``` var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]; ``` into: ``` var arraystring = '[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]'; ``` **EDIT2**: Now i use the string-solution (traversal the array and add some '"' ':' ',' '{}' manually) as i mentioned just above, is there any potential problems??
2011/08/30
[ "https://Stackoverflow.com/questions/7242804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342366/" ]
You have several options when dealing with JSON on .NET * You can simply keep the array as is in the DB and retrieve it as is and use it * You can parse it into an Object using [JSON.NET Library](http://json.codeplex.com/) for example on the 2nd case you simple use the JSON.NET method: ``` Newtonsoft.Json.Converters.KeyValuePairConverter ``` Or be fancy and use a [Custom Deserialize](http://james.newtonking.com/projects/json/help/) as it's really easy to pass to and from JSON. --- Let's imagine that you are posting something like this: ``` $.post("myForm.aspx", [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}], function() { // all done. }); ``` This will be converted to `A,B,C` when requesting the data using `Request.Form["name"]` or simply `Request["name"]` so you should change all the naming convention first and then you can simple use `Request["nameA"]`, `Request["nameB"]`, etc...
Ok it turns out that using JSON.parse and JSON.stringify is a not-bad solution.
2,948
How do I query an EOSIO system contract table ? As a learning challenge, I am trying to figure out how to calculate the amount of EOS votes cast and aggregate attributes of vote. Can I use **eosjs** to do this ? I can't figure out where all this information is documented. EOS dev portal seems to be missing this information all together. Thanks in advance.
2018/10/25
[ "https://eosio.stackexchange.com/questions/2948", "https://eosio.stackexchange.com", "https://eosio.stackexchange.com/users/2460/" ]
System tables are not (yet) well documented. You have to browse the source code. E.g. for voters you will find table `eosio voters` here: <https://github.com/EOSIO/eos/blob/905e7c85714aee4286fa180ce946f15ceb4ce73c/contracts/eosio.system/eosio.system.hpp#L115> `cleos -u https://eu.eosdac.io get table eosio eosio voters` will return the first rows.
You have two options two read any table (whether system table or table of another contract) by connecting to a public node: * cleos `get table` call: <https://developers.eos.io/eosio-cleos/reference#cleos-get-table> * rcp api `get_table_rows` call <https://developers.eos.io/eosio-nodeos/reference#get_table_rows>
310,416
I want to create a table with all the people who works in a store. What would be the title of such a table? "Members"? "Workers", "Employees", something else?
2016/02/28
[ "https://english.stackexchange.com/questions/310416", "https://english.stackexchange.com", "https://english.stackexchange.com/users/162774/" ]
Consider [Workforce](http://www.merriam-webster.com/dictionary/workforce) > > the group of people who work for a particular organization or business > > > Synonyms include [Personnel](http://www.merriam-webster.com/dictionary/personnel), [Staff](http://www.merriam-webster.com/dictionary/staff)
A boss is not necessarily an employer. A boss is someone who bosses (directs, manages, supervises,...) others. If the employer is a corporation or other non-human entity/organization, and **if the boss is also an employee**, then the word is *employee*. This is perhaps the most common case. If the boss is the employer (a human, such as a business owner) then there is no term I'm aware of - they are all people at XYZ organization. And IMO, *workforce* refers not to an employer but to those who are employed. This can include bosses, if they too are employees. Similarly, if the workers are not actually employees - for example, in a volunteer organization. There, bosses and those whom they boss are perhaps all *members* (or associates or volunteers or participants) of the organization.
43,793,366
Here is the screenshot from chrome dev tools. Here I want to override .ui-menu class and want to increase its with to "20em". [![enter image description here](https://i.stack.imgur.com/qIcsf.png)](https://i.stack.imgur.com/qIcsf.png) Here is what I am trying to override it : ``` .menu.ui-menu{ width:20em; } ``` I know my css is loading after the base css. Why its not taking the css supplied in custom css class? **UPDATE** None of the suggestions provided below worked for me. I have added a div and provided id to div "menu". Now when I use following css , it works : ``` #menu { width:20em; background-color: yellow; } ``` Here is the screenshot from console: [![enter image description here](https://i.stack.imgur.com/B7uP9.png)](https://i.stack.imgur.com/B7uP9.png) Still unable to increase width of menu that has class "ui-menu". Can someone please help in identifying the selector for "ui-menu" ?
2017/05/04
[ "https://Stackoverflow.com/questions/43793366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3550077/" ]
You just need a space between `.menu` and `.ui-menu`, like this: ``` .menu .ui-menu { width:20em; } ``` `.menu.ui-menu` is looking for an element with both the `menu` and `ui-menu` classes, whereas `.menu .ui-menu` is looking for an element with class `ui-menu` that is a child of `menu`.
The ui-menu class is on a div, so you could write: ``` div.ui-menu { width:20em; } ``` or ``` .ui-menu { width:20em !important; } ``` or ``` body .ui-menu{ width:20em; } ``` or something else, all solutions are higher weighted than the ".ui-menu" style as there already is at the moment
43,793,366
Here is the screenshot from chrome dev tools. Here I want to override .ui-menu class and want to increase its with to "20em". [![enter image description here](https://i.stack.imgur.com/qIcsf.png)](https://i.stack.imgur.com/qIcsf.png) Here is what I am trying to override it : ``` .menu.ui-menu{ width:20em; } ``` I know my css is loading after the base css. Why its not taking the css supplied in custom css class? **UPDATE** None of the suggestions provided below worked for me. I have added a div and provided id to div "menu". Now when I use following css , it works : ``` #menu { width:20em; background-color: yellow; } ``` Here is the screenshot from console: [![enter image description here](https://i.stack.imgur.com/B7uP9.png)](https://i.stack.imgur.com/B7uP9.png) Still unable to increase width of menu that has class "ui-menu". Can someone please help in identifying the selector for "ui-menu" ?
2017/05/04
[ "https://Stackoverflow.com/questions/43793366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3550077/" ]
You just need a space between `.menu` and `.ui-menu`, like this: ``` .menu .ui-menu { width:20em; } ``` `.menu.ui-menu` is looking for an element with both the `menu` and `ui-menu` classes, whereas `.menu .ui-menu` is looking for an element with class `ui-menu` that is a child of `menu`.
I found answer to this problem. I am trying to set the css in angular 4 application and all styles are encapsulated by default. to fix this , use following code in component class: ``` import { ViewEncapsulation } from '@angular/core'; @Component({ encapsulation: ViewEncapsulation.None }) ``` Once this is done, all css overriding will work as expected.
43,793,366
Here is the screenshot from chrome dev tools. Here I want to override .ui-menu class and want to increase its with to "20em". [![enter image description here](https://i.stack.imgur.com/qIcsf.png)](https://i.stack.imgur.com/qIcsf.png) Here is what I am trying to override it : ``` .menu.ui-menu{ width:20em; } ``` I know my css is loading after the base css. Why its not taking the css supplied in custom css class? **UPDATE** None of the suggestions provided below worked for me. I have added a div and provided id to div "menu". Now when I use following css , it works : ``` #menu { width:20em; background-color: yellow; } ``` Here is the screenshot from console: [![enter image description here](https://i.stack.imgur.com/B7uP9.png)](https://i.stack.imgur.com/B7uP9.png) Still unable to increase width of menu that has class "ui-menu". Can someone please help in identifying the selector for "ui-menu" ?
2017/05/04
[ "https://Stackoverflow.com/questions/43793366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3550077/" ]
I found answer to this problem. I am trying to set the css in angular 4 application and all styles are encapsulated by default. to fix this , use following code in component class: ``` import { ViewEncapsulation } from '@angular/core'; @Component({ encapsulation: ViewEncapsulation.None }) ``` Once this is done, all css overriding will work as expected.
The ui-menu class is on a div, so you could write: ``` div.ui-menu { width:20em; } ``` or ``` .ui-menu { width:20em !important; } ``` or ``` body .ui-menu{ width:20em; } ``` or something else, all solutions are higher weighted than the ".ui-menu" style as there already is at the moment
18,295,126
I have a big problem for getting/computing the minutes. Scenario: I have a form which is the user can input the seconds [5s, 10s, 25s, 30s, 60s]. I called the table *"Duration"* I already have *"Duration"* [compose of minutes:seconds], in my database which is ***"1:5"*** [the last input]. Then I insert again another seconds ***"10s"***... \*the format is ***minutes:seconds*** The correct output should be: **1:15** The current result is : **0:15** AS we see. I have a problem in computing the minutes. The codes I will show is good for subtracting the seconds. But now I need to revised it to adding the seconds. Here's my code: ``` $duration = $_POST["duration"]; if(sizeof($bldg) == 1) { $total = sizeof($bldg)-1; } else { $total = sizeof($bldg)%2; } for($i=0; $i<sizeof($bldg);$i++) { $result = mysql_query("SELECT fldTotalDuration FROM tbldata WHERE fldNetname = '".$network."' AND fldBldgName = '".$bldg[$i]."' AND fldWeek = '".$week."' AND fldMonth = '".$month."' "); if(mysql_num_rows($result)==0) { $totalduration = ""; $seconds = 0; $minutes = 0; $computeSecMin = $seconds * $minutes; $subSecMin = $computeSecMin + $duration; $getMin = floor($subSecMin/60); $getSec = $subSecMin%60; $totalduration = $getMin .":". $getSec; } else{ $row = mysql_fetch_array($result); $time = explode(":",$row['fldTotalDuration']); $dur = explode(" ",$duration); $computeSecMin = 60 * $time[0]; $subSecMin = $computeSecMin + $time[1] + $dur[0]; $getMin = floor($subSecMin/60); $getSec = $subSecMin%60; $totalduration = $getMin .":". $getSec; } } $query = "INSERT INTO tbldata(fldNetname,fldBldgName,fldPlaylist,fldMonth,fldWeek,fldDuration,fldFrom,fldTo,fldTotalDuration) VALUES ('".$network."','".$bldg[$i]."','".$AdName."','".$month."','".$week."','".$duration."','".$from."','".$to."', '".$totalduration."')"; mysql_query($query) or die (mysql_error()); ``` $duration = is came from another form where its a combobox/dropdown that is consists of 5s, 10s, 25s, 30s, 60s. Currently, for adding the seconds is okay but for minutes is not good. my problem for the computation is this ***"$getMin = floor($subSecMin/60); "*** .The result of this is ***"0"*** but it should be ***"1"*** because this computation is for *"minutes"*. Thanks for helping me with this problem.
2013/08/18
[ "https://Stackoverflow.com/questions/18295126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2617970/" ]
Are you using `GET` or `POST` to submit your form data? If you're using `POST`, you can check the request method: ``` if($_SERVER['REQUEST_METHOD'] == 'POST') { // Validate form data } else { // Display form } ``` If you're using `GET` you should check if any of the data you need is set. For example: ``` if(isset($_GET["arg1"]) || isset($_GET["arg2"]) || isset($_GET["arg3"]) || ...) { // Validate data } else { // Display form } ```
You can also have an `<input type="submit" name="submit" value="Submit" />` and you can check `if (isset($_POST['submit'])) { ...` (I assume you're using Post; most forms should be Post, but it'll work with Get too). You can easily have multiple forms on the same page, and just check the presence of different submit buttons. I find this a little more elegant for checking whether the form was submitted; afterwards you validate the fields (e.g. whether they were filled out, etc.).
18,295,126
I have a big problem for getting/computing the minutes. Scenario: I have a form which is the user can input the seconds [5s, 10s, 25s, 30s, 60s]. I called the table *"Duration"* I already have *"Duration"* [compose of minutes:seconds], in my database which is ***"1:5"*** [the last input]. Then I insert again another seconds ***"10s"***... \*the format is ***minutes:seconds*** The correct output should be: **1:15** The current result is : **0:15** AS we see. I have a problem in computing the minutes. The codes I will show is good for subtracting the seconds. But now I need to revised it to adding the seconds. Here's my code: ``` $duration = $_POST["duration"]; if(sizeof($bldg) == 1) { $total = sizeof($bldg)-1; } else { $total = sizeof($bldg)%2; } for($i=0; $i<sizeof($bldg);$i++) { $result = mysql_query("SELECT fldTotalDuration FROM tbldata WHERE fldNetname = '".$network."' AND fldBldgName = '".$bldg[$i]."' AND fldWeek = '".$week."' AND fldMonth = '".$month."' "); if(mysql_num_rows($result)==0) { $totalduration = ""; $seconds = 0; $minutes = 0; $computeSecMin = $seconds * $minutes; $subSecMin = $computeSecMin + $duration; $getMin = floor($subSecMin/60); $getSec = $subSecMin%60; $totalduration = $getMin .":". $getSec; } else{ $row = mysql_fetch_array($result); $time = explode(":",$row['fldTotalDuration']); $dur = explode(" ",$duration); $computeSecMin = 60 * $time[0]; $subSecMin = $computeSecMin + $time[1] + $dur[0]; $getMin = floor($subSecMin/60); $getSec = $subSecMin%60; $totalduration = $getMin .":". $getSec; } } $query = "INSERT INTO tbldata(fldNetname,fldBldgName,fldPlaylist,fldMonth,fldWeek,fldDuration,fldFrom,fldTo,fldTotalDuration) VALUES ('".$network."','".$bldg[$i]."','".$AdName."','".$month."','".$week."','".$duration."','".$from."','".$to."', '".$totalduration."')"; mysql_query($query) or die (mysql_error()); ``` $duration = is came from another form where its a combobox/dropdown that is consists of 5s, 10s, 25s, 30s, 60s. Currently, for adding the seconds is okay but for minutes is not good. my problem for the computation is this ***"$getMin = floor($subSecMin/60); "*** .The result of this is ***"0"*** but it should be ***"1"*** because this computation is for *"minutes"*. Thanks for helping me with this problem.
2013/08/18
[ "https://Stackoverflow.com/questions/18295126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2617970/" ]
I have done like this to solve the Issue `public function funName(){` `// to avoid validation when the page loads` `if($_SERVER['REQUEST_METHOD'] != 'POST') {` `$this->load->view('user/index');` `}` ``` ... //rest of content ``` `}`
You can also have an `<input type="submit" name="submit" value="Submit" />` and you can check `if (isset($_POST['submit'])) { ...` (I assume you're using Post; most forms should be Post, but it'll work with Get too). You can easily have multiple forms on the same page, and just check the presence of different submit buttons. I find this a little more elegant for checking whether the form was submitted; afterwards you validate the fields (e.g. whether they were filled out, etc.).
35,167,576
I manage to get the data I want from database using `array_push` and `encode` it into `JSON` in `PHP`. The results I get are like below, ``` { "name":[ "Lucky Draw Ticket", "KIP Voucher RM10", "KIP Voucher RM20", "KIP Voucher RM50" ], "image":[ "\/l\/u\/lucky_draw_ticket_1.jpg", "\/c\/a\/cash-voucher.jpg", "\/c\/a\/cash-voucher2.jpg", "\/c\/a\/cash-voucher50_1.jpg" ], "price":[ "50.0000", "1500.0000", "2500.0000", "5000.0000" ]} ``` But now I want to separate it into something like below, but I don't know how to do. ``` { "catalog":[ { "name": "Lucky Draw Ticket", "image": "\/l\/u\/lucky_draw_ticket_1.jpg", "price": "50.0000" }, { "name": "KIP Voucher RM10", "image": "\/c\/a\/cash-voucher.jpg", "price": "1500.0000" }, { "name": "KIP Voucher RM20", "image": "\/c\/a\/cash-voucher2.jpg", "price": "2500.0000" }, { "name": "KIP Voucher RM20", "image": "\/c\/a\/cash-voucher50_1.jpg" "price": "5000.0000" } ]} ```
2016/02/03
[ "https://Stackoverflow.com/questions/35167576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4697373/" ]
Try this: * create a Json object from the Json string, * reorganize the object into a temporary PHP array, * create a Json object (string) from the PHP arrray. Code ---- ``` <?php $sjson='{ "name":[ "Lucky Draw Ticket", "KIP Voucher RM10", "KIP Voucher RM20", "KIP Voucher RM50" ], "image":[ "\/l\/u\/lucky_draw_ticket_1.jpg", "\/c\/a\/cash-voucher.jpg", "\/c\/a\/cash-voucher2.jpg", "\/c\/a\/cash-voucher50_1.jpg" ], "price":[ "50.0000", "1500.0000", "2500.0000", "5000.0000" ]}'; $tarray = json_decode($sjson); $newarray = array('catalog'=>array()); foreach($tarray->name as $ix => $name) { $newarray['catalog'][]=array( 'name' => $tarray->name[$ix], 'image' => $tarray->image[$ix], 'price' => $tarray->price[$ix], ); } $sjson = json_encode($newarray); // echo '<pre>'; var_dump($sjson); echo '</pre>'; ?> ``` Result ------ ``` { "catalog":[ { "name":"Lucky Draw Ticket", "image":"\/l\/u\/lucky_draw_ticket_1.jpg", "price":"50.0000" }, { "name":"KIP Voucher RM10", "image":"\/c\/a\/cash-voucher.jpg", "price":"1500.0000" }, { "name":"KIP Voucher RM20", "image":"\/c\/a\/cash-voucher2.jpg", "price":"2500.0000" }, { "name":"KIP Voucher RM50", "image":"\/c\/a\/cash-voucher50_1.jpg", "price":"5000.0000" } ] } ```
An example: ``` <?php $data = json_decode('{ "name":[ "Lucky Draw Ticket", "KIP Voucher RM10", "KIP Voucher RM20", "KIP Voucher RM50" ], "image":[ "\/l\/u\/lucky_draw_ticket_1.jpg", "\/c\/a\/cash-voucher.jpg", "\/c\/a\/cash-voucher2.jpg", "\/c\/a\/cash-voucher50_1.jpg" ], "price":[ "50.0000", "1500.0000", "2500.0000", "5000.0000" ]}', true); $result = [ 'catalog' => [ ] ]; for ($i=0; $i<=count($data); $i++) { $temp = []; array_push($temp, $data['name'][$i]); array_push($temp, $data['image'][$i]); array_push($temp, $data['price'][$i]); array_push($result['catalog'], $temp); } ?> <pre> <?php print_r($result); ?> </pre> <?php // Convert back to JSON $json = json_encode($result); ?> ```
35,167,576
I manage to get the data I want from database using `array_push` and `encode` it into `JSON` in `PHP`. The results I get are like below, ``` { "name":[ "Lucky Draw Ticket", "KIP Voucher RM10", "KIP Voucher RM20", "KIP Voucher RM50" ], "image":[ "\/l\/u\/lucky_draw_ticket_1.jpg", "\/c\/a\/cash-voucher.jpg", "\/c\/a\/cash-voucher2.jpg", "\/c\/a\/cash-voucher50_1.jpg" ], "price":[ "50.0000", "1500.0000", "2500.0000", "5000.0000" ]} ``` But now I want to separate it into something like below, but I don't know how to do. ``` { "catalog":[ { "name": "Lucky Draw Ticket", "image": "\/l\/u\/lucky_draw_ticket_1.jpg", "price": "50.0000" }, { "name": "KIP Voucher RM10", "image": "\/c\/a\/cash-voucher.jpg", "price": "1500.0000" }, { "name": "KIP Voucher RM20", "image": "\/c\/a\/cash-voucher2.jpg", "price": "2500.0000" }, { "name": "KIP Voucher RM20", "image": "\/c\/a\/cash-voucher50_1.jpg" "price": "5000.0000" } ]} ```
2016/02/03
[ "https://Stackoverflow.com/questions/35167576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4697373/" ]
Try this: * create a Json object from the Json string, * reorganize the object into a temporary PHP array, * create a Json object (string) from the PHP arrray. Code ---- ``` <?php $sjson='{ "name":[ "Lucky Draw Ticket", "KIP Voucher RM10", "KIP Voucher RM20", "KIP Voucher RM50" ], "image":[ "\/l\/u\/lucky_draw_ticket_1.jpg", "\/c\/a\/cash-voucher.jpg", "\/c\/a\/cash-voucher2.jpg", "\/c\/a\/cash-voucher50_1.jpg" ], "price":[ "50.0000", "1500.0000", "2500.0000", "5000.0000" ]}'; $tarray = json_decode($sjson); $newarray = array('catalog'=>array()); foreach($tarray->name as $ix => $name) { $newarray['catalog'][]=array( 'name' => $tarray->name[$ix], 'image' => $tarray->image[$ix], 'price' => $tarray->price[$ix], ); } $sjson = json_encode($newarray); // echo '<pre>'; var_dump($sjson); echo '</pre>'; ?> ``` Result ------ ``` { "catalog":[ { "name":"Lucky Draw Ticket", "image":"\/l\/u\/lucky_draw_ticket_1.jpg", "price":"50.0000" }, { "name":"KIP Voucher RM10", "image":"\/c\/a\/cash-voucher.jpg", "price":"1500.0000" }, { "name":"KIP Voucher RM20", "image":"\/c\/a\/cash-voucher2.jpg", "price":"2500.0000" }, { "name":"KIP Voucher RM50", "image":"\/c\/a\/cash-voucher50_1.jpg", "price":"5000.0000" } ] } ```
Try this.. ``` $str = '{ "name":[ "Lucky Draw Ticket", "KIP Voucher RM10", "KIP Voucher RM20", "KIP Voucher RM50" ], "image":[ "\/l\/u\/lucky_draw_ticket_1.jpg", "\/c\/a\/cash-voucher.jpg", "\/c\/a\/cash-voucher2.jpg", "\/c\/a\/cash-voucher50_1.jpg" ], "price":[ "50.0000", "1500.0000", "2500.0000", "5000.0000" ]}'; $jsonArr = json_decode($str, true); //create array in needed format $finalArr = array(); foreach ($jsonArr AS $key => $dataArr) { $count = count($dataArr); for ($indx = 0; $indx < $count; $indx++) { $finalArr['catalog'][$indx][$key] = $dataArr[$indx]; } } //output $jsonFinal = json_encode($finalArr, true); echo $jsonFinal; ```
35,167,576
I manage to get the data I want from database using `array_push` and `encode` it into `JSON` in `PHP`. The results I get are like below, ``` { "name":[ "Lucky Draw Ticket", "KIP Voucher RM10", "KIP Voucher RM20", "KIP Voucher RM50" ], "image":[ "\/l\/u\/lucky_draw_ticket_1.jpg", "\/c\/a\/cash-voucher.jpg", "\/c\/a\/cash-voucher2.jpg", "\/c\/a\/cash-voucher50_1.jpg" ], "price":[ "50.0000", "1500.0000", "2500.0000", "5000.0000" ]} ``` But now I want to separate it into something like below, but I don't know how to do. ``` { "catalog":[ { "name": "Lucky Draw Ticket", "image": "\/l\/u\/lucky_draw_ticket_1.jpg", "price": "50.0000" }, { "name": "KIP Voucher RM10", "image": "\/c\/a\/cash-voucher.jpg", "price": "1500.0000" }, { "name": "KIP Voucher RM20", "image": "\/c\/a\/cash-voucher2.jpg", "price": "2500.0000" }, { "name": "KIP Voucher RM20", "image": "\/c\/a\/cash-voucher50_1.jpg" "price": "5000.0000" } ]} ```
2016/02/03
[ "https://Stackoverflow.com/questions/35167576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4697373/" ]
Try this: * create a Json object from the Json string, * reorganize the object into a temporary PHP array, * create a Json object (string) from the PHP arrray. Code ---- ``` <?php $sjson='{ "name":[ "Lucky Draw Ticket", "KIP Voucher RM10", "KIP Voucher RM20", "KIP Voucher RM50" ], "image":[ "\/l\/u\/lucky_draw_ticket_1.jpg", "\/c\/a\/cash-voucher.jpg", "\/c\/a\/cash-voucher2.jpg", "\/c\/a\/cash-voucher50_1.jpg" ], "price":[ "50.0000", "1500.0000", "2500.0000", "5000.0000" ]}'; $tarray = json_decode($sjson); $newarray = array('catalog'=>array()); foreach($tarray->name as $ix => $name) { $newarray['catalog'][]=array( 'name' => $tarray->name[$ix], 'image' => $tarray->image[$ix], 'price' => $tarray->price[$ix], ); } $sjson = json_encode($newarray); // echo '<pre>'; var_dump($sjson); echo '</pre>'; ?> ``` Result ------ ``` { "catalog":[ { "name":"Lucky Draw Ticket", "image":"\/l\/u\/lucky_draw_ticket_1.jpg", "price":"50.0000" }, { "name":"KIP Voucher RM10", "image":"\/c\/a\/cash-voucher.jpg", "price":"1500.0000" }, { "name":"KIP Voucher RM20", "image":"\/c\/a\/cash-voucher2.jpg", "price":"2500.0000" }, { "name":"KIP Voucher RM50", "image":"\/c\/a\/cash-voucher50_1.jpg", "price":"5000.0000" } ] } ```
> > Use this code to get exact result what you expect.. > > > `$string = your json string.` > > > ``` $json_decode = json_decode($string,true); $temp = array(); $i = 0; foreach($json_decode as $key=>$val){ $temp['catalog'][$i]['name'] = $json_decode['name'][$i]; $temp['catalog'][$i]['image'] = $json_decode['image'][$i]; $temp['catalog'][$i]['price'] = $json_decode['price'][$i]; $i++; } echo "<pre>"; print_r($temp); print_r(json_encode($temp)); ```
35,167,576
I manage to get the data I want from database using `array_push` and `encode` it into `JSON` in `PHP`. The results I get are like below, ``` { "name":[ "Lucky Draw Ticket", "KIP Voucher RM10", "KIP Voucher RM20", "KIP Voucher RM50" ], "image":[ "\/l\/u\/lucky_draw_ticket_1.jpg", "\/c\/a\/cash-voucher.jpg", "\/c\/a\/cash-voucher2.jpg", "\/c\/a\/cash-voucher50_1.jpg" ], "price":[ "50.0000", "1500.0000", "2500.0000", "5000.0000" ]} ``` But now I want to separate it into something like below, but I don't know how to do. ``` { "catalog":[ { "name": "Lucky Draw Ticket", "image": "\/l\/u\/lucky_draw_ticket_1.jpg", "price": "50.0000" }, { "name": "KIP Voucher RM10", "image": "\/c\/a\/cash-voucher.jpg", "price": "1500.0000" }, { "name": "KIP Voucher RM20", "image": "\/c\/a\/cash-voucher2.jpg", "price": "2500.0000" }, { "name": "KIP Voucher RM20", "image": "\/c\/a\/cash-voucher50_1.jpg" "price": "5000.0000" } ]} ```
2016/02/03
[ "https://Stackoverflow.com/questions/35167576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4697373/" ]
Try this: * create a Json object from the Json string, * reorganize the object into a temporary PHP array, * create a Json object (string) from the PHP arrray. Code ---- ``` <?php $sjson='{ "name":[ "Lucky Draw Ticket", "KIP Voucher RM10", "KIP Voucher RM20", "KIP Voucher RM50" ], "image":[ "\/l\/u\/lucky_draw_ticket_1.jpg", "\/c\/a\/cash-voucher.jpg", "\/c\/a\/cash-voucher2.jpg", "\/c\/a\/cash-voucher50_1.jpg" ], "price":[ "50.0000", "1500.0000", "2500.0000", "5000.0000" ]}'; $tarray = json_decode($sjson); $newarray = array('catalog'=>array()); foreach($tarray->name as $ix => $name) { $newarray['catalog'][]=array( 'name' => $tarray->name[$ix], 'image' => $tarray->image[$ix], 'price' => $tarray->price[$ix], ); } $sjson = json_encode($newarray); // echo '<pre>'; var_dump($sjson); echo '</pre>'; ?> ``` Result ------ ``` { "catalog":[ { "name":"Lucky Draw Ticket", "image":"\/l\/u\/lucky_draw_ticket_1.jpg", "price":"50.0000" }, { "name":"KIP Voucher RM10", "image":"\/c\/a\/cash-voucher.jpg", "price":"1500.0000" }, { "name":"KIP Voucher RM20", "image":"\/c\/a\/cash-voucher2.jpg", "price":"2500.0000" }, { "name":"KIP Voucher RM50", "image":"\/c\/a\/cash-voucher50_1.jpg", "price":"5000.0000" } ] } ```
Simply you can use `array_map` like as ``` array_map(null,$jsonArr['name'],$jsonArr['image'],$jsonArr['price']); ``` So your code looks like as ``` $jsonArr = json_decode($json, true); $result['catalog'] = array_map(null,$jsonArr['name'],$jsonArr['image'],$jsonArr['price']); echo json_encode($result); ``` Output: ``` { "catalog": [ [ "Lucky Draw Ticket", "\/l\/u\/lucky_draw_ticket_1.jpg", "50.0000" ], [ "KIP Voucher RM10", "\/c\/a\/cash-voucher.jpg", "1500.0000" ], [ "KIP Voucher RM20", "\/c\/a\/cash-voucher2.jpg", "2500.0000" ], [ "KIP Voucher RM50", "\/c\/a\/cash-voucher50_1.jpg", "5000.0000" ] ] } ```
1,995,666
I made a huge error in a gigantic XML file. ``` <item1> <item2> <item1> //.. tons of stuff... </item1> </item2> </item1> ``` I need to replace the outer item1 with something else. But find and replace isn't working because of the matching inner item1. I've tried searching by multiple pieces of information, but the single-line nature of every find and replace I find makes it impossible, and all of the data is tabbed. Any ideas?
2010/01/03
[ "https://Stackoverflow.com/questions/1995666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84685/" ]
If you can match a regular expression then you could match: ``` <item1>\n[any whitespace]<item2> ``` and change it to: ``` <item3>\n[any whitespace]<item2> ``` and the same for ``` </item1>\n[any whitespace]</item2> ``` and change it to: ``` </item3>\n[any whitespace]</item2> ``` I haven't specified the [any whitespace] expression as I know it's different for different editors.
Use a regular expression search or other advanced search/replace method to replace the inner <item1> tag with something else temporarily (by specifying the tab characters before it as well). Then replace the remaining item1 tags, which will now be the outer ones, before changing your temporary ones back again.
1,995,666
I made a huge error in a gigantic XML file. ``` <item1> <item2> <item1> //.. tons of stuff... </item1> </item2> </item1> ``` I need to replace the outer item1 with something else. But find and replace isn't working because of the matching inner item1. I've tried searching by multiple pieces of information, but the single-line nature of every find and replace I find makes it impossible, and all of the data is tabbed. Any ideas?
2010/01/03
[ "https://Stackoverflow.com/questions/1995666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84685/" ]
[xmlstarlet](http://xmlstar.sourceforge.net/) can help.
If the XML is all formatted like that, you should be able to use regular expressions. You might also try formatters to get that format. Otherwise you could read the XML with an XML-parser in a language you know, change it there and write it back to disk.
1,995,666
I made a huge error in a gigantic XML file. ``` <item1> <item2> <item1> //.. tons of stuff... </item1> </item2> </item1> ``` I need to replace the outer item1 with something else. But find and replace isn't working because of the matching inner item1. I've tried searching by multiple pieces of information, but the single-line nature of every find and replace I find makes it impossible, and all of the data is tabbed. Any ideas?
2010/01/03
[ "https://Stackoverflow.com/questions/1995666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84685/" ]
If you can match a regular expression then you could match: ``` <item1>\n[any whitespace]<item2> ``` and change it to: ``` <item3>\n[any whitespace]<item2> ``` and the same for ``` </item1>\n[any whitespace]</item2> ``` and change it to: ``` </item3>\n[any whitespace]</item2> ``` I haven't specified the [any whitespace] expression as I know it's different for different editors.
If the XML is all formatted like that, you should be able to use regular expressions. You might also try formatters to get that format. Otherwise you could read the XML with an XML-parser in a language you know, change it there and write it back to disk.
1,995,666
I made a huge error in a gigantic XML file. ``` <item1> <item2> <item1> //.. tons of stuff... </item1> </item2> </item1> ``` I need to replace the outer item1 with something else. But find and replace isn't working because of the matching inner item1. I've tried searching by multiple pieces of information, but the single-line nature of every find and replace I find makes it impossible, and all of the data is tabbed. Any ideas?
2010/01/03
[ "https://Stackoverflow.com/questions/1995666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84685/" ]
Can you use the tabs to your advantage? If it is as regular as your example then you can probably search and replace on `\t\t\t<item>` (or whatever syntax you need to search with tabs) with whatever else you need.
If you can match a regular expression then you could match: ``` <item1>\n[any whitespace]<item2> ``` and change it to: ``` <item3>\n[any whitespace]<item2> ``` and the same for ``` </item1>\n[any whitespace]</item2> ``` and change it to: ``` </item3>\n[any whitespace]</item2> ``` I haven't specified the [any whitespace] expression as I know it's different for different editors.
1,995,666
I made a huge error in a gigantic XML file. ``` <item1> <item2> <item1> //.. tons of stuff... </item1> </item2> </item1> ``` I need to replace the outer item1 with something else. But find and replace isn't working because of the matching inner item1. I've tried searching by multiple pieces of information, but the single-line nature of every find and replace I find makes it impossible, and all of the data is tabbed. Any ideas?
2010/01/03
[ "https://Stackoverflow.com/questions/1995666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84685/" ]
Regex may have worked in this instance, but regex is generally NOT the best means of modifying XML. [XML is not regular](http://welbog.homeip.net/glue/53/XML-is-not-regular). You should use XML tools to parse and manipulate XML data, or you will likely run into problems at some point. Transforming the XML using an XSLT [identity transform](http://en.wikipedia.org/wiki/Identity_transform) with a template for the particular "item1" element is one example that would be a more safe, robust solution: ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:apply-templates /> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="item1[item2/item1]" > <!--Replace this literal element "NEW_ITEM_ELEMENT" with whatever name you need to change "item1" elements to: --> <NEW_ITEM_ELEMENT> <xsl:apply-templates /> </NEW_ITEM_ELEMENT> </xsl:template> </xsl:stylesheet> ```
If the XML is all formatted like that, you should be able to use regular expressions. You might also try formatters to get that format. Otherwise you could read the XML with an XML-parser in a language you know, change it there and write it back to disk.
1,995,666
I made a huge error in a gigantic XML file. ``` <item1> <item2> <item1> //.. tons of stuff... </item1> </item2> </item1> ``` I need to replace the outer item1 with something else. But find and replace isn't working because of the matching inner item1. I've tried searching by multiple pieces of information, but the single-line nature of every find and replace I find makes it impossible, and all of the data is tabbed. Any ideas?
2010/01/03
[ "https://Stackoverflow.com/questions/1995666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84685/" ]
If you can match a regular expression then you could match: ``` <item1>\n[any whitespace]<item2> ``` and change it to: ``` <item3>\n[any whitespace]<item2> ``` and the same for ``` </item1>\n[any whitespace]</item2> ``` and change it to: ``` </item3>\n[any whitespace]</item2> ``` I haven't specified the [any whitespace] expression as I know it's different for different editors.
Regex may have worked in this instance, but regex is generally NOT the best means of modifying XML. [XML is not regular](http://welbog.homeip.net/glue/53/XML-is-not-regular). You should use XML tools to parse and manipulate XML data, or you will likely run into problems at some point. Transforming the XML using an XSLT [identity transform](http://en.wikipedia.org/wiki/Identity_transform) with a template for the particular "item1" element is one example that would be a more safe, robust solution: ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:apply-templates /> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="item1[item2/item1]" > <!--Replace this literal element "NEW_ITEM_ELEMENT" with whatever name you need to change "item1" elements to: --> <NEW_ITEM_ELEMENT> <xsl:apply-templates /> </NEW_ITEM_ELEMENT> </xsl:template> </xsl:stylesheet> ```
1,995,666
I made a huge error in a gigantic XML file. ``` <item1> <item2> <item1> //.. tons of stuff... </item1> </item2> </item1> ``` I need to replace the outer item1 with something else. But find and replace isn't working because of the matching inner item1. I've tried searching by multiple pieces of information, but the single-line nature of every find and replace I find makes it impossible, and all of the data is tabbed. Any ideas?
2010/01/03
[ "https://Stackoverflow.com/questions/1995666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84685/" ]
Can you use the tabs to your advantage? If it is as regular as your example then you can probably search and replace on `\t\t\t<item>` (or whatever syntax you need to search with tabs) with whatever else you need.
[xmlstarlet](http://xmlstar.sourceforge.net/) can help.
1,995,666
I made a huge error in a gigantic XML file. ``` <item1> <item2> <item1> //.. tons of stuff... </item1> </item2> </item1> ``` I need to replace the outer item1 with something else. But find and replace isn't working because of the matching inner item1. I've tried searching by multiple pieces of information, but the single-line nature of every find and replace I find makes it impossible, and all of the data is tabbed. Any ideas?
2010/01/03
[ "https://Stackoverflow.com/questions/1995666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84685/" ]
Can you use the tabs to your advantage? If it is as regular as your example then you can probably search and replace on `\t\t\t<item>` (or whatever syntax you need to search with tabs) with whatever else you need.
Use a regular expression search or other advanced search/replace method to replace the inner <item1> tag with something else temporarily (by specifying the tab characters before it as well). Then replace the remaining item1 tags, which will now be the outer ones, before changing your temporary ones back again.
1,995,666
I made a huge error in a gigantic XML file. ``` <item1> <item2> <item1> //.. tons of stuff... </item1> </item2> </item1> ``` I need to replace the outer item1 with something else. But find and replace isn't working because of the matching inner item1. I've tried searching by multiple pieces of information, but the single-line nature of every find and replace I find makes it impossible, and all of the data is tabbed. Any ideas?
2010/01/03
[ "https://Stackoverflow.com/questions/1995666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84685/" ]
Can you use the tabs to your advantage? If it is as regular as your example then you can probably search and replace on `\t\t\t<item>` (or whatever syntax you need to search with tabs) with whatever else you need.
If the XML is all formatted like that, you should be able to use regular expressions. You might also try formatters to get that format. Otherwise you could read the XML with an XML-parser in a language you know, change it there and write it back to disk.
1,995,666
I made a huge error in a gigantic XML file. ``` <item1> <item2> <item1> //.. tons of stuff... </item1> </item2> </item1> ``` I need to replace the outer item1 with something else. But find and replace isn't working because of the matching inner item1. I've tried searching by multiple pieces of information, but the single-line nature of every find and replace I find makes it impossible, and all of the data is tabbed. Any ideas?
2010/01/03
[ "https://Stackoverflow.com/questions/1995666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84685/" ]
Can you use the tabs to your advantage? If it is as regular as your example then you can probably search and replace on `\t\t\t<item>` (or whatever syntax you need to search with tabs) with whatever else you need.
Regex may have worked in this instance, but regex is generally NOT the best means of modifying XML. [XML is not regular](http://welbog.homeip.net/glue/53/XML-is-not-regular). You should use XML tools to parse and manipulate XML data, or you will likely run into problems at some point. Transforming the XML using an XSLT [identity transform](http://en.wikipedia.org/wiki/Identity_transform) with a template for the particular "item1" element is one example that would be a more safe, robust solution: ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:apply-templates /> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="item1[item2/item1]" > <!--Replace this literal element "NEW_ITEM_ELEMENT" with whatever name you need to change "item1" elements to: --> <NEW_ITEM_ELEMENT> <xsl:apply-templates /> </NEW_ITEM_ELEMENT> </xsl:template> </xsl:stylesheet> ```
63,429,311
I need some help with my code, I have got a problem with fetch the text while ignore the class `menu-list-count` as it will display the value next to the text. When I try this: ``` var mailfolder = $(this).not('[class="menu-list-count"]').text(); ``` The return output will be: ``` test1 2 ``` It should be: test1 Here is the html: ``` <a id="iJ" class="menu-list-item mailfolder" href="#test1" target="_top" title="test1" tabindex="-1" draggable="false"> <div class="qj"> <i style="float: left;" class="folder_icon"></i> </div> <span style="margin-left: 7px;">test1 <span class="menu-list-count">2</span></span> </a> ``` Here is the code: ``` $(document).on('click', '.mailfolder', function(e) { e.preventDefault(); var mailfolder = $(this).not('[class="menu-list-count"]').text(); alert(mailfolder); }); ``` I have tried this: ``` var mailfolder = $(this).find('span:not(.menu-list-count)').text(); ``` It doesn't work when I try it as i still getting `test1 2` so I dont really know what to do, Can you please show me an example how I can get the span text while ignoring the class `menu-list-count`?
2020/08/15
[ "https://Stackoverflow.com/questions/63429311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12632670/" ]
Because you have a span in a span, in order to select the right one you need to change this line: ``` $(this).not('[class="menu-list-count"]') ``` to: ``` $(this).find('span:not([class="menu-list-count"])') ``` In order to get only the text belonging to the upper span you can combine [.contents()](https://api.jquery.com/contents/) with [.filter()](https://api.jquery.com/filter/): ``` $(this).find('span:not([class="menu-list-count"])').contents().filter(function() { return this.nodeType === Node.TEXT_NODE; // get only text nodes }).text() ``` The snippet: ```js $(document).on('click', '.mailfolder', function(e) { e.preventDefault(); var mailfolder = $(this).find('span:not([class="menu-list-count"])').contents().filter(function() { return this.nodeType === Node.TEXT_NODE; }).text(); console.log(mailfolder); }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a id="iJ" class="menu-list-item mailfolder" href="#test1" target="_top" title="test1" tabindex="-1" draggable="false"> <div class="qj"> <i style="float: left;" class="folder_icon"></i> </div> <span style="margin-left: 7px;">test1 <span class="menu-list-count">2</span></span> </a> ```
I'm not sure with JQuery, but with plain JS you can use `childNodes` to filter everything that is not a textNode and then concatenate the result. I've wrote a small JSFiddle to show how it works: <https://jsfiddle.net/sandro_paganotti/4873muzp/6/> HTML ``` <div> Hello <b>Some Text</b> </div> ``` JS: ``` const nodes = Array.from(document.querySelector('div').childNodes); const text = nodes.map(t => t.nodeType == Node.TEXT_NODE ? t.textContent : '' ); console.log(text.join('')); ```
19,506,095
Google Adwords Editor ver 10.2.1 It is possible to change the ad text for existing ads via the UI? I would like to make changes by importing a csv file. I have tried exporting my campaign, editing the csv file and re-importing the file using Adwords Editor. But the changed text is imported as a **new** ad - not a change to the existing ad. Is it possible to make changes to existing ads using the import functionality?
2013/10/21
[ "https://Stackoverflow.com/questions/19506095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
In AdWords, it is impossible to change the text of ads, no matter what method you use. * Editor will create new ads for you. * You can upload a CSV file into the web interface, and that will generate new ads. * You can use the "edit" functionality in the UI, and that will still create new ads. To summarize - nothing you can do :)
Since AdWords register data for a certain ad you can never have the old data assigned to a new/changed ad since that data wouldn't be correct for that new/changed ad. Just remove all the old ads and import the new ones.
13,411,260
There is a tag `<tr:goButton>` in trinidad for which description is as below: > > The `goButton` creates a push button that navigates directly to another location instead of delivering an action. It can be used in place of commandButton where a server-side action is not needed. > > > Do we've similar one in JSF 2.0 Mojarra? If not, how can we implement this?
2012/11/16
[ "https://Stackoverflow.com/questions/13411260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693664/" ]
You should consider how many clients will use your app at the same time on server side, and the the time to transfer the data. I suggest to convert to pdf on the client side if it is possible.
You could transfer the data to PHP and have it generate your tables using html2pdf. It has css support so I recommend it.
13,411,260
There is a tag `<tr:goButton>` in trinidad for which description is as below: > > The `goButton` creates a push button that navigates directly to another location instead of delivering an action. It can be used in place of commandButton where a server-side action is not needed. > > > Do we've similar one in JSF 2.0 Mojarra? If not, how can we implement this?
2012/11/16
[ "https://Stackoverflow.com/questions/13411260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693664/" ]
You should consider how many clients will use your app at the same time on server side, and the the time to transfer the data. I suggest to convert to pdf on the client side if it is possible.
Definitely create the PDF files on your client device: [Drawing and Printing Guide for iOS](http://developer.apple.com/library/ios/#documentation/2ddrawing/conceptual/drawingprintingios/GeneratingPDF/GeneratingPDF.html)
61,466,338
Given the following ndarray `t` - ``` In [26]: t.shape Out[26]: (3, 3, 2) In [27]: t Out[27]: array([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]], [[12, 13], [14, 15], [16, 17]]]) ``` this piecewise linear interpolant for the points `t[:, 0, 0]` can evaluated for `[0 , 0.66666667, 1.33333333, 2.]` as follows using [numpy.interp](https://numpy.org/doc/1.18/reference/generated/numpy.interp.html?highlight=interp#numpy.interp) - ``` In [38]: x = np.linspace(0, t.shape[0]-1, 4) In [39]: x Out[39]: array([0. , 0.66666667, 1.33333333, 2. ]) In [30]: xp = np.arange(t.shape[0]) In [31]: xp Out[31]: array([0, 1, 2]) In [32]: fp = t[:,0,0] In [33]: fp Out[33]: array([ 0, 6, 12]) In [40]: np.interp(x, xp, fp) Out[40]: array([ 0., 4., 8., 12.]) ``` How can all the interpolants be efficiently calculated and returned together for all values of `fp` - ``` array([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 4, 5], [ 6, 7], [ 8, 9]], [[ 8, 9], [10, 11], [12, 13]], [[12, 13], [14, 15], [16, 17]]]) ```
2020/04/27
[ "https://Stackoverflow.com/questions/61466338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309803/" ]
As the interpolation is 1d with changing `y` values it must be run for each 1d slice of t. It's probably faster to loop explicitly but neater to loop using np.apply\_along\_axis ``` import numpy as np t = np.arange( 18 ).reshape(3,3,2) x = np.linspace( 0, t.shape[0]-1, 4) xp = np.arange(t.shape[0]) def interfunc( arr ): """ Function interpolates a 1d array. """ return np.interp( x, xp, arr ) np.apply_along_axis( interfunc, 0, t ) # apply function along axis 0 """ Result array([[[ 0., 1.], [ 2., 3.], [ 4., 5.]], [[ 4., 5.], [ 6., 7.], [ 8., 9.]], [[ 8., 9.], [10., 11.], [12., 13.]], [[12., 13.], [14., 15.], [16., 17.]]]) """ ``` With explicit loops ``` result = np.zeros((4,3,2)) for c in range(t.shape[1]): for p in range(t.shape[2]): result[:,c,p] = np.interp( x, xp, t[:,c,p]) ``` On my machine the second option runs in half the time. **Edit to use `np.nditer`** As the result and the parameter have different shapes I seem to have to create two np.nditer objects one for the parameter and one for the result. This is my first attempt to use `nditer` for anything so it could be over complicated. ``` def test( t ): ts = t.shape result = np.zeros((ts[0]+1,ts[1],ts[2])) param = np.nditer( [t], ['external_loop'], ['readonly'], order = 'F') with np.nditer( [result], ['external_loop'], ['writeonly'], order = 'F') as res: for p, r in zip( param, res ): r[:] = interfunc(p) return result ``` It's slightly slower than the explicit loops and less easy to follow than either of the other solutions.
You could try `scipy.interpolate.interp1d`: ``` from scipy.interpolate import interp1d import numpy as np t = np.array([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]], [[12, 13], [14, 15], [16, 17]]]) # for the first slice f = interp1d(np.arange(t.shape[0]), t[..., 0], axis=0) # returns a function which you call with values within range np.arange(t.shape[0]) # data used for interpolation t[..., 0] >>> array([[ 0, 2, 4], [ 6, 8, 10], [12, 14, 16]]) f(1) >>> array([ 6., 8., 10.]) f(1.5) >>> array([ 9., 11., 13.]) ```
61,466,338
Given the following ndarray `t` - ``` In [26]: t.shape Out[26]: (3, 3, 2) In [27]: t Out[27]: array([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]], [[12, 13], [14, 15], [16, 17]]]) ``` this piecewise linear interpolant for the points `t[:, 0, 0]` can evaluated for `[0 , 0.66666667, 1.33333333, 2.]` as follows using [numpy.interp](https://numpy.org/doc/1.18/reference/generated/numpy.interp.html?highlight=interp#numpy.interp) - ``` In [38]: x = np.linspace(0, t.shape[0]-1, 4) In [39]: x Out[39]: array([0. , 0.66666667, 1.33333333, 2. ]) In [30]: xp = np.arange(t.shape[0]) In [31]: xp Out[31]: array([0, 1, 2]) In [32]: fp = t[:,0,0] In [33]: fp Out[33]: array([ 0, 6, 12]) In [40]: np.interp(x, xp, fp) Out[40]: array([ 0., 4., 8., 12.]) ``` How can all the interpolants be efficiently calculated and returned together for all values of `fp` - ``` array([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 4, 5], [ 6, 7], [ 8, 9]], [[ 8, 9], [10, 11], [12, 13]], [[12, 13], [14, 15], [16, 17]]]) ```
2020/04/27
[ "https://Stackoverflow.com/questions/61466338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309803/" ]
As requested by @Tis Chris, here is a solution using `np.nditer` with the `multi_index` flag but I prefer the explicit nested `for` loops method above because it is 10% faster ``` In [29]: t = np.arange( 18 ).reshape(3,3,2) In [30]: ax0old = np.arange(t.shape[0]) In [31]: ax0new = np.linspace(0, t.shape[0]-1, 4) In [32]: tnew = np.zeros((len(ax0new), t.shape[1], t.shape[2])) In [33]: it = np.nditer(t[0], flags=['multi_index']) In [34]: for _ in it: ...: tnew[:, it.multi_index[0], it.multi_index[1]] = np.interp(ax0new, ax0old, t[:, it.multi_ ...: index[0], it.multi_index[1]]) ...: In [35]: tnew Out[35]: array([[[ 0., 1.], [ 2., 3.], [ 4., 5.]], [[ 4., 5.], [ 6., 7.], [ 8., 9.]], [[ 8., 9.], [10., 11.], [12., 13.]], [[12., 13.], [14., 15.], [16., 17.]]]) ```
You could try `scipy.interpolate.interp1d`: ``` from scipy.interpolate import interp1d import numpy as np t = np.array([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]], [[12, 13], [14, 15], [16, 17]]]) # for the first slice f = interp1d(np.arange(t.shape[0]), t[..., 0], axis=0) # returns a function which you call with values within range np.arange(t.shape[0]) # data used for interpolation t[..., 0] >>> array([[ 0, 2, 4], [ 6, 8, 10], [12, 14, 16]]) f(1) >>> array([ 6., 8., 10.]) f(1.5) >>> array([ 9., 11., 13.]) ```
61,466,338
Given the following ndarray `t` - ``` In [26]: t.shape Out[26]: (3, 3, 2) In [27]: t Out[27]: array([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]], [[12, 13], [14, 15], [16, 17]]]) ``` this piecewise linear interpolant for the points `t[:, 0, 0]` can evaluated for `[0 , 0.66666667, 1.33333333, 2.]` as follows using [numpy.interp](https://numpy.org/doc/1.18/reference/generated/numpy.interp.html?highlight=interp#numpy.interp) - ``` In [38]: x = np.linspace(0, t.shape[0]-1, 4) In [39]: x Out[39]: array([0. , 0.66666667, 1.33333333, 2. ]) In [30]: xp = np.arange(t.shape[0]) In [31]: xp Out[31]: array([0, 1, 2]) In [32]: fp = t[:,0,0] In [33]: fp Out[33]: array([ 0, 6, 12]) In [40]: np.interp(x, xp, fp) Out[40]: array([ 0., 4., 8., 12.]) ``` How can all the interpolants be efficiently calculated and returned together for all values of `fp` - ``` array([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 4, 5], [ 6, 7], [ 8, 9]], [[ 8, 9], [10, 11], [12, 13]], [[12, 13], [14, 15], [16, 17]]]) ```
2020/04/27
[ "https://Stackoverflow.com/questions/61466338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309803/" ]
As the interpolation is 1d with changing `y` values it must be run for each 1d slice of t. It's probably faster to loop explicitly but neater to loop using np.apply\_along\_axis ``` import numpy as np t = np.arange( 18 ).reshape(3,3,2) x = np.linspace( 0, t.shape[0]-1, 4) xp = np.arange(t.shape[0]) def interfunc( arr ): """ Function interpolates a 1d array. """ return np.interp( x, xp, arr ) np.apply_along_axis( interfunc, 0, t ) # apply function along axis 0 """ Result array([[[ 0., 1.], [ 2., 3.], [ 4., 5.]], [[ 4., 5.], [ 6., 7.], [ 8., 9.]], [[ 8., 9.], [10., 11.], [12., 13.]], [[12., 13.], [14., 15.], [16., 17.]]]) """ ``` With explicit loops ``` result = np.zeros((4,3,2)) for c in range(t.shape[1]): for p in range(t.shape[2]): result[:,c,p] = np.interp( x, xp, t[:,c,p]) ``` On my machine the second option runs in half the time. **Edit to use `np.nditer`** As the result and the parameter have different shapes I seem to have to create two np.nditer objects one for the parameter and one for the result. This is my first attempt to use `nditer` for anything so it could be over complicated. ``` def test( t ): ts = t.shape result = np.zeros((ts[0]+1,ts[1],ts[2])) param = np.nditer( [t], ['external_loop'], ['readonly'], order = 'F') with np.nditer( [result], ['external_loop'], ['writeonly'], order = 'F') as res: for p, r in zip( param, res ): r[:] = interfunc(p) return result ``` It's slightly slower than the explicit loops and less easy to follow than either of the other solutions.
As requested by @Tis Chris, here is a solution using `np.nditer` with the `multi_index` flag but I prefer the explicit nested `for` loops method above because it is 10% faster ``` In [29]: t = np.arange( 18 ).reshape(3,3,2) In [30]: ax0old = np.arange(t.shape[0]) In [31]: ax0new = np.linspace(0, t.shape[0]-1, 4) In [32]: tnew = np.zeros((len(ax0new), t.shape[1], t.shape[2])) In [33]: it = np.nditer(t[0], flags=['multi_index']) In [34]: for _ in it: ...: tnew[:, it.multi_index[0], it.multi_index[1]] = np.interp(ax0new, ax0old, t[:, it.multi_ ...: index[0], it.multi_index[1]]) ...: In [35]: tnew Out[35]: array([[[ 0., 1.], [ 2., 3.], [ 4., 5.]], [[ 4., 5.], [ 6., 7.], [ 8., 9.]], [[ 8., 9.], [10., 11.], [12., 13.]], [[12., 13.], [14., 15.], [16., 17.]]]) ```
53,955,190
I have this code ``` DefaultTableModel defaultTableModel = (DefaultTableModel) jTable1.getModel(); int row = defaultTableModel.getRowCount(); for (int i = 0; i < row; i++) { String id = (String) defaultTableModel.getValueAt(row, 0); ``` But I'm getting exception at line : ``` String id = (String) defaultTableModel.getValueAt(row, 0); ``` So even though `System.out.println(id);` able to return rows in `jTable` I tried many other questions mentioned same problem but doesn't helpful.
2018/12/28
[ "https://Stackoverflow.com/questions/53955190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try below change. I think it should work. ``` for (int i = 0; i < row; i++) { // Changed row+1 to row String id = (String) defaultTableModel.getValueAt(i, 0); // Changed row to i ```
Your `for` statement should be: ``` for (int i = 0; i < row; i++) { ``` Also as scary wombat says: ``` String id = (String) defaultTableModel.getValueAt(i, 0); ```
69,072,718
I have followed the documentation [here](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-brief-introduction-0000001061991343) and [here](https://developer.huawei.com/consumer/en/codelab/HMSMapKit/index.html#0) (which are pretty straight forward), but the map view does not load any tiles. I use HMS Toolkit, and the Configuration Wizard results in success. I also have set my api key, using this line in both my application class and my activity class onCreate. MapsInitializer.setApiKey(HUAWEI\_API\_KEY); Here is the device information and SDK version: * Phone model: Huawei Y7 Prime 2018 * EMUI version: 8.0.0 * HMS Core version: 6.1.0.305 * Map SDK version: com.huawei.hms:maps:6.0.0.301 Here is the screen: [![enter image description here](https://i.stack.imgur.com/hSret.jpg)](https://i.stack.imgur.com/hSret.jpg) Relevant error logs: > > E/HmsMapKit\_MapView\_151: createDelegate: creator == null > > > E/HmsMapKit\_GrsClient\_24: GRS returns empty. > > > E/HmsMapKit\_ErrorTraceLogPusher\_4: cache error trace log : > ErrorTraceLogDTO{ scenario = GET\_GRS\_URL\_FAILED', message='GRS returns > empty, service name is com.huawei.hms.map.'} > > > E/HmsMapKit\_ErrorTraceLogPusher\_12: eventId is null or empty. > > > E/HmsMapKit\_AuthenticateClient\_27: Exception occur > com.huawei.hms.maps.foundation.client.c > > > E/HmsMapKit\_ErrorTraceLogPusher\_4: cache error trace log : > ErrorTraceLogDTO{ scenario = ACCESS\_SERVICE\_ERROR', message='060001 : > NETWORK\_ERROR'} > > > E/HmsMapKit\_AuthenticateCache\_0: authenticate error, throw > RetryException. > > > E/HmsMapKit\_CopyrightDelegate\_27: get copyright statement html data > failed: htmlData = null > > > E/HmsMapKit\_TileCache\_38: startUrlRequest Identity fail, do not has > permission get tile. authResult :060011 > > > PS: I have the exact same problem with [this demo](https://github.com/HMS-Core/hms-mapkit-demo).
2021/09/06
[ "https://Stackoverflow.com/questions/69072718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4227387/" ]
First you may refer to [this Docs](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/error-code-0000001050992007) to see if there's an error code. The official demo also runs incorrectly. so there is a high probability that the problem is caused by a signature or API key problem. Please check as follows: * Check whether the Map Kit API is enabled in AppGallery Connect. If not, enable it, download the .json file to replace the existing one in the code, and then check whether the SHA256 fingerprint is correct. * In the Map SDK 5.0.0.300 or later for Android, you must set an API key before initializing the map. (1) Set the API key in the entrance class of your project. ``` // In the entrance class (inherited from android.app.Application) of the app, // call the setApiKey method in the overridden onCreate() method. public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); // Set the API key. MapsInitializer.setApiKey("Your API Key"); } } ``` (2) Set the API key in Fragment or MapView. ``` @Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate: "); super.onCreate(savedInstanceState); // Set the API key before calling setContentView. MapsInitializer.setApiKey("Your API Key"); setContentView(R.layout.basic_demo); ``` For details about different causes of this problem, You could aslo refer to this [answer](https://stackoverflow.com/a/64475114/13329100).
You need to generate and upload to AppGallery Connect **two SHA-256 keys**, one for debug version and one for release. for generating key for debug version you need to: 1. open cmd 2. run command `cd [path to directory with keytool.exe file]` for example: `cd C:\Program Files\Java\jdk1.8.0_301\bin` 3. run command `keytool -list -v -keystore [path to debug.keystore]\debug.keystore -alias androiddebugkey -storepass android -keypass android` 4. copy SHA-256 key and add it to *AppGallery Connect -> Project Settings -> App information -> SHA-256 certificate fingerprint* for release version do everything the same, but replace the path to the key for signing the release build in 2 step and enter real release alias and password in 3 step
53,400,878
I am trying to do something similar to a `Averageif` with `max` and `min`. Current formula : ``` =IF(J15<0,MAX('CS+MS'!C:C),MIN('CS+MS'!C:C)) ``` When I'm looking in CS+MS Sheet I want to do something like averageif where I can search column B for a word then return column C. Is this possble?
2018/11/20
[ "https://Stackoverflow.com/questions/53400878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8462962/" ]
The ideal way to achieve this is with named queues. Have multiple workers set up, some working on `Production-East` environment and some on `Production-West` environment. That way both DAGs show up in the UI but they execute only on the worker machines that have that specific environment on them. From the [documentation for queues](https://learn.microsoft.com/en-us/azure/postgresql/concepts-ssl-connection-security): When using the CeleryExecutor, the celery queues that tasks are sent to can be specified. queue is an attribute of BaseOperator, so any task can be assigned to any queue. The default queue for the environment is defined in the `airflow.cfg`’s `celery -> default_queue`. This defines the queue that tasks get assigned to when not specified, as well as which queue Airflow workers listen to when started. Workers can listen to one or multiple queues of tasks. When a worker is started (using the command `airflow worker`), a set of comma delimited queue names can be specified (e.g. `airflow worker -q spark`). This worker will then only pick up tasks wired to the specified queue(s). This can be useful if you need specialized workers, either from a resource perspective (for say very lightweight tasks where one worker could take thousands of tasks without a problem), or from an environment perspective (you want a worker running from within the Spark cluster itself because it needs a very specific environment and security rights).
Have the files for each group put inside a subfolder and then set the `dags_folder` path to point to the appropriate subfolder for the server.
6,869,460
I'm encountering a strange OpenGL Bug. OpenGL is pretty new to me, but we're required to use it in my AI class (because the teacher is really a Graphics professor). Either way, this is happening: <http://img818.imageshack.us/img818/422/reversiothello.png> It happens to only the topmost, leftmost polygon. In other words, it finds the furthest polygon left, and then the furthest up and it does that to it. (There is not currently anything erasing polygons from the board). My display function is this: ``` void display_func(void) { glClearColor(0.0, 0.45, 0.0, 1.0); // Background Color (Forest Green :3) glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0, 0.0, 0.0); draw_board(); glFlush(); glutSwapBuffers(); }; ``` My draw\_board function is this: ``` void draw_board() { int size = 8; int stepX = WINDOW_XS / size; int stepY = WINDOW_YS / size; glColor3f(0.0,0.0,0.0); // line color black glBegin(GL_LINES); // Draw Columns for(int i = 0;i <= WINDOW_XS;i += stepX) { glVertex2i(i,0); glVertex2i(i, WINDOW_YS); } // Draw Rows for(int j = 0;j <= WINDOW_YS;j += stepY) { glVertex2i(0, j); glVertex2i(WINDOW_XS, j); } // Draw Circles for(int i = 0;i < 8;++i) { for(int j = 0;j < 8;++j) { if(engine->getOnBoard(i,j) == Reversi::PIECE_NONE) continue; if(engine->getOnBoard(i,j) == Reversi::PIECE_WHITE) glColor3f(1.0,1.0,1.0); if(engine->getOnBoard(i,j) == Reversi::PIECE_BLACK) glColor3f(0.0,0.0,0.0); int drawX = ((i+1)*64)-32; int drawY = 512-((j+1)*64)+32; gl_drawCircle(drawX,drawY,30); } } glEnd(); }; ``` My mouse function is this: ``` void mouse_func(int button, int state, int x, int y) { if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && x < WINDOW_XS) { // row and column index x = (int)( x / (WINDOW_XS/8) ); y = (int)( y / (WINDOW_YS/8) ); std::cout << "Attempting to make a move at " << x << "," << y << std::endl; if(engine->makeMove(x,y)) { glutPostRedisplay(); } } }; ``` and my gl\_drawCircle function is this: ``` void gl_drawCircle(float x, float y, float r) { // http://stackoverflow.com/questions/5094992/c-drawing-a-2d-circle-in-opengl/5095188#5095188 glBegin( GL_POLYGON ); float t; int n; for(t = 0,n = 0; n <= 90; ++n, t = float(n)/90.f ) // increment by a fraction of the maximum { glVertex2f( x + sin( t * 2 * PI ) * r, y + cos( t * 2 * PI ) * r ); } glEnd(); } ``` Can anyone please help me?
2011/07/29
[ "https://Stackoverflow.com/questions/6869460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43790/" ]
The only bug worth giving an answer that I can find is that your `draw_board` function doesn't use properly the `glBegin` and `glEnd` statements. You have to use a `glEnd` statement before calling `gl_drawCircle`, otherwise you'll get a nasty behavior. Edit: you first circle is drawn using lines because the `glBegin` is ignored (since you are in a `glBegin` context). All other circles are done ok because you do a `glEnd` before calling `glBegin` again. The first drawn circle is the leftmost, topmost circle.
You need a call to glEnd after drawing the rows. When you do not call glEnd, OpenGL ignores your call `glBegin( GL_POLYGON );` and assumes you still want to draw lines. So just adding `glEnd ();` after drawing the rows should solve it.
1,702,003
I'm trying to zip a stream from .Net that can be read from Java code. So as input I have a byte array, which I want to compress and I'm expecting to have a binary array. I've tested with SharpZipLib and DotNetZip to the compressed byte array, but unfortunately I always get an error when trying to uncompress it using the java.util.zip.Deflater class in Java. Do someone have a code sample of compressing a String or a byte array with .Net and de-compressing it with the java.util.zip.Deflater class?
2009/11/09
[ "https://Stackoverflow.com/questions/1702003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207066/" ]
You shouldn't need to touch `Deflater`. `Deflater` deals with decompressing individual entries within the zip file. [`ZipInputStream`](http://java.sun.com/javase/6/docs/api/java/util/zip/ZipInputStream.html) is the odd class to go for. There is also [`ZipFile`](http://java.sun.com/javase/6/docs/api/java/util/zip/ZipFile.html) if you really need to go for random access to an actual file (for many reasons, I wouldn't recommend it).
Here is the page from Sun on ZipStreams: <http://java.sun.com/developer/technicalArticles/Programming/compression/> Another library that deals with ZipStreams is POI. It is more focused on working with MS OFfic XML format docs but it might have some different insights as to how to handle the stream. <http://poi.apache.org/apidocs/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.html>
1,702,003
I'm trying to zip a stream from .Net that can be read from Java code. So as input I have a byte array, which I want to compress and I'm expecting to have a binary array. I've tested with SharpZipLib and DotNetZip to the compressed byte array, but unfortunately I always get an error when trying to uncompress it using the java.util.zip.Deflater class in Java. Do someone have a code sample of compressing a String or a byte array with .Net and de-compressing it with the java.util.zip.Deflater class?
2009/11/09
[ "https://Stackoverflow.com/questions/1702003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207066/" ]
Inflater doesn't read zip streams. It reads ZLIB (or DEFLATE) streams. The ZIP format surrounds a pure DEFLATE stream with additional metadata. Inflater doesn't handle that metadata. --- If you are inflating on the Java side, you need Inflater. On the .NET side you can use the Ionic.Zlib.ZlibStream class from DotNetZip to compress - in other words to produce something the Java Inflater can read. I've just tested this; this code works. The Java side decompresses what the .NET side has compressed. .NET side: ``` byte[] compressed = Ionic.Zlib.ZlibStream .CompressString(originalText); File.WriteAllBytes("ToInflate.bin", compressed); ``` Java side: ``` public void Run() throws java.io.FileNotFoundException, java.io.IOException, java.util.zip.DataFormatException, java.io.UnsupportedEncodingException, java.security.NoSuchAlgorithmException { String filename = "ToInflate.bin"; File file = new File(filename); InputStream is = new FileInputStream(file); // Get the size of the file int length = (int)file.length(); byte[] deflated = new byte[length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < deflated.length && (numRead=is.read(deflated, offset, deflated.length-offset)) >= 0) { offset += numRead; } // Decompress the bytes Inflater decompressor = new Inflater(); decompressor.setInput(deflated, 0, length); byte[] result = new byte[100]; int totalRead= 0; while ((numRead = decompressor.inflate(result)) > 0) totalRead += numRead; decompressor.end(); System.out.println("Inflate: total size of inflated data: " + totalRead + "\n"); result = new byte[totalRead]; decompressor = new Inflater(); decompressor.setInput(deflated, 0, length); int resultLength = decompressor.inflate(result); decompressor.end(); // Decode the bytes into a String String outputString = new String(result, 0, resultLength, "UTF-8"); System.out.println("Inflate: inflated string: " + outputString + "\n"); } ``` (I'm kinda rusty at Java so it might stand some improvement, but you get the idea)
Here is the page from Sun on ZipStreams: <http://java.sun.com/developer/technicalArticles/Programming/compression/> Another library that deals with ZipStreams is POI. It is more focused on working with MS OFfic XML format docs but it might have some different insights as to how to handle the stream. <http://poi.apache.org/apidocs/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.html>
1,702,003
I'm trying to zip a stream from .Net that can be read from Java code. So as input I have a byte array, which I want to compress and I'm expecting to have a binary array. I've tested with SharpZipLib and DotNetZip to the compressed byte array, but unfortunately I always get an error when trying to uncompress it using the java.util.zip.Deflater class in Java. Do someone have a code sample of compressing a String or a byte array with .Net and de-compressing it with the java.util.zip.Deflater class?
2009/11/09
[ "https://Stackoverflow.com/questions/1702003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207066/" ]
You shouldn't need to touch `Deflater`. `Deflater` deals with decompressing individual entries within the zip file. [`ZipInputStream`](http://java.sun.com/javase/6/docs/api/java/util/zip/ZipInputStream.html) is the odd class to go for. There is also [`ZipFile`](http://java.sun.com/javase/6/docs/api/java/util/zip/ZipFile.html) if you really need to go for random access to an actual file (for many reasons, I wouldn't recommend it).
Inflater doesn't read zip streams. It reads ZLIB (or DEFLATE) streams. The ZIP format surrounds a pure DEFLATE stream with additional metadata. Inflater doesn't handle that metadata. --- If you are inflating on the Java side, you need Inflater. On the .NET side you can use the Ionic.Zlib.ZlibStream class from DotNetZip to compress - in other words to produce something the Java Inflater can read. I've just tested this; this code works. The Java side decompresses what the .NET side has compressed. .NET side: ``` byte[] compressed = Ionic.Zlib.ZlibStream .CompressString(originalText); File.WriteAllBytes("ToInflate.bin", compressed); ``` Java side: ``` public void Run() throws java.io.FileNotFoundException, java.io.IOException, java.util.zip.DataFormatException, java.io.UnsupportedEncodingException, java.security.NoSuchAlgorithmException { String filename = "ToInflate.bin"; File file = new File(filename); InputStream is = new FileInputStream(file); // Get the size of the file int length = (int)file.length(); byte[] deflated = new byte[length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < deflated.length && (numRead=is.read(deflated, offset, deflated.length-offset)) >= 0) { offset += numRead; } // Decompress the bytes Inflater decompressor = new Inflater(); decompressor.setInput(deflated, 0, length); byte[] result = new byte[100]; int totalRead= 0; while ((numRead = decompressor.inflate(result)) > 0) totalRead += numRead; decompressor.end(); System.out.println("Inflate: total size of inflated data: " + totalRead + "\n"); result = new byte[totalRead]; decompressor = new Inflater(); decompressor.setInput(deflated, 0, length); int resultLength = decompressor.inflate(result); decompressor.end(); // Decode the bytes into a String String outputString = new String(result, 0, resultLength, "UTF-8"); System.out.println("Inflate: inflated string: " + outputString + "\n"); } ``` (I'm kinda rusty at Java so it might stand some improvement, but you get the idea)
1,114,693
I'm in the mood to break things. Current system: ``` Linux Kublai-1888 4.18.0-13-generic #14-Ubuntu SMP Wed Dec 5 09:04:24 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux ``` I didn't even know 5 existed! Are there any benefits I should be aware about? I'm going to uninstall my graphics drivers beforehand since it'll probably break. Wish me luck! If you've got a way to reinstall pip2/pip3 with proper metadata + $PATH + so it's not broken I'd like that too. Reference materials I will use: [Reinstalling CUDA, which I use to enhance my gfx performance](https://askubuntu.com/questions/530043/removing-nvidia-cuda-toolkit-and-installing-new-one#530050https://askubuntu.com/questions/530043/removing-nvidia-cuda-toolkit-and-installing-new-one#530050) [Info on different types of kernels](https://askubuntu.com/questions/687784/how-to-switch-between-low-latency-and-generic-kernels) [Kernel sources](https://kernel.ubuntu.com/~kernel-ppa/mainline/) [Official docs on Nvidia headers and making sure you don't screw yourself](https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html) [More of the above, but Github guy, so you can trust it more](https://gist.github.com/wangruohui/df039f0dc434d6486f5d4d098aa52d07)
2019/02/01
[ "https://askubuntu.com/questions/1114693", "https://askubuntu.com", "https://askubuntu.com/users/913404/" ]
After installing a mainline Linux kernel such as version 5 you can still reboot and select the previous version. At the Grub menu select **Advanced Options**. A sub menu appears showing all your previously installed kernels that have not been auto removed or manually removed.
Everything went fine. It's always good to uninstall everything before upgrading.
60,335,749
1. Is it always wise to use NULL after a delete in legacy code without any smartpointers to prevent dangling pointers? (bad design architecture of the legacy code excluded) ``` int* var = new int(100); delete var; var = NULL; ``` 2. Does it also make sense in destructors? 3. In a getter, does it make sense to test for NULL in second step? Or is it undefinied behavier anyway? ``` Foo* getPointer() { if (m_var!=NULL) { // <-is this wise return m_var; } else { return nullptr; } } ``` 4. What about this formalism as an alternative? In which cases will it crash? ``` Foo* getPointer() { if (m_var) { // <- return m_var; } else { return nullptr; } } ``` 5. (Edit) Will the code crash in example 3./4. if A. NULL is used after delete or B. NULL is not used after delete.
2020/02/21
[ "https://Stackoverflow.com/questions/60335749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8120645/" ]
> > 1. Is it always wise to use NULL after a delete in legacy code without any smartpointers to prevent dangling pointers? (bad design architecture of the legacy code excluded) > > > > ``` > int* var = new int(100); > // ... > delete var; > var = NULL; > > ``` > > Only useful if you test `var` afterward. if scope ends, or if you set other value, setting to null is unneeded. > > 2. Does it also make sense in destructors? > > > nullify members in destructor is useless as you cannot access them without UB afterward anyway. (but that might help with debugger) > > 3. In a getter, does it make sense to test for NULL in second step? Or is it undefinied behavier anyway? > [..] > 4. [..] > > > `if (m_var != NULL)` and `if (m_var)` are equivalent. It is unneeded, as, if pointer is `nullptr`, you return `nullptr`, if pointer is not `nullptr`, you return that pointer, so your getter can simply be `return m_var;`
Avoid writing code like this ``` int* var = new int(100); // ... do work ... delete var; ``` This is prone to memory leaks if "*do work*" throws, `return`s or otherwise breaks out of current scope (it may not be the case right now but later when "*do work*" needs to be extended/changed). Always wrap heap-allocated objects in [RAII](https://en.cppreference.com/w/cpp/language/raii) such that the destructor *always* runs on scope exit, freeing the memory. If you do have code like this, then setting `var` to NULL or even better a bad value like -1 in a Debug build can be helpful in catching use-after-free and double-delete errors. In case of a destructor: Setting the pointer to `NULL` in a destructor is not needed. * In production code it's a waste of CPU time (writing a value that will never be read again). * In debug code it makes catching [double-deletes](https://stackoverflow.com/questions/9169774/what-happens-in-a-double-delete) harder. Some compilers fill deleted objects with a marker like `0xDDDDDDDD` such that a second `delete` or any other dereference of the pointer will cause a memory access exception. If the pointer is set to `NULL`, `delete` will silently ignore it, hiding the error.
60,335,749
1. Is it always wise to use NULL after a delete in legacy code without any smartpointers to prevent dangling pointers? (bad design architecture of the legacy code excluded) ``` int* var = new int(100); delete var; var = NULL; ``` 2. Does it also make sense in destructors? 3. In a getter, does it make sense to test for NULL in second step? Or is it undefinied behavier anyway? ``` Foo* getPointer() { if (m_var!=NULL) { // <-is this wise return m_var; } else { return nullptr; } } ``` 4. What about this formalism as an alternative? In which cases will it crash? ``` Foo* getPointer() { if (m_var) { // <- return m_var; } else { return nullptr; } } ``` 5. (Edit) Will the code crash in example 3./4. if A. NULL is used after delete or B. NULL is not used after delete.
2020/02/21
[ "https://Stackoverflow.com/questions/60335749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8120645/" ]
> > 1. Is it always wise to use NULL after a delete in legacy code without any smartpointers to prevent dangling pointers? (bad design architecture of the legacy code excluded) > > > > ``` > int* var = new int(100); > // ... > delete var; > var = NULL; > > ``` > > Only useful if you test `var` afterward. if scope ends, or if you set other value, setting to null is unneeded. > > 2. Does it also make sense in destructors? > > > nullify members in destructor is useless as you cannot access them without UB afterward anyway. (but that might help with debugger) > > 3. In a getter, does it make sense to test for NULL in second step? Or is it undefinied behavier anyway? > [..] > 4. [..] > > > `if (m_var != NULL)` and `if (m_var)` are equivalent. It is unneeded, as, if pointer is `nullptr`, you return `nullptr`, if pointer is not `nullptr`, you return that pointer, so your getter can simply be `return m_var;`
This question is really opinion-based, so I'll offer some opinions ... but also a justification for those opinions, which will hopefully be more useful for learning than the opinions themselves. > > 1. Is it always wise to use NULL after a delete in legacy code without any smartpointers to prevent dangling pointers? (bad design architecture of the legacy code excluded) > > > Short answer: no. It is generally recommended to avoid raw pointers whenever possible. Regardless of which C++ standard your code claims compliance with. Even if you somehow find yourself needing to use a raw pointer, it is safer to ensure the pointer ceases to exist when no longer needed, rather than setting it to NULL. That can be achieved with scope (e.g. the pointer is local to a scope, and that scope ends immediately after `delete pointer` - which absolutely prevents subsequent use of the pointer at all). If a pointer cannot be used when no longer needed, it cannot be accidentally used - and does not need to be set to `NULL`. This also works for a pointer that is a member of a class, since the pointer ceases to exist when the containing object does i.e. after the destructor completes. The idiom of "set a pointer to NULL when no longer needed, and check for NULL before using it" doesn't prevent stupid mistakes. As a rough rule, any idiom that requires a programmer to remember to do something - such as setting a pointer to NULL, or comparing a pointer to NULL - is vulnerable to programmer mistakes (forgetting to do what they are required to do). > > 2. Does it also make sense in destructors? > > > Generally speaking, no. Once the destructor completes, the pointer (assuming it is a member of the class) will cease to exist as well. Setting it to NULL immediately before it ceases to exist achieves nothing. If you have a class with a destructor that, for some reason, shares the pointer with other objects (i.e. the value of the pointer remains valid, and presumably the object it points at, still exist after the destructor completes) then the answer may be different. But that is an exceedingly rare use case - and one which is usually probably better avoided, since it becomes more difficult to manage lifetime of the pointer or the object it points at - and therefore easier to introduce obscure bugs. Setting a pointer to `NULL` when done is generally not a solution to such bugs. > > 3. In a getter, does it make sense to test for NULL in second step? Or is it undefinied behavier anyway? > > > Obviously that depends on how the pointer was initialised. If the pointer is uninitialised, even comparing it with `NULL` gives undefined behaviour. In general terms, I would not do it. There will presumably be some code that initialised the pointer. If that code cannot appropriately initialise a pointer, then *that* code should deal with the problem in a way that prevents your function being called. Examples may include throwing an exception, terminating program execution. That allows your function to safely ASSUME the pointer points at a valid object. > > 4. What about this formalism as an alternative? In which cases will it crash? > > > The "formalism" is identical to the previous one - practically the difference is stylistic. In both cases, if `m_var` is uninitialised, accessing its value gives undefined behaviour. Otherwise the behaviour of the function is well-defined. A crash is not guaranteed in any circumstances. Undefined behaviour is not required to result in a crash. If the caller exhibits undefined behaviour (e.g. if your function returns `NULL` the caller dereferences it anyway) there is nothing your function can do to prevent that.
60,335,749
1. Is it always wise to use NULL after a delete in legacy code without any smartpointers to prevent dangling pointers? (bad design architecture of the legacy code excluded) ``` int* var = new int(100); delete var; var = NULL; ``` 2. Does it also make sense in destructors? 3. In a getter, does it make sense to test for NULL in second step? Or is it undefinied behavier anyway? ``` Foo* getPointer() { if (m_var!=NULL) { // <-is this wise return m_var; } else { return nullptr; } } ``` 4. What about this formalism as an alternative? In which cases will it crash? ``` Foo* getPointer() { if (m_var) { // <- return m_var; } else { return nullptr; } } ``` 5. (Edit) Will the code crash in example 3./4. if A. NULL is used after delete or B. NULL is not used after delete.
2020/02/21
[ "https://Stackoverflow.com/questions/60335749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8120645/" ]
> > 1. Is it always wise to use NULL after a delete in legacy code without any smartpointers to prevent dangling pointers? (bad design architecture of the legacy code excluded) > > > > ``` > int* var = new int(100); > // ... > delete var; > var = NULL; > > ``` > > Only useful if you test `var` afterward. if scope ends, or if you set other value, setting to null is unneeded. > > 2. Does it also make sense in destructors? > > > nullify members in destructor is useless as you cannot access them without UB afterward anyway. (but that might help with debugger) > > 3. In a getter, does it make sense to test for NULL in second step? Or is it undefinied behavier anyway? > [..] > 4. [..] > > > `if (m_var != NULL)` and `if (m_var)` are equivalent. It is unneeded, as, if pointer is `nullptr`, you return `nullptr`, if pointer is not `nullptr`, you return that pointer, so your getter can simply be `return m_var;`
The case you describe remains relatively simple, because the variable is described in a local scope. But look for example at this scenario: ``` struct MyObject { public : MyObject (int i){ m_piVal = new int(i); }; ~MyObject (){ delete m_piVal; }; public: static int *m_piVal; }; int* MyObject::m_piVal = NULL; ``` You may have a double free problem by writing this: ``` MyObject *pObj1 = new MyObject(1); MyObject *pObj2 = new MyObject(2); //........... delete pObj1; delete pObj2; // You will have double Free on static pointer (m_piVal) ``` Or here: ``` struct MyObject2 { public : MyObject2 (int i){ m_piVal = new int(i); }; ~MyObject2 (){ delete m_piVal; }; public: int *m_piVal; }; ``` when you write this: ``` MyObject2 Obj3 (3); MyObject2 Obj4 = Obj3; ``` At destruction, you will have double Free here because Obj3.m\_piVal = Obj4.m\_piVal So there are some cases that need special attention (Implement : **smart pointer, copy constructor, ...**) to manage the pointer
60,335,749
1. Is it always wise to use NULL after a delete in legacy code without any smartpointers to prevent dangling pointers? (bad design architecture of the legacy code excluded) ``` int* var = new int(100); delete var; var = NULL; ``` 2. Does it also make sense in destructors? 3. In a getter, does it make sense to test for NULL in second step? Or is it undefinied behavier anyway? ``` Foo* getPointer() { if (m_var!=NULL) { // <-is this wise return m_var; } else { return nullptr; } } ``` 4. What about this formalism as an alternative? In which cases will it crash? ``` Foo* getPointer() { if (m_var) { // <- return m_var; } else { return nullptr; } } ``` 5. (Edit) Will the code crash in example 3./4. if A. NULL is used after delete or B. NULL is not used after delete.
2020/02/21
[ "https://Stackoverflow.com/questions/60335749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8120645/" ]
Avoid writing code like this ``` int* var = new int(100); // ... do work ... delete var; ``` This is prone to memory leaks if "*do work*" throws, `return`s or otherwise breaks out of current scope (it may not be the case right now but later when "*do work*" needs to be extended/changed). Always wrap heap-allocated objects in [RAII](https://en.cppreference.com/w/cpp/language/raii) such that the destructor *always* runs on scope exit, freeing the memory. If you do have code like this, then setting `var` to NULL or even better a bad value like -1 in a Debug build can be helpful in catching use-after-free and double-delete errors. In case of a destructor: Setting the pointer to `NULL` in a destructor is not needed. * In production code it's a waste of CPU time (writing a value that will never be read again). * In debug code it makes catching [double-deletes](https://stackoverflow.com/questions/9169774/what-happens-in-a-double-delete) harder. Some compilers fill deleted objects with a marker like `0xDDDDDDDD` such that a second `delete` or any other dereference of the pointer will cause a memory access exception. If the pointer is set to `NULL`, `delete` will silently ignore it, hiding the error.
The case you describe remains relatively simple, because the variable is described in a local scope. But look for example at this scenario: ``` struct MyObject { public : MyObject (int i){ m_piVal = new int(i); }; ~MyObject (){ delete m_piVal; }; public: static int *m_piVal; }; int* MyObject::m_piVal = NULL; ``` You may have a double free problem by writing this: ``` MyObject *pObj1 = new MyObject(1); MyObject *pObj2 = new MyObject(2); //........... delete pObj1; delete pObj2; // You will have double Free on static pointer (m_piVal) ``` Or here: ``` struct MyObject2 { public : MyObject2 (int i){ m_piVal = new int(i); }; ~MyObject2 (){ delete m_piVal; }; public: int *m_piVal; }; ``` when you write this: ``` MyObject2 Obj3 (3); MyObject2 Obj4 = Obj3; ``` At destruction, you will have double Free here because Obj3.m\_piVal = Obj4.m\_piVal So there are some cases that need special attention (Implement : **smart pointer, copy constructor, ...**) to manage the pointer
60,335,749
1. Is it always wise to use NULL after a delete in legacy code without any smartpointers to prevent dangling pointers? (bad design architecture of the legacy code excluded) ``` int* var = new int(100); delete var; var = NULL; ``` 2. Does it also make sense in destructors? 3. In a getter, does it make sense to test for NULL in second step? Or is it undefinied behavier anyway? ``` Foo* getPointer() { if (m_var!=NULL) { // <-is this wise return m_var; } else { return nullptr; } } ``` 4. What about this formalism as an alternative? In which cases will it crash? ``` Foo* getPointer() { if (m_var) { // <- return m_var; } else { return nullptr; } } ``` 5. (Edit) Will the code crash in example 3./4. if A. NULL is used after delete or B. NULL is not used after delete.
2020/02/21
[ "https://Stackoverflow.com/questions/60335749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8120645/" ]
This question is really opinion-based, so I'll offer some opinions ... but also a justification for those opinions, which will hopefully be more useful for learning than the opinions themselves. > > 1. Is it always wise to use NULL after a delete in legacy code without any smartpointers to prevent dangling pointers? (bad design architecture of the legacy code excluded) > > > Short answer: no. It is generally recommended to avoid raw pointers whenever possible. Regardless of which C++ standard your code claims compliance with. Even if you somehow find yourself needing to use a raw pointer, it is safer to ensure the pointer ceases to exist when no longer needed, rather than setting it to NULL. That can be achieved with scope (e.g. the pointer is local to a scope, and that scope ends immediately after `delete pointer` - which absolutely prevents subsequent use of the pointer at all). If a pointer cannot be used when no longer needed, it cannot be accidentally used - and does not need to be set to `NULL`. This also works for a pointer that is a member of a class, since the pointer ceases to exist when the containing object does i.e. after the destructor completes. The idiom of "set a pointer to NULL when no longer needed, and check for NULL before using it" doesn't prevent stupid mistakes. As a rough rule, any idiom that requires a programmer to remember to do something - such as setting a pointer to NULL, or comparing a pointer to NULL - is vulnerable to programmer mistakes (forgetting to do what they are required to do). > > 2. Does it also make sense in destructors? > > > Generally speaking, no. Once the destructor completes, the pointer (assuming it is a member of the class) will cease to exist as well. Setting it to NULL immediately before it ceases to exist achieves nothing. If you have a class with a destructor that, for some reason, shares the pointer with other objects (i.e. the value of the pointer remains valid, and presumably the object it points at, still exist after the destructor completes) then the answer may be different. But that is an exceedingly rare use case - and one which is usually probably better avoided, since it becomes more difficult to manage lifetime of the pointer or the object it points at - and therefore easier to introduce obscure bugs. Setting a pointer to `NULL` when done is generally not a solution to such bugs. > > 3. In a getter, does it make sense to test for NULL in second step? Or is it undefinied behavier anyway? > > > Obviously that depends on how the pointer was initialised. If the pointer is uninitialised, even comparing it with `NULL` gives undefined behaviour. In general terms, I would not do it. There will presumably be some code that initialised the pointer. If that code cannot appropriately initialise a pointer, then *that* code should deal with the problem in a way that prevents your function being called. Examples may include throwing an exception, terminating program execution. That allows your function to safely ASSUME the pointer points at a valid object. > > 4. What about this formalism as an alternative? In which cases will it crash? > > > The "formalism" is identical to the previous one - practically the difference is stylistic. In both cases, if `m_var` is uninitialised, accessing its value gives undefined behaviour. Otherwise the behaviour of the function is well-defined. A crash is not guaranteed in any circumstances. Undefined behaviour is not required to result in a crash. If the caller exhibits undefined behaviour (e.g. if your function returns `NULL` the caller dereferences it anyway) there is nothing your function can do to prevent that.
The case you describe remains relatively simple, because the variable is described in a local scope. But look for example at this scenario: ``` struct MyObject { public : MyObject (int i){ m_piVal = new int(i); }; ~MyObject (){ delete m_piVal; }; public: static int *m_piVal; }; int* MyObject::m_piVal = NULL; ``` You may have a double free problem by writing this: ``` MyObject *pObj1 = new MyObject(1); MyObject *pObj2 = new MyObject(2); //........... delete pObj1; delete pObj2; // You will have double Free on static pointer (m_piVal) ``` Or here: ``` struct MyObject2 { public : MyObject2 (int i){ m_piVal = new int(i); }; ~MyObject2 (){ delete m_piVal; }; public: int *m_piVal; }; ``` when you write this: ``` MyObject2 Obj3 (3); MyObject2 Obj4 = Obj3; ``` At destruction, you will have double Free here because Obj3.m\_piVal = Obj4.m\_piVal So there are some cases that need special attention (Implement : **smart pointer, copy constructor, ...**) to manage the pointer
42,435,469
I have a query which calls a function in a package to create a percentage value as a sum of about 30 columns. What I'd like to do is update each row based on the "sum of counted columns" as a percentage. The select query is: ``` SELECT checklist_id, row_status, eba_cm_checklist_std.get_row_percent_complete(pc.id,pc.checklist_id,pc.max_col_num) AS percent_complete FROM ( SELECT ( SELECT COUNT(id) FROM eba_cm_checklist_columns WHERE checklist_id = r.checklist_id ) AS max_col_num, r.* FROM eba_cm_checklist_rows r ORDER BY r.row_order, r.name ) pc ``` and the package.function that creates the percentage is "eba\_cm\_checklist\_std.get\_row\_percent\_complete". The query outputs the following: ``` checklist_id row_status percent_complete 97176759931088640236098007249022291412 Red 0 97176759931071715274623402440576404948 Red 0 97176759931071715274623402440576404948 Red 0 97176759931071715274623402440576404948 Red 0 97176759931088640236098007249022291412 Red 0 97176759931088640236098007249022291412 Red 0 97176759931081386681180319473974054356 Grey 100 97176759931051163535689953744606399956 Grey 100 ``` The difficulty I'm having is that the expression is using a nested select statement based on the output of a function and I can't get my head around how to update the physical "eba\_cm\_checklist\_rows" table based on the output of the query. Basically, I want to do the following: ``` update set row_status = 'Green' where percent_complete = 100 ```
2017/02/24
[ "https://Stackoverflow.com/questions/42435469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3410393/" ]
Assuming there's not a library which will implement this functionality for you, using `path.parse` doesn't have to be clunky - I actually think using that is probably the cleanest way of doing this: ``` let { dir, name, ext } = path.parse("a/path/to/file.json"); let path1 = path.join(dir, name + "-original" + ext); let path2 = path.join(dir, name + "-comarand" + ext); ``` That code snippet uses [destructuring](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), so you'll need a recent-ish version of Node to run it. That said, you could just replace that with accessing the parsed path object normally: ``` let p = path.parse("a/path/to/file.json"); let path1 = path.join(p.dir, p.name + "-original" + p.ext); let path2 = path.join(p.dir, p.name + "-comarand" + p.ext); ``` Not that much worse! If this is something you'd be doing frequently in your project, it wouldn't be too hard to lift it out into a utility function, like so: ``` function suffixFilename(path, suffix) { let { dir, name, ext } = path.parse(path); return path.join(dir, name + "-" + suffix + ext); } let path1 = suffixFilename("a/path/to/file.json", "original"); let path2 = suffixFilename("a/path/to/file.json", "comparand"); ```
In addition to @joe's answer, here's a simpler version that needs the [`modify-filename`](https://www.npmjs.com/package/modify-filename) package. ``` var modifyFilename = require('modify-filename'); const originalPath = "a/path/to/file.json"; const originalFilename = modifyFilename(originalPath, (name, ext) => { return `${name}-original${ext}`; }); const comparandFilename = modifyFilename(originalPath, (name, ext) => { return `${name}-comparand${ext}`; }); ```
48,677,250
From a web analyst perspective on any given website i am looking find out which same page anchors are clicked the most by console logging the anchor's text value (inner html text) in the console for now. The approach i took was to take the current page url after every anchor click and check to see if their had been any hash changes at the end of the url string and if so print that anchor's text value in the console. ``` var anchor = $("a[href^=\\#]"); anchor.on("click", function(){ if("onhashchange" in window) { var anchorText = this.text; console.log(anchorText); } }); ``` I'm having issues with the code I wrote because its returning the inner Html text for any anchors on the page(except the ones with external links) but I only want to track the ones that lead to a section on the same page. Would the approach i took need to be revised to even begin with ? Here is some of the html I am working with and different anchors I want to track and ones I don't. ``` <!-- Where the click on the anchor i want to target happens --> <nav> <h2 class="wb-inv">Promotions</h2> <ul class="toc lst-spcd col-md-12"> <li class="col-md-4"> <a href="#story1" class="list-group-item">Anchor for section 1</a> </li> </nav> <!-- below is the section of the same page the anchors would point to --> <div class="col-md-12 pull-left"> <h2 id="story1">Section 1 Title </h2> <p>Random paragraph 1</p> </div> <!-- The html I'm working with contains a set of tabs that reveal information as you click them, the href attribute and the id are both in the anchor. This is an example of anchors I wouldn't want to track--> <a tabindex="-1" id="details-panel1-lnk" role="tab" aria-selected="false" aria-controls="details-panel1" href="#details-panel1"> <h2 class="h5 mrgn-tp-sm mrgn-bttm-sm">Online</h2> </a> ```
2018/02/08
[ "https://Stackoverflow.com/questions/48677250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328610/" ]
How about using joblib ? This is not a straight vectorization, but the different starting points will be executed in parallel. ``` from scipy.optimize import fsolve import numpy as np from joblib import Parallel, delayed def equations(x): # x+y^2-4, sin(x)+x*y-3 ret = np.array([x[0]+x[1]**2-4, np.sin(x[0]) + x[0]*x[1] - 3]).T return ret p1 = np.array([0,0]) # first initial value p2 = np.array([1,1]) # second initial value x0 = [p1, p2] sol = Parallel(n_jobs=2)(delayed(fsolve)(equations, x0=p) for p in x0) print(sol) ``` The parameter `n_jobs` controls how many concurrent jobs are running.
``` def eq(x): return x[0] + x[1]**2 - 4 , np.sin(x[0]) + x[0]*x[1] - 3 fsolve(eq, [0, 1]) output: array([ 1.23639399, 1.6624097 ]) ``` In this case, I would suggest using a brute force method: ``` x0 = [[i, j] for i, j in zip(range(10), range(10))] for xnot in x0: print(fsolve(eq, xnot)) [ 1.33088471e-07 2.09094320e+00] [ 1.23639399 1.6624097 ] [ 1.23639399 1.6624097 ] [ 1.23639399 1.6624097 ] [ 1.23639399 1.6624097 ] [ 1.23639399 1.6624097 ] [ 1.23639399 1.6624097 ] [ 1.23639399 1.6624097 ] [ 1.23639399 1.6624097 ] [ 1.23639399 1.6624097 ] ```
70,276,149
as i title says. I think code will describe what i want to do. input: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] ``` expected output: ``` sum of polish signs in words - [0, 0, 3, 2, 3, 0, 1, 0] ``` My work: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] sumOfChars = [len(i) for i in words] polish = 'ą ć ę ł ń ó ś ź ż'.split() lista = [] for i in words: for x in i: if x in polish: lista.append(x) print(sumOfChars) print(lista) ``` And my output: ``` [3, 12, 4, 4, 16, 8, 7, 15] # ^ sum of chars in every string ['ż', 'ó', 'ł', 'ź', 'ń', 'ż', 'ó', 'ł', 'ę'] # ^ special signs in my strings ```
2021/12/08
[ "https://Stackoverflow.com/questions/70276149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17626416/" ]
If there is only one match. You need to use find(). Inside of the find method, you want to use some() to look for an \_id match. ```js const users = [ { name: "Jack", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, { _id: "41ss16512315615645bk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, ], }, { name: "Joe", workspaces: [ { _id: "CHANGED_ID", permissions: ["CAN_DELETE_WORKSPACE"], }, ], }, ]; const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; const active = users.find(function (user) { return user.workspaces.some( function (workspace) { return workspace._id === activeWorkspace._id; }); }); console.log(active); // Same thing as above, just done with a modern approach const active2 = users.find(({workspaces}) => workspaces.some(({_id}) => _id === activeWorkspace._id)); console.log(active2); ``` --- Now if there could be more than one match (your orginal code before the typo, you would use filter() and some() to find all users that have the workspace in their array. ```js const users = [ { name: "Jack", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, { _id: "41ss16512315615645bk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, ], }, { name: "Joe", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE"], }, ], }, ]; const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; const active = users.filter(function (user) { return user.workspaces.some( function (workspace) { return workspace._id === activeWorkspace._id; }); }); console.log(active); // Same thing as above, just done with a modern approach const active2 = users.filter(({workspaces}) => workspaces.some(({_id}) => _id === activeWorkspace._id)); console.log(active2); ```
`users.map(u => u.workspaces).flat().filter(w => w._id === activeWorkspaceId);` <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat>
70,276,149
as i title says. I think code will describe what i want to do. input: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] ``` expected output: ``` sum of polish signs in words - [0, 0, 3, 2, 3, 0, 1, 0] ``` My work: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] sumOfChars = [len(i) for i in words] polish = 'ą ć ę ł ń ó ś ź ż'.split() lista = [] for i in words: for x in i: if x in polish: lista.append(x) print(sumOfChars) print(lista) ``` And my output: ``` [3, 12, 4, 4, 16, 8, 7, 15] # ^ sum of chars in every string ['ż', 'ó', 'ł', 'ź', 'ń', 'ż', 'ó', 'ł', 'ę'] # ^ special signs in my strings ```
2021/12/08
[ "https://Stackoverflow.com/questions/70276149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17626416/" ]
I adjusted the provided data from Joe so he doesn't have permissions ```js const users = [{ name: "Jack", workspaces: [{ _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, { _id: "41ss16512315615645bk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, ], }, { name: "Joe", workspaces: [{ _id: "61216512315615645bk", permissions: ["CAN_DELETE_WORKSPACE"], }, ], }, ]; const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; function findPermittedUser() { return users.filter(user => { let hasPermission = false user.workspaces.forEach(workspace => { if (activeWorkspace._id == workspace._id) { hasPermission = true } }) return hasPermission }) } console.log(findPermittedUser()) ```
`users.map(u => u.workspaces).flat().filter(w => w._id === activeWorkspaceId);` <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat>
70,276,149
as i title says. I think code will describe what i want to do. input: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] ``` expected output: ``` sum of polish signs in words - [0, 0, 3, 2, 3, 0, 1, 0] ``` My work: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] sumOfChars = [len(i) for i in words] polish = 'ą ć ę ł ń ó ś ź ż'.split() lista = [] for i in words: for x in i: if x in polish: lista.append(x) print(sumOfChars) print(lista) ``` And my output: ``` [3, 12, 4, 4, 16, 8, 7, 15] # ^ sum of chars in every string ['ż', 'ó', 'ł', 'ź', 'ń', 'ż', 'ó', 'ł', 'ę'] # ^ special signs in my strings ```
2021/12/08
[ "https://Stackoverflow.com/questions/70276149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17626416/" ]
You can use `map` and `filter` to "filter" out the unwanted ids from the `users` object. Something like : ```js const users = [ { "name": "Jack", "workspaces": [ { "_id": "61216512315615645jbk", "permissions": [ "CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT" ] }, { "_id": "41ss16512315615645bk", "permissions": [ "CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT" ] } ] }, { "name": "Joe", "workspaces": [ { "_id": "61216512315615645jbk", "permissions": [ "CAN_DELETE_WORKSPACE" ] } ] } ] const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; const filteredUsers = users.map(item => ({ name : item.name, workspaces: item.workspaces.filter(user => user._id === activeWorkspace._id)} )); console.log(filteredUsers); ```
`users.map(u => u.workspaces).flat().filter(w => w._id === activeWorkspaceId);` <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat>
70,276,149
as i title says. I think code will describe what i want to do. input: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] ``` expected output: ``` sum of polish signs in words - [0, 0, 3, 2, 3, 0, 1, 0] ``` My work: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] sumOfChars = [len(i) for i in words] polish = 'ą ć ę ł ń ó ś ź ż'.split() lista = [] for i in words: for x in i: if x in polish: lista.append(x) print(sumOfChars) print(lista) ``` And my output: ``` [3, 12, 4, 4, 16, 8, 7, 15] # ^ sum of chars in every string ['ż', 'ó', 'ł', 'ź', 'ń', 'ż', 'ó', 'ł', 'ę'] # ^ special signs in my strings ```
2021/12/08
[ "https://Stackoverflow.com/questions/70276149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17626416/" ]
This should work (tested): ```js const filteredUsers = users.filter( user => user.workspaces.reduce( (acc, workspace) => acc || workspace._id === activeWorkspace._id, false) ) ) ``` Explanation: We are using `filter` and `reduce` as evident from the code. What the code is doing is pretty simple, first, we want to apply `filter` on the user array. Now in the filter, we need to define the logic, which should return `true` whenever our condition happens to be true. Since we have an array of workspaces, we need to iterate over all of them to check if our activeWorkspace.\_id exists in any of them. For this, you can use a for loop and return `true` when you find it, else return `false` if not. But the functional way of doing it would be to use `reduce` and initialize the accumulator with `false`. Every time you access a workspace, you return `acc || <our condition>`. Notice how if even once our condition returns true, the accumulator becomes `true` for the rest of the execution of `reduce`. This is slightly poor in performance since you are not exiting as soon as you have found your workspace.\_id as you would have done in case of a `for` loop.
`users.map(u => u.workspaces).flat().filter(w => w._id === activeWorkspaceId);` <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat>
70,276,149
as i title says. I think code will describe what i want to do. input: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] ``` expected output: ``` sum of polish signs in words - [0, 0, 3, 2, 3, 0, 1, 0] ``` My work: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] sumOfChars = [len(i) for i in words] polish = 'ą ć ę ł ń ó ś ź ż'.split() lista = [] for i in words: for x in i: if x in polish: lista.append(x) print(sumOfChars) print(lista) ``` And my output: ``` [3, 12, 4, 4, 16, 8, 7, 15] # ^ sum of chars in every string ['ż', 'ó', 'ł', 'ź', 'ń', 'ż', 'ó', 'ł', 'ę'] # ^ special signs in my strings ```
2021/12/08
[ "https://Stackoverflow.com/questions/70276149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17626416/" ]
If there is only one match. You need to use find(). Inside of the find method, you want to use some() to look for an \_id match. ```js const users = [ { name: "Jack", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, { _id: "41ss16512315615645bk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, ], }, { name: "Joe", workspaces: [ { _id: "CHANGED_ID", permissions: ["CAN_DELETE_WORKSPACE"], }, ], }, ]; const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; const active = users.find(function (user) { return user.workspaces.some( function (workspace) { return workspace._id === activeWorkspace._id; }); }); console.log(active); // Same thing as above, just done with a modern approach const active2 = users.find(({workspaces}) => workspaces.some(({_id}) => _id === activeWorkspace._id)); console.log(active2); ``` --- Now if there could be more than one match (your orginal code before the typo, you would use filter() and some() to find all users that have the workspace in their array. ```js const users = [ { name: "Jack", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, { _id: "41ss16512315615645bk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, ], }, { name: "Joe", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE"], }, ], }, ]; const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; const active = users.filter(function (user) { return user.workspaces.some( function (workspace) { return workspace._id === activeWorkspace._id; }); }); console.log(active); // Same thing as above, just done with a modern approach const active2 = users.filter(({workspaces}) => workspaces.some(({_id}) => _id === activeWorkspace._id)); console.log(active2); ```
I adjusted the provided data from Joe so he doesn't have permissions ```js const users = [{ name: "Jack", workspaces: [{ _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, { _id: "41ss16512315615645bk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, ], }, { name: "Joe", workspaces: [{ _id: "61216512315615645bk", permissions: ["CAN_DELETE_WORKSPACE"], }, ], }, ]; const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; function findPermittedUser() { return users.filter(user => { let hasPermission = false user.workspaces.forEach(workspace => { if (activeWorkspace._id == workspace._id) { hasPermission = true } }) return hasPermission }) } console.log(findPermittedUser()) ```
70,276,149
as i title says. I think code will describe what i want to do. input: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] ``` expected output: ``` sum of polish signs in words - [0, 0, 3, 2, 3, 0, 1, 0] ``` My work: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] sumOfChars = [len(i) for i in words] polish = 'ą ć ę ł ń ó ś ź ż'.split() lista = [] for i in words: for x in i: if x in polish: lista.append(x) print(sumOfChars) print(lista) ``` And my output: ``` [3, 12, 4, 4, 16, 8, 7, 15] # ^ sum of chars in every string ['ż', 'ó', 'ł', 'ź', 'ń', 'ż', 'ó', 'ł', 'ę'] # ^ special signs in my strings ```
2021/12/08
[ "https://Stackoverflow.com/questions/70276149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17626416/" ]
If there is only one match. You need to use find(). Inside of the find method, you want to use some() to look for an \_id match. ```js const users = [ { name: "Jack", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, { _id: "41ss16512315615645bk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, ], }, { name: "Joe", workspaces: [ { _id: "CHANGED_ID", permissions: ["CAN_DELETE_WORKSPACE"], }, ], }, ]; const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; const active = users.find(function (user) { return user.workspaces.some( function (workspace) { return workspace._id === activeWorkspace._id; }); }); console.log(active); // Same thing as above, just done with a modern approach const active2 = users.find(({workspaces}) => workspaces.some(({_id}) => _id === activeWorkspace._id)); console.log(active2); ``` --- Now if there could be more than one match (your orginal code before the typo, you would use filter() and some() to find all users that have the workspace in their array. ```js const users = [ { name: "Jack", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, { _id: "41ss16512315615645bk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, ], }, { name: "Joe", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE"], }, ], }, ]; const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; const active = users.filter(function (user) { return user.workspaces.some( function (workspace) { return workspace._id === activeWorkspace._id; }); }); console.log(active); // Same thing as above, just done with a modern approach const active2 = users.filter(({workspaces}) => workspaces.some(({_id}) => _id === activeWorkspace._id)); console.log(active2); ```
You can use `map` and `filter` to "filter" out the unwanted ids from the `users` object. Something like : ```js const users = [ { "name": "Jack", "workspaces": [ { "_id": "61216512315615645jbk", "permissions": [ "CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT" ] }, { "_id": "41ss16512315615645bk", "permissions": [ "CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT" ] } ] }, { "name": "Joe", "workspaces": [ { "_id": "61216512315615645jbk", "permissions": [ "CAN_DELETE_WORKSPACE" ] } ] } ] const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; const filteredUsers = users.map(item => ({ name : item.name, workspaces: item.workspaces.filter(user => user._id === activeWorkspace._id)} )); console.log(filteredUsers); ```
70,276,149
as i title says. I think code will describe what i want to do. input: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] ``` expected output: ``` sum of polish signs in words - [0, 0, 3, 2, 3, 0, 1, 0] ``` My work: ``` words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy'] sumOfChars = [len(i) for i in words] polish = 'ą ć ę ł ń ó ś ź ż'.split() lista = [] for i in words: for x in i: if x in polish: lista.append(x) print(sumOfChars) print(lista) ``` And my output: ``` [3, 12, 4, 4, 16, 8, 7, 15] # ^ sum of chars in every string ['ż', 'ó', 'ł', 'ź', 'ń', 'ż', 'ó', 'ł', 'ę'] # ^ special signs in my strings ```
2021/12/08
[ "https://Stackoverflow.com/questions/70276149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17626416/" ]
If there is only one match. You need to use find(). Inside of the find method, you want to use some() to look for an \_id match. ```js const users = [ { name: "Jack", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, { _id: "41ss16512315615645bk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, ], }, { name: "Joe", workspaces: [ { _id: "CHANGED_ID", permissions: ["CAN_DELETE_WORKSPACE"], }, ], }, ]; const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; const active = users.find(function (user) { return user.workspaces.some( function (workspace) { return workspace._id === activeWorkspace._id; }); }); console.log(active); // Same thing as above, just done with a modern approach const active2 = users.find(({workspaces}) => workspaces.some(({_id}) => _id === activeWorkspace._id)); console.log(active2); ``` --- Now if there could be more than one match (your orginal code before the typo, you would use filter() and some() to find all users that have the workspace in their array. ```js const users = [ { name: "Jack", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, { _id: "41ss16512315615645bk", permissions: ["CAN_DELETE_WORKSPACE", "CAN_EDIT_PROJECT"], }, ], }, { name: "Joe", workspaces: [ { _id: "61216512315615645jbk", permissions: ["CAN_DELETE_WORKSPACE"], }, ], }, ]; const activeWorkspace = { name: "W1", _id: "61216512315615645jbk", }; const active = users.filter(function (user) { return user.workspaces.some( function (workspace) { return workspace._id === activeWorkspace._id; }); }); console.log(active); // Same thing as above, just done with a modern approach const active2 = users.filter(({workspaces}) => workspaces.some(({_id}) => _id === activeWorkspace._id)); console.log(active2); ```
This should work (tested): ```js const filteredUsers = users.filter( user => user.workspaces.reduce( (acc, workspace) => acc || workspace._id === activeWorkspace._id, false) ) ) ``` Explanation: We are using `filter` and `reduce` as evident from the code. What the code is doing is pretty simple, first, we want to apply `filter` on the user array. Now in the filter, we need to define the logic, which should return `true` whenever our condition happens to be true. Since we have an array of workspaces, we need to iterate over all of them to check if our activeWorkspace.\_id exists in any of them. For this, you can use a for loop and return `true` when you find it, else return `false` if not. But the functional way of doing it would be to use `reduce` and initialize the accumulator with `false`. Every time you access a workspace, you return `acc || <our condition>`. Notice how if even once our condition returns true, the accumulator becomes `true` for the rest of the execution of `reduce`. This is slightly poor in performance since you are not exiting as soon as you have found your workspace.\_id as you would have done in case of a `for` loop.
53,878,969
I want to find records in a (Oracle SQL) table using the creation date field where records are older than 24hrs and set some status once. To find records using a operators like > but if anyone can suggest quick SQL where clause statement to find records older than 24hrs that would be nice.
2018/12/21
[ "https://Stackoverflow.com/questions/53878969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9921755/" ]
You can use below query to fetch the same SELECT \* FROM mytable WHERE record\_date >= SYSDATE - 1
Get records younger than 24 hours: ``` SELECT * FROM table WHERE record_date > SYSDATE - 1 ``` Get records older than 24 hours: ``` SELECT * FROM table WHERE record_date < SYSDATE - 1 ``` Get records from today: ``` SELECT * FROM table WHERE record_date >= TRUNC(SYSDATE) ``` Get records from before today: ``` SELECT * FROM table WHERE record_date < TRUNC(SYSDATE ``` Set records older than 24 h to old status: ``` UPDATE table SET status = 'old' WHERE record_date < SYSYDATE - 1 ``` Remember that adding/subtracting numbers to dates in oracle adds or removes that number of days or part days. ``` 01-Jan-1970 00:00:00 + 1.5 = 02-Jan-1970 00:06:00 ``` Let's add 3 days 17 hours and 26 minutes: ``` 01-Jan-1970 00:00:00 + 3 + (17/24) + (26/60/24) ```
38,366,674
When trying to install 'graphics tools' in xcode (Xcode -> open developer tool -> More developer tools, I get: ``` {"responseId":"ba7bd79e-487a-49b6-9bf1-f4085dc9e27e","resultCode":1003,"resultString":"request.uri.notfound","userString":"Invalid request, Service mapping to the requested URL is not available. ","creationTimestamp":"2016-07-14T05:58:55Z","userLocale":"en_US","requestUrl":"https://developer.apple.com:443/downloads/index.action?name=for%20Xcode","httpCode":200,"suppressed":[]} ``` When trying to install from here (downloads): <https://developer.apple.com/opengl/> I get: ``` {"responseId":"76bb89d6-d9a7-4c67-b24e-d65c03e83973","resultCode":1003,"resultString":"request.uri.notfound","userString":"Invalid request, Service mapping to the requested URL is not available. ","creationTimestamp":"2016-07-14T06:00:40Z","userLocale":"en_US","requestUrl":"https://developer.apple.com:443/downloads/index.action?q=graphics","httpCode":200,"suppressed":[]} ``` Anyone got a idea how to install graphics tools? /A
2016/07/14
[ "https://Stackoverflow.com/questions/38366674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2353816/" ]
Passing an `attribute` to element might not work as element needs to be in `ready` state for that. Below are three ways that might help you with what you are trying **One way** to `lazy register` your elements in `Polymer` is to use `Polymer.Class` instead of `Polymer` constructor. This way until you register your element manually it will not get rendered. Below is an working example of same. ```html <base href="https://polygit.org/components/"> <script src="webcomponentsjs/webcomponents-lite.js"></script> <link rel="import" href="polymer/polymer.html"> <dom-module id="poly-form"> <template> <style></style> I am parent Element <div> <button onclick='register()'>Save</button> </div> <show-form></show-form> </template> </dom-module> <script> Polymer({ is: 'poly-form', }); //element to lazy register var showForm = Polymer.Class({ is: 'show-form', ready: function() { this.textContent = 'I am working...'; } }); function register() { var form = document.querySelector('poly-form'); //lazy register the element document.registerElement('show-form', showForm); } </script> <poly-form></poly-form> ``` In this example `show-form` element does not render until the button is clicked. **Note** I've never really tried this with element containing `dom`. **Second way** this should also be possible with [`importHref`](https://www.polymer-project.org/1.0/docs/api/Polymer.Base#method-importHref) method. **Third way** is `global setting` [lazy-register](https://www.polymer-project.org/1.0/docs/devguide/settings) where element gets register only when its first instance is called. Sorry, the snippet is not as well constructed as it could have been. Hope it helps.
[Class Style Constructor](https://www.polymer-project.org/1.0/docs/devguide/registering-elements#element-constructor) > > If you want to set up your custom element's prototype chain but not register it immediately, you can use the Polymer.Class function. Polymer.Class takes the same prototype argument as the Polymer function, and sets up the prototype chain, but does not register the element. Instead it returns a constructor that can be passed to document.registerElement to register your element with the browser, and after which can be used to instantiate new instances of your element via code. > > > > ``` > var MyElement = Polymer.Class({ > > is: 'my-element', > > // See below for lifecycle callbacks > created: function() { > this.textContent = 'My element!'; > } > > }); > document.registerElement('my-element', MyElement); > > // Equivalent: > var el1 = new MyElement(); > var el2 = document.createElement('my-element'); > > ``` > >
52,228,887
I know the difference between `==` and `===` when applied to primitive values. But for objects, they both seem to be a simple identity comparison. ``` var a = {} var b = a var c = {} a == b // true a === b // true a == c // false a === c // false ``` Is there any situation where comparing two objects will provide different results for each operator, or are they functionally equivalent?
2018/09/07
[ "https://Stackoverflow.com/questions/52228887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7496073/" ]
Looks like it The only way I know to "check for object equality" in javascript is to deep check every possible key (but even then it is just duck type checking)
Well... `===` is "compare identity and type". You've determined that you're comparing two objects (so "type" is the same), that leaves "compare identity", which is the same as `==`. Likewise, if you compare two `number`s, since you already know they are the same type (`number`), `===` is the same as `==`. There is nothing special or different about objects vs. primitives here. It's just that the only type for objects is `object`.
52,228,887
I know the difference between `==` and `===` when applied to primitive values. But for objects, they both seem to be a simple identity comparison. ``` var a = {} var b = a var c = {} a == b // true a === b // true a == c // false a === c // false ``` Is there any situation where comparing two objects will provide different results for each operator, or are they functionally equivalent?
2018/09/07
[ "https://Stackoverflow.com/questions/52228887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7496073/" ]
Yes, comparing two objects with `==` is the same as comparing them with `===`. Just as comparing two strings with `==` is the same as `===`. If the type of values are the same, both comparing methods will give the same result. [As the specification states](http://www.ecma-international.org/ecma-262/9.0/index.html#sec-abstract-equality-comparison): > > 7.2.14 Abstract Equality Comparison > =================================== > > > The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed > as follows: > > > 1. If Type(x) is the same as Type(y), then > * Return the result of > performing Strict Equality Comparison x === y. > > >
Looks like it The only way I know to "check for object equality" in javascript is to deep check every possible key (but even then it is just duck type checking)
52,228,887
I know the difference between `==` and `===` when applied to primitive values. But for objects, they both seem to be a simple identity comparison. ``` var a = {} var b = a var c = {} a == b // true a === b // true a == c // false a === c // false ``` Is there any situation where comparing two objects will provide different results for each operator, or are they functionally equivalent?
2018/09/07
[ "https://Stackoverflow.com/questions/52228887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7496073/" ]
Yes, comparing two objects with `==` is the same as comparing them with `===`. Just as comparing two strings with `==` is the same as `===`. If the type of values are the same, both comparing methods will give the same result. [As the specification states](http://www.ecma-international.org/ecma-262/9.0/index.html#sec-abstract-equality-comparison): > > 7.2.14 Abstract Equality Comparison > =================================== > > > The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed > as follows: > > > 1. If Type(x) is the same as Type(y), then > * Return the result of > performing Strict Equality Comparison x === y. > > >
Well... `===` is "compare identity and type". You've determined that you're comparing two objects (so "type" is the same), that leaves "compare identity", which is the same as `==`. Likewise, if you compare two `number`s, since you already know they are the same type (`number`), `===` is the same as `==`. There is nothing special or different about objects vs. primitives here. It's just that the only type for objects is `object`.
52,228,887
I know the difference between `==` and `===` when applied to primitive values. But for objects, they both seem to be a simple identity comparison. ``` var a = {} var b = a var c = {} a == b // true a === b // true a == c // false a === c // false ``` Is there any situation where comparing two objects will provide different results for each operator, or are they functionally equivalent?
2018/09/07
[ "https://Stackoverflow.com/questions/52228887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7496073/" ]
The extra = in `===` ensures both sides are of the same type. `a` and `c` both are objects, the same type. So `==` or `===` is irrelevant here.
Well... `===` is "compare identity and type". You've determined that you're comparing two objects (so "type" is the same), that leaves "compare identity", which is the same as `==`. Likewise, if you compare two `number`s, since you already know they are the same type (`number`), `===` is the same as `==`. There is nothing special or different about objects vs. primitives here. It's just that the only type for objects is `object`.
52,228,887
I know the difference between `==` and `===` when applied to primitive values. But for objects, they both seem to be a simple identity comparison. ``` var a = {} var b = a var c = {} a == b // true a === b // true a == c // false a === c // false ``` Is there any situation where comparing two objects will provide different results for each operator, or are they functionally equivalent?
2018/09/07
[ "https://Stackoverflow.com/questions/52228887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7496073/" ]
Yes, comparing two objects with `==` is the same as comparing them with `===`. Just as comparing two strings with `==` is the same as `===`. If the type of values are the same, both comparing methods will give the same result. [As the specification states](http://www.ecma-international.org/ecma-262/9.0/index.html#sec-abstract-equality-comparison): > > 7.2.14 Abstract Equality Comparison > =================================== > > > The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed > as follows: > > > 1. If Type(x) is the same as Type(y), then > * Return the result of > performing Strict Equality Comparison x === y. > > >
The extra = in `===` ensures both sides are of the same type. `a` and `c` both are objects, the same type. So `==` or `===` is irrelevant here.
43,604,529
My application will take data using form and save it to the database and then draw it using chartjs . **I have tried this code but gives me an error. My code is as follows :** ``` def get_temperature_show(request): all_temperatures = Temper.objects.all() dates_label = [] sensor1_temp = [] sensor2_temp = [] sensor3_temp = [] sensor4_temp = [] for model in all_temperatures: dates_label.append(model.date) sensor1_temp.append(model.sensor1_temp) sensor2_temp.append(model.sensor2_temp) sensor3_temp.append(model.sensor3_temp) sensor4_temp.append(model.sensor4_temp) data = { 'dates': dates_label, 'sensor1': sensor1_temp, 'sensor2': sensor2_temp, 'sensor3': sensor3_temp, 'sensor4': sensor4_temp } return render(request, 'weather/showtemper.html', json.dumps({"data":data})) ``` But it gives the following- ![datetime.date(2017, 4, 4) is not JSON serializable](https://i.stack.imgur.com/IsFgF.png) My template example is like this: ``` var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'], datasets: [{ label: 'apples', data: [12, 19, 3, 17, 6, 3, 7], backgroundColor: "rgba(153,255,51,0.4)" }, { label: 'oranges', data: [2, 29, 5, 5, 2, 3, 10], backgroundColor: "rgba(255,153,0,0.4)" }] } }); ``` Please help me to resolve this error Thanks in advance
2017/04/25
[ "https://Stackoverflow.com/questions/43604529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5045972/" ]
**View should be like this:** ``` def get_temperature_show(request): data = Temper.objects.all() return render(request,'weather/showtemper.html',{'data':data}) ``` **In the template just iterate the data. Code is as follows:** ``` var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { {# labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],#} labels: [{% for d in data %} "{{ d.date }}", {% endfor %}], datasets: [{ label: 'Sensor 1', {# data: [12, 19, 3, 17, 6, 3, 7],#} data: [{% for temp in data %} "{{ temp.sensor1_temp }}", {% endfor %}], backgroundColor: "rgba(153,255,51,0.4)" }, { label: 'Sensor 2', data: [{% for temp in data %} "{{ temp.sensor2_temp }}", {% endfor %}], backgroundColor: "rgba(255,153,0,0.4)" }, { label: 'Sensor 3', data: [{% for temp in data %} "{{ temp.sensor3_temp }}", {% endfor %}], backgroundColor: "rgba(0,0,255,0.4)" }, { label: 'Sensor 4', data: [{% for temp in data %} "{{ temp.sensor4_temp }}", {% endfor %}], backgroundColor: "rgba(255,0,0,0.4)" }] } }); ```
``` from json import JSONEncoder class MyEncoder(JSONEncoder): def default(self, o): if isinstance( o, datetime.datetime): return o.isoformat() return o json.dumps(cls=MyEncoder) ``` try this when you are dumping in your django code
64,801,905
I have a requirement where I have to extract two lines of text just after the Table of Contents in a Word Document. The text is hidden and added just for use in VBA. I did some research and found out that I can extract text from a word Document using the `Range` object and so I tried hardcoding it and I got the value I wanted by using ``` MsgBox ActiveDocument.Paragraphs(43).Range.Text ``` Now this code can work for a specific document but for a new document I don't know where the Table of Contents will end and the exact line number from where I have to extract. Any help is appreciated and thanks in advance.
2020/11/12
[ "https://Stackoverflow.com/questions/64801905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7292231/" ]
You can use `String.prototype.toLowerCase` on both the input value and the word: ```js function openPage() { var x = document.getElementById("search").value; if (x.toLowerCase() === "Oyaide".toLowerCase()) { window.location.replace("/Products#!/oyaide/sort/manual"); } } ```
I think you may want something like this to have more than one location to go to ```js const locations = { "oyaide" : "/Products#!/oyaide/sort/manual", "something" : "/Products#!/something/sort/manual" } window.addEventListener("load",function() { document.getElementById("search").addEventListener("input",function() { const val = this.value.toLowerCase(); // case insensitive const loc = locations[val]; // as soon as one exists if (loc) location.replace(loc); // use it }); }); ``` ```html <input type="search" autocomplete="off" value="" placeholder="Search here..." id="search" /> ```
14,209
For example, ailerons allow air to flow past both the top and bottom surfaces, which makes it more aerodynamic than speedbrakes. Also, plane rudders have air flowing on both sides, which is apparently mote efficient than a spoiler. Why does this happen?
2015/04/17
[ "https://aviation.stackexchange.com/questions/14209", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/8021/" ]
For low drag, you want to minimize the surface changes presented to the air flow. Large changes in the surface will create turbulence and pressure changes that contribute to drag. Small changes will minimize these sources of drag. When you move a control surface like an aileron or elevator, air is flowing past both sides of the airfoil. Although this changes the direction of the flow, which gives the control force as well as some drag, the air can still flow past both sides. In the case of a spoiler, the air cannot flow past both sides. This increases the frontal area presented to the flow, and creates a low pressure area behind the deployed surface. Creating a low-pressure area behind an object is a big contributor to drag, which is why [aerodynamic bodies tend to have a teardrop shape](http://exploration.grc.nasa.gov/education/rocket/shaped.html). Spoilers on the wing also have the effect of reducing lift. By disrupting the smooth low-pressure flow over the upper surface of the wing, they reduce the effectiveness of the wing, effectively [stalling the affected portion](https://aviation.stackexchange.com/q/6366/1696). For an illustration of both principles in action, [see this video](https://www.youtube.com/watch?v=ysb5QIHcLSQ) of a speed brake on a Mooney. This shows how even a relatively small object, when disrupting the air flow, can add a significant amount of drag.
The main answer is drag. A spoiler will create more drag than a surface that allows flow over both sides. In the case of speed brakes this is what you want to happen as you want to slow the plane down. With control surfaces you want to alter airflow with out creating excess drag.
14,209
For example, ailerons allow air to flow past both the top and bottom surfaces, which makes it more aerodynamic than speedbrakes. Also, plane rudders have air flowing on both sides, which is apparently mote efficient than a spoiler. Why does this happen?
2015/04/17
[ "https://aviation.stackexchange.com/questions/14209", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/8021/" ]
The reason is that both sides of a control surface experience pressure changes, both ahead and aft of the hinge line. In case of spoilers and speed brakes, only one side is affected, so the effectiveness is only half as big. Please see the pressure coefficient plots of an airfoil for three different flap deflections below. Upper and lower surface pressure are shown by color-coded lines, and lower lines belong to the lower surface. Dashed lines show the inviscid pressure, and solid lines the pressure distribution with friction effects added. The wider two lines of the same color are apart, the more lift is created. Note the contour plot below, which follows the color scheme of the pressure plots. ![E502 with three flap angles](https://i.stack.imgur.com/p4Z2X.png) While control surfaces normally are deflected by less than ±20°, regular spoilers are extended by 60° or more to create as much drag as possible. But even if they are extended by similar angles to those of a control surface, the air will have no chance to flow orderly along the leeward side. Instead, this side will only have separated, chaotic airflow, while the windward side will show a flow pattern very similar to the windward side of a control surface. The pressure in separated flow will not change with deflection angle, so this side will not contribute any lift effect. Note in the picture above that the pressure level over the whole chord is pushed up or down by the flap, because the flap is located in the aft portion of the airfoil. In contrast to that, spoilers are mounted mid-chord, where their influence over the pressure level is smaller. This reduces the lift effects of spoilers even more.
The main answer is drag. A spoiler will create more drag than a surface that allows flow over both sides. In the case of speed brakes this is what you want to happen as you want to slow the plane down. With control surfaces you want to alter airflow with out creating excess drag.
14,209
For example, ailerons allow air to flow past both the top and bottom surfaces, which makes it more aerodynamic than speedbrakes. Also, plane rudders have air flowing on both sides, which is apparently mote efficient than a spoiler. Why does this happen?
2015/04/17
[ "https://aviation.stackexchange.com/questions/14209", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/8021/" ]
The main answer is drag. A spoiler will create more drag than a surface that allows flow over both sides. In the case of speed brakes this is what you want to happen as you want to slow the plane down. With control surfaces you want to alter airflow with out creating excess drag.
I think you question comes to the difference between aerodynamic body and blunt body. It is no so much linked to exposing one or two surfaces to the external flow, but more linked to the shape exposed to the external flow. An aerodynamic body has a shape which produces low drag, aerodynamic bodies have a very small size normal to the direction of flight. For example, the wing is really thin in the vertical direction, but huge is the direction the plane is expected to flight. A blunt body is the oppossite way around, exposes a big surface in front of the moving direction. The spoilers are a very good example. I can give you a practical example, you hand. When you are in your car (in movement) and you extend your hand outside the car, having the hand parallel to the ground, you don't notice significant "pressure" or "force" over your hand (please use some nice speed...) however is you set your palm looking to the direction the car is moving, the "pressure" over you hand is much bigger as you are exposing a bigger surface. Example the same phenomena with your hand is happening with ailerons, rudders and airbrake. We use an airbrake to stop the airplane, that is why we use like your palm in the car. Stop the airplane. Ailerons and rudders are intended to not stop the airplane, but control it. That's why the intention is to have low drag.
14,209
For example, ailerons allow air to flow past both the top and bottom surfaces, which makes it more aerodynamic than speedbrakes. Also, plane rudders have air flowing on both sides, which is apparently mote efficient than a spoiler. Why does this happen?
2015/04/17
[ "https://aviation.stackexchange.com/questions/14209", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/8021/" ]
For low drag, you want to minimize the surface changes presented to the air flow. Large changes in the surface will create turbulence and pressure changes that contribute to drag. Small changes will minimize these sources of drag. When you move a control surface like an aileron or elevator, air is flowing past both sides of the airfoil. Although this changes the direction of the flow, which gives the control force as well as some drag, the air can still flow past both sides. In the case of a spoiler, the air cannot flow past both sides. This increases the frontal area presented to the flow, and creates a low pressure area behind the deployed surface. Creating a low-pressure area behind an object is a big contributor to drag, which is why [aerodynamic bodies tend to have a teardrop shape](http://exploration.grc.nasa.gov/education/rocket/shaped.html). Spoilers on the wing also have the effect of reducing lift. By disrupting the smooth low-pressure flow over the upper surface of the wing, they reduce the effectiveness of the wing, effectively [stalling the affected portion](https://aviation.stackexchange.com/q/6366/1696). For an illustration of both principles in action, [see this video](https://www.youtube.com/watch?v=ysb5QIHcLSQ) of a speed brake on a Mooney. This shows how even a relatively small object, when disrupting the air flow, can add a significant amount of drag.
The reason is that both sides of a control surface experience pressure changes, both ahead and aft of the hinge line. In case of spoilers and speed brakes, only one side is affected, so the effectiveness is only half as big. Please see the pressure coefficient plots of an airfoil for three different flap deflections below. Upper and lower surface pressure are shown by color-coded lines, and lower lines belong to the lower surface. Dashed lines show the inviscid pressure, and solid lines the pressure distribution with friction effects added. The wider two lines of the same color are apart, the more lift is created. Note the contour plot below, which follows the color scheme of the pressure plots. ![E502 with three flap angles](https://i.stack.imgur.com/p4Z2X.png) While control surfaces normally are deflected by less than ±20°, regular spoilers are extended by 60° or more to create as much drag as possible. But even if they are extended by similar angles to those of a control surface, the air will have no chance to flow orderly along the leeward side. Instead, this side will only have separated, chaotic airflow, while the windward side will show a flow pattern very similar to the windward side of a control surface. The pressure in separated flow will not change with deflection angle, so this side will not contribute any lift effect. Note in the picture above that the pressure level over the whole chord is pushed up or down by the flap, because the flap is located in the aft portion of the airfoil. In contrast to that, spoilers are mounted mid-chord, where their influence over the pressure level is smaller. This reduces the lift effects of spoilers even more.
14,209
For example, ailerons allow air to flow past both the top and bottom surfaces, which makes it more aerodynamic than speedbrakes. Also, plane rudders have air flowing on both sides, which is apparently mote efficient than a spoiler. Why does this happen?
2015/04/17
[ "https://aviation.stackexchange.com/questions/14209", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/8021/" ]
For low drag, you want to minimize the surface changes presented to the air flow. Large changes in the surface will create turbulence and pressure changes that contribute to drag. Small changes will minimize these sources of drag. When you move a control surface like an aileron or elevator, air is flowing past both sides of the airfoil. Although this changes the direction of the flow, which gives the control force as well as some drag, the air can still flow past both sides. In the case of a spoiler, the air cannot flow past both sides. This increases the frontal area presented to the flow, and creates a low pressure area behind the deployed surface. Creating a low-pressure area behind an object is a big contributor to drag, which is why [aerodynamic bodies tend to have a teardrop shape](http://exploration.grc.nasa.gov/education/rocket/shaped.html). Spoilers on the wing also have the effect of reducing lift. By disrupting the smooth low-pressure flow over the upper surface of the wing, they reduce the effectiveness of the wing, effectively [stalling the affected portion](https://aviation.stackexchange.com/q/6366/1696). For an illustration of both principles in action, [see this video](https://www.youtube.com/watch?v=ysb5QIHcLSQ) of a speed brake on a Mooney. This shows how even a relatively small object, when disrupting the air flow, can add a significant amount of drag.
I think you question comes to the difference between aerodynamic body and blunt body. It is no so much linked to exposing one or two surfaces to the external flow, but more linked to the shape exposed to the external flow. An aerodynamic body has a shape which produces low drag, aerodynamic bodies have a very small size normal to the direction of flight. For example, the wing is really thin in the vertical direction, but huge is the direction the plane is expected to flight. A blunt body is the oppossite way around, exposes a big surface in front of the moving direction. The spoilers are a very good example. I can give you a practical example, you hand. When you are in your car (in movement) and you extend your hand outside the car, having the hand parallel to the ground, you don't notice significant "pressure" or "force" over your hand (please use some nice speed...) however is you set your palm looking to the direction the car is moving, the "pressure" over you hand is much bigger as you are exposing a bigger surface. Example the same phenomena with your hand is happening with ailerons, rudders and airbrake. We use an airbrake to stop the airplane, that is why we use like your palm in the car. Stop the airplane. Ailerons and rudders are intended to not stop the airplane, but control it. That's why the intention is to have low drag.
14,209
For example, ailerons allow air to flow past both the top and bottom surfaces, which makes it more aerodynamic than speedbrakes. Also, plane rudders have air flowing on both sides, which is apparently mote efficient than a spoiler. Why does this happen?
2015/04/17
[ "https://aviation.stackexchange.com/questions/14209", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/8021/" ]
The reason is that both sides of a control surface experience pressure changes, both ahead and aft of the hinge line. In case of spoilers and speed brakes, only one side is affected, so the effectiveness is only half as big. Please see the pressure coefficient plots of an airfoil for three different flap deflections below. Upper and lower surface pressure are shown by color-coded lines, and lower lines belong to the lower surface. Dashed lines show the inviscid pressure, and solid lines the pressure distribution with friction effects added. The wider two lines of the same color are apart, the more lift is created. Note the contour plot below, which follows the color scheme of the pressure plots. ![E502 with three flap angles](https://i.stack.imgur.com/p4Z2X.png) While control surfaces normally are deflected by less than ±20°, regular spoilers are extended by 60° or more to create as much drag as possible. But even if they are extended by similar angles to those of a control surface, the air will have no chance to flow orderly along the leeward side. Instead, this side will only have separated, chaotic airflow, while the windward side will show a flow pattern very similar to the windward side of a control surface. The pressure in separated flow will not change with deflection angle, so this side will not contribute any lift effect. Note in the picture above that the pressure level over the whole chord is pushed up or down by the flap, because the flap is located in the aft portion of the airfoil. In contrast to that, spoilers are mounted mid-chord, where their influence over the pressure level is smaller. This reduces the lift effects of spoilers even more.
I think you question comes to the difference between aerodynamic body and blunt body. It is no so much linked to exposing one or two surfaces to the external flow, but more linked to the shape exposed to the external flow. An aerodynamic body has a shape which produces low drag, aerodynamic bodies have a very small size normal to the direction of flight. For example, the wing is really thin in the vertical direction, but huge is the direction the plane is expected to flight. A blunt body is the oppossite way around, exposes a big surface in front of the moving direction. The spoilers are a very good example. I can give you a practical example, you hand. When you are in your car (in movement) and you extend your hand outside the car, having the hand parallel to the ground, you don't notice significant "pressure" or "force" over your hand (please use some nice speed...) however is you set your palm looking to the direction the car is moving, the "pressure" over you hand is much bigger as you are exposing a bigger surface. Example the same phenomena with your hand is happening with ailerons, rudders and airbrake. We use an airbrake to stop the airplane, that is why we use like your palm in the car. Stop the airplane. Ailerons and rudders are intended to not stop the airplane, but control it. That's why the intention is to have low drag.
2,273,679
I am having a problem with a linked image. ``` <TR class="a"> <TD><A href="http://CA_NB_1_1-pr.jpg" rel="lightbox"><IMG src="CA_NB_1_1-th-pr.jpg"><BR><BR></A></TD> <TD class="hdsmlbr"><A href="http://127.0.0.1/odds/aptrqr2/view/1">35 Savoie Drive, Moncton, New Brunswick, Canada</A></TD> </TR> ``` This image has padding at the bottom of it that I cannot seem to find to kill. I have used CSS Reset from Yahoo to see if that helped, and even removed all CSS to see if I can locate the problem. Using Firebug, I tried a few on the fly methods of nullifying the padding, but nothing seems to work. Can anyone else figure out what the problem may be? <http://monkeylook.bendauphinee.com/>
2010/02/16
[ "https://Stackoverflow.com/questions/2273679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202184/" ]
It might be the two `<br>`'s...
You're trailing your image with two break-tags: `<BR><BR>`. Those would give the same impression. Sure enough, when removed the "extra padding" vanishes.