qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
646,425
I'm trying to configure a Debian Linux (ARMHF 3.8.13-bone20) on a BeagleBone Black to use German as the default language and keyboard layout, which does not work, and I can't see why. I'm talking about the console settings, not X or Gnome etc. Here are my settings and what I did so far: ``` dpkg-reconfigure locales ``` Here I chose `de_DE.UTF-8 UTF-8` and unselected `en_US.UTF-8 UTF-8`. Output from `locale`: ``` LANG=de_DE.UTF-8 LANGUAGE=de_DE.UTF-8 LC_CTYPE="de_DE.UTF-8" LC_NUMERIC="de_DE.UTF-8" LC_TIME="de_DE.UTF-8" LC_COLLATE="de_DE.UTF-8" LC_MONETARY="de_DE.UTF-8" LC_MESSAGES="de_DE.UTF-8" LC_PAPER="de_DE.UTF-8" LC_NAME="de_DE.UTF-8" LC_ADDRESS="de_DE.UTF-8" LC_TELEPHONE="de_DE.UTF-8" LC_MEASUREMENT="de_DE.UTF-8" LC_IDENTIFICATION="de_DE.UTF-8" LC_ALL= ``` Content of `/etc/default/locale`: ``` LANG=de_DE.UTF-8 LANGUAGE=de_DE.UTF-8 ``` Content of `/etc/default/keyboard`: ``` # KEYBOARD CONFIGURATION FILE # Consult the keyboard(5) manual page. XKBMODEL="pc105" XKBLAYOUT="de" XKBVARIANT="nodeadkeys" XKBOPTIONS="terminate:ctrl_alt_bksp" BACKSPACE="guess" ``` I ran `setupcon` after making these settings and it didn't change anything, the layout still was `en_US`. After that, I ran ``` dpkg-reconfigure keyboard-configuration ``` and set `German - no dead keys` as keyboard layout. Still no change, neither at once nor after a reboot. Next, I tried ``` dpkg-reconfigure console-data ``` Here I chose ``` Choose layout from entire list ``` and then ``` pc / quertz / German / Standard / latin1 - no dead keys ``` The output after that was: ``` Looking for keymap to install: de-latin1-nodeadkeys # ``` At this moment, the correct keyboard layout is present, but unfortunately things revert to the English (US) keyboard layout after reboot. What can I do to permanently change the keyboard layout? As far as I can see the correct keymap must be present as it can get loaded, but only until the next reboot. What am I missing here? Update: When connecting via SSH the German keymap gets loaded.
2013/09/17
[ "https://superuser.com/questions/646425", "https://superuser.com", "https://superuser.com/users/233574/" ]
You might try to add the boot parameters of `debian-installer/keymap=de` and `keymap=de`. Also, the answer at the thread [Keyboard layout HELP](http://www.turnkeylinux.org/forum/support/20130912/keyboard-layout-help) says : > > 1. Go to the webmin and do this SYSTEM -> SOFTWARE PACKADGES -> UPGRADE ALL > 2. (I don't recall if the order was this) Go to the console and do the following: > > > apt-get install console-data > > apt-get install console-setup > > apt-get install console-locales > > apt-get install keyboard-configuration > 3. Do the dpkg-reconfigure for each of the packets above. REBOOT. > > > So maybe your problem is that you haven't done all of them before rebooting.
To change the german keyboard in Kali Linux 2020.02 (Debian) do the following: 1. `dpkg-reconfigure locales` Choose `de_DE.UTF-8 UTF-8` and unselect `en_US.UTF-8 UTF-8` (by pressing `Space`) 2. `dpkg-reconfigure keyboard-configuration` Choose your keyboard hardware 3. For Kali Linux 2020.2 (Debian) goto GUI *Settings*/*Settings Editor* To Channel *Keyboard-layout* Under Line *XkbLayout String* change the value to `de` (delete `us`) This permanently changes the layout to the german keyboard.
646,425
I'm trying to configure a Debian Linux (ARMHF 3.8.13-bone20) on a BeagleBone Black to use German as the default language and keyboard layout, which does not work, and I can't see why. I'm talking about the console settings, not X or Gnome etc. Here are my settings and what I did so far: ``` dpkg-reconfigure locales ``` Here I chose `de_DE.UTF-8 UTF-8` and unselected `en_US.UTF-8 UTF-8`. Output from `locale`: ``` LANG=de_DE.UTF-8 LANGUAGE=de_DE.UTF-8 LC_CTYPE="de_DE.UTF-8" LC_NUMERIC="de_DE.UTF-8" LC_TIME="de_DE.UTF-8" LC_COLLATE="de_DE.UTF-8" LC_MONETARY="de_DE.UTF-8" LC_MESSAGES="de_DE.UTF-8" LC_PAPER="de_DE.UTF-8" LC_NAME="de_DE.UTF-8" LC_ADDRESS="de_DE.UTF-8" LC_TELEPHONE="de_DE.UTF-8" LC_MEASUREMENT="de_DE.UTF-8" LC_IDENTIFICATION="de_DE.UTF-8" LC_ALL= ``` Content of `/etc/default/locale`: ``` LANG=de_DE.UTF-8 LANGUAGE=de_DE.UTF-8 ``` Content of `/etc/default/keyboard`: ``` # KEYBOARD CONFIGURATION FILE # Consult the keyboard(5) manual page. XKBMODEL="pc105" XKBLAYOUT="de" XKBVARIANT="nodeadkeys" XKBOPTIONS="terminate:ctrl_alt_bksp" BACKSPACE="guess" ``` I ran `setupcon` after making these settings and it didn't change anything, the layout still was `en_US`. After that, I ran ``` dpkg-reconfigure keyboard-configuration ``` and set `German - no dead keys` as keyboard layout. Still no change, neither at once nor after a reboot. Next, I tried ``` dpkg-reconfigure console-data ``` Here I chose ``` Choose layout from entire list ``` and then ``` pc / quertz / German / Standard / latin1 - no dead keys ``` The output after that was: ``` Looking for keymap to install: de-latin1-nodeadkeys # ``` At this moment, the correct keyboard layout is present, but unfortunately things revert to the English (US) keyboard layout after reboot. What can I do to permanently change the keyboard layout? As far as I can see the correct keymap must be present as it can get loaded, but only until the next reboot. What am I missing here? Update: When connecting via SSH the German keymap gets loaded.
2013/09/17
[ "https://superuser.com/questions/646425", "https://superuser.com", "https://superuser.com/users/233574/" ]
The solution for me was to comment out all the locale relevant variables at `/etc/profile` ``` #export LANG="de_DE.utf8" #export LANGUAGE="de_DE.utf8" #export LC_ALL="de_DE.utf8" ``` (I wanted to get rid off the German :)) and then set my locale as I wish within `/etc/default/locale` The debian wiki page <https://wiki.debian.org/Locale> was the most helpfull document I found.
To change the german keyboard in Kali Linux 2020.02 (Debian) do the following: 1. `dpkg-reconfigure locales` Choose `de_DE.UTF-8 UTF-8` and unselect `en_US.UTF-8 UTF-8` (by pressing `Space`) 2. `dpkg-reconfigure keyboard-configuration` Choose your keyboard hardware 3. For Kali Linux 2020.2 (Debian) goto GUI *Settings*/*Settings Editor* To Channel *Keyboard-layout* Under Line *XkbLayout String* change the value to `de` (delete `us`) This permanently changes the layout to the german keyboard.
36,701,820
I'm using viewPager to create a layout with tabs and in each tab I use a Fragment. One of them is to get all de user contacts and put it on a ListView. But I want to call de AssyncTask only if the Fragment is displayed on screen. is there a method to do it? TY
2016/04/18
[ "https://Stackoverflow.com/questions/36701820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277507/" ]
Start your AsyncTask in onStart which is the method called once the fragment becomes visible to the user. onCreateView will be called even if the fragment doesn't become visible. See also: <http://developer.android.com/reference/android/app/Fragment.html#onStart()> I would however recommend to use a loader instead of AsyncTask (e.g. an AsyncTaskLoader <http://developer.android.com/reference/android/content/AsyncTaskLoader.html>).
You can check to see if it's visible with `.isVisible()` something like this ``` MyFragmentClass fragment = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("fragmentTAG"); if (fragment != null && fragment.isVisible()) { // call AsyncTask } ```
36,701,820
I'm using viewPager to create a layout with tabs and in each tab I use a Fragment. One of them is to get all de user contacts and put it on a ListView. But I want to call de AssyncTask only if the Fragment is displayed on screen. is there a method to do it? TY
2016/04/18
[ "https://Stackoverflow.com/questions/36701820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277507/" ]
you can use ``` @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if(isVisibleToUser) { //things to do when fragment is visible } } ``` Even it is called before onCreateView.
You can check to see if it's visible with `.isVisible()` something like this ``` MyFragmentClass fragment = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("fragmentTAG"); if (fragment != null && fragment.isVisible()) { // call AsyncTask } ```
68,703,810
I want to get only filtered tweet but i got this error. How can i solve it? What is the meaning of this error? ``` tweets = api.user_timeline(screen_name = "elonmusk", count = 200000, lang = "en", tweet_mode = "extended") word="Dogecoin" for tweet in tweets: if word in tweet: df = pd.DataFrame([tweet.full_text], columns = ["tweet"]) ``` TypeError: argument of type 'Status' is not iterable
2021/08/08
[ "https://Stackoverflow.com/questions/68703810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16524573/" ]
I recommend you to save the information in a context. then you can retrieve the data on whatever intent that is in the same context.
To add on to the answer of @MizarConstanti, you can use the following for your entities: * For date you can use entity `@sys.date` * For first name `@sys.given-name` * For last name `@sys.last-name` NOTE: For given name and last name entities, these entities could only recognize the common names ([reference](https://cloud.google.com/dialogflow/es/docs/reference/system-entities)). An alternative for getting dates and names is you can create training phrases in this manner and extract the information using the defined entities. **Intent-> test intent** [![enter image description here](https://i.stack.imgur.com/sfJHR.png)](https://i.stack.imgur.com/sfJHR.png) [![enter image description here](https://i.stack.imgur.com/eg3tW.png)](https://i.stack.imgur.com/eg3tW.png) **Intent -> getName** [![enter image description here](https://i.stack.imgur.com/tl1X8.png)](https://i.stack.imgur.com/tl1X8.png) [![enter image description here](https://i.stack.imgur.com/4aALf.png)](https://i.stack.imgur.com/4aALf.png) If you are using library `dialogflow-fulfillment` in Dialogflow inline editor these entities could be called using this code: ``` 'use strict'; const functions = require('firebase-functions'); const {WebhookClient} = require('dialogflow-fulfillment'); const {Card, Suggestion} = require('dialogflow-fulfillment'); const axios = require('axios'); process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => { const agent = new WebhookClient({ request, response }); function yourFunctionHandler(agent) { // initial value of agent.parameters.date is 1994-07-29T12:00:00+08:00 // thus the splitting done below const date = agent.parameters.date.split('T')[0]; const year = agent.parameters.date.split('-')[0]; const month = agent.parameters.date.split('-')[1]; const day = agent.parameters.date.split('-')[2].split('T')[0]; agent.add(`year: ${year}, month:${month}, day:${day}`); } function getName(agent) { const lastName = agent.parameters.lastName; const firstName= agent.parameters.givenName; agent.add(`first: ${firstName}, last: ${lastName}`); } // Run the proper function handler based on the matched Dialogflow intent name let intentMap = new Map(); intentMap.set('test intent', yourFunctionHandler); intentMap.set('getName', getName); agent.handleRequest(intentMap); }); ``` Test for date and name intent: [![enter image description here](https://i.stack.imgur.com/Ew0P0.png)](https://i.stack.imgur.com/Ew0P0.png)
68,703,810
I want to get only filtered tweet but i got this error. How can i solve it? What is the meaning of this error? ``` tweets = api.user_timeline(screen_name = "elonmusk", count = 200000, lang = "en", tweet_mode = "extended") word="Dogecoin" for tweet in tweets: if word in tweet: df = pd.DataFrame([tweet.full_text], columns = ["tweet"]) ``` TypeError: argument of type 'Status' is not iterable
2021/08/08
[ "https://Stackoverflow.com/questions/68703810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16524573/" ]
I recommend you to save the information in a context. then you can retrieve the data on whatever intent that is in the same context.
First I recommend you to get the variable from the Dialogflow without backend, then read it from the diagnostic info, if the information is watched you can get from the backend response.
68,703,810
I want to get only filtered tweet but i got this error. How can i solve it? What is the meaning of this error? ``` tweets = api.user_timeline(screen_name = "elonmusk", count = 200000, lang = "en", tweet_mode = "extended") word="Dogecoin" for tweet in tweets: if word in tweet: df = pd.DataFrame([tweet.full_text], columns = ["tweet"]) ``` TypeError: argument of type 'Status' is not iterable
2021/08/08
[ "https://Stackoverflow.com/questions/68703810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16524573/" ]
To add on to the answer of @MizarConstanti, you can use the following for your entities: * For date you can use entity `@sys.date` * For first name `@sys.given-name` * For last name `@sys.last-name` NOTE: For given name and last name entities, these entities could only recognize the common names ([reference](https://cloud.google.com/dialogflow/es/docs/reference/system-entities)). An alternative for getting dates and names is you can create training phrases in this manner and extract the information using the defined entities. **Intent-> test intent** [![enter image description here](https://i.stack.imgur.com/sfJHR.png)](https://i.stack.imgur.com/sfJHR.png) [![enter image description here](https://i.stack.imgur.com/eg3tW.png)](https://i.stack.imgur.com/eg3tW.png) **Intent -> getName** [![enter image description here](https://i.stack.imgur.com/tl1X8.png)](https://i.stack.imgur.com/tl1X8.png) [![enter image description here](https://i.stack.imgur.com/4aALf.png)](https://i.stack.imgur.com/4aALf.png) If you are using library `dialogflow-fulfillment` in Dialogflow inline editor these entities could be called using this code: ``` 'use strict'; const functions = require('firebase-functions'); const {WebhookClient} = require('dialogflow-fulfillment'); const {Card, Suggestion} = require('dialogflow-fulfillment'); const axios = require('axios'); process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => { const agent = new WebhookClient({ request, response }); function yourFunctionHandler(agent) { // initial value of agent.parameters.date is 1994-07-29T12:00:00+08:00 // thus the splitting done below const date = agent.parameters.date.split('T')[0]; const year = agent.parameters.date.split('-')[0]; const month = agent.parameters.date.split('-')[1]; const day = agent.parameters.date.split('-')[2].split('T')[0]; agent.add(`year: ${year}, month:${month}, day:${day}`); } function getName(agent) { const lastName = agent.parameters.lastName; const firstName= agent.parameters.givenName; agent.add(`first: ${firstName}, last: ${lastName}`); } // Run the proper function handler based on the matched Dialogflow intent name let intentMap = new Map(); intentMap.set('test intent', yourFunctionHandler); intentMap.set('getName', getName); agent.handleRequest(intentMap); }); ``` Test for date and name intent: [![enter image description here](https://i.stack.imgur.com/Ew0P0.png)](https://i.stack.imgur.com/Ew0P0.png)
First I recommend you to get the variable from the Dialogflow without backend, then read it from the diagnostic info, if the information is watched you can get from the backend response.
26,576
I've read all the books and have seen all the movies (at least 3 times), but I've been wondering: **Is there ever a time when Harry wears contacts instead of glasses?** My memory is pretty good, but it's not *that* good ;) I'm so used to seeing him in glasses that I've never really thought about alternatives.
2012/11/06
[ "https://scifi.stackexchange.com/questions/26576", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/10667/" ]
There is nothing in the books to suggest Harry wore contact lenses at any point during the series. However, in both the movie and the book *Harry Potter and the Deathly Hallows* (part 2 in terms of the movies), during the *King's Cross* scene (where Harry is "killed" by Voldemort) he becomes conscious of *not* wearing or needing glasses while in that state of stasis. > > He sat up. His body appeared unscathed. He touched his face. He was not wearing glasses any more. > > > *Deathly Hallows* - page 565 - Bloomsbury - chapter 35, *King's Cross* > > > ![*Harry Potter and the Deathly Hallows - Part 2* Harry without glasses.](https://i.stack.imgur.com/BNEJc.jpg) *Harry Potter and the Deathly Hallows - Part 2* - Warner Bros. Moving on, I don't think J.K. Rowling would have wanted Harry to wear contact lenses; the fact that her hero wore glasses had personal significance to J.K. Rowling: > > **Eun Ji An for Raincoast.com, Canada:** I was wondering why Harry had glasses? > > > **J.K. Rowling:** Because I had glasses all through my childhood and I was sick and tired of the person in the books who wore the glasses was always the brainy one and it really irritated me and I wanted to read about a hero wearing glasses. **It also has a symbolic function, Harry is the eyes on to the books in the sense that it is always Harry's point of view, so there was also that, you know, facet of him wearing glasses.** > > > [**CBBC Newsround -- Interview with J.K. Rowling**](http://news.bbc.co.uk/cbbcnews/hi/newsid_4690000/newsid_4690800/4690885.stm) -- 07.18.05 > > > As late in the series as *Deathly Hallows*, Harry is still wearing glasses, as evidenced in the chapter *The Seven Potters*: > > ‘Harry, your eyesight really is awful,’ said Hermione, as she put on glasses. > > > *Deathly Hallows* - page 49 - Bloomsbury - chapter 4, *The Seven Potters* > > > As well, in the wizarding world, some physical ailments seem to be unable to be fixed by magic. One could make a case for utilizing Muggle treatments (which contact lenses would be), as Arthur Weasley accepted Muggle stitches for Nagini's bite when the wizarding treatments the St. Mungo's staff was giving him didn't work as well as they should have. Molly Weasley had a fit over this; however, Harry himself was raised in the Muggle world and might have been more amenable to contact lenses than purebloods or half-bloods who grew up in the wizarding world. This is just one point of view to consider. To reiterate, there is no *canon* evidence that Harry Potter ever wore contact lenses or had Lasik surgery or fixed his eyesight magically or anything like that.
**Harry is never mentioned as wearing contacts**, including where he would be the most likely to do so (playing Quidditch). To the contrary, the book stresses that he wore regular glasses, since Hermione needed to magick his eyeglasses to be rainproof when playing in the rain.. The "never" comes from my search of all the relevant sources: * "electronically searched softcopy text of all 7 books and didn't find a single instance of 'contact' or 'contacts' associated with eyewear" * Googling for "Harry Potter" + contacts/"contact lenses" * Search of accio quotes for JKR tidbits (same search strings).
42,538,411
I have a dataframe that looks like this (this is a sample of a larger dataframe): ``` dvmph variable value 1 1 X0 100.0 2 3 X0 2486.6 3 5 X0 100519.3 4 7 X0 471515.0 5 1 X1 973180.2 6 3 X1 758789.6 7 5 X1 500884.34 8 7 X1 441252.43 9 9 X1 228094.07 10 1 X2 358144.00 11 3 X2 173614.35 12 5 X2 73395.79 13 7 X2 79245.32 14 9 X2 59789.64 15 1 X3 35539.05 16 3 X3 23196.88 17 5 X3 15686.76 18 7 X3 10589.20 19 9 X3 11124.05 20 1 X4 5221.25 21 3 X4 5630.40 22 5 X4 4045.34 23 7 X4 13108.06 24 9 X4 302.23 ``` I want to get a stacked bar chart something like this (the axes will be different, since the above data is just a sample): [![enter image description here](https://i.stack.imgur.com/2pGpE.png)](https://i.stack.imgur.com/2pGpE.png) Here is my current code: ``` ggplot(data, aes(variable, dvmph, fill=value)) + geom_bar(stat='identity', position='stack') ``` I don't care about the color difference, but the y-axis is very distorted, and I'm not sure what I'm doing wrong: [![enter image description here](https://i.stack.imgur.com/5j5Zw.png)](https://i.stack.imgur.com/5j5Zw.png) The end goal for this data is to plot all the bars on a polar axis, with dvmph as r and variable as theta (apologies for the terrible drawing, I hope this makes sense): ![](https://imgur.com/zyww3rn.png) My two questions are: 1. Why is my y-axis so distorted? 2. Is there an easy way to plot these bars on a polar plot?
2017/03/01
[ "https://Stackoverflow.com/questions/42538411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5199451/" ]
From you drawing, I believe you are passing the wrong values to `aes()` -- that is, for your stacked bar example, I believe you want this: ``` ggplot(df, aes(x = variable, y = value, fill = factor(dvmph))) + geom_col() ``` [![Plot](https://i.stack.imgur.com/lz6o9.png)](https://i.stack.imgur.com/lz6o9.png) Then you can add `coord_polar()` to obtain the following: ``` ggplot(df, aes(x = variable, y = value, fill = factor(dvmph))) + geom_col() + coord_polar() ``` [![Plot Polar](https://i.stack.imgur.com/cOwiA.png)](https://i.stack.imgur.com/cOwiA.png) If you dislike the scientific notation, you could always add: `+ scale_y_continuous(labels = scales::comma_format())`
You have two predictor variables, `variable` and `dvmph`, and one response variable `value` which is a frequency. So, your approach to plot both predictor variables in an x-y-plot, or as polar plot with angle and radius, resp., and show the response variable color-coded is sensible. Unfortunately, you have chosen the wrong geometry. Please, try `geom_tile()` instead of `geom_bar()`: ``` library(ggplot2) ggplot(DT, aes(variable, factor(dvmph), fill=value)) + geom_tile() ``` [![enter image description here](https://i.stack.imgur.com/1yNfx.png)](https://i.stack.imgur.com/1yNfx.png) or in polar coordinates: ``` ggplot(DT, aes(variable, factor(dvmph), fill=value)) + geom_tile() + coord_polar() + theme_linedraw() ``` [![enter image description here](https://i.stack.imgur.com/vggv2.png)](https://i.stack.imgur.com/vggv2.png)
66,944,844
### CODE Here's the code for a function which is triggered when a person clicks on "Add to Cart" button. It creates a row inside the cart using the data from localStorage about the items selected by the user from the menu. ``` function addItemToCart() { var cartRow = document.createElement("div"); cartRow.classList.add("cart-row"); var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> var cartItemNames = cartItems.getElementsByClassName("cart-item-title"); //Putting the data var locStore = JSON.parse(localStorage.getItem("selectedProduct")); var cartRowContents = locStore.map((item) => { return ` <div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1"> <button class="btn btn-danger" type="button">REMOVE</button> </div>`; }); cartRowContents = cartRowContents.join(""); cartRow.innerHTML = cartRowContents; cartItems.append(cartRow); cartRow .getElementsByClassName("btn-danger")[0] .addEventListener("click", removeCartItem); cartRow .getElementsByClassName("cart-quantity-input")[0] .addEventListener("change", quantityChanged); } ``` ### ISSUE Whenever the user clicks on "Add TO cart", the item is stored in localStorage. Now, let's say I have one item in my localStorage something like this:- ``` [{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}] ``` Using the above data, I create a row in my Cart. Till here, it works completely fine. Now, I add another item in my localStorage and now the localStorage looks something like this:- ``` [{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}, {"productID":"2","image":"http://127.0.0.1:5500/Images/pizza.png","price":350,"title":"Veggie Supreme","sizePrice":"100","quantity":1}]" ``` Now, `addItemToCart()` is triggered again as we have selected another item. This time, it will show two items in a single row because it is also considering the first item in localStorage which actually has already been considered. What should I do to avoid this problem? ### OUTPUT - UI (CART) [![Cart looks like this on UI. You can see that Tandoori Paneer is coming twice in the cart.](https://i.stack.imgur.com/rIRaY.png)](https://i.stack.imgur.com/rIRaY.png)
2021/04/04
[ "https://Stackoverflow.com/questions/66944844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11973720/" ]
Something like this should do (note that I can't test it without the whole context): ``` function addItemToCart(item) { var cartRow = document.createElement("div"); cartRow.classList.add("cart-row"); var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> var cartItemNames = cartItems.getElementsByClassName("cart-item-title"); //Putting the data var cartRowContents = ` <div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1"> <button class="btn btn-danger" type="button">REMOVE</button> </div>`; cartRowContents = cartRowContents.join(""); cartRow.innerHTML = cartRowContents; cartItems.append(cartRow); cartRow .getElementsByClassName("btn-danger")[0] .addEventListener("click", removeCartItem); cartRow .getElementsByClassName("cart-quantity-input")[0] .addEventListener("change", quantityChanged); } /** * Render all the items in cart, * call this instead of addItemToCart after an item was added to local storage. **/ function renderItemsInCart() { var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> carItems.innerHTML = ""; var locStore = JSON.parse(localStorage.getItem("selectedProduct")); var cartRowContents = locStore.map((item) => addItemToCart(item)); } ```
Why not access the last element of `locStore` since that would be the latest one right ? Currently you're calling `.map` on the whole **localStorage** items but I am assuming that `addItemToCart` is only called after your `localStorage` is updated with a recent item and you just want the **DOM** to reflect that latest change. I think the below should work :- ``` var item = locStore[locStore.length-1]; var cartRowContents = `<div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1"> <button class="btn btn-danger" type="button">REMOVE</button> </div>`; ```
66,944,844
### CODE Here's the code for a function which is triggered when a person clicks on "Add to Cart" button. It creates a row inside the cart using the data from localStorage about the items selected by the user from the menu. ``` function addItemToCart() { var cartRow = document.createElement("div"); cartRow.classList.add("cart-row"); var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> var cartItemNames = cartItems.getElementsByClassName("cart-item-title"); //Putting the data var locStore = JSON.parse(localStorage.getItem("selectedProduct")); var cartRowContents = locStore.map((item) => { return ` <div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1"> <button class="btn btn-danger" type="button">REMOVE</button> </div>`; }); cartRowContents = cartRowContents.join(""); cartRow.innerHTML = cartRowContents; cartItems.append(cartRow); cartRow .getElementsByClassName("btn-danger")[0] .addEventListener("click", removeCartItem); cartRow .getElementsByClassName("cart-quantity-input")[0] .addEventListener("change", quantityChanged); } ``` ### ISSUE Whenever the user clicks on "Add TO cart", the item is stored in localStorage. Now, let's say I have one item in my localStorage something like this:- ``` [{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}] ``` Using the above data, I create a row in my Cart. Till here, it works completely fine. Now, I add another item in my localStorage and now the localStorage looks something like this:- ``` [{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}, {"productID":"2","image":"http://127.0.0.1:5500/Images/pizza.png","price":350,"title":"Veggie Supreme","sizePrice":"100","quantity":1}]" ``` Now, `addItemToCart()` is triggered again as we have selected another item. This time, it will show two items in a single row because it is also considering the first item in localStorage which actually has already been considered. What should I do to avoid this problem? ### OUTPUT - UI (CART) [![Cart looks like this on UI. You can see that Tandoori Paneer is coming twice in the cart.](https://i.stack.imgur.com/rIRaY.png)](https://i.stack.imgur.com/rIRaY.png)
2021/04/04
[ "https://Stackoverflow.com/questions/66944844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11973720/" ]
Something like this should do (note that I can't test it without the whole context): ``` function addItemToCart(item) { var cartRow = document.createElement("div"); cartRow.classList.add("cart-row"); var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> var cartItemNames = cartItems.getElementsByClassName("cart-item-title"); //Putting the data var cartRowContents = ` <div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1"> <button class="btn btn-danger" type="button">REMOVE</button> </div>`; cartRowContents = cartRowContents.join(""); cartRow.innerHTML = cartRowContents; cartItems.append(cartRow); cartRow .getElementsByClassName("btn-danger")[0] .addEventListener("click", removeCartItem); cartRow .getElementsByClassName("cart-quantity-input")[0] .addEventListener("change", quantityChanged); } /** * Render all the items in cart, * call this instead of addItemToCart after an item was added to local storage. **/ function renderItemsInCart() { var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> carItems.innerHTML = ""; var locStore = JSON.parse(localStorage.getItem("selectedProduct")); var cartRowContents = locStore.map((item) => addItemToCart(item)); } ```
You can just empty the whole Cart in the begging of the function, and then let the function populate everything from LocalStorage.
66,944,844
### CODE Here's the code for a function which is triggered when a person clicks on "Add to Cart" button. It creates a row inside the cart using the data from localStorage about the items selected by the user from the menu. ``` function addItemToCart() { var cartRow = document.createElement("div"); cartRow.classList.add("cart-row"); var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> var cartItemNames = cartItems.getElementsByClassName("cart-item-title"); //Putting the data var locStore = JSON.parse(localStorage.getItem("selectedProduct")); var cartRowContents = locStore.map((item) => { return ` <div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1"> <button class="btn btn-danger" type="button">REMOVE</button> </div>`; }); cartRowContents = cartRowContents.join(""); cartRow.innerHTML = cartRowContents; cartItems.append(cartRow); cartRow .getElementsByClassName("btn-danger")[0] .addEventListener("click", removeCartItem); cartRow .getElementsByClassName("cart-quantity-input")[0] .addEventListener("change", quantityChanged); } ``` ### ISSUE Whenever the user clicks on "Add TO cart", the item is stored in localStorage. Now, let's say I have one item in my localStorage something like this:- ``` [{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}] ``` Using the above data, I create a row in my Cart. Till here, it works completely fine. Now, I add another item in my localStorage and now the localStorage looks something like this:- ``` [{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}, {"productID":"2","image":"http://127.0.0.1:5500/Images/pizza.png","price":350,"title":"Veggie Supreme","sizePrice":"100","quantity":1}]" ``` Now, `addItemToCart()` is triggered again as we have selected another item. This time, it will show two items in a single row because it is also considering the first item in localStorage which actually has already been considered. What should I do to avoid this problem? ### OUTPUT - UI (CART) [![Cart looks like this on UI. You can see that Tandoori Paneer is coming twice in the cart.](https://i.stack.imgur.com/rIRaY.png)](https://i.stack.imgur.com/rIRaY.png)
2021/04/04
[ "https://Stackoverflow.com/questions/66944844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11973720/" ]
Something like this should do (note that I can't test it without the whole context): ``` function addItemToCart(item) { var cartRow = document.createElement("div"); cartRow.classList.add("cart-row"); var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> var cartItemNames = cartItems.getElementsByClassName("cart-item-title"); //Putting the data var cartRowContents = ` <div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1"> <button class="btn btn-danger" type="button">REMOVE</button> </div>`; cartRowContents = cartRowContents.join(""); cartRow.innerHTML = cartRowContents; cartItems.append(cartRow); cartRow .getElementsByClassName("btn-danger")[0] .addEventListener("click", removeCartItem); cartRow .getElementsByClassName("cart-quantity-input")[0] .addEventListener("change", quantityChanged); } /** * Render all the items in cart, * call this instead of addItemToCart after an item was added to local storage. **/ function renderItemsInCart() { var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> carItems.innerHTML = ""; var locStore = JSON.parse(localStorage.getItem("selectedProduct")); var cartRowContents = locStore.map((item) => addItemToCart(item)); } ```
I know an answer has been accepted but, assuming your item has an ID you can make use of that to make each cart row unique(for updating quantity and deleting cart item). **PS:** I didn't test this. It's just to optimize and fix your UI issue ``` //add cart item row function addItemToCart () { document.getElementsByClassName("cart-items")[0].insertAdjacentHTML( 'beforeend', `<div class="cart-row" id="cartid-${item.id}"> <div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1" id="quantityid-${item.id} onchange="quantityChanged"> <button class="btn btn-danger" type="button" onclick="removeCartItem(this)">REMOVE</button> </div> </div>` ) } //remove the cart item row function removeCartItem (input) { input.parentNode.remove() } /** * Render all the items in cart, * call this instead of addItemToCart after an item was added to local storage. **/ function renderItemsInCart() { var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> carItems.innerHTML = ""; var locStore = JSON.parse(localStorage.getItem("selectedProduct")); var cartRowContents = locStore.map((item) => addItemToCart(item)); } ```
66,944,844
### CODE Here's the code for a function which is triggered when a person clicks on "Add to Cart" button. It creates a row inside the cart using the data from localStorage about the items selected by the user from the menu. ``` function addItemToCart() { var cartRow = document.createElement("div"); cartRow.classList.add("cart-row"); var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> var cartItemNames = cartItems.getElementsByClassName("cart-item-title"); //Putting the data var locStore = JSON.parse(localStorage.getItem("selectedProduct")); var cartRowContents = locStore.map((item) => { return ` <div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1"> <button class="btn btn-danger" type="button">REMOVE</button> </div>`; }); cartRowContents = cartRowContents.join(""); cartRow.innerHTML = cartRowContents; cartItems.append(cartRow); cartRow .getElementsByClassName("btn-danger")[0] .addEventListener("click", removeCartItem); cartRow .getElementsByClassName("cart-quantity-input")[0] .addEventListener("change", quantityChanged); } ``` ### ISSUE Whenever the user clicks on "Add TO cart", the item is stored in localStorage. Now, let's say I have one item in my localStorage something like this:- ``` [{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}] ``` Using the above data, I create a row in my Cart. Till here, it works completely fine. Now, I add another item in my localStorage and now the localStorage looks something like this:- ``` [{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}, {"productID":"2","image":"http://127.0.0.1:5500/Images/pizza.png","price":350,"title":"Veggie Supreme","sizePrice":"100","quantity":1}]" ``` Now, `addItemToCart()` is triggered again as we have selected another item. This time, it will show two items in a single row because it is also considering the first item in localStorage which actually has already been considered. What should I do to avoid this problem? ### OUTPUT - UI (CART) [![Cart looks like this on UI. You can see that Tandoori Paneer is coming twice in the cart.](https://i.stack.imgur.com/rIRaY.png)](https://i.stack.imgur.com/rIRaY.png)
2021/04/04
[ "https://Stackoverflow.com/questions/66944844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11973720/" ]
I know an answer has been accepted but, assuming your item has an ID you can make use of that to make each cart row unique(for updating quantity and deleting cart item). **PS:** I didn't test this. It's just to optimize and fix your UI issue ``` //add cart item row function addItemToCart () { document.getElementsByClassName("cart-items")[0].insertAdjacentHTML( 'beforeend', `<div class="cart-row" id="cartid-${item.id}"> <div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1" id="quantityid-${item.id} onchange="quantityChanged"> <button class="btn btn-danger" type="button" onclick="removeCartItem(this)">REMOVE</button> </div> </div>` ) } //remove the cart item row function removeCartItem (input) { input.parentNode.remove() } /** * Render all the items in cart, * call this instead of addItemToCart after an item was added to local storage. **/ function renderItemsInCart() { var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> carItems.innerHTML = ""; var locStore = JSON.parse(localStorage.getItem("selectedProduct")); var cartRowContents = locStore.map((item) => addItemToCart(item)); } ```
Why not access the last element of `locStore` since that would be the latest one right ? Currently you're calling `.map` on the whole **localStorage** items but I am assuming that `addItemToCart` is only called after your `localStorage` is updated with a recent item and you just want the **DOM** to reflect that latest change. I think the below should work :- ``` var item = locStore[locStore.length-1]; var cartRowContents = `<div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1"> <button class="btn btn-danger" type="button">REMOVE</button> </div>`; ```
66,944,844
### CODE Here's the code for a function which is triggered when a person clicks on "Add to Cart" button. It creates a row inside the cart using the data from localStorage about the items selected by the user from the menu. ``` function addItemToCart() { var cartRow = document.createElement("div"); cartRow.classList.add("cart-row"); var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> var cartItemNames = cartItems.getElementsByClassName("cart-item-title"); //Putting the data var locStore = JSON.parse(localStorage.getItem("selectedProduct")); var cartRowContents = locStore.map((item) => { return ` <div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1"> <button class="btn btn-danger" type="button">REMOVE</button> </div>`; }); cartRowContents = cartRowContents.join(""); cartRow.innerHTML = cartRowContents; cartItems.append(cartRow); cartRow .getElementsByClassName("btn-danger")[0] .addEventListener("click", removeCartItem); cartRow .getElementsByClassName("cart-quantity-input")[0] .addEventListener("change", quantityChanged); } ``` ### ISSUE Whenever the user clicks on "Add TO cart", the item is stored in localStorage. Now, let's say I have one item in my localStorage something like this:- ``` [{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}] ``` Using the above data, I create a row in my Cart. Till here, it works completely fine. Now, I add another item in my localStorage and now the localStorage looks something like this:- ``` [{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}, {"productID":"2","image":"http://127.0.0.1:5500/Images/pizza.png","price":350,"title":"Veggie Supreme","sizePrice":"100","quantity":1}]" ``` Now, `addItemToCart()` is triggered again as we have selected another item. This time, it will show two items in a single row because it is also considering the first item in localStorage which actually has already been considered. What should I do to avoid this problem? ### OUTPUT - UI (CART) [![Cart looks like this on UI. You can see that Tandoori Paneer is coming twice in the cart.](https://i.stack.imgur.com/rIRaY.png)](https://i.stack.imgur.com/rIRaY.png)
2021/04/04
[ "https://Stackoverflow.com/questions/66944844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11973720/" ]
I know an answer has been accepted but, assuming your item has an ID you can make use of that to make each cart row unique(for updating quantity and deleting cart item). **PS:** I didn't test this. It's just to optimize and fix your UI issue ``` //add cart item row function addItemToCart () { document.getElementsByClassName("cart-items")[0].insertAdjacentHTML( 'beforeend', `<div class="cart-row" id="cartid-${item.id}"> <div class="cart-item cart-column"> <img class="cart-item-image" src="${item.image}" width="100" height="100"> <span class="cart-item-title">${item.title}</span> <span class="cart-item-size">"Rs.${item.sizePrice}"</span> </div> <span class="cart-price cart-column">${item.price}</span> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1" id="quantityid-${item.id} onchange="quantityChanged"> <button class="btn btn-danger" type="button" onclick="removeCartItem(this)">REMOVE</button> </div> </div>` ) } //remove the cart item row function removeCartItem (input) { input.parentNode.remove() } /** * Render all the items in cart, * call this instead of addItemToCart after an item was added to local storage. **/ function renderItemsInCart() { var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items"> carItems.innerHTML = ""; var locStore = JSON.parse(localStorage.getItem("selectedProduct")); var cartRowContents = locStore.map((item) => addItemToCart(item)); } ```
You can just empty the whole Cart in the begging of the function, and then let the function populate everything from LocalStorage.
14,099,596
I have a ListView that its ItemsPanelTemplate is a Canvas, and every item is a rectangle. I'm trying to draw a Rectangle outside the Canvas in the position of (-50,-50) with no successive. can I do that somehow ? ![enter image description here](https://i.stack.imgur.com/rJ4Ns.png) The XAML: ``` <Grid > <ListView BorderThickness="0" BorderBrush="Transparent" ItemsSource="{Binding Rectangles}" Height="200" Width="200"> <ListView.Resources> <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Canvas.Left" Value="{Binding Left, Mode=TwoWay}" /> <Setter Property="Canvas.Top" Value="{Binding Top, Mode=TwoWay}" /> </Style> </ListView.Resources> <ListView.ItemTemplate> <DataTemplate DataType="{x:Type WpfApplication2:RectangleModel}"> <Rectangle Width="30" Height="30" Canvas.Left="{Binding Left}" Canvas.Right="{Binding Right}" Fill="LightCoral" ClipToBounds="False"/> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemsPanel> <ItemsPanelTemplate> <Canvas Background="LightBlue"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView> </Grid> ``` Code behind: ``` public partial class MainWindow : Window { public List<RectangleModel> Rectangles { get; set; } public MainWindow() { Rectangles = new List<RectangleModel>(); Rectangles.Add(new RectangleModel { Left = -50, Top = -50 }); Rectangles.Add(new RectangleModel { Left = 0, Top = 0 }); Rectangles.Add(new RectangleModel { Left = 50, Top = 50 }); DataContext = this; InitializeComponent(); } } ```
2012/12/31
[ "https://Stackoverflow.com/questions/14099596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138627/" ]
I may be wrong, but this seems to be rather simple problem (I may have completely assumed the wrong thing, but I'm not sure so I'm going with the assumption just in case). You've defined your `ListView` to be 200 by 200 and your `Canvas` is taking all that space. Judging by your picture, I feel it is `Canvas` that you want to be of 200 by 200 not the `ListView`. **Xaml:** ``` <Grid > <ListView BorderThickness="0" BorderBrush="Transparent" ItemsSource="{Binding Rectangles}"> <ListView.Resources> <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Canvas.Left" Value="{Binding Left, Mode=TwoWay}" /> <Setter Property="Canvas.Top" Value="{Binding Top, Mode=TwoWay}" /> </Style> </ListView.Resources> <ListView.ItemTemplate> <DataTemplate DataType="{x:Type wpfApplication1:RectangleModel}"> <Rectangle Width="30" Height="10" Canvas.Left="{Binding Left}" Canvas.Top="{Binding Top}" Fill="LightCoral" ClipToBounds="False"/> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemsPanel> <ItemsPanelTemplate> <Canvas Background="LightBlue" ClipToBounds="False" Height="200" Width="200"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView> </Grid> ``` **Result:** ![enter image description here](https://i.stack.imgur.com/dLaiS.png)
Try this style (I removed the scrollviewer from the default tamplate): I agree with the comments saying a control that draws like this is doubtful. ``` <Window x:Class="CanvasListView.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:CanvasListView="clr-namespace:CanvasListView" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" d:DataContext="{d:DesignInstance Type=CanvasListView:MainWindow,IsDesignTimeCreatable=True}" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <SolidColorBrush x:Key="ListBorder" Color="#828790"/> <Style TargetType="{x:Type ListView}"> <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/> <Setter Property="BorderBrush" Value="{StaticResource ListBorder}"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.CanContentScroll" Value="true"/> <Setter Property="ScrollViewer.PanningMode" Value="Both"/> <Setter Property="Stylus.IsFlicksEnabled" Value="False"/> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListView}"> <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="true"> <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/> </Trigger> <Trigger Property="IsGrouping" Value="true"> <Setter Property="ScrollViewer.CanContentScroll" Value="false"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid> <ListView BorderThickness="0" BorderBrush="Transparent" ItemsSource="{Binding Rectangles}" Height="200" Width="200"> <ListView.Resources> <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Canvas.Left" Value="{Binding Left, Mode=TwoWay}" /> <Setter Property="Canvas.Top" Value="{Binding Top, Mode=TwoWay}" /> </Style> </ListView.Resources> <ListView.ItemTemplate> <DataTemplate DataType="{x:Type CanvasListView:RectangleModel}"> <Rectangle Width="30" Height="30" Fill="{Binding Color}"/> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemsPanel> <ItemsPanelTemplate> <Canvas Background="LightBlue"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView> </Grid> </Window> ``` I added a color property in the viewmodel: ``` public string Color { get; set; } ```
14,099,596
I have a ListView that its ItemsPanelTemplate is a Canvas, and every item is a rectangle. I'm trying to draw a Rectangle outside the Canvas in the position of (-50,-50) with no successive. can I do that somehow ? ![enter image description here](https://i.stack.imgur.com/rJ4Ns.png) The XAML: ``` <Grid > <ListView BorderThickness="0" BorderBrush="Transparent" ItemsSource="{Binding Rectangles}" Height="200" Width="200"> <ListView.Resources> <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Canvas.Left" Value="{Binding Left, Mode=TwoWay}" /> <Setter Property="Canvas.Top" Value="{Binding Top, Mode=TwoWay}" /> </Style> </ListView.Resources> <ListView.ItemTemplate> <DataTemplate DataType="{x:Type WpfApplication2:RectangleModel}"> <Rectangle Width="30" Height="30" Canvas.Left="{Binding Left}" Canvas.Right="{Binding Right}" Fill="LightCoral" ClipToBounds="False"/> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemsPanel> <ItemsPanelTemplate> <Canvas Background="LightBlue"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView> </Grid> ``` Code behind: ``` public partial class MainWindow : Window { public List<RectangleModel> Rectangles { get; set; } public MainWindow() { Rectangles = new List<RectangleModel>(); Rectangles.Add(new RectangleModel { Left = -50, Top = -50 }); Rectangles.Add(new RectangleModel { Left = 0, Top = 0 }); Rectangles.Add(new RectangleModel { Left = 50, Top = 50 }); DataContext = this; InitializeComponent(); } } ```
2012/12/31
[ "https://Stackoverflow.com/questions/14099596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138627/" ]
Try this style (I removed the scrollviewer from the default tamplate): I agree with the comments saying a control that draws like this is doubtful. ``` <Window x:Class="CanvasListView.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:CanvasListView="clr-namespace:CanvasListView" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" d:DataContext="{d:DesignInstance Type=CanvasListView:MainWindow,IsDesignTimeCreatable=True}" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <SolidColorBrush x:Key="ListBorder" Color="#828790"/> <Style TargetType="{x:Type ListView}"> <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/> <Setter Property="BorderBrush" Value="{StaticResource ListBorder}"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.CanContentScroll" Value="true"/> <Setter Property="ScrollViewer.PanningMode" Value="Both"/> <Setter Property="Stylus.IsFlicksEnabled" Value="False"/> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListView}"> <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="true"> <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/> </Trigger> <Trigger Property="IsGrouping" Value="true"> <Setter Property="ScrollViewer.CanContentScroll" Value="false"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid> <ListView BorderThickness="0" BorderBrush="Transparent" ItemsSource="{Binding Rectangles}" Height="200" Width="200"> <ListView.Resources> <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Canvas.Left" Value="{Binding Left, Mode=TwoWay}" /> <Setter Property="Canvas.Top" Value="{Binding Top, Mode=TwoWay}" /> </Style> </ListView.Resources> <ListView.ItemTemplate> <DataTemplate DataType="{x:Type CanvasListView:RectangleModel}"> <Rectangle Width="30" Height="30" Fill="{Binding Color}"/> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemsPanel> <ItemsPanelTemplate> <Canvas Background="LightBlue"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView> </Grid> </Window> ``` I added a color property in the viewmodel: ``` public string Color { get; set; } ```
I did it via Popup, it looks well but I dont know whether it fits in your requirement or not ``` <Grid Background="Transparent"> <ListView BorderThickness="0" BorderBrush="Transparent" ItemsSource="{Binding Rectangles}" Height="200" Width="200"> <ListView.Resources> <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Canvas.Left" Value="{Binding Left, Mode=TwoWay}" /> <Setter Property="Canvas.Top" Value="{Binding Top, Mode=TwoWay}" /> </Style> </ListView.Resources> <ListView.ItemTemplate> <DataTemplate DataType="{x:Type WpfApplication2:RectangleModel}"> <Popup Width="30" Height="30" Canvas.Left="{Binding Left}" Canvas.Right="{Binding Right}" IsOpen="True" ClipToBounds="False"> <Rectangle Fill="LightCoral"/> </Popup> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemsPanel> <ItemsPanelTemplate> <Canvas Background="LightBlue"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView> </Grid> ``` This gives same result as you want. But you need to work more on that like their relative positions and all.
14,099,596
I have a ListView that its ItemsPanelTemplate is a Canvas, and every item is a rectangle. I'm trying to draw a Rectangle outside the Canvas in the position of (-50,-50) with no successive. can I do that somehow ? ![enter image description here](https://i.stack.imgur.com/rJ4Ns.png) The XAML: ``` <Grid > <ListView BorderThickness="0" BorderBrush="Transparent" ItemsSource="{Binding Rectangles}" Height="200" Width="200"> <ListView.Resources> <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Canvas.Left" Value="{Binding Left, Mode=TwoWay}" /> <Setter Property="Canvas.Top" Value="{Binding Top, Mode=TwoWay}" /> </Style> </ListView.Resources> <ListView.ItemTemplate> <DataTemplate DataType="{x:Type WpfApplication2:RectangleModel}"> <Rectangle Width="30" Height="30" Canvas.Left="{Binding Left}" Canvas.Right="{Binding Right}" Fill="LightCoral" ClipToBounds="False"/> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemsPanel> <ItemsPanelTemplate> <Canvas Background="LightBlue"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView> </Grid> ``` Code behind: ``` public partial class MainWindow : Window { public List<RectangleModel> Rectangles { get; set; } public MainWindow() { Rectangles = new List<RectangleModel>(); Rectangles.Add(new RectangleModel { Left = -50, Top = -50 }); Rectangles.Add(new RectangleModel { Left = 0, Top = 0 }); Rectangles.Add(new RectangleModel { Left = 50, Top = 50 }); DataContext = this; InitializeComponent(); } } ```
2012/12/31
[ "https://Stackoverflow.com/questions/14099596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138627/" ]
I may be wrong, but this seems to be rather simple problem (I may have completely assumed the wrong thing, but I'm not sure so I'm going with the assumption just in case). You've defined your `ListView` to be 200 by 200 and your `Canvas` is taking all that space. Judging by your picture, I feel it is `Canvas` that you want to be of 200 by 200 not the `ListView`. **Xaml:** ``` <Grid > <ListView BorderThickness="0" BorderBrush="Transparent" ItemsSource="{Binding Rectangles}"> <ListView.Resources> <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Canvas.Left" Value="{Binding Left, Mode=TwoWay}" /> <Setter Property="Canvas.Top" Value="{Binding Top, Mode=TwoWay}" /> </Style> </ListView.Resources> <ListView.ItemTemplate> <DataTemplate DataType="{x:Type wpfApplication1:RectangleModel}"> <Rectangle Width="30" Height="10" Canvas.Left="{Binding Left}" Canvas.Top="{Binding Top}" Fill="LightCoral" ClipToBounds="False"/> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemsPanel> <ItemsPanelTemplate> <Canvas Background="LightBlue" ClipToBounds="False" Height="200" Width="200"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView> </Grid> ``` **Result:** ![enter image description here](https://i.stack.imgur.com/dLaiS.png)
I did it via Popup, it looks well but I dont know whether it fits in your requirement or not ``` <Grid Background="Transparent"> <ListView BorderThickness="0" BorderBrush="Transparent" ItemsSource="{Binding Rectangles}" Height="200" Width="200"> <ListView.Resources> <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Canvas.Left" Value="{Binding Left, Mode=TwoWay}" /> <Setter Property="Canvas.Top" Value="{Binding Top, Mode=TwoWay}" /> </Style> </ListView.Resources> <ListView.ItemTemplate> <DataTemplate DataType="{x:Type WpfApplication2:RectangleModel}"> <Popup Width="30" Height="30" Canvas.Left="{Binding Left}" Canvas.Right="{Binding Right}" IsOpen="True" ClipToBounds="False"> <Rectangle Fill="LightCoral"/> </Popup> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemsPanel> <ItemsPanelTemplate> <Canvas Background="LightBlue"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView> </Grid> ``` This gives same result as you want. But you need to work more on that like their relative positions and all.
26,021
Is it possible to achieve stereo sound totally without the "Center". Only extremely Right and Left pan (e.g. Choirs). If yes, please tell me how? I'm using Ozone iZotope plug-in.
2013/12/19
[ "https://sound.stackexchange.com/questions/26021", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/6561/" ]
Not practically. In stereo sound, the phantom center is the 'illusion'. Exactly center is whatever is exactly identical between the two channels. One can generalize and say that the width of the image is proportional to how 'different' the two sounds are. But it actually turns out this is a mathematical property of sound. Ignoring that there are a few other subtle queues humans pick up on that determine direction, mainly when you are talking about a stereo pan, you are talking about a phase difference. So if the center is when the left and right channels are completely in phase, then completely eliminating the center would be when the left and right are 100% out of phase. And you can try that out: take some mono signal and invert the phase of one side and it sounds basically about as "wide" as you'll get. But there's a problem which is that since sound sums additively, if you sum the two channels they subtract and disappear completely. There are other problems but that is the most drastic and what happens if you try to completely eliminate the center. Doing any kind of stereo pan effect is just a balance between how wide you want it to sound and how much crap it becomes when it (inevitably) becomes much narrower on everyone's laptops (or can be summed to mono completely for radio). [Ozone has M/S mode](http://www.izotope.com/support/help/ozone/pages/mid_side_processing.htm) for basically everything now. A pretty obvious choice is to raise a high shelf on the sides.
One can achieve such an effect by adding a plug-in to a channel that can phase-invert either the left or right stereo channel. This is a great way to make a pad fill up an entire audio space.
16,103,407
Here is my situation. I have a file called `iframe.html`, which contains the code to for a image slideshow. The code is somewhat like ``` <html> <head> <!-- Have added title and js files (jquery, slideshow.js) etc. --> </head> <body> <!-- Contains the images which are rendered as slidehow. --> <!-- have hierarchy like 'div' inside 'div' etc. --> </body> </html> ``` Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in `index.html`, they can add by adding following lines: ``` <iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe> ``` This will bring the complete HTML code from `iframe.html` to `index.html`, now I need a way to access the elements in the iframe to adjust some of their properties. Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this? I tried with no success to access the iframe components from `index.html` by something like ``` $('#iframe').contents(); ``` but get the error: > > TypeError: Cannot call method 'contents' of null > > > So, I think to implement the logic in `iframe.html` where the slideshow should check the width and height of parent and set its height accordingly. I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.
2013/04/19
[ "https://Stackoverflow.com/questions/16103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312737/" ]
Try this code: `$('#iframe').contents().find("html").html();` This will return all the html in your iframe. Instead of `.find("html")` you can use any selector you want eg: `.find('body')`,`.find('div#mydiv')`.
``` var iframe = document.getElementById('iframe'); $(iframe).contents().find("html").html(); ```
16,103,407
Here is my situation. I have a file called `iframe.html`, which contains the code to for a image slideshow. The code is somewhat like ``` <html> <head> <!-- Have added title and js files (jquery, slideshow.js) etc. --> </head> <body> <!-- Contains the images which are rendered as slidehow. --> <!-- have hierarchy like 'div' inside 'div' etc. --> </body> </html> ``` Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in `index.html`, they can add by adding following lines: ``` <iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe> ``` This will bring the complete HTML code from `iframe.html` to `index.html`, now I need a way to access the elements in the iframe to adjust some of their properties. Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this? I tried with no success to access the iframe components from `index.html` by something like ``` $('#iframe').contents(); ``` but get the error: > > TypeError: Cannot call method 'contents' of null > > > So, I think to implement the logic in `iframe.html` where the slideshow should check the width and height of parent and set its height accordingly. I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.
2013/04/19
[ "https://Stackoverflow.com/questions/16103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312737/" ]
Try this code: `$('#iframe').contents().find("html").html();` This will return all the html in your iframe. Instead of `.find("html")` you can use any selector you want eg: `.find('body')`,`.find('div#mydiv')`.
``` $('#iframe').load(function() { var src = $('#iframe').contents().find("html").html(); alert(src); }); ```
16,103,407
Here is my situation. I have a file called `iframe.html`, which contains the code to for a image slideshow. The code is somewhat like ``` <html> <head> <!-- Have added title and js files (jquery, slideshow.js) etc. --> </head> <body> <!-- Contains the images which are rendered as slidehow. --> <!-- have hierarchy like 'div' inside 'div' etc. --> </body> </html> ``` Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in `index.html`, they can add by adding following lines: ``` <iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe> ``` This will bring the complete HTML code from `iframe.html` to `index.html`, now I need a way to access the elements in the iframe to adjust some of their properties. Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this? I tried with no success to access the iframe components from `index.html` by something like ``` $('#iframe').contents(); ``` but get the error: > > TypeError: Cannot call method 'contents' of null > > > So, I think to implement the logic in `iframe.html` where the slideshow should check the width and height of parent and set its height accordingly. I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.
2013/04/19
[ "https://Stackoverflow.com/questions/16103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312737/" ]
This line will retrieve the whole HTML code of the frame. By using other methods instead of `innerHTML` you can traverse DOM of the inner document. ``` document.getElementById('iframe').contentWindow.document.body.innerHTML ``` Thing to remember is that this will work only if the frame source is on the same domain. If it is from a different domain, cross-site-scripting (XSS) protection will kick in.
Just for reference's sake. This is how to do it with JQuery (useful for instance when you cannot query by element id): ``` $('#iframe').get(0).contentWindow.document.body.innerHTML ```
16,103,407
Here is my situation. I have a file called `iframe.html`, which contains the code to for a image slideshow. The code is somewhat like ``` <html> <head> <!-- Have added title and js files (jquery, slideshow.js) etc. --> </head> <body> <!-- Contains the images which are rendered as slidehow. --> <!-- have hierarchy like 'div' inside 'div' etc. --> </body> </html> ``` Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in `index.html`, they can add by adding following lines: ``` <iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe> ``` This will bring the complete HTML code from `iframe.html` to `index.html`, now I need a way to access the elements in the iframe to adjust some of their properties. Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this? I tried with no success to access the iframe components from `index.html` by something like ``` $('#iframe').contents(); ``` but get the error: > > TypeError: Cannot call method 'contents' of null > > > So, I think to implement the logic in `iframe.html` where the slideshow should check the width and height of parent and set its height accordingly. I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.
2013/04/19
[ "https://Stackoverflow.com/questions/16103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312737/" ]
this works for me because it works fine in ie8. ``` $('#iframe').contents().find("html").html(); ``` but if you like to use javascript aside for jquery you may use like this ``` var iframe = document.getElementById('iframecontent'); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; var val_1 = innerDoc.getElementById('value_1').value; ```
This can be another solution if jquery is loaded in iframe.html. ``` $('#iframe')[0].contentWindow.$("html").html() ```
16,103,407
Here is my situation. I have a file called `iframe.html`, which contains the code to for a image slideshow. The code is somewhat like ``` <html> <head> <!-- Have added title and js files (jquery, slideshow.js) etc. --> </head> <body> <!-- Contains the images which are rendered as slidehow. --> <!-- have hierarchy like 'div' inside 'div' etc. --> </body> </html> ``` Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in `index.html`, they can add by adding following lines: ``` <iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe> ``` This will bring the complete HTML code from `iframe.html` to `index.html`, now I need a way to access the elements in the iframe to adjust some of their properties. Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this? I tried with no success to access the iframe components from `index.html` by something like ``` $('#iframe').contents(); ``` but get the error: > > TypeError: Cannot call method 'contents' of null > > > So, I think to implement the logic in `iframe.html` where the slideshow should check the width and height of parent and set its height accordingly. I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.
2013/04/19
[ "https://Stackoverflow.com/questions/16103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312737/" ]
This line will retrieve the whole HTML code of the frame. By using other methods instead of `innerHTML` you can traverse DOM of the inner document. ``` document.getElementById('iframe').contentWindow.document.body.innerHTML ``` Thing to remember is that this will work only if the frame source is on the same domain. If it is from a different domain, cross-site-scripting (XSS) protection will kick in.
If you have ***Div*** as follows in one ***Iframe*** ``` <iframe id="ifrmReportViewer" name="ifrmReportViewer" frameborder="0" width="980" <div id="EndLetterSequenceNoToShow" runat="server"> 11441551 </div> Or <form id="form1" runat="server"> <div style="clear: both; width: 998px; margin: 0 auto;" id="divInnerForm"> Some Text </div> </form> </iframe> ``` Then you can find the text of those ***Div*** using the following code ``` var iContentBody = $("#ifrmReportViewer").contents().find("body"); var endLetterSequenceNo = iContentBody.find("#EndLetterSequenceNoToShow").text(); var divInnerFormText = iContentBody.find("#divInnerForm").text(); ``` I hope this will help someone.
16,103,407
Here is my situation. I have a file called `iframe.html`, which contains the code to for a image slideshow. The code is somewhat like ``` <html> <head> <!-- Have added title and js files (jquery, slideshow.js) etc. --> </head> <body> <!-- Contains the images which are rendered as slidehow. --> <!-- have hierarchy like 'div' inside 'div' etc. --> </body> </html> ``` Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in `index.html`, they can add by adding following lines: ``` <iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe> ``` This will bring the complete HTML code from `iframe.html` to `index.html`, now I need a way to access the elements in the iframe to adjust some of their properties. Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this? I tried with no success to access the iframe components from `index.html` by something like ``` $('#iframe').contents(); ``` but get the error: > > TypeError: Cannot call method 'contents' of null > > > So, I think to implement the logic in `iframe.html` where the slideshow should check the width and height of parent and set its height accordingly. I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.
2013/04/19
[ "https://Stackoverflow.com/questions/16103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312737/" ]
``` var iframe = document.getElementById('iframe'); $(iframe).contents().find("html").html(); ```
``` $(editFrame).contents().find("html").html(); ```
16,103,407
Here is my situation. I have a file called `iframe.html`, which contains the code to for a image slideshow. The code is somewhat like ``` <html> <head> <!-- Have added title and js files (jquery, slideshow.js) etc. --> </head> <body> <!-- Contains the images which are rendered as slidehow. --> <!-- have hierarchy like 'div' inside 'div' etc. --> </body> </html> ``` Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in `index.html`, they can add by adding following lines: ``` <iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe> ``` This will bring the complete HTML code from `iframe.html` to `index.html`, now I need a way to access the elements in the iframe to adjust some of their properties. Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this? I tried with no success to access the iframe components from `index.html` by something like ``` $('#iframe').contents(); ``` but get the error: > > TypeError: Cannot call method 'contents' of null > > > So, I think to implement the logic in `iframe.html` where the slideshow should check the width and height of parent and set its height accordingly. I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.
2013/04/19
[ "https://Stackoverflow.com/questions/16103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312737/" ]
``` $(editFrame).contents().find("html").html(); ```
Just for reference's sake. This is how to do it with JQuery (useful for instance when you cannot query by element id): ``` $('#iframe').get(0).contentWindow.document.body.innerHTML ```
16,103,407
Here is my situation. I have a file called `iframe.html`, which contains the code to for a image slideshow. The code is somewhat like ``` <html> <head> <!-- Have added title and js files (jquery, slideshow.js) etc. --> </head> <body> <!-- Contains the images which are rendered as slidehow. --> <!-- have hierarchy like 'div' inside 'div' etc. --> </body> </html> ``` Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in `index.html`, they can add by adding following lines: ``` <iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe> ``` This will bring the complete HTML code from `iframe.html` to `index.html`, now I need a way to access the elements in the iframe to adjust some of their properties. Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this? I tried with no success to access the iframe components from `index.html` by something like ``` $('#iframe').contents(); ``` but get the error: > > TypeError: Cannot call method 'contents' of null > > > So, I think to implement the logic in `iframe.html` where the slideshow should check the width and height of parent and set its height accordingly. I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.
2013/04/19
[ "https://Stackoverflow.com/questions/16103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312737/" ]
This line will retrieve the whole HTML code of the frame. By using other methods instead of `innerHTML` you can traverse DOM of the inner document. ``` document.getElementById('iframe').contentWindow.document.body.innerHTML ``` Thing to remember is that this will work only if the frame source is on the same domain. If it is from a different domain, cross-site-scripting (XSS) protection will kick in.
``` $(editFrame).contents().find("html").html(); ```
16,103,407
Here is my situation. I have a file called `iframe.html`, which contains the code to for a image slideshow. The code is somewhat like ``` <html> <head> <!-- Have added title and js files (jquery, slideshow.js) etc. --> </head> <body> <!-- Contains the images which are rendered as slidehow. --> <!-- have hierarchy like 'div' inside 'div' etc. --> </body> </html> ``` Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in `index.html`, they can add by adding following lines: ``` <iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe> ``` This will bring the complete HTML code from `iframe.html` to `index.html`, now I need a way to access the elements in the iframe to adjust some of their properties. Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this? I tried with no success to access the iframe components from `index.html` by something like ``` $('#iframe').contents(); ``` but get the error: > > TypeError: Cannot call method 'contents' of null > > > So, I think to implement the logic in `iframe.html` where the slideshow should check the width and height of parent and set its height accordingly. I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.
2013/04/19
[ "https://Stackoverflow.com/questions/16103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312737/" ]
Just for reference's sake. This is how to do it with JQuery (useful for instance when you cannot query by element id): ``` $('#iframe').get(0).contentWindow.document.body.innerHTML ```
``` $('#iframe').load(function() { var src = $('#iframe').contents().find("html").html(); alert(src); }); ```
16,103,407
Here is my situation. I have a file called `iframe.html`, which contains the code to for a image slideshow. The code is somewhat like ``` <html> <head> <!-- Have added title and js files (jquery, slideshow.js) etc. --> </head> <body> <!-- Contains the images which are rendered as slidehow. --> <!-- have hierarchy like 'div' inside 'div' etc. --> </body> </html> ``` Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in `index.html`, they can add by adding following lines: ``` <iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe> ``` This will bring the complete HTML code from `iframe.html` to `index.html`, now I need a way to access the elements in the iframe to adjust some of their properties. Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this? I tried with no success to access the iframe components from `index.html` by something like ``` $('#iframe').contents(); ``` but get the error: > > TypeError: Cannot call method 'contents' of null > > > So, I think to implement the logic in `iframe.html` where the slideshow should check the width and height of parent and set its height accordingly. I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.
2013/04/19
[ "https://Stackoverflow.com/questions/16103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312737/" ]
Why not try Ajax, check a code part 1 or part 2 (use comment). ```js $(document).ready(function(){ console.clear(); /* // PART 1 ERROR // Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Sandbox access violation: Blocked a frame at "http://stacksnippets.net" from accessing a frame at "null". Both frames are sandboxed and lack the "allow-same-origin" flag. console.log("PART 1:: "); console.log($('iframe#sandro').contents().find("html").html()); */ // PART 2 $.ajax({ url: $("iframe#sandro").attr("src"), type: 'GET', dataType: 'html' }).done(function(html) { console.log("PART 2:: "); console.log(html); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <html> <body> <iframe id="sandro" src="https://jsfiddle.net/robots.txt"></iframe> </body> </html> ```
``` $('#iframe').load(function() { var src = $('#iframe').contents().find("html").html(); alert(src); }); ```
34,266
What I'm trying to say is should Light tell Teru that killing from scrape paper is possible, then if Teru kept a real deathnote paper with him 24/7, surely that in the final showdown, whoever names written on that piece of paper they surely will die, won't they? That way you don't even need to worry about the book switching scheme.
2016/07/15
[ "https://anime.stackexchange.com/questions/34266", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/26187/" ]
Whole point of Teru was to be a decoy. If SPK had seen Mikami using a seperate paper of the real death note would be a give away. For example. Instead of visiting the bank to retrieve the real Deathnote, Megami might have used the paper. Which would still give him away. Light made sure the Mikami had NO access to the real DeathNote and explicitly said him to only take it out on the D-Day. This is basically an speculative question containing the What-if Scenarios. You can plausibly say that something might've worked out, but as I have just said above... Chances are it would have blown up more easily. Because SPK would have been dead if Mikami had trusted Light and not gone to retrieve the Real DeathNote from the bank. EDIT: I get the question was why didn't Mikami keep a seperate real piece of DN paper for the day of the final D-Day instead of the DN. I answered this What-if scenario with a plausible explaination that Mikami may have used it to kill Takada. Then I went on to explain this was why Light didn't want ANY piece of real Death Note with Mikami, to keep the plan full proof. **Tl;dr Mikami didn't keep the DN paper because Light told him not to. This was because Light just like Near wanted to play complete and full proof game but lost to the external factors of Mello and Mikami**
This is the email x-kira should be recieved prior to Jan 28th... In exactly 1 month and 29 days from today, the 26th of January. Do not go to the bank to pick up the note. Instead and I suggest sometime in December. Make 2 copies not one of the notebook. Keep one in your brief case and the other in the bank vault. Keep the original but burry it by using a name to do so for you. That way you cannot be tracked. Then keep a page on you and on the day of 28th January at 1pm. Use this page to rest on the fake that the spk will use. Write down Nate River first. Then kill the rest except light Yagami. -LY ;]
1,104,930
$p,q$ primes. prove $p=q$ if and only if $p$ divides $q$. $p|q$ stands for '$p$ divides $q$' $p|q\Leftrightarrow p=q$ $\Leftarrow$: $p(1)=q$ and therefore $p|q$ $\Rightarrow$: if $p=\pm 1$, $p|q\Rightarrow p=q$ does not hold: all you need is one case to disprove an implication: $1|2 \rightarrow 1=2$, $-1|2 \rightarrow -1=2$ evaluate to $true\rightarrow false$, $true\rightarrow false$ which both evaluate to $false$. in turn, $p|q\Leftrightarrow p=q$ does not hold for $p=\pm 1$ for $p\neq \pm 1$: proof by contraposition: $[p|q\Rightarrow p=q]\Leftrightarrow [p\neq q\Rightarrow p\nmid q]$ $p\neq q\Rightarrow p\nmid q$: $p\neq q$ $\therefore q=p+r(r$ an integer) $=p+p\_1p\_2...p\_n;\space$ primes $ p\_1,p\_2,...p\_n\neq p$; they cannot equal $p$ because then the prime $q$ would be divisible by something other than itself and $1$, namely $p$. $\therefore p\nmid q$ Please verify proof.
2015/01/15
[ "https://math.stackexchange.com/questions/1104930", "https://math.stackexchange.com", "https://math.stackexchange.com/users/99402/" ]
$(\Leftarrow)$ looks good. For $(\Rightarrow)$ I would say: If $p\mid q$ then as $q$ is a prime, $p=\pm1$ or $p=\pm q$ but $p$ is a prime so $p=q$. I am using: If $q>1$ then $q$ is a prime if and only if the following is true: $d\mid q$ implies $d=\pm1$ or $d=\pm q$.
If $p|q$ and $q|p$, then $p = aq$ and $q = bp$, where $a, b$ are integers. Combining these conditions we get $p = abp$, so $p(1-ab) = 0$. There are no divisors of zero in $\mathbb Z$, so $1 = ab$. The only units (invertible elements) in the ring of integers are $1$ and $-1$, so $p = \pm q$. But you were assuming that both $p, q$ are prime (therefore positive) and the conclusion is that $p = q$.
66,391,894
I have a string like this `str ="out = sings<=20,gef=='one'"`. Now I want to remove the first out and = but not the <= and ==. How do I do it, though we can use the replace function it replaces all the =. I only want the first word and the = sing should be removed. My code: ``` st ="out = sings<=20,gef=='one'" st1=st.replace('out', "") print(st1) st2 = st1.replace('=', "") print(st2) ``` This gives, ``` st1: = sings<=20,gef=='one' st2 :sings<20,gef'one' ``` Expected Output: ``` st1: = sings<=20,gef=='one' st2 : sings<=20,gef=='one' ```
2021/02/26
[ "https://Stackoverflow.com/questions/66391894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15276517/" ]
add space while replacing ``` st ="out = sings<=20,gef=='one'" st1=st.replace('out', "") print(st1) st2 = st1.replace(' = ', "") print(st2) ``` output ``` = sings<=20,gef=='one' sings<=20,gef=='one' ```
You can specify the no of replacements to make using the count argument of replace. ``` st ="out = sings<=20,gef=='one'" st1=st.replace('out', "") print(st1) st2 = st1.replace('=', "", 1) print(st2) ```
66,391,894
I have a string like this `str ="out = sings<=20,gef=='one'"`. Now I want to remove the first out and = but not the <= and ==. How do I do it, though we can use the replace function it replaces all the =. I only want the first word and the = sing should be removed. My code: ``` st ="out = sings<=20,gef=='one'" st1=st.replace('out', "") print(st1) st2 = st1.replace('=', "") print(st2) ``` This gives, ``` st1: = sings<=20,gef=='one' st2 :sings<20,gef'one' ``` Expected Output: ``` st1: = sings<=20,gef=='one' st2 : sings<=20,gef=='one' ```
2021/02/26
[ "https://Stackoverflow.com/questions/66391894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15276517/" ]
You can match from the start of the string the first word characters followed by an equals sign between 1 or more whitespace chars. In the replacement use an empty string. ``` import re st ="out = sings<=20,gef=='one'" result = re.sub(r"^\w+\s+=\s+", "", st) print (result) ``` Output ``` sings<=20,gef=='one' ```
You can specify the no of replacements to make using the count argument of replace. ``` st ="out = sings<=20,gef=='one'" st1=st.replace('out', "") print(st1) st2 = st1.replace('=', "", 1) print(st2) ```
4,856,255
I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls. I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ? `Fork` : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible). The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code. `Vfork`: The basic difference between `vfork()` and `fork()` is that when a new process is created with `vfork()`, the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls `execve()`, at which point the parent process continues. This means that the child process of a `vfork()` must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the `vfork()` call, and it must not call `exit()` (if it needs to exit, it should use `_exit()`; actually, this is also true for the child of a normal `fork()`). `Exec`: The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. `exec()` replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an `exec()` error. `Clone`: `clone()`, as `fork()`, creates a new process. Unlike `fork()`, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. When the child process is created with `clone()`, it executes the function application *fn(arg)* (This differs from `fork()`, where execution continues in the child from the point of the original `fork()` call.) The *fn* argument is a pointer to a function that is called by the child process at the beginning of its execution. The *arg* argument is passed to the *fn* function. When the *fn(arg)* function application returns, the child process terminates. The integer returned by *fn* is the exit code for the child process. The child process may also terminate explicitly by calling `exit(2)` or after receiving a fatal signal. Information gotten from: * [Differences between fork and exec](https://stackoverflow.com/questions/1653340/exec-and-fork) * <http://www.allinterview.com/showanswers/59616.html> * <http://www.unixguide.net/unix/programming/1.1.2.shtml> * <http://linux.about.com/library/cmd/blcmdl2_clone.htm> Thanks for taking the time to read this ! :)
2011/01/31
[ "https://Stackoverflow.com/questions/4856255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476033/" ]
* `vfork()` is an obsolete optimization. Before good memory management, `fork()` made a full copy of the parent's memory, so it was pretty expensive. since in many cases a `fork()` was followed by `exec()`, which discards the current memory map and creates a new one, it was a needless expense. Nowadays, `fork()` doesn't copy the memory; it's simply set as "copy on write", so `fork()`+`exec()` is just as efficient as `vfork()`+`exec()`. * `clone()` is the syscall used by `fork()`. with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.
* `execve()` replaces the current executable image with another one loaded from an executable file. * `fork()` creates a child process. * `vfork()` is a historical optimized version of `fork()`, meant to be used when `execve()` is called directly after `fork()`. It turned out to work well in non-MMU systems (where `fork()` cannot work in an efficient manner) and when `fork()`ing processes with a huge memory footprint to run some small program (think Java's `Runtime.exec()`). POSIX has standardized the `posix_spawn()` to replace these latter two more modern uses of `vfork()`. * `posix_spawn()` does the equivalent of a `fork()/execve()`, and also allows some fd juggling in between. It's supposed to replace `fork()/execve()`, mainly for non-MMU platforms. * `pthread_create()` creates a new thread. * `clone()` is a Linux-specific call, which can be used to implement anything from `fork()` to `pthread_create()`. It gives a lot of control. Inspired on `rfork()`. * `rfork()` is a Plan-9 specific call. It's supposed to be a generic call, allowing several degrees of sharing, between full processes and threads.
4,856,255
I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls. I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ? `Fork` : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible). The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code. `Vfork`: The basic difference between `vfork()` and `fork()` is that when a new process is created with `vfork()`, the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls `execve()`, at which point the parent process continues. This means that the child process of a `vfork()` must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the `vfork()` call, and it must not call `exit()` (if it needs to exit, it should use `_exit()`; actually, this is also true for the child of a normal `fork()`). `Exec`: The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. `exec()` replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an `exec()` error. `Clone`: `clone()`, as `fork()`, creates a new process. Unlike `fork()`, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. When the child process is created with `clone()`, it executes the function application *fn(arg)* (This differs from `fork()`, where execution continues in the child from the point of the original `fork()` call.) The *fn* argument is a pointer to a function that is called by the child process at the beginning of its execution. The *arg* argument is passed to the *fn* function. When the *fn(arg)* function application returns, the child process terminates. The integer returned by *fn* is the exit code for the child process. The child process may also terminate explicitly by calling `exit(2)` or after receiving a fatal signal. Information gotten from: * [Differences between fork and exec](https://stackoverflow.com/questions/1653340/exec-and-fork) * <http://www.allinterview.com/showanswers/59616.html> * <http://www.unixguide.net/unix/programming/1.1.2.shtml> * <http://linux.about.com/library/cmd/blcmdl2_clone.htm> Thanks for taking the time to read this ! :)
2011/01/31
[ "https://Stackoverflow.com/questions/4856255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476033/" ]
* `vfork()` is an obsolete optimization. Before good memory management, `fork()` made a full copy of the parent's memory, so it was pretty expensive. since in many cases a `fork()` was followed by `exec()`, which discards the current memory map and creates a new one, it was a needless expense. Nowadays, `fork()` doesn't copy the memory; it's simply set as "copy on write", so `fork()`+`exec()` is just as efficient as `vfork()`+`exec()`. * `clone()` is the syscall used by `fork()`. with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.
in fork(), either child or parent process will execute based on cpu selection.. But in vfork(), surely child will execute first. after child terminated, parent will execute.
4,856,255
I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls. I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ? `Fork` : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible). The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code. `Vfork`: The basic difference between `vfork()` and `fork()` is that when a new process is created with `vfork()`, the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls `execve()`, at which point the parent process continues. This means that the child process of a `vfork()` must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the `vfork()` call, and it must not call `exit()` (if it needs to exit, it should use `_exit()`; actually, this is also true for the child of a normal `fork()`). `Exec`: The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. `exec()` replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an `exec()` error. `Clone`: `clone()`, as `fork()`, creates a new process. Unlike `fork()`, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. When the child process is created with `clone()`, it executes the function application *fn(arg)* (This differs from `fork()`, where execution continues in the child from the point of the original `fork()` call.) The *fn* argument is a pointer to a function that is called by the child process at the beginning of its execution. The *arg* argument is passed to the *fn* function. When the *fn(arg)* function application returns, the child process terminates. The integer returned by *fn* is the exit code for the child process. The child process may also terminate explicitly by calling `exit(2)` or after receiving a fatal signal. Information gotten from: * [Differences between fork and exec](https://stackoverflow.com/questions/1653340/exec-and-fork) * <http://www.allinterview.com/showanswers/59616.html> * <http://www.unixguide.net/unix/programming/1.1.2.shtml> * <http://linux.about.com/library/cmd/blcmdl2_clone.htm> Thanks for taking the time to read this ! :)
2011/01/31
[ "https://Stackoverflow.com/questions/4856255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476033/" ]
* `vfork()` is an obsolete optimization. Before good memory management, `fork()` made a full copy of the parent's memory, so it was pretty expensive. since in many cases a `fork()` was followed by `exec()`, which discards the current memory map and creates a new one, it was a needless expense. Nowadays, `fork()` doesn't copy the memory; it's simply set as "copy on write", so `fork()`+`exec()` is just as efficient as `vfork()`+`exec()`. * `clone()` is the syscall used by `fork()`. with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.
The fork(),vfork() and clone() all call the do\_fork() to do the real work, but with different parameters. ``` asmlinkage int sys_fork(struct pt_regs regs) { return do_fork(SIGCHLD, regs.esp, &regs, 0); } asmlinkage int sys_clone(struct pt_regs regs) { unsigned long clone_flags; unsigned long newsp; clone_flags = regs.ebx; newsp = regs.ecx; if (!newsp) newsp = regs.esp; return do_fork(clone_flags, newsp, &regs, 0); } asmlinkage int sys_vfork(struct pt_regs regs) { return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, regs.esp, &regs, 0); } #define CLONE_VFORK 0x00004000 /* set if the parent wants the child to wake it up on mm_release */ #define CLONE_VM 0x00000100 /* set if VM shared between processes */ SIGCHLD means the child should send this signal to its father when exit. ``` For fork, the child and father has the independent VM page table, but since the efficiency, fork will not really copy any pages, it just set all the writeable pages to readonly for child process. So when child process want to write something on that page, an page exception happen and kernel will alloc a new page cloned from the old page with write permission. That's called "copy on write". For vfork, the virtual memory is exactly by child and father---just because of that, father and child can't be awake concurrently since they will influence each other. So the father will sleep at the end of "do\_fork()" and awake when child call exit() or execve() since then it will own new page table. Here is the code(in do\_fork()) that the father sleep. ``` if ((clone_flags & CLONE_VFORK) && (retval > 0)) down(&sem); return retval; ``` Here is the code(in mm\_release() called by exit() and execve()) which awake the father. ``` up(tsk->p_opptr->vfork_sem); ``` For sys\_clone(), it is more flexible since you can input any clone\_flags to it. So pthread\_create() call this system call with many clone\_flags: int clone\_flags = (CLONE\_VM | CLONE\_FS | CLONE\_FILES | CLONE\_SIGNAL | CLONE\_SETTLS | CLONE\_PARENT\_SETTID | CLONE\_CHILD\_CLEARTID | CLONE\_SYSVSEM); Summary: the fork(),vfork() and clone() will create child processes with different mount of sharing resource with the father process. We also can say the vfork() and clone() can create threads(actually they are processes since they have independent task\_struct) since they share the VM page table with father process.
4,856,255
I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls. I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ? `Fork` : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible). The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code. `Vfork`: The basic difference between `vfork()` and `fork()` is that when a new process is created with `vfork()`, the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls `execve()`, at which point the parent process continues. This means that the child process of a `vfork()` must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the `vfork()` call, and it must not call `exit()` (if it needs to exit, it should use `_exit()`; actually, this is also true for the child of a normal `fork()`). `Exec`: The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. `exec()` replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an `exec()` error. `Clone`: `clone()`, as `fork()`, creates a new process. Unlike `fork()`, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. When the child process is created with `clone()`, it executes the function application *fn(arg)* (This differs from `fork()`, where execution continues in the child from the point of the original `fork()` call.) The *fn* argument is a pointer to a function that is called by the child process at the beginning of its execution. The *arg* argument is passed to the *fn* function. When the *fn(arg)* function application returns, the child process terminates. The integer returned by *fn* is the exit code for the child process. The child process may also terminate explicitly by calling `exit(2)` or after receiving a fatal signal. Information gotten from: * [Differences between fork and exec](https://stackoverflow.com/questions/1653340/exec-and-fork) * <http://www.allinterview.com/showanswers/59616.html> * <http://www.unixguide.net/unix/programming/1.1.2.shtml> * <http://linux.about.com/library/cmd/blcmdl2_clone.htm> Thanks for taking the time to read this ! :)
2011/01/31
[ "https://Stackoverflow.com/questions/4856255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476033/" ]
* `vfork()` is an obsolete optimization. Before good memory management, `fork()` made a full copy of the parent's memory, so it was pretty expensive. since in many cases a `fork()` was followed by `exec()`, which discards the current memory map and creates a new one, it was a needless expense. Nowadays, `fork()` doesn't copy the memory; it's simply set as "copy on write", so `fork()`+`exec()` is just as efficient as `vfork()`+`exec()`. * `clone()` is the syscall used by `fork()`. with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.
1. `fork()` - creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW). 2. `vfork()` - creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call `fork()`, child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic `fork()`! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either `exec()` (create a new virtual address space and a transition to a different stack) or `_exit()` (termination of the process execution). `vfork()` is the optimization of `fork()` for "fork-and-exec" model. It can be performed 4-5 times faster than the `fork()`, because unlike the `fork()` (even with COW kept in the mind), implementation of `vfork()` system call does not include the creation of a new address space (the allocation and setting up of new page directories). 3. `clone()` - creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, `clone()` system call is the base which is used for the implementation of `pthread_create()` and all the family of the `fork()` system calls. 4. `exec()` - resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with `fork()` system call together form a classical UNIX process management model called "fork-and-exec".
4,856,255
I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls. I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ? `Fork` : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible). The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code. `Vfork`: The basic difference between `vfork()` and `fork()` is that when a new process is created with `vfork()`, the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls `execve()`, at which point the parent process continues. This means that the child process of a `vfork()` must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the `vfork()` call, and it must not call `exit()` (if it needs to exit, it should use `_exit()`; actually, this is also true for the child of a normal `fork()`). `Exec`: The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. `exec()` replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an `exec()` error. `Clone`: `clone()`, as `fork()`, creates a new process. Unlike `fork()`, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. When the child process is created with `clone()`, it executes the function application *fn(arg)* (This differs from `fork()`, where execution continues in the child from the point of the original `fork()` call.) The *fn* argument is a pointer to a function that is called by the child process at the beginning of its execution. The *arg* argument is passed to the *fn* function. When the *fn(arg)* function application returns, the child process terminates. The integer returned by *fn* is the exit code for the child process. The child process may also terminate explicitly by calling `exit(2)` or after receiving a fatal signal. Information gotten from: * [Differences between fork and exec](https://stackoverflow.com/questions/1653340/exec-and-fork) * <http://www.allinterview.com/showanswers/59616.html> * <http://www.unixguide.net/unix/programming/1.1.2.shtml> * <http://linux.about.com/library/cmd/blcmdl2_clone.htm> Thanks for taking the time to read this ! :)
2011/01/31
[ "https://Stackoverflow.com/questions/4856255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476033/" ]
* `execve()` replaces the current executable image with another one loaded from an executable file. * `fork()` creates a child process. * `vfork()` is a historical optimized version of `fork()`, meant to be used when `execve()` is called directly after `fork()`. It turned out to work well in non-MMU systems (where `fork()` cannot work in an efficient manner) and when `fork()`ing processes with a huge memory footprint to run some small program (think Java's `Runtime.exec()`). POSIX has standardized the `posix_spawn()` to replace these latter two more modern uses of `vfork()`. * `posix_spawn()` does the equivalent of a `fork()/execve()`, and also allows some fd juggling in between. It's supposed to replace `fork()/execve()`, mainly for non-MMU platforms. * `pthread_create()` creates a new thread. * `clone()` is a Linux-specific call, which can be used to implement anything from `fork()` to `pthread_create()`. It gives a lot of control. Inspired on `rfork()`. * `rfork()` is a Plan-9 specific call. It's supposed to be a generic call, allowing several degrees of sharing, between full processes and threads.
in fork(), either child or parent process will execute based on cpu selection.. But in vfork(), surely child will execute first. after child terminated, parent will execute.
4,856,255
I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls. I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ? `Fork` : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible). The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code. `Vfork`: The basic difference between `vfork()` and `fork()` is that when a new process is created with `vfork()`, the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls `execve()`, at which point the parent process continues. This means that the child process of a `vfork()` must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the `vfork()` call, and it must not call `exit()` (if it needs to exit, it should use `_exit()`; actually, this is also true for the child of a normal `fork()`). `Exec`: The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. `exec()` replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an `exec()` error. `Clone`: `clone()`, as `fork()`, creates a new process. Unlike `fork()`, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. When the child process is created with `clone()`, it executes the function application *fn(arg)* (This differs from `fork()`, where execution continues in the child from the point of the original `fork()` call.) The *fn* argument is a pointer to a function that is called by the child process at the beginning of its execution. The *arg* argument is passed to the *fn* function. When the *fn(arg)* function application returns, the child process terminates. The integer returned by *fn* is the exit code for the child process. The child process may also terminate explicitly by calling `exit(2)` or after receiving a fatal signal. Information gotten from: * [Differences between fork and exec](https://stackoverflow.com/questions/1653340/exec-and-fork) * <http://www.allinterview.com/showanswers/59616.html> * <http://www.unixguide.net/unix/programming/1.1.2.shtml> * <http://linux.about.com/library/cmd/blcmdl2_clone.htm> Thanks for taking the time to read this ! :)
2011/01/31
[ "https://Stackoverflow.com/questions/4856255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476033/" ]
* `execve()` replaces the current executable image with another one loaded from an executable file. * `fork()` creates a child process. * `vfork()` is a historical optimized version of `fork()`, meant to be used when `execve()` is called directly after `fork()`. It turned out to work well in non-MMU systems (where `fork()` cannot work in an efficient manner) and when `fork()`ing processes with a huge memory footprint to run some small program (think Java's `Runtime.exec()`). POSIX has standardized the `posix_spawn()` to replace these latter two more modern uses of `vfork()`. * `posix_spawn()` does the equivalent of a `fork()/execve()`, and also allows some fd juggling in between. It's supposed to replace `fork()/execve()`, mainly for non-MMU platforms. * `pthread_create()` creates a new thread. * `clone()` is a Linux-specific call, which can be used to implement anything from `fork()` to `pthread_create()`. It gives a lot of control. Inspired on `rfork()`. * `rfork()` is a Plan-9 specific call. It's supposed to be a generic call, allowing several degrees of sharing, between full processes and threads.
The fork(),vfork() and clone() all call the do\_fork() to do the real work, but with different parameters. ``` asmlinkage int sys_fork(struct pt_regs regs) { return do_fork(SIGCHLD, regs.esp, &regs, 0); } asmlinkage int sys_clone(struct pt_regs regs) { unsigned long clone_flags; unsigned long newsp; clone_flags = regs.ebx; newsp = regs.ecx; if (!newsp) newsp = regs.esp; return do_fork(clone_flags, newsp, &regs, 0); } asmlinkage int sys_vfork(struct pt_regs regs) { return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, regs.esp, &regs, 0); } #define CLONE_VFORK 0x00004000 /* set if the parent wants the child to wake it up on mm_release */ #define CLONE_VM 0x00000100 /* set if VM shared between processes */ SIGCHLD means the child should send this signal to its father when exit. ``` For fork, the child and father has the independent VM page table, but since the efficiency, fork will not really copy any pages, it just set all the writeable pages to readonly for child process. So when child process want to write something on that page, an page exception happen and kernel will alloc a new page cloned from the old page with write permission. That's called "copy on write". For vfork, the virtual memory is exactly by child and father---just because of that, father and child can't be awake concurrently since they will influence each other. So the father will sleep at the end of "do\_fork()" and awake when child call exit() or execve() since then it will own new page table. Here is the code(in do\_fork()) that the father sleep. ``` if ((clone_flags & CLONE_VFORK) && (retval > 0)) down(&sem); return retval; ``` Here is the code(in mm\_release() called by exit() and execve()) which awake the father. ``` up(tsk->p_opptr->vfork_sem); ``` For sys\_clone(), it is more flexible since you can input any clone\_flags to it. So pthread\_create() call this system call with many clone\_flags: int clone\_flags = (CLONE\_VM | CLONE\_FS | CLONE\_FILES | CLONE\_SIGNAL | CLONE\_SETTLS | CLONE\_PARENT\_SETTID | CLONE\_CHILD\_CLEARTID | CLONE\_SYSVSEM); Summary: the fork(),vfork() and clone() will create child processes with different mount of sharing resource with the father process. We also can say the vfork() and clone() can create threads(actually they are processes since they have independent task\_struct) since they share the VM page table with father process.
4,856,255
I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls. I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ? `Fork` : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible). The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code. `Vfork`: The basic difference between `vfork()` and `fork()` is that when a new process is created with `vfork()`, the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls `execve()`, at which point the parent process continues. This means that the child process of a `vfork()` must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the `vfork()` call, and it must not call `exit()` (if it needs to exit, it should use `_exit()`; actually, this is also true for the child of a normal `fork()`). `Exec`: The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. `exec()` replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an `exec()` error. `Clone`: `clone()`, as `fork()`, creates a new process. Unlike `fork()`, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. When the child process is created with `clone()`, it executes the function application *fn(arg)* (This differs from `fork()`, where execution continues in the child from the point of the original `fork()` call.) The *fn* argument is a pointer to a function that is called by the child process at the beginning of its execution. The *arg* argument is passed to the *fn* function. When the *fn(arg)* function application returns, the child process terminates. The integer returned by *fn* is the exit code for the child process. The child process may also terminate explicitly by calling `exit(2)` or after receiving a fatal signal. Information gotten from: * [Differences between fork and exec](https://stackoverflow.com/questions/1653340/exec-and-fork) * <http://www.allinterview.com/showanswers/59616.html> * <http://www.unixguide.net/unix/programming/1.1.2.shtml> * <http://linux.about.com/library/cmd/blcmdl2_clone.htm> Thanks for taking the time to read this ! :)
2011/01/31
[ "https://Stackoverflow.com/questions/4856255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476033/" ]
* `execve()` replaces the current executable image with another one loaded from an executable file. * `fork()` creates a child process. * `vfork()` is a historical optimized version of `fork()`, meant to be used when `execve()` is called directly after `fork()`. It turned out to work well in non-MMU systems (where `fork()` cannot work in an efficient manner) and when `fork()`ing processes with a huge memory footprint to run some small program (think Java's `Runtime.exec()`). POSIX has standardized the `posix_spawn()` to replace these latter two more modern uses of `vfork()`. * `posix_spawn()` does the equivalent of a `fork()/execve()`, and also allows some fd juggling in between. It's supposed to replace `fork()/execve()`, mainly for non-MMU platforms. * `pthread_create()` creates a new thread. * `clone()` is a Linux-specific call, which can be used to implement anything from `fork()` to `pthread_create()`. It gives a lot of control. Inspired on `rfork()`. * `rfork()` is a Plan-9 specific call. It's supposed to be a generic call, allowing several degrees of sharing, between full processes and threads.
1. `fork()` - creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW). 2. `vfork()` - creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call `fork()`, child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic `fork()`! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either `exec()` (create a new virtual address space and a transition to a different stack) or `_exit()` (termination of the process execution). `vfork()` is the optimization of `fork()` for "fork-and-exec" model. It can be performed 4-5 times faster than the `fork()`, because unlike the `fork()` (even with COW kept in the mind), implementation of `vfork()` system call does not include the creation of a new address space (the allocation and setting up of new page directories). 3. `clone()` - creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, `clone()` system call is the base which is used for the implementation of `pthread_create()` and all the family of the `fork()` system calls. 4. `exec()` - resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with `fork()` system call together form a classical UNIX process management model called "fork-and-exec".
4,856,255
I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls. I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ? `Fork` : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible). The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code. `Vfork`: The basic difference between `vfork()` and `fork()` is that when a new process is created with `vfork()`, the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls `execve()`, at which point the parent process continues. This means that the child process of a `vfork()` must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the `vfork()` call, and it must not call `exit()` (if it needs to exit, it should use `_exit()`; actually, this is also true for the child of a normal `fork()`). `Exec`: The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. `exec()` replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an `exec()` error. `Clone`: `clone()`, as `fork()`, creates a new process. Unlike `fork()`, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. When the child process is created with `clone()`, it executes the function application *fn(arg)* (This differs from `fork()`, where execution continues in the child from the point of the original `fork()` call.) The *fn* argument is a pointer to a function that is called by the child process at the beginning of its execution. The *arg* argument is passed to the *fn* function. When the *fn(arg)* function application returns, the child process terminates. The integer returned by *fn* is the exit code for the child process. The child process may also terminate explicitly by calling `exit(2)` or after receiving a fatal signal. Information gotten from: * [Differences between fork and exec](https://stackoverflow.com/questions/1653340/exec-and-fork) * <http://www.allinterview.com/showanswers/59616.html> * <http://www.unixguide.net/unix/programming/1.1.2.shtml> * <http://linux.about.com/library/cmd/blcmdl2_clone.htm> Thanks for taking the time to read this ! :)
2011/01/31
[ "https://Stackoverflow.com/questions/4856255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476033/" ]
The fork(),vfork() and clone() all call the do\_fork() to do the real work, but with different parameters. ``` asmlinkage int sys_fork(struct pt_regs regs) { return do_fork(SIGCHLD, regs.esp, &regs, 0); } asmlinkage int sys_clone(struct pt_regs regs) { unsigned long clone_flags; unsigned long newsp; clone_flags = regs.ebx; newsp = regs.ecx; if (!newsp) newsp = regs.esp; return do_fork(clone_flags, newsp, &regs, 0); } asmlinkage int sys_vfork(struct pt_regs regs) { return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, regs.esp, &regs, 0); } #define CLONE_VFORK 0x00004000 /* set if the parent wants the child to wake it up on mm_release */ #define CLONE_VM 0x00000100 /* set if VM shared between processes */ SIGCHLD means the child should send this signal to its father when exit. ``` For fork, the child and father has the independent VM page table, but since the efficiency, fork will not really copy any pages, it just set all the writeable pages to readonly for child process. So when child process want to write something on that page, an page exception happen and kernel will alloc a new page cloned from the old page with write permission. That's called "copy on write". For vfork, the virtual memory is exactly by child and father---just because of that, father and child can't be awake concurrently since they will influence each other. So the father will sleep at the end of "do\_fork()" and awake when child call exit() or execve() since then it will own new page table. Here is the code(in do\_fork()) that the father sleep. ``` if ((clone_flags & CLONE_VFORK) && (retval > 0)) down(&sem); return retval; ``` Here is the code(in mm\_release() called by exit() and execve()) which awake the father. ``` up(tsk->p_opptr->vfork_sem); ``` For sys\_clone(), it is more flexible since you can input any clone\_flags to it. So pthread\_create() call this system call with many clone\_flags: int clone\_flags = (CLONE\_VM | CLONE\_FS | CLONE\_FILES | CLONE\_SIGNAL | CLONE\_SETTLS | CLONE\_PARENT\_SETTID | CLONE\_CHILD\_CLEARTID | CLONE\_SYSVSEM); Summary: the fork(),vfork() and clone() will create child processes with different mount of sharing resource with the father process. We also can say the vfork() and clone() can create threads(actually they are processes since they have independent task\_struct) since they share the VM page table with father process.
in fork(), either child or parent process will execute based on cpu selection.. But in vfork(), surely child will execute first. after child terminated, parent will execute.
4,856,255
I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls. I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ? `Fork` : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible). The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code. `Vfork`: The basic difference between `vfork()` and `fork()` is that when a new process is created with `vfork()`, the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls `execve()`, at which point the parent process continues. This means that the child process of a `vfork()` must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the `vfork()` call, and it must not call `exit()` (if it needs to exit, it should use `_exit()`; actually, this is also true for the child of a normal `fork()`). `Exec`: The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. `exec()` replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an `exec()` error. `Clone`: `clone()`, as `fork()`, creates a new process. Unlike `fork()`, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. When the child process is created with `clone()`, it executes the function application *fn(arg)* (This differs from `fork()`, where execution continues in the child from the point of the original `fork()` call.) The *fn* argument is a pointer to a function that is called by the child process at the beginning of its execution. The *arg* argument is passed to the *fn* function. When the *fn(arg)* function application returns, the child process terminates. The integer returned by *fn* is the exit code for the child process. The child process may also terminate explicitly by calling `exit(2)` or after receiving a fatal signal. Information gotten from: * [Differences between fork and exec](https://stackoverflow.com/questions/1653340/exec-and-fork) * <http://www.allinterview.com/showanswers/59616.html> * <http://www.unixguide.net/unix/programming/1.1.2.shtml> * <http://linux.about.com/library/cmd/blcmdl2_clone.htm> Thanks for taking the time to read this ! :)
2011/01/31
[ "https://Stackoverflow.com/questions/4856255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476033/" ]
1. `fork()` - creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW). 2. `vfork()` - creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call `fork()`, child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic `fork()`! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either `exec()` (create a new virtual address space and a transition to a different stack) or `_exit()` (termination of the process execution). `vfork()` is the optimization of `fork()` for "fork-and-exec" model. It can be performed 4-5 times faster than the `fork()`, because unlike the `fork()` (even with COW kept in the mind), implementation of `vfork()` system call does not include the creation of a new address space (the allocation and setting up of new page directories). 3. `clone()` - creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, `clone()` system call is the base which is used for the implementation of `pthread_create()` and all the family of the `fork()` system calls. 4. `exec()` - resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with `fork()` system call together form a classical UNIX process management model called "fork-and-exec".
in fork(), either child or parent process will execute based on cpu selection.. But in vfork(), surely child will execute first. after child terminated, parent will execute.
4,856,255
I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls. I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ? `Fork` : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible). The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code. `Vfork`: The basic difference between `vfork()` and `fork()` is that when a new process is created with `vfork()`, the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls `execve()`, at which point the parent process continues. This means that the child process of a `vfork()` must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the `vfork()` call, and it must not call `exit()` (if it needs to exit, it should use `_exit()`; actually, this is also true for the child of a normal `fork()`). `Exec`: The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. `exec()` replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an `exec()` error. `Clone`: `clone()`, as `fork()`, creates a new process. Unlike `fork()`, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. When the child process is created with `clone()`, it executes the function application *fn(arg)* (This differs from `fork()`, where execution continues in the child from the point of the original `fork()` call.) The *fn* argument is a pointer to a function that is called by the child process at the beginning of its execution. The *arg* argument is passed to the *fn* function. When the *fn(arg)* function application returns, the child process terminates. The integer returned by *fn* is the exit code for the child process. The child process may also terminate explicitly by calling `exit(2)` or after receiving a fatal signal. Information gotten from: * [Differences between fork and exec](https://stackoverflow.com/questions/1653340/exec-and-fork) * <http://www.allinterview.com/showanswers/59616.html> * <http://www.unixguide.net/unix/programming/1.1.2.shtml> * <http://linux.about.com/library/cmd/blcmdl2_clone.htm> Thanks for taking the time to read this ! :)
2011/01/31
[ "https://Stackoverflow.com/questions/4856255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476033/" ]
1. `fork()` - creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW). 2. `vfork()` - creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call `fork()`, child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic `fork()`! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either `exec()` (create a new virtual address space and a transition to a different stack) or `_exit()` (termination of the process execution). `vfork()` is the optimization of `fork()` for "fork-and-exec" model. It can be performed 4-5 times faster than the `fork()`, because unlike the `fork()` (even with COW kept in the mind), implementation of `vfork()` system call does not include the creation of a new address space (the allocation and setting up of new page directories). 3. `clone()` - creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, `clone()` system call is the base which is used for the implementation of `pthread_create()` and all the family of the `fork()` system calls. 4. `exec()` - resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with `fork()` system call together form a classical UNIX process management model called "fork-and-exec".
The fork(),vfork() and clone() all call the do\_fork() to do the real work, but with different parameters. ``` asmlinkage int sys_fork(struct pt_regs regs) { return do_fork(SIGCHLD, regs.esp, &regs, 0); } asmlinkage int sys_clone(struct pt_regs regs) { unsigned long clone_flags; unsigned long newsp; clone_flags = regs.ebx; newsp = regs.ecx; if (!newsp) newsp = regs.esp; return do_fork(clone_flags, newsp, &regs, 0); } asmlinkage int sys_vfork(struct pt_regs regs) { return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, regs.esp, &regs, 0); } #define CLONE_VFORK 0x00004000 /* set if the parent wants the child to wake it up on mm_release */ #define CLONE_VM 0x00000100 /* set if VM shared between processes */ SIGCHLD means the child should send this signal to its father when exit. ``` For fork, the child and father has the independent VM page table, but since the efficiency, fork will not really copy any pages, it just set all the writeable pages to readonly for child process. So when child process want to write something on that page, an page exception happen and kernel will alloc a new page cloned from the old page with write permission. That's called "copy on write". For vfork, the virtual memory is exactly by child and father---just because of that, father and child can't be awake concurrently since they will influence each other. So the father will sleep at the end of "do\_fork()" and awake when child call exit() or execve() since then it will own new page table. Here is the code(in do\_fork()) that the father sleep. ``` if ((clone_flags & CLONE_VFORK) && (retval > 0)) down(&sem); return retval; ``` Here is the code(in mm\_release() called by exit() and execve()) which awake the father. ``` up(tsk->p_opptr->vfork_sem); ``` For sys\_clone(), it is more flexible since you can input any clone\_flags to it. So pthread\_create() call this system call with many clone\_flags: int clone\_flags = (CLONE\_VM | CLONE\_FS | CLONE\_FILES | CLONE\_SIGNAL | CLONE\_SETTLS | CLONE\_PARENT\_SETTID | CLONE\_CHILD\_CLEARTID | CLONE\_SYSVSEM); Summary: the fork(),vfork() and clone() will create child processes with different mount of sharing resource with the father process. We also can say the vfork() and clone() can create threads(actually they are processes since they have independent task\_struct) since they share the VM page table with father process.
34,330,248
I am using Ionic framework to create an app like Meeting room booking for an organization.I am new to Ionic framework. I need you guys to help in the following thinks 1).Oauth for Google signin 2)access Google calendar by send request with access token 3)need to get the JSON response for request. 4)and also,Important think is need to get the resource calendar (rooms,Projectors etc.,) Please guide me how can i do that with Ionic framework.Still now I did not get any good tutorials. Thanks in Advance!!!!
2015/12/17
[ "https://Stackoverflow.com/questions/34330248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1901946/" ]
@arun, I have developed a small hybrid app using ionic2 and integrated google calendar in the app. You can see a quick demo of the app @ [Google calendar in Ionic 2 app demo on android device](https://www.youtube.com/watch?v=QSwbBQTiYaU). If this is what you are looking for, I believe the things you mentioned in the question which is google oauth login, accessing calendar and sending invites are covered. I am not sure whether you are developing using Ionic2. If yes please see the demo video and detailed steps. [Demo and steps to integrate google calendar in the Ionic 2 app](http://nishanthkabra.com/ionic2GoogleCalandar.html)
**Ionic framework** is integration of AngularJS which is best framework for cross platform. Which has large support of **ngCordova plugins**. I have some links for you 1. For Google oAuth - <http://blog.ionic.io/oauth-ionic-ngcordova/> 2. For Google calender - <http://www.raymondcamden.com/2015/09/18/integrating-the-calendar-into-your-ionic-app> You can refer Intel@XDK is one of the best tool. I used it to develop cross development app wich supports multiple frameworks with IONIC.
34,330,248
I am using Ionic framework to create an app like Meeting room booking for an organization.I am new to Ionic framework. I need you guys to help in the following thinks 1).Oauth for Google signin 2)access Google calendar by send request with access token 3)need to get the JSON response for request. 4)and also,Important think is need to get the resource calendar (rooms,Projectors etc.,) Please guide me how can i do that with Ionic framework.Still now I did not get any good tutorials. Thanks in Advance!!!!
2015/12/17
[ "https://Stackoverflow.com/questions/34330248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1901946/" ]
**Ionic framework** is integration of AngularJS which is best framework for cross platform. Which has large support of **ngCordova plugins**. I have some links for you 1. For Google oAuth - <http://blog.ionic.io/oauth-ionic-ngcordova/> 2. For Google calender - <http://www.raymondcamden.com/2015/09/18/integrating-the-calendar-into-your-ionic-app> You can refer Intel@XDK is one of the best tool. I used it to develop cross development app wich supports multiple frameworks with IONIC.
I have been looking for ages to integrate data from the google calendar into Ionic without any luck. I have now been able to integrate it into my ionic app through my backend in node.js, I advice you to do the same. This is the code I used in my backend ``` let eventCategories = require('./event.model'); let fs = require('fs'); let readline = require('readline'); let google = require('googleapis'); let googleAuth = require('google-auth-library'); // If modifying these scopes, delete your previously saved credentials // at ~/.credentials/calendar-nodejs-quickstart.json let SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']; let TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/'; let TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json'; module.exports = { getEventCategories, getEvents, setResponseStatus }; function getEventCategories(){ return eventCategories.find({}); } function getEvents(calendarId) { return loadClientSecrets() .then(res => authorize(JSON.parse(res)) .then(response => listEvents(response, calendarId))) } function loadClientSecrets(){ return new Promise(function (fulfill, reject){ fs.readFile('client_secret.json', function processClientSecrets(err, content){ if (err){ console.log('Error loading client secret file: '+ err); reject(err); } else fulfill(content); }) }) } /** * Create an OAuth2 client with the given credentials, and then execute the * given callback function. */ function authorize(credentials) { return new Promise(function (fulfill, reject){ let clientSecret = credentials.installed.client_secret; let clientId = credentials.installed.client_id; let redirectUrl = credentials.installed.redirect_uris[0]; let auth = new googleAuth(); let oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl); // Check if we have previously stored a token. fs.readFile(TOKEN_PATH, function(err, token) { if (err) { fulfill(getNewToken(oauth2Client)); } else { oauth2Client.credentials = JSON.parse(token); fulfill(oauth2Client); } }); }) } /** * Get and store new token after prompting for user authorization, and then * execute the given callback with the authorized OAuth2 client. */ function getNewToken(oauth2Client) { new Promise (function (fulfill, reject){ let authUrl = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: SCOPES }); console.log('Authorize this app by visiting this url: ', authUrl); let rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Enter the code from that page here: ', function(code) { rl.close(); oauth2Client.getToken(code, function(err, token) { if (err) { console.log('Error while trying to retrieve access token', err); reject(err); } oauth2Client.credentials = token; storeToken(token); fulfill(oauth2Client); }); }); }) } /** * Store token to disk be used in later program executions. */ function storeToken(token) { try { fs.mkdirSync(TOKEN_DIR); } catch (err) { if (err.code != 'EEXIST') { throw err; } } fs.writeFile(TOKEN_PATH, JSON.stringify(token)); console.log('Token stored to ' + TOKEN_PATH); } /** * Lists the next 10 events on the user's primary calendar. */ function listEvents(auth, calendarId) { return new Promise(function ( fulfill, reject){ var calendar = google.calendar('v3'); calendar.events.list({ auth: auth, calendarId: calendarId, timeMin: (new Date()).toISOString(), maxResults: 10, singleEvents: true, orderBy: 'startTime' }, function(err, response) { if (err) { console.log('The API returned an error: ' + err); reject(err); } var events = response.items; if (events.length == 0) { console.log('No upcoming events found.'); } else { console.log('Upcoming 10 events:'); for (var i = 0; i < events.length; i++) { var event = events[i]; var start = event.start.dateTime || event.start.date; console.log('%s - %s', start, event.summary); } // return events fulfill(events) } }); }) function setResponseStatus(){ } } ```
34,330,248
I am using Ionic framework to create an app like Meeting room booking for an organization.I am new to Ionic framework. I need you guys to help in the following thinks 1).Oauth for Google signin 2)access Google calendar by send request with access token 3)need to get the JSON response for request. 4)and also,Important think is need to get the resource calendar (rooms,Projectors etc.,) Please guide me how can i do that with Ionic framework.Still now I did not get any good tutorials. Thanks in Advance!!!!
2015/12/17
[ "https://Stackoverflow.com/questions/34330248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1901946/" ]
@arun, I have developed a small hybrid app using ionic2 and integrated google calendar in the app. You can see a quick demo of the app @ [Google calendar in Ionic 2 app demo on android device](https://www.youtube.com/watch?v=QSwbBQTiYaU). If this is what you are looking for, I believe the things you mentioned in the question which is google oauth login, accessing calendar and sending invites are covered. I am not sure whether you are developing using Ionic2. If yes please see the demo video and detailed steps. [Demo and steps to integrate google calendar in the Ionic 2 app](http://nishanthkabra.com/ionic2GoogleCalandar.html)
I have been looking for ages to integrate data from the google calendar into Ionic without any luck. I have now been able to integrate it into my ionic app through my backend in node.js, I advice you to do the same. This is the code I used in my backend ``` let eventCategories = require('./event.model'); let fs = require('fs'); let readline = require('readline'); let google = require('googleapis'); let googleAuth = require('google-auth-library'); // If modifying these scopes, delete your previously saved credentials // at ~/.credentials/calendar-nodejs-quickstart.json let SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']; let TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/'; let TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json'; module.exports = { getEventCategories, getEvents, setResponseStatus }; function getEventCategories(){ return eventCategories.find({}); } function getEvents(calendarId) { return loadClientSecrets() .then(res => authorize(JSON.parse(res)) .then(response => listEvents(response, calendarId))) } function loadClientSecrets(){ return new Promise(function (fulfill, reject){ fs.readFile('client_secret.json', function processClientSecrets(err, content){ if (err){ console.log('Error loading client secret file: '+ err); reject(err); } else fulfill(content); }) }) } /** * Create an OAuth2 client with the given credentials, and then execute the * given callback function. */ function authorize(credentials) { return new Promise(function (fulfill, reject){ let clientSecret = credentials.installed.client_secret; let clientId = credentials.installed.client_id; let redirectUrl = credentials.installed.redirect_uris[0]; let auth = new googleAuth(); let oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl); // Check if we have previously stored a token. fs.readFile(TOKEN_PATH, function(err, token) { if (err) { fulfill(getNewToken(oauth2Client)); } else { oauth2Client.credentials = JSON.parse(token); fulfill(oauth2Client); } }); }) } /** * Get and store new token after prompting for user authorization, and then * execute the given callback with the authorized OAuth2 client. */ function getNewToken(oauth2Client) { new Promise (function (fulfill, reject){ let authUrl = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: SCOPES }); console.log('Authorize this app by visiting this url: ', authUrl); let rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Enter the code from that page here: ', function(code) { rl.close(); oauth2Client.getToken(code, function(err, token) { if (err) { console.log('Error while trying to retrieve access token', err); reject(err); } oauth2Client.credentials = token; storeToken(token); fulfill(oauth2Client); }); }); }) } /** * Store token to disk be used in later program executions. */ function storeToken(token) { try { fs.mkdirSync(TOKEN_DIR); } catch (err) { if (err.code != 'EEXIST') { throw err; } } fs.writeFile(TOKEN_PATH, JSON.stringify(token)); console.log('Token stored to ' + TOKEN_PATH); } /** * Lists the next 10 events on the user's primary calendar. */ function listEvents(auth, calendarId) { return new Promise(function ( fulfill, reject){ var calendar = google.calendar('v3'); calendar.events.list({ auth: auth, calendarId: calendarId, timeMin: (new Date()).toISOString(), maxResults: 10, singleEvents: true, orderBy: 'startTime' }, function(err, response) { if (err) { console.log('The API returned an error: ' + err); reject(err); } var events = response.items; if (events.length == 0) { console.log('No upcoming events found.'); } else { console.log('Upcoming 10 events:'); for (var i = 0; i < events.length; i++) { var event = events[i]; var start = event.start.dateTime || event.start.date; console.log('%s - %s', start, event.summary); } // return events fulfill(events) } }); }) function setResponseStatus(){ } } ```
45,697,404
I have two SQL Server 2008 R2 servers one for PROD and the other for DR. I am trying to add log shipping for a database called School. Steps so far * Back up School database * Restore with database using the UI or using the following SQL statement i.e. ``` Restore database "School" From disk ='t:\Data\School.bak' with NoRecovery ``` * The result is database is stuck in Restoring * If I restore the database with ``` Restore database "School" From disk ='t:\Data\School.bak' With recovery ``` The database restore completes but the log shipping fails. * I have deleted the database and recreated it again using ``` Restore database "School" From disk ='t:\Data\School.bak' With **NoRecovery** ``` but it is still stuck in **Restoring state**. Is there a way that I can restore the database without having the database been stuck in the restoring state.
2017/08/15
[ "https://Stackoverflow.com/questions/45697404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1339913/" ]
This seems like expected behavior to me. Am I misreading something? After you've restored the database and any differential or required transaction log backups with the `NORECOVERY` option, you need to tell SQL Server you're done restoring files. The `NORECOVERY` option is specifically there to let you restore multiple files. You should just need to run: ``` RESTORE DATABASE [School] WITH RECOVERY; ``` That will tell SQL Server you're done, and it will complete the restoration and it will no longer show up as restoring.
> > I have deleted the database and recreated it again using Restore database "School" from disk ='t:\Data\School.bak' with NoRecovery > > > you have to use below command as well,if you dont have any further logs ``` restore database databasename with recovery ``` **some more info:** > > Restore with database using the UI or using the following SQL statement i.e. > > > next time try to issue restore statement using tsql,so that you can know status ``` restore database databasename from disk="path" with stats=5 ``` now if you want to know indepth details on where it is and what it is doing,you can use a trace flag like below ``` dbcc traceon(3004,3605,-1) GO restore database databasename from disk="path" with stats=5 ``` this logs output to errorlog like below > > 2008-01-23 08:59:56.26 spid52 RestoreDatabase: Database dbPerf\_MAIN > > 2008-01-23 08:59:56.26 spid52 Opening backup set > > 2008-01-23 08:59:56.31 spid52 Restore: Configuration section loaded2008-01-23 08:59:56.31 spid52 Restore: Backup set is open > > 2008-01-23 08:59:56.31 spid52 Restore: Planning begins > > 2008-01-23 08:59:56.32 spid52 Halting FullText crawls on database dbPerf\_MAIN > > 2008-01-23 08:59:56.32 spid52 Dismounting FullText catalogs > > 2008-01-23 08:59:56.32 spid52 X-locking database: dbPerf\_MAIN > > 2008-01-23 08:59:56.32 spid52 Restore: Planning complete > > 2008-01-23 08:59:56.32 spid52 Restore: BeginRestore (offline) on dbPerf\_MAIN > > 2008-01-23 08:59:56.40 spid52 Restore: PreparingContainers > 2008-01-23 08:59:56.43 spid52 Restore: Containers are ready > > > For your current problem, you can look at event log as it will log current phase > > Is there a way that I can restore the database without having the database been stuck in the restoring state. > > > you will have to get the spid of the backup and see the wait type and troubleshoot accordingly ``` select * from sys.dm_Exec_requests where sessionid=backupspid ```
68,197,195
I am trying follow this tutorial: <https://html.form.guide/email-form/php-form-to-email/> to deploy a simple php script to google App Engine. I want to load the form from localhost and post to the app engine link. When I do, the `$_POST` is empty. Is this an issue when posting from another server/localhost to an app-engine hosted service? Code: app.yaml: ``` runtime: php55 api_version: 1 threadsafe: true handlers: - url: .* script: formemailer.php ``` php script: ``` <?php if(!isset($_POST['submit'])) { echo "error; you need to submit the form!"; } ?> ``` Form: ``` <form method="post" action="https://<url>.appspot.com/formemailer.php"> <p> <label for='name'>Enter Name: </label><br> <input type="text" name="name"> </p> <input type="submit" name="submit" value="submit" /> </form> ```
2021/06/30
[ "https://Stackoverflow.com/questions/68197195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1803682/" ]
you can post data to another server by writing the true url if your url was ok the post data must be passed but if you checked your url and it's true but you still have a problem you can use api calls to do that by ``` header('Content-Type: application/json'); $data = json_decode(file_get_contents("php://input")); header("Content-Type: application/json"); $name = $data->name; $to = "[email protected]"; $message = $name . "hiii"; $subject = "test mail"; mail($to, $message, $subject); ``` by doing this you can make a api call with curl to do the mail function and pass the information from the server by curl request i hope you find this answer helpful and if `mail()` function didn't worked for you or gave you an error you can try phpmailer if you have any questions you can comment and i will answer them
appspot.com has been the host to a lot of fishing attacks. It is likely blocked as a safety issue.
68,197,195
I am trying follow this tutorial: <https://html.form.guide/email-form/php-form-to-email/> to deploy a simple php script to google App Engine. I want to load the form from localhost and post to the app engine link. When I do, the `$_POST` is empty. Is this an issue when posting from another server/localhost to an app-engine hosted service? Code: app.yaml: ``` runtime: php55 api_version: 1 threadsafe: true handlers: - url: .* script: formemailer.php ``` php script: ``` <?php if(!isset($_POST['submit'])) { echo "error; you need to submit the form!"; } ?> ``` Form: ``` <form method="post" action="https://<url>.appspot.com/formemailer.php"> <p> <label for='name'>Enter Name: </label><br> <input type="text" name="name"> </p> <input type="submit" name="submit" value="submit" /> </form> ```
2021/06/30
[ "https://Stackoverflow.com/questions/68197195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1803682/" ]
> > Is this an issue when posting from another server/localhost to an app-engine hosted service? > > > No, the server receives the POST request as it is send. And yes, as you have an issue doing so. --- It should work, but what to do now? Verify with the networking tools in your browser what is actually send to the server. This might already give you some more insights. The networking tools are nowadays with your browser, please see: * Chrome (or Chromium, Vivaldi etc.): [Inspect network activity](https://developer.chrome.com/docs/devtools/network/) * Firefox: [Network Monitor](https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor) or the documentation of your browser. --- For a PHP 5 application running on *Google App Engine* you can find a dedicated tutorial handling form input at: * [Handling User Input in Forms](https://cloud.google.com/appengine/docs/standard/php/getting-started/handling-user-input-in-forms) However *strongly* recommended is (not only on App Engine but in general) to use the PHP 7 runtime. This *should* be independent to your problem, however better start with PHP 7 from the beginning (if you allow me this comment). The general information (also for PHP 5 and 7) is available here: * [How Requests are Handled](https://cloud.google.com/appengine/docs/standard/php/how-requests-are-handled) If you would like to learn about how PHP in general handles this, independent to any platform, you can find it outlined in the PHP manual here: * [Dealing with Forms](https://www.php.net/manual/en/tutorial.forms.php) * [Variables From External Sources](https://www.php.net/manual/en/language.variables.external.php) For the general handling in browsers for what you ask for - the form on one host (or even a HTML file locally) posting to another host, please see this related Q/A: * [Cross Domain Form POSTing](https://stackoverflow.com/q/11423682/367456)
appspot.com has been the host to a lot of fishing attacks. It is likely blocked as a safety issue.
31,192,751
Example Of Data: ``` <property> <price>2080000</price> <country>France</country> <currency>euro</currency> <locations> <location_9>Ski</location_9> <location_16>50km or less to airport</location_16> <location_17>0-2KM to amenities</location_17> </locations> <secondaryproptypes> <secondaryproptypes_1>Holiday Home</secondaryproptypes_1> </secondaryproptypes> <features> <features_30>Woodburner(s)</features_30> <features_9>Private parking</features_9> <features_23>Mountain view</features_23> <features_2>Mains Drains</features_2> </features> ``` Example Of Property Class: ``` public class Property { public decimal price { get; set; } public string country { get; set; } public string currency { get; set; } public List<Location> locations { get; set; } } ``` Example of Locations Class: ``` public class Location { public string location { get; set; } } ``` Main Code: (Also tried many derivatives, but this is how it stands when I gave up) ``` public void LoadXMLURL() { XDocument document = XDocument.Load("file.xml"); var properties = (from p in document.Root.Elements("property") select new Property { price = Convert.ToDecimal(p.Element("price").Value), country = p.Element("country").Value, currency = p.Element("currency").Value, locations = new List<Location>(from l in p.Descendants("location") select new Location { location = (string)l }) } ).ToList(); ``` I did try a number of ways of storing the list of location data nodes. Such as arrays and other lists. Now I think my main issue is that because the nodes are varying; "location\_9" "location\_16" I cannot specify the nodes to look at, as strictly as I could with the previous nodes.
2015/07/02
[ "https://Stackoverflow.com/questions/31192751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3461845/" ]
``` var arr = [ "10Regular", "18Regular", "14Long", "14Regular", "10Long", "16Long", "12Long", "20Regular", "16Regular", "12Regular", "18Long" ]; var trimmedAndSorted = arr.map(function(e) { return e.replace(/(\d+[a-z]).*/i, '$1'); }).sort(); ``` Got a downvote so I assume there is a syntax error, but I tested with [a JSFiddle and it appears to work](https://jsfiddle.net/s06pbzgz/2/).
If you just want to sort them using the numbers in front, regardless of the letters that come after them, given `arr` as you array: ``` arr.map(function(entry){ // extract the number and first letter as [number, letter] return entry.match(/^(\d+)(.{1})/).slice(1) }).sort(function(a, b){ // Sort the array by the number part return +a[0] - +b[0]; }).map(function(entry){ // Join the two parts return entry.join(''); }); // ["10R", "10L", "12R", "12L", "14L", "14R", "16L", "16R", "18R", "18L", "20R"] ```
31,192,751
Example Of Data: ``` <property> <price>2080000</price> <country>France</country> <currency>euro</currency> <locations> <location_9>Ski</location_9> <location_16>50km or less to airport</location_16> <location_17>0-2KM to amenities</location_17> </locations> <secondaryproptypes> <secondaryproptypes_1>Holiday Home</secondaryproptypes_1> </secondaryproptypes> <features> <features_30>Woodburner(s)</features_30> <features_9>Private parking</features_9> <features_23>Mountain view</features_23> <features_2>Mains Drains</features_2> </features> ``` Example Of Property Class: ``` public class Property { public decimal price { get; set; } public string country { get; set; } public string currency { get; set; } public List<Location> locations { get; set; } } ``` Example of Locations Class: ``` public class Location { public string location { get; set; } } ``` Main Code: (Also tried many derivatives, but this is how it stands when I gave up) ``` public void LoadXMLURL() { XDocument document = XDocument.Load("file.xml"); var properties = (from p in document.Root.Elements("property") select new Property { price = Convert.ToDecimal(p.Element("price").Value), country = p.Element("country").Value, currency = p.Element("currency").Value, locations = new List<Location>(from l in p.Descendants("location") select new Location { location = (string)l }) } ).ToList(); ``` I did try a number of ways of storing the list of location data nodes. Such as arrays and other lists. Now I think my main issue is that because the nodes are varying; "location\_9" "location\_16" I cannot specify the nodes to look at, as strictly as I could with the previous nodes.
2015/07/02
[ "https://Stackoverflow.com/questions/31192751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3461845/" ]
``` var arr = [ "10Regular", "18Regular", "14Long", "14Regular", "10Long", "16Long", "12Long", "20Regular", "16Regular", "12Regular", "18Long" ]; var trimmedAndSorted = arr.map(function(e) { return e.replace(/(\d+[a-z]).*/i, '$1'); }).sort(); ``` Got a downvote so I assume there is a syntax error, but I tested with [a JSFiddle and it appears to work](https://jsfiddle.net/s06pbzgz/2/).
Define a sorting function, that takes functions for augmented sorting --------------------------------------------------------------------- My favorite sorting function (which is more versatile than needed for just this task) can sort arrays of values or objects of any nested depth and accepts an optional function for priming the value, and an optional function for secondary "then by" sorting. **Sort by, then by function:** ``` var by = function (path, reverse, primer, then) { // Light weight json deep access var get = function (obj, path) { if (path) { path = path.split('.'); for (var i = 0, len = path.length - 1; i < len; i++) { obj = obj[path[i]]; }; return obj[path[len]]; } return obj; }, // Invokes primer function if provided prime = function (obj) { return primer ? primer(get(obj, path)) : get(obj, path); }; // Actual sorting function to be returned to native .sort method return function (a, b) { var A = prime(a), B = prime(b); return ( (A < B) ? -1 : (A > B) ? 1 : // If A == B, then sort by supplemental 'by' function received as 'then' (typeof then === 'function') ? then(a, b) : 0 ) * [1,-1][+!!reverse]; }; }; ``` *Acknowledgement: The above function is my fork of a function that I found as a response to this [Stack Overflow question](https://stackoverflow.com/a/979325/2502532).* **Basic usage:** ``` array.sort( by(path[, reverse[, primer[, then]]]) ); ``` **Example usage with your array:** ``` /* THE ARRAY */ var arr = ["10Regular", "18Regular", "14Long", "14Regular", "10Long", "16Long", "12Long", "20Regular", "16Regular", "12Regular", "18Long"]; /* THE EXAMPLE */ arr.sort( by(null, false, function (x) { // Primer var y = x.substr(0,2); return parseFloat(y); }, by(null, false, // Secondary "then by" sort function (x) { // Primer var y = x.substr(2); return y; } ) ) ); ``` The idea here is to split your value into the two parts by which you wish to sort it. Assuming that your string values will always begin with two-digit numbers, we define a priming function that uses `.substr` to return just the first two digits. This primed value gets passed along to the return function in the closure just for the comparison, while preserving the original value to be sorted. We then define a secondary "then by" sorting function which takes the same form as the first (you just pass in another instance of `by()`). In this secondary `by()` function, we define another priming function that uses `.substr` again to return the second half of the string. **Complete working example with output:** ```js /* THE FUNCTION */ var by = function (path, reverse, primer, then) { // Light weight json deep access var get = function (obj, path) { if (path) { path = path.split('.'); for (var i = 0, len = path.length - 1; i < len; i++) { obj = obj[path[i]]; }; return obj[path[len]]; } return obj; }, // Invokes primer function if provided prime = function (obj) { return primer ? primer(get(obj, path)) : get(obj, path); }; // Actual sorting function to be returned to native .sort method return function (a, b) { var A = prime(a), B = prime(b); return ( (A < B) ? -1 : (A > B) ? 1 : // If A == B, then sort by supplemental 'by' function received as 'then' (typeof then === 'function') ? then(a, b) : 0 ) * [1,-1][+!!reverse]; }; }; /* THE ARRAY */ var arr = ["10Regular", "18Regular", "14Long", "14Regular", "10Long", "16Long", "12Long", "20Regular", "16Regular", "12Regular", "18Long"]; /* THE EXAMPLE */ arr.sort( by(null, false, function (x) { var y = x.substr(0,2); return parseFloat(y); }, by(null, false, function (x) { var y = x.substr(2); return y; } ) ) ); // Output var t1 = document.getElementById('t1'); t1.innerHTML += '<caption>Sort by, then by</caption>'; for (var i = 0; i < arr.length; i++) { t1.innerHTML += '<tr><td>' + arr[i] + '</td></tr>'; } ``` ```css html { font: normal 62.5% Arial, sans-serif; } body { padding: 10px; } table { font-size: 1.3em; margin-bottom: 18px; width: 50%; border: none; } table caption { font-weight: bold; font-size: 1.5rem; } table td { color: #333; padding: 9px; vertical-align: middle; text-align: left; line-height: 1em; border-bottom: 1px solid #bcbec0; font: normal 1.3em monospace; } ``` ```html <table id="t1"></table> ```
27,768,143
I tried to solve this with logarithm rules: O(n^2) = 2^O(log(n^2)) c\*n^2 = 2^log(n^2c) Im not sure that is true?
2015/01/04
[ "https://Stackoverflow.com/questions/27768143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3630497/" ]
I solved this error changing the initial project to the Entity Project. Look: Update-Database -Verbose **Using StartUp project 'SCVE.Web'.** <-- this ir error Using NuGet project 'SCVE.EntityFramework'.
I had this same problem with a freshly created ASP.NET project. First I tried to set the startup project as mentioned above. There was no startup project selected and I was unable to select one. Ultimately I updated my Visual Studio from 2015 Update 1 to 2015 Update 3 and ``` update-database ``` executed without problems.
27,768,143
I tried to solve this with logarithm rules: O(n^2) = 2^O(log(n^2)) c\*n^2 = 2^log(n^2c) Im not sure that is true?
2015/01/04
[ "https://Stackoverflow.com/questions/27768143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3630497/" ]
As explained in other answers, the problem usually comes from having the wrong Initial project in Package Manager Console. In my case the console was ignoring the value I selected in the Default Project drop down list, and also the `-StartUpProjectName` parameter, and reproducing the wrong behavior of trying to connect to some default database engine, as Mikk's answer describes, in my case using a SqlExpress engine. My problem was caused by a wrong solution configuration: if your solution has several projects and is meant to be run with the configuration option "Multiple startup projects", but you just downloaded it from your source code control repository, then it is possible that the default configuration option "Single startup project" is being applied to the solution (this config value usually is not checked-in in the source code control). In this case the Package Manager Console just ignores the startup project selected in its combo and just applies the default startup project in the solution, which may not have a connection string, as specified in Mikk's answer. So I fixed it by changing the solution properties: `Common properties` / `Startup project` / Select `Multiple startup projects` instead of `Single startup project`, and after that the Package Manager Console would accept the Project name and update the right database.
Try with this Connectionstring: ``` <connectionStrings> <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=D:\USERS\USERNAME\DOCUMENTS\TestDatabase\testdb.MDF;Initial Catalog=testdb;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> ```
27,768,143
I tried to solve this with logarithm rules: O(n^2) = 2^O(log(n^2)) c\*n^2 = 2^log(n^2c) Im not sure that is true?
2015/01/04
[ "https://Stackoverflow.com/questions/27768143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3630497/" ]
Try with this Connectionstring: ``` <connectionStrings> <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=D:\USERS\USERNAME\DOCUMENTS\TestDatabase\testdb.MDF;Initial Catalog=testdb;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> ```
``` PM>Update-Database ``` error and solution which I did today in 4 hours. I am very much new in .net coding, but yes in PHP I have 10+ years experience. It took me 4 hours to solve this. 1.My `first Mistake:` I was not having Microsoft SQL Server 2019 in my laptop locally I was having this through AZURE which is not works for localhost, so I installed this locally after download, it took around 2 Hours. 2.Second changed mistake= ``` "DevConnection": "Server=localhost;Database=PaymentDetailDB;Trusted_Connection=True;MultipleActiveResultSets=True;" ``` then it works for me [![Error](https://i.stack.imgur.com/o27EE.png)](https://i.stack.imgur.com/o27EE.png) [![Error solution](https://i.stack.imgur.com/BUu02.png)](https://i.stack.imgur.com/BUu02.png) [![Error solved](https://i.stack.imgur.com/AZNnU.png)](https://i.stack.imgur.com/AZNnU.png) [![After error solved database](https://i.stack.imgur.com/eJzul.png)](https://i.stack.imgur.com/eJzul.png)
27,768,143
I tried to solve this with logarithm rules: O(n^2) = 2^O(log(n^2)) c\*n^2 = 2^log(n^2c) Im not sure that is true?
2015/01/04
[ "https://Stackoverflow.com/questions/27768143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3630497/" ]
As explained in other answers, the problem usually comes from having the wrong Initial project in Package Manager Console. In my case the console was ignoring the value I selected in the Default Project drop down list, and also the `-StartUpProjectName` parameter, and reproducing the wrong behavior of trying to connect to some default database engine, as Mikk's answer describes, in my case using a SqlExpress engine. My problem was caused by a wrong solution configuration: if your solution has several projects and is meant to be run with the configuration option "Multiple startup projects", but you just downloaded it from your source code control repository, then it is possible that the default configuration option "Single startup project" is being applied to the solution (this config value usually is not checked-in in the source code control). In this case the Package Manager Console just ignores the startup project selected in its combo and just applies the default startup project in the solution, which may not have a connection string, as specified in Mikk's answer. So I fixed it by changing the solution properties: `Common properties` / `Startup project` / Select `Multiple startup projects` instead of `Single startup project`, and after that the Package Manager Console would accept the Project name and update the right database.
> > A network-related or instance-specific error occurred while > establishing a connection to SQL Server. The server was not found or > was not accessible. Verify that the instance name is correct and that > SQL Server is configured to allow remote connections. (provider: SQL > Network Interfaces, error: 26 - Error Locating Server/Instance > Specified) > > > This error message informs you that it is not possible to connect to `SQL Server`. The possible reasons and their elimination is described below: 1) SQL Server is not started. Starting of it will allow you to see your SQL Server/instance in the drop-down list of available SQL Servers. * Go to the Start menu -> Control Panel -> Administration Tools -> Services. * In the list of services find SQL Server (instance name, by default it is EZPARTS5) and check its status, it must be Started (if it is not started, then right click on SQL Server and select Start from the context menu). 2) Firewall is blocking port 1433 (MSSQL standard port for connections). It can be disabled following the steps below: * Go to the Start menu -> Control Panel -> Administration Tools -> Services. * Find Firewall service, it must be disabled (if it is not, then right click the service and select Stop from the context menu). Note: More information on this can be found on the official Microsoft site: [***Link***](http://msdn.microsoft.com/en-us/library/cc646023.aspx) 3) TCP/IP protocol is disabled for MSSQL protocols. To enable it, see the steps below: * Navigate to SQL Server Configuration Manager in the Start menu. * Specify settings for TCP/IP protocol in SQL Server Configuration Manager. * Restart the computer. Note: More information on this can be found on the official Microsoft site: [***Link***](http://msdn.microsoft.com/en-us/library/bb909712%28v=vs.90%29.aspx) 4) Make sure your database engine is configured to accept remote connections (If you are using centralized database): * Open SQL Server Management Studio. * Right click SQL Server instance -> Properties -> Connections -> Check the Allow remote connections to this server box. * Go to the General section and check name of SQL Server specified in the Name field. 5) If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings. Usually the format needed to specify the database server is machinename\instancename. 6) Make sure your login account has access permission on the database you used during login. Alternative: If you still can’t get any connection, you may want to create a SQL account on the server, a corresponding SQL user on the database in question, and just use this username/password login data to connect to SQL Server. Referred from this [***link***](http://support.sysonline.com/support/articles/4000016491-errmsg-a-network-related-or-instance-specific-error-occurred-while-establishing-a-connection-to-sql)
27,768,143
I tried to solve this with logarithm rules: O(n^2) = 2^O(log(n^2)) c\*n^2 = 2^log(n^2c) Im not sure that is true?
2015/01/04
[ "https://Stackoverflow.com/questions/27768143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3630497/" ]
As explained in other answers, the problem usually comes from having the wrong Initial project in Package Manager Console. In my case the console was ignoring the value I selected in the Default Project drop down list, and also the `-StartUpProjectName` parameter, and reproducing the wrong behavior of trying to connect to some default database engine, as Mikk's answer describes, in my case using a SqlExpress engine. My problem was caused by a wrong solution configuration: if your solution has several projects and is meant to be run with the configuration option "Multiple startup projects", but you just downloaded it from your source code control repository, then it is possible that the default configuration option "Single startup project" is being applied to the solution (this config value usually is not checked-in in the source code control). In this case the Package Manager Console just ignores the startup project selected in its combo and just applies the default startup project in the solution, which may not have a connection string, as specified in Mikk's answer. So I fixed it by changing the solution properties: `Common properties` / `Startup project` / Select `Multiple startup projects` instead of `Single startup project`, and after that the Package Manager Console would accept the Project name and update the right database.
I had this same problem with a freshly created ASP.NET project. First I tried to set the startup project as mentioned above. There was no startup project selected and I was unable to select one. Ultimately I updated my Visual Studio from 2015 Update 1 to 2015 Update 3 and ``` update-database ``` executed without problems.
27,768,143
I tried to solve this with logarithm rules: O(n^2) = 2^O(log(n^2)) c\*n^2 = 2^log(n^2c) Im not sure that is true?
2015/01/04
[ "https://Stackoverflow.com/questions/27768143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3630497/" ]
I solved this error changing the initial project to the Entity Project. Look: Update-Database -Verbose **Using StartUp project 'SCVE.Web'.** <-- this ir error Using NuGet project 'SCVE.EntityFramework'.
If you are trying to connect to Sql Server instead of localdb then make sure the default connection factory in web.config file is as below: ``` <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"> <parameters> <parameter value="Data Source=.\SQLEXPRESS2012; Integrated Security=True; MultipleActiveResultSets=True" /> </parameters> </defaultConnectionFactory> ```
27,768,143
I tried to solve this with logarithm rules: O(n^2) = 2^O(log(n^2)) c\*n^2 = 2^log(n^2c) Im not sure that is true?
2015/01/04
[ "https://Stackoverflow.com/questions/27768143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3630497/" ]
I had similar problem and fixed it when I changed the "start-up project" from another module to the module containing references to all other projects in the solution. Right-click module >> click "Set as StartUp Project"
Diego's answer is correct. This problem occurs when there is no connection string in project marked as startup project. Then EF tries to connect to some default database engine to perform update. In my case it tried to use express, and for some reason it couldn't connect. And the error was thrown. Run your "update-database" with option "-Verbose". One of the lines there shows which StartUp project is used. Check your connection string in this project, or change the startup project to the one that has correct connection string. That solves the problem.
27,768,143
I tried to solve this with logarithm rules: O(n^2) = 2^O(log(n^2)) c\*n^2 = 2^log(n^2c) Im not sure that is true?
2015/01/04
[ "https://Stackoverflow.com/questions/27768143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3630497/" ]
Diego's answer is correct. This problem occurs when there is no connection string in project marked as startup project. Then EF tries to connect to some default database engine to perform update. In my case it tried to use express, and for some reason it couldn't connect. And the error was thrown. Run your "update-database" with option "-Verbose". One of the lines there shows which StartUp project is used. Check your connection string in this project, or change the startup project to the one that has correct connection string. That solves the problem.
``` PM>Update-Database ``` error and solution which I did today in 4 hours. I am very much new in .net coding, but yes in PHP I have 10+ years experience. It took me 4 hours to solve this. 1.My `first Mistake:` I was not having Microsoft SQL Server 2019 in my laptop locally I was having this through AZURE which is not works for localhost, so I installed this locally after download, it took around 2 Hours. 2.Second changed mistake= ``` "DevConnection": "Server=localhost;Database=PaymentDetailDB;Trusted_Connection=True;MultipleActiveResultSets=True;" ``` then it works for me [![Error](https://i.stack.imgur.com/o27EE.png)](https://i.stack.imgur.com/o27EE.png) [![Error solution](https://i.stack.imgur.com/BUu02.png)](https://i.stack.imgur.com/BUu02.png) [![Error solved](https://i.stack.imgur.com/AZNnU.png)](https://i.stack.imgur.com/AZNnU.png) [![After error solved database](https://i.stack.imgur.com/eJzul.png)](https://i.stack.imgur.com/eJzul.png)
27,768,143
I tried to solve this with logarithm rules: O(n^2) = 2^O(log(n^2)) c\*n^2 = 2^log(n^2c) Im not sure that is true?
2015/01/04
[ "https://Stackoverflow.com/questions/27768143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3630497/" ]
As explained in other answers, the problem usually comes from having the wrong Initial project in Package Manager Console. In my case the console was ignoring the value I selected in the Default Project drop down list, and also the `-StartUpProjectName` parameter, and reproducing the wrong behavior of trying to connect to some default database engine, as Mikk's answer describes, in my case using a SqlExpress engine. My problem was caused by a wrong solution configuration: if your solution has several projects and is meant to be run with the configuration option "Multiple startup projects", but you just downloaded it from your source code control repository, then it is possible that the default configuration option "Single startup project" is being applied to the solution (this config value usually is not checked-in in the source code control). In this case the Package Manager Console just ignores the startup project selected in its combo and just applies the default startup project in the solution, which may not have a connection string, as specified in Mikk's answer. So I fixed it by changing the solution properties: `Common properties` / `Startup project` / Select `Multiple startup projects` instead of `Single startup project`, and after that the Package Manager Console would accept the Project name and update the right database.
``` PM>Update-Database ``` error and solution which I did today in 4 hours. I am very much new in .net coding, but yes in PHP I have 10+ years experience. It took me 4 hours to solve this. 1.My `first Mistake:` I was not having Microsoft SQL Server 2019 in my laptop locally I was having this through AZURE which is not works for localhost, so I installed this locally after download, it took around 2 Hours. 2.Second changed mistake= ``` "DevConnection": "Server=localhost;Database=PaymentDetailDB;Trusted_Connection=True;MultipleActiveResultSets=True;" ``` then it works for me [![Error](https://i.stack.imgur.com/o27EE.png)](https://i.stack.imgur.com/o27EE.png) [![Error solution](https://i.stack.imgur.com/BUu02.png)](https://i.stack.imgur.com/BUu02.png) [![Error solved](https://i.stack.imgur.com/AZNnU.png)](https://i.stack.imgur.com/AZNnU.png) [![After error solved database](https://i.stack.imgur.com/eJzul.png)](https://i.stack.imgur.com/eJzul.png)
27,768,143
I tried to solve this with logarithm rules: O(n^2) = 2^O(log(n^2)) c\*n^2 = 2^log(n^2c) Im not sure that is true?
2015/01/04
[ "https://Stackoverflow.com/questions/27768143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3630497/" ]
Diego's answer is correct. This problem occurs when there is no connection string in project marked as startup project. Then EF tries to connect to some default database engine to perform update. In my case it tried to use express, and for some reason it couldn't connect. And the error was thrown. Run your "update-database" with option "-Verbose". One of the lines there shows which StartUp project is used. Check your connection string in this project, or change the startup project to the one that has correct connection string. That solves the problem.
Try with this Connectionstring: ``` <connectionStrings> <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=D:\USERS\USERNAME\DOCUMENTS\TestDatabase\testdb.MDF;Initial Catalog=testdb;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> ```
70,189,729
I am just looking at assertDoesNotThrow() in the JUnit documentation [here](https://junit.org/junit5/docs/5.3.0/api/org/junit/jupiter/api/Assertions.html#assertDoesNotThrow(org.junit.jupiter.api.function.Executable)). I know that you can specify the type of exception with assertThrows() but it appears from the documentation that you cannot do that with assertDoesNotThrow(). Is there a particular reason for that? If you wanted to show that, for example, a method does not throw a ParseException, how would you go about doing that? Edit: I should have put "does not throw a ParseException when given a particular argument e.g. "hello".
2021/12/01
[ "https://Stackoverflow.com/questions/70189729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10957099/" ]
The *default* for a Java test is that it asserts that the function doesn't throw. You don't need to do any extra work for that; you only need to do extra work to allow it to throw. To test that a method does not throw a `ParseException`, run it. That's all.
Trying to prove a method does not throw exception is like saying purple unicorns don't exist. One has to check every spot in the universe to prove that. On the other hand if you check the spots where purple unicorns might live and don't see any of them, you can *approximate* and tell they don't exist in this context. So while testing methods to see if they behave as expected, you test edge cases, boundary conditions. And for some of those cases you expect your method to throw exceptions, hence the `assertThrows()`. Other than that it's not possible/meaningless to try to prove a method does not throw exceptions in Java. Because you can't prove a method is pure, i.e. it will behave exactly same every time you run it.
151,687
I have a Query String (URL) filter on my SharePoint 2013 page that is currently passing a string parameter which I then use to filter a list. This list is displayed in a view on my web part page. I want to add a "Title" object above my list view to show the value of the filter parameter that I'm passing to filter the list. Does anyone know how I can do this? I looked through the web part options that were available to add, and couldn't find one to simply display the result of the query string filter.
2015/08/07
[ "https://sharepoint.stackexchange.com/questions/151687", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/44915/" ]
The Author column is of `LookUp` Type. Here is the complete list. ``` var ctx = new SP.ClientContext.get_current(); var list = ctx.get_web().get_lists().getByTitle("Vacation Replacement"); var query = new SP.CamlQuery(); var specifier = "<Where><Eq><FieldRef Name='Author' LookupId='True'/><Value Type='Lookup'><UserID/></Value></Eq></Where>"; query.set_viewXml("<View><Query>"+specifier+"</Query></View>"); var collListItems = list.getItems(query); ctx.load(collListItems); ctx.executeQueryAsync( function(){ var enumerator = collListItems.getEnumerator(); while(enumerator.moveNext()){ var item = enumerator.get_current(); alert("ID : " + item.get_id()); } }, function(sender,args){ alert("Request Failed."+args.get_message() + "\n" + args.get_stackTrace()); } ); ```
Create a custom view of the list and select radio button Show items only when the following is true: created by is equal to type [Me] save the list. [![enter image description here](https://i.stack.imgur.com/otAZa.png)](https://i.stack.imgur.com/otAZa.png) ``` function getItemsFromView() { var context = new SP.ClientContext.get_current(); var list = context.get_web().get_lists().getByTitle('ListName'); var view = list.get_views().getByTitle('CustomViewName'); context.load(view); context.executeQueryAsync( function(sender, args) {OnSuccess("<View><Query>" + view.get_viewQuery() + "</Query></View>")}, function(sender, args) {alert("error: " + args.get_message());} ); } ``` It will fetch your records of logged in user only. Its Done!!
151,687
I have a Query String (URL) filter on my SharePoint 2013 page that is currently passing a string parameter which I then use to filter a list. This list is displayed in a view on my web part page. I want to add a "Title" object above my list view to show the value of the filter parameter that I'm passing to filter the list. Does anyone know how I can do this? I looked through the web part options that were available to add, and couldn't find one to simply display the result of the query string filter.
2015/08/07
[ "https://sharepoint.stackexchange.com/questions/151687", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/44915/" ]
``` var context = new SP.ClientContext.get_current(); var list = context.get_web().get_lists().getByTitle("ListName"); var cQuery = new SP.CamlQuery(); var camlXML = "<View><Query><Where><Eq><FieldRef Name='Author' LookupId='True'/><Value Type='Lookup'>" + _spPageContextInfo.userId + "</Value></Eq></Where></Query></View>"; cQuery.set_viewXml(camlXML); var listitems = list.getItems(cQuery); context.load(listitems); context.executeQueryAsync(function() { var enumerator = listitems.getEnumerator(); while (enumerator.moveNext()) { var item = enumerator.get_current().get_fieldValues(); console.log(item); } }, function(s, a) { console.error(a.get_message()); }); ``` Though it works, I prefer the query provided by Yayati to use `<UserID/>` in caml Query instead of `_spPageContextInfo.userId` , as this userid is only available on SharePoint application pages in browser. however you can use this query to get items of a specific user, instead of current user by passing the userid.
Create a custom view of the list and select radio button Show items only when the following is true: created by is equal to type [Me] save the list. [![enter image description here](https://i.stack.imgur.com/otAZa.png)](https://i.stack.imgur.com/otAZa.png) ``` function getItemsFromView() { var context = new SP.ClientContext.get_current(); var list = context.get_web().get_lists().getByTitle('ListName'); var view = list.get_views().getByTitle('CustomViewName'); context.load(view); context.executeQueryAsync( function(sender, args) {OnSuccess("<View><Query>" + view.get_viewQuery() + "</Query></View>")}, function(sender, args) {alert("error: " + args.get_message());} ); } ``` It will fetch your records of logged in user only. Its Done!!
151,687
I have a Query String (URL) filter on my SharePoint 2013 page that is currently passing a string parameter which I then use to filter a list. This list is displayed in a view on my web part page. I want to add a "Title" object above my list view to show the value of the filter parameter that I'm passing to filter the list. Does anyone know how I can do this? I looked through the web part options that were available to add, and couldn't find one to simply display the result of the query string filter.
2015/08/07
[ "https://sharepoint.stackexchange.com/questions/151687", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/44915/" ]
The Author column is of `LookUp` Type. Here is the complete list. ``` var ctx = new SP.ClientContext.get_current(); var list = ctx.get_web().get_lists().getByTitle("Vacation Replacement"); var query = new SP.CamlQuery(); var specifier = "<Where><Eq><FieldRef Name='Author' LookupId='True'/><Value Type='Lookup'><UserID/></Value></Eq></Where>"; query.set_viewXml("<View><Query>"+specifier+"</Query></View>"); var collListItems = list.getItems(query); ctx.load(collListItems); ctx.executeQueryAsync( function(){ var enumerator = collListItems.getEnumerator(); while(enumerator.moveNext()){ var item = enumerator.get_current(); alert("ID : " + item.get_id()); } }, function(sender,args){ alert("Request Failed."+args.get_message() + "\n" + args.get_stackTrace()); } ); ```
To get current user Id ``` clientContext = new SP.ClientContext.get_current(); var user=clientContext.get_web().get_currentUser(); clientContext.load(user); clientContext.executeQueryAsync(function(){ var userId=user.get_id(); var query="<Where><Eq>"+ "<FieldRef Name="Author" LookupId="TRUE" />"+ "<Value Type="Integer">" +userId + "</Value></Eq></Where>"; },failCallbackMethod); ``` This [link](http://www.ashokraja.me/tips/How-to-use-User-Name-User-Id-Logged-in-User-Id-in-SharePoint-CAML-Query) might help you
151,687
I have a Query String (URL) filter on my SharePoint 2013 page that is currently passing a string parameter which I then use to filter a list. This list is displayed in a view on my web part page. I want to add a "Title" object above my list view to show the value of the filter parameter that I'm passing to filter the list. Does anyone know how I can do this? I looked through the web part options that were available to add, and couldn't find one to simply display the result of the query string filter.
2015/08/07
[ "https://sharepoint.stackexchange.com/questions/151687", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/44915/" ]
``` var context = new SP.ClientContext.get_current(); var list = context.get_web().get_lists().getByTitle("ListName"); var cQuery = new SP.CamlQuery(); var camlXML = "<View><Query><Where><Eq><FieldRef Name='Author' LookupId='True'/><Value Type='Lookup'>" + _spPageContextInfo.userId + "</Value></Eq></Where></Query></View>"; cQuery.set_viewXml(camlXML); var listitems = list.getItems(cQuery); context.load(listitems); context.executeQueryAsync(function() { var enumerator = listitems.getEnumerator(); while (enumerator.moveNext()) { var item = enumerator.get_current().get_fieldValues(); console.log(item); } }, function(s, a) { console.error(a.get_message()); }); ``` Though it works, I prefer the query provided by Yayati to use `<UserID/>` in caml Query instead of `_spPageContextInfo.userId` , as this userid is only available on SharePoint application pages in browser. however you can use this query to get items of a specific user, instead of current user by passing the userid.
To get current user Id ``` clientContext = new SP.ClientContext.get_current(); var user=clientContext.get_web().get_currentUser(); clientContext.load(user); clientContext.executeQueryAsync(function(){ var userId=user.get_id(); var query="<Where><Eq>"+ "<FieldRef Name="Author" LookupId="TRUE" />"+ "<Value Type="Integer">" +userId + "</Value></Eq></Where>"; },failCallbackMethod); ``` This [link](http://www.ashokraja.me/tips/How-to-use-User-Name-User-Id-Logged-in-User-Id-in-SharePoint-CAML-Query) might help you
151,687
I have a Query String (URL) filter on my SharePoint 2013 page that is currently passing a string parameter which I then use to filter a list. This list is displayed in a view on my web part page. I want to add a "Title" object above my list view to show the value of the filter parameter that I'm passing to filter the list. Does anyone know how I can do this? I looked through the web part options that were available to add, and couldn't find one to simply display the result of the query string filter.
2015/08/07
[ "https://sharepoint.stackexchange.com/questions/151687", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/44915/" ]
``` var context = new SP.ClientContext.get_current(); var list = context.get_web().get_lists().getByTitle("ListName"); var cQuery = new SP.CamlQuery(); var camlXML = "<View><Query><Where><Eq><FieldRef Name='Author' LookupId='True'/><Value Type='Lookup'>" + _spPageContextInfo.userId + "</Value></Eq></Where></Query></View>"; cQuery.set_viewXml(camlXML); var listitems = list.getItems(cQuery); context.load(listitems); context.executeQueryAsync(function() { var enumerator = listitems.getEnumerator(); while (enumerator.moveNext()) { var item = enumerator.get_current().get_fieldValues(); console.log(item); } }, function(s, a) { console.error(a.get_message()); }); ``` Though it works, I prefer the query provided by Yayati to use `<UserID/>` in caml Query instead of `_spPageContextInfo.userId` , as this userid is only available on SharePoint application pages in browser. however you can use this query to get items of a specific user, instead of current user by passing the userid.
The Author column is of `LookUp` Type. Here is the complete list. ``` var ctx = new SP.ClientContext.get_current(); var list = ctx.get_web().get_lists().getByTitle("Vacation Replacement"); var query = new SP.CamlQuery(); var specifier = "<Where><Eq><FieldRef Name='Author' LookupId='True'/><Value Type='Lookup'><UserID/></Value></Eq></Where>"; query.set_viewXml("<View><Query>"+specifier+"</Query></View>"); var collListItems = list.getItems(query); ctx.load(collListItems); ctx.executeQueryAsync( function(){ var enumerator = collListItems.getEnumerator(); while(enumerator.moveNext()){ var item = enumerator.get_current(); alert("ID : " + item.get_id()); } }, function(sender,args){ alert("Request Failed."+args.get_message() + "\n" + args.get_stackTrace()); } ); ```
96,396
a bit of background to the question, I'm a junior developer and we have recently been given flexitime which so far is working well as I get to start at 8am and leave at 4:30pm. Today I arrived at 7:30 (I like to be early so I can have a coffee in the office before I start my work) however no one arrived to open the office until 9am. So my question is, should I leave at the the normal time (5:30 pm) or when I would usually leave(4:30 pm)?
2017/08/02
[ "https://workplace.stackexchange.com/questions/96396", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/53342/" ]
Today, work till 5:30. Yes it's not your fault that you couldn't start at 8 - but you still need to ensure you're working your contracted hours. Make sure today though that you discuss with your boss what happens in future. If the company is offering flexible hours - they need to ensure you can start work when you want to (because that's the whole point).
This is a tricky one. The basic answer is: You were there at the disposition of the employer in the time agreed upon with him; that you did not were able to do work due to factors external to you does not change that. It is not different to, say, staying an hour idle at work because of the computer do not work due to a power outage. One small "but" is that it may be difficult to prove that you were there at 8 pm; but since you state you are there everyday that sould not be much of an issue. Also any message contacting your coworkers and reporting the issue with the doors should help. Check with your boss that he knowns that you were there at 8:00 am. The big "but" is that you have just started with flex time, which means that the system still has to be worked out and your employer is still evaluating it. If the employer gets to the conclussion that the system leads to employees working less hours(either if it is not the employees'fault), he may want to return to strict time. I am not saying that it would happen by just one incident, but if it happens more times it could be determinant.
96,396
a bit of background to the question, I'm a junior developer and we have recently been given flexitime which so far is working well as I get to start at 8am and leave at 4:30pm. Today I arrived at 7:30 (I like to be early so I can have a coffee in the office before I start my work) however no one arrived to open the office until 9am. So my question is, should I leave at the the normal time (5:30 pm) or when I would usually leave(4:30 pm)?
2017/08/02
[ "https://workplace.stackexchange.com/questions/96396", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/53342/" ]
Unless there was a pre-existing conversation with your boss that you were coming in at 8 and that someone would be there to open the office then I'd say that this time you'll just have to take it on the chin and work till 5:30. What I would do though is explain to your boss (in a non-confrontational, non-accusatory way) that there was no-one to open the office when you arrived and ask if you need to be letting people know about any plans to arrive "early" to ensure a keyholder opens up, or if the office *won't* be opening pre-9:00 on a day you were planning to come in early that you can at least adjust your plans. Most likely this is just a blip that is down to the organisation adjusting to the flexitime (you mention it is a recent development).
Today, work till 5:30. Yes it's not your fault that you couldn't start at 8 - but you still need to ensure you're working your contracted hours. Make sure today though that you discuss with your boss what happens in future. If the company is offering flexible hours - they need to ensure you can start work when you want to (because that's the whole point).
96,396
a bit of background to the question, I'm a junior developer and we have recently been given flexitime which so far is working well as I get to start at 8am and leave at 4:30pm. Today I arrived at 7:30 (I like to be early so I can have a coffee in the office before I start my work) however no one arrived to open the office until 9am. So my question is, should I leave at the the normal time (5:30 pm) or when I would usually leave(4:30 pm)?
2017/08/02
[ "https://workplace.stackexchange.com/questions/96396", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/53342/" ]
Today, work till 5:30. Yes it's not your fault that you couldn't start at 8 - but you still need to ensure you're working your contracted hours. Make sure today though that you discuss with your boss what happens in future. If the company is offering flexible hours - they need to ensure you can start work when you want to (because that's the whole point).
Just ask your manager. Don't assume anything and simply ask. Something odd happened today and you want to know how to proceed as well as set up an example for future instances should it happen again. This is the exact situation where the only correct thing to do is ask your manager. You shouldn't "just do the work" without asking because depending on your company guidelines that could push you into overtime hours or the like, which may or may not be "ok". You shouldn't assume the opposite either, since you don't want to short-change your workplace work-hours. Just ask.
96,396
a bit of background to the question, I'm a junior developer and we have recently been given flexitime which so far is working well as I get to start at 8am and leave at 4:30pm. Today I arrived at 7:30 (I like to be early so I can have a coffee in the office before I start my work) however no one arrived to open the office until 9am. So my question is, should I leave at the the normal time (5:30 pm) or when I would usually leave(4:30 pm)?
2017/08/02
[ "https://workplace.stackexchange.com/questions/96396", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/53342/" ]
Unless there was a pre-existing conversation with your boss that you were coming in at 8 and that someone would be there to open the office then I'd say that this time you'll just have to take it on the chin and work till 5:30. What I would do though is explain to your boss (in a non-confrontational, non-accusatory way) that there was no-one to open the office when you arrived and ask if you need to be letting people know about any plans to arrive "early" to ensure a keyholder opens up, or if the office *won't* be opening pre-9:00 on a day you were planning to come in early that you can at least adjust your plans. Most likely this is just a blip that is down to the organisation adjusting to the flexitime (you mention it is a recent development).
This is a tricky one. The basic answer is: You were there at the disposition of the employer in the time agreed upon with him; that you did not were able to do work due to factors external to you does not change that. It is not different to, say, staying an hour idle at work because of the computer do not work due to a power outage. One small "but" is that it may be difficult to prove that you were there at 8 pm; but since you state you are there everyday that sould not be much of an issue. Also any message contacting your coworkers and reporting the issue with the doors should help. Check with your boss that he knowns that you were there at 8:00 am. The big "but" is that you have just started with flex time, which means that the system still has to be worked out and your employer is still evaluating it. If the employer gets to the conclussion that the system leads to employees working less hours(either if it is not the employees'fault), he may want to return to strict time. I am not saying that it would happen by just one incident, but if it happens more times it could be determinant.
96,396
a bit of background to the question, I'm a junior developer and we have recently been given flexitime which so far is working well as I get to start at 8am and leave at 4:30pm. Today I arrived at 7:30 (I like to be early so I can have a coffee in the office before I start my work) however no one arrived to open the office until 9am. So my question is, should I leave at the the normal time (5:30 pm) or when I would usually leave(4:30 pm)?
2017/08/02
[ "https://workplace.stackexchange.com/questions/96396", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/53342/" ]
With all implementations of flextime that I know, there is a set of rules, in particular **core and maximum work hours**. You need to be there at least during core hours (e.g. 10am-2pm), and you may only work during a certain window (e.g. 7am-7pm). Was that not communicated? If not, then talk to your manager and ask them to set this policy. Then everyone will know what is or is not possible with flextime. As to today: If you normally start at 8 and leave at 4:30, I don't see why you cannot leave at 4:30 today, too. The time from 7:30 to 8 is probably on you, because it was not clear whether you can start before 8, but if your normal day starts at 8 am, and the door is locked, that's not your fault.
This is a tricky one. The basic answer is: You were there at the disposition of the employer in the time agreed upon with him; that you did not were able to do work due to factors external to you does not change that. It is not different to, say, staying an hour idle at work because of the computer do not work due to a power outage. One small "but" is that it may be difficult to prove that you were there at 8 pm; but since you state you are there everyday that sould not be much of an issue. Also any message contacting your coworkers and reporting the issue with the doors should help. Check with your boss that he knowns that you were there at 8:00 am. The big "but" is that you have just started with flex time, which means that the system still has to be worked out and your employer is still evaluating it. If the employer gets to the conclussion that the system leads to employees working less hours(either if it is not the employees'fault), he may want to return to strict time. I am not saying that it would happen by just one incident, but if it happens more times it could be determinant.
96,396
a bit of background to the question, I'm a junior developer and we have recently been given flexitime which so far is working well as I get to start at 8am and leave at 4:30pm. Today I arrived at 7:30 (I like to be early so I can have a coffee in the office before I start my work) however no one arrived to open the office until 9am. So my question is, should I leave at the the normal time (5:30 pm) or when I would usually leave(4:30 pm)?
2017/08/02
[ "https://workplace.stackexchange.com/questions/96396", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/53342/" ]
Unless there was a pre-existing conversation with your boss that you were coming in at 8 and that someone would be there to open the office then I'd say that this time you'll just have to take it on the chin and work till 5:30. What I would do though is explain to your boss (in a non-confrontational, non-accusatory way) that there was no-one to open the office when you arrived and ask if you need to be letting people know about any plans to arrive "early" to ensure a keyholder opens up, or if the office *won't* be opening pre-9:00 on a day you were planning to come in early that you can at least adjust your plans. Most likely this is just a blip that is down to the organisation adjusting to the flexitime (you mention it is a recent development).
With all implementations of flextime that I know, there is a set of rules, in particular **core and maximum work hours**. You need to be there at least during core hours (e.g. 10am-2pm), and you may only work during a certain window (e.g. 7am-7pm). Was that not communicated? If not, then talk to your manager and ask them to set this policy. Then everyone will know what is or is not possible with flextime. As to today: If you normally start at 8 and leave at 4:30, I don't see why you cannot leave at 4:30 today, too. The time from 7:30 to 8 is probably on you, because it was not clear whether you can start before 8, but if your normal day starts at 8 am, and the door is locked, that's not your fault.
96,396
a bit of background to the question, I'm a junior developer and we have recently been given flexitime which so far is working well as I get to start at 8am and leave at 4:30pm. Today I arrived at 7:30 (I like to be early so I can have a coffee in the office before I start my work) however no one arrived to open the office until 9am. So my question is, should I leave at the the normal time (5:30 pm) or when I would usually leave(4:30 pm)?
2017/08/02
[ "https://workplace.stackexchange.com/questions/96396", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/53342/" ]
Unless there was a pre-existing conversation with your boss that you were coming in at 8 and that someone would be there to open the office then I'd say that this time you'll just have to take it on the chin and work till 5:30. What I would do though is explain to your boss (in a non-confrontational, non-accusatory way) that there was no-one to open the office when you arrived and ask if you need to be letting people know about any plans to arrive "early" to ensure a keyholder opens up, or if the office *won't* be opening pre-9:00 on a day you were planning to come in early that you can at least adjust your plans. Most likely this is just a blip that is down to the organisation adjusting to the flexitime (you mention it is a recent development).
Just ask your manager. Don't assume anything and simply ask. Something odd happened today and you want to know how to proceed as well as set up an example for future instances should it happen again. This is the exact situation where the only correct thing to do is ask your manager. You shouldn't "just do the work" without asking because depending on your company guidelines that could push you into overtime hours or the like, which may or may not be "ok". You shouldn't assume the opposite either, since you don't want to short-change your workplace work-hours. Just ask.
96,396
a bit of background to the question, I'm a junior developer and we have recently been given flexitime which so far is working well as I get to start at 8am and leave at 4:30pm. Today I arrived at 7:30 (I like to be early so I can have a coffee in the office before I start my work) however no one arrived to open the office until 9am. So my question is, should I leave at the the normal time (5:30 pm) or when I would usually leave(4:30 pm)?
2017/08/02
[ "https://workplace.stackexchange.com/questions/96396", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/53342/" ]
With all implementations of flextime that I know, there is a set of rules, in particular **core and maximum work hours**. You need to be there at least during core hours (e.g. 10am-2pm), and you may only work during a certain window (e.g. 7am-7pm). Was that not communicated? If not, then talk to your manager and ask them to set this policy. Then everyone will know what is or is not possible with flextime. As to today: If you normally start at 8 and leave at 4:30, I don't see why you cannot leave at 4:30 today, too. The time from 7:30 to 8 is probably on you, because it was not clear whether you can start before 8, but if your normal day starts at 8 am, and the door is locked, that's not your fault.
Just ask your manager. Don't assume anything and simply ask. Something odd happened today and you want to know how to proceed as well as set up an example for future instances should it happen again. This is the exact situation where the only correct thing to do is ask your manager. You shouldn't "just do the work" without asking because depending on your company guidelines that could push you into overtime hours or the like, which may or may not be "ok". You shouldn't assume the opposite either, since you don't want to short-change your workplace work-hours. Just ask.
39,751,570
I dont know if I can post this here or not. But a strange thing happened recently. I use pycharm to run my python codes and surprisingly when I opened a piece of my code - it got deleted. The file is 0KB now - for some reason. I am using this file for over a month now and this happened when I opened it and the file automatically got deleted from pycharm and next it became 0KB. When I tried to delete this file: I get the following Error 0xx800710FE: This file is currently not available for use on this computer
2016/09/28
[ "https://Stackoverflow.com/questions/39751570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4463825/" ]
Finally, I found a way but I'm not sure at all that it's a conventional way: ``` //... function is_foobar($value) { //return true or false; } $resolver = new OptionsResolver(); $resolver->setRequired('data'); $resolver->setAllowedTypes('data', 'foobar'); //... ``` --- **EDIT:** Well, after I sleep on, I think my approach is wrong, because it's already done by using `setAllowedValues` or `addAllowedValues` methods: ``` $resolver->setAllowedValues('foo', function ($value) { return $value instanceof Foo && $value instanceof Bar; }); ``` So it's not necessary to use `setAllowedTypes` for this purpose.
The signature of `OptionsResolver::setAllowedTypes()` is just [this](http://api.symfony.com/3.1/Symfony/Component/OptionsResolver/OptionsResolver.html#method_setAllowedTypes): ``` setAllowedTypes(string $option, string|string[] $allowedTypes) ``` The argument `$allowedTypes` can accept a list of strings, and is used as a logic *OR*, so *any* of those types will be allowed - that's all you can do I'm afraid... Note that in order to allow the complex combinations you want, you'd need either more arguments or other methods, otherwise there's no way to know whether you want "any of these types", "all of these types at the same time", "any type but these ones" or any other combination you can imagine... I guess they may provide a method that accepts a callback function as the second argument, so you can do any crazy checks you want, but *AFAIK* that doesn't exist (yet).
39,751,570
I dont know if I can post this here or not. But a strange thing happened recently. I use pycharm to run my python codes and surprisingly when I opened a piece of my code - it got deleted. The file is 0KB now - for some reason. I am using this file for over a month now and this happened when I opened it and the file automatically got deleted from pycharm and next it became 0KB. When I tried to delete this file: I get the following Error 0xx800710FE: This file is currently not available for use on this computer
2016/09/28
[ "https://Stackoverflow.com/questions/39751570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4463825/" ]
See [Define a form option allowed values depending on another option value in a FormType](https://stackoverflow.com/questions/35204850/define-a-form-option-allowed-values-depending-on-another-option-value-in-a-formt/35215869#35215869). You should use a **normalizer** for this: ``` use Symfony\Component\Form\Exception\InvalidConfigurationException; $resolver->setNormalizer('data', function(Options $options, $data) { if (!$data instanceof Foo && !$data instanceof Bar) { throw new InvalidConfigurationException('"data" option must implement "Foo" and "Bar" interfaces.'); } return $data; }); ```
The signature of `OptionsResolver::setAllowedTypes()` is just [this](http://api.symfony.com/3.1/Symfony/Component/OptionsResolver/OptionsResolver.html#method_setAllowedTypes): ``` setAllowedTypes(string $option, string|string[] $allowedTypes) ``` The argument `$allowedTypes` can accept a list of strings, and is used as a logic *OR*, so *any* of those types will be allowed - that's all you can do I'm afraid... Note that in order to allow the complex combinations you want, you'd need either more arguments or other methods, otherwise there's no way to know whether you want "any of these types", "all of these types at the same time", "any type but these ones" or any other combination you can imagine... I guess they may provide a method that accepts a callback function as the second argument, so you can do any crazy checks you want, but *AFAIK* that doesn't exist (yet).
39,751,570
I dont know if I can post this here or not. But a strange thing happened recently. I use pycharm to run my python codes and surprisingly when I opened a piece of my code - it got deleted. The file is 0KB now - for some reason. I am using this file for over a month now and this happened when I opened it and the file automatically got deleted from pycharm and next it became 0KB. When I tried to delete this file: I get the following Error 0xx800710FE: This file is currently not available for use on this computer
2016/09/28
[ "https://Stackoverflow.com/questions/39751570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4463825/" ]
See [Define a form option allowed values depending on another option value in a FormType](https://stackoverflow.com/questions/35204850/define-a-form-option-allowed-values-depending-on-another-option-value-in-a-formt/35215869#35215869). You should use a **normalizer** for this: ``` use Symfony\Component\Form\Exception\InvalidConfigurationException; $resolver->setNormalizer('data', function(Options $options, $data) { if (!$data instanceof Foo && !$data instanceof Bar) { throw new InvalidConfigurationException('"data" option must implement "Foo" and "Bar" interfaces.'); } return $data; }); ```
Finally, I found a way but I'm not sure at all that it's a conventional way: ``` //... function is_foobar($value) { //return true or false; } $resolver = new OptionsResolver(); $resolver->setRequired('data'); $resolver->setAllowedTypes('data', 'foobar'); //... ``` --- **EDIT:** Well, after I sleep on, I think my approach is wrong, because it's already done by using `setAllowedValues` or `addAllowedValues` methods: ``` $resolver->setAllowedValues('foo', function ($value) { return $value instanceof Foo && $value instanceof Bar; }); ``` So it's not necessary to use `setAllowedTypes` for this purpose.
19,142,546
I had this setup: ``` images image1.jpg image2.jpg header.html about index.php image3.jpg ``` But going to MyWebsite.com/About gave it an extra slash on the end. I decided to go with the solution of creating a file called about in my home directory: ``` images image1.jpg image2.jpg header.html about aboutfiles image3.jpg ``` The problem is that now this file won't let me use .php: ``` <?php include('header.html');?> ``` It's not showing the header file. What can I do to make this work?
2013/10/02
[ "https://Stackoverflow.com/questions/19142546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/561395/" ]
Your problem is that your web server does not recognize the filename "about" as a php document. You have three options 1. Use a ".php" extension on your page document, such as "index.php" which will run your php scripting. 2. Install a solution such as mod\_rewrite that will translate urls such as /about to a file actual like "about.php". 3. Adjust your servers mime-type for php documents. Learn more about MIME types here. <https://developer.mozilla.org/en-US/docs/Properly_Configuring_Server_MIME_Types> The first solution is the simplest and easiest, in any document you use PHP, the extension should be .php
About the `mywebsite.com/about` issue, it's more an Apache configuration issue. You have to tell Apache that index.php should be an index file.
19,142,546
I had this setup: ``` images image1.jpg image2.jpg header.html about index.php image3.jpg ``` But going to MyWebsite.com/About gave it an extra slash on the end. I decided to go with the solution of creating a file called about in my home directory: ``` images image1.jpg image2.jpg header.html about aboutfiles image3.jpg ``` The problem is that now this file won't let me use .php: ``` <?php include('header.html');?> ``` It's not showing the header file. What can I do to make this work?
2013/10/02
[ "https://Stackoverflow.com/questions/19142546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/561395/" ]
Your problem is that your web server does not recognize the filename "about" as a php document. You have three options 1. Use a ".php" extension on your page document, such as "index.php" which will run your php scripting. 2. Install a solution such as mod\_rewrite that will translate urls such as /about to a file actual like "about.php". 3. Adjust your servers mime-type for php documents. Learn more about MIME types here. <https://developer.mozilla.org/en-US/docs/Properly_Configuring_Server_MIME_Types> The first solution is the simplest and easiest, in any document you use PHP, the extension should be .php
First, you can configure your Apache (or IIS) to use whatever Extensions to process PHP-Code. You can define `.ThisIsAPHPFile` as valid extension, if you want. However, Directorys are always reflected with a trailing `/`: `www.example.com/dir1/` (Browsers not always showing the trailing `/`) while files have an extension: `www.example.com/dir1/index.html`. So, from what i see, you want to use `www.example.com/about` but showing the about-FILE ? Therefore you can use rewrite Engines of your Webserver. Either have a look at mod-rewrite (<http://httpd.apache.org/docs/current/en/mod/mod_rewrite.html>), when using Apache, or (one possibility) ISAPI-Rewrite (<http://www.isapirewrite.com/docs/>), when using IIS.
19,142,546
I had this setup: ``` images image1.jpg image2.jpg header.html about index.php image3.jpg ``` But going to MyWebsite.com/About gave it an extra slash on the end. I decided to go with the solution of creating a file called about in my home directory: ``` images image1.jpg image2.jpg header.html about aboutfiles image3.jpg ``` The problem is that now this file won't let me use .php: ``` <?php include('header.html');?> ``` It's not showing the header file. What can I do to make this work?
2013/10/02
[ "https://Stackoverflow.com/questions/19142546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/561395/" ]
Your problem is that your web server does not recognize the filename "about" as a php document. You have three options 1. Use a ".php" extension on your page document, such as "index.php" which will run your php scripting. 2. Install a solution such as mod\_rewrite that will translate urls such as /about to a file actual like "about.php". 3. Adjust your servers mime-type for php documents. Learn more about MIME types here. <https://developer.mozilla.org/en-US/docs/Properly_Configuring_Server_MIME_Types> The first solution is the simplest and easiest, in any document you use PHP, the extension should be .php
If you edit your virtualhost directive in your apache conf file, you can add the following: ``` DefaultType application/x-httpd-php ``` This will tell apache to send web paths that do not end in an extension to render using the php engine. Therefore, /about would act as if it was about.php. Another potentially more useful approach is to name the file about.php on the server, and allow referencing it without the .php in the url. For this, you would configure it the opposite way. ``` RewriteEngine on RewriteCond %{DOCUMENT_ROOT}/$1.php -f RewriteRule ^(([^/]+/)*[^.]+)$ /$1.php [L] ```
7,851,036
Is there any way to set my `base_url()` from my controller's ? OR Can I set my `base_url` `Dynamic` ? How can I achieved this ?
2011/10/21
[ "https://Stackoverflow.com/questions/7851036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676755/" ]
After Searching i found the solution . yes we can change the base\_url from our controller as ``` $this->config->set_item('base_url','http://example.com/xyz') ; ``` Ref: [User Guide](http://ellislab.com/codeigniter/user-guide/libraries/config.html) May this answer should help some one .
The base url is set in your config file, so you can update the $config variable from your controllers before you call `base_url()`. <http://codeigniter.com/forums/viewthread/60181/> **EDIT** Of course, I haven't tested this, so don't know if the overwrite will actually work as expected. You could always extend the url helper with your own class and override the base\_url method.
7,851,036
Is there any way to set my `base_url()` from my controller's ? OR Can I set my `base_url` `Dynamic` ? How can I achieved this ?
2011/10/21
[ "https://Stackoverflow.com/questions/7851036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676755/" ]
After Searching i found the solution . yes we can change the base\_url from our controller as ``` $this->config->set_item('base_url','http://example.com/xyz') ; ``` Ref: [User Guide](http://ellislab.com/codeigniter/user-guide/libraries/config.html) May this answer should help some one .
OK, so this was fun, but it might not work right and/or break all kinds of other stuff. But, if you make these changes in the relevant files, you can have multiple base url config settings in the config file like so: ``` $config['base_url']['default'] = 'http://firstbase.xyz'; $config['base_url']['otherbase'] = 'http://secondbase.xyz'; ``` which can be called like `base_url('','default');//produces <http://firstbase.xyz>`. It seems much easier/better to use `$this->config->set_item('base_url','http://abc.com/xyz') ;` as you found in the docs. --- system/helpers/url\_helper.php : line ~63 ``` if ( ! function_exists('base_url')) { function base_url($uri = '',$index='') { $CI =& get_instance(); return $CI->config->base_url($uri,$index); } } ``` --- system/core/Config.php > > line ~66 > > > ``` $this->set_item('base_url', $index); ``` > > line ~175 > > > ``` function item($item, $index = '') { if ($index == '') { if ( ! isset($this->config[$item])) { return FALSE; } $pref = $this->config[$item]; } else { if ( ! isset($this->config[$index])) { return FALSE; } if ( ! isset($this->config[$index][$item])) { return FALSE; } $pref = $this->config[$index][$item]; } return $pref; } ``` > > line ~214 > > > ``` function slash_item($item,$index) { if ( ! isset($this->config[$item][$index])) { return FALSE; } if( trim($this->config[$item][$index]) == '') { return ''; } return rtrim($this->config[$item][$index], '/').'/'; } ``` > > line ~265 > > > ``` function base_url($uri = '',$index='') { return $this->slash_item('base_url',$index).ltrim($this->_uri_string($uri),'/'); } ``` > > line ~332 > > > ``` function set_item($item, $value, $index) { $this->config[$item][$index] = $value; } ```
57,200,052
**Target** : if the **8th (or n of )** of character in string **match condition**, **then update in new column** **By word in a single string :** ``` # if i want to check the 3rd character IN[0]: s = "apple" s[2] OUT[0]: 'p' ``` **Code** : ``` tt = pd.DataFrame({"CC":["T020203J71500","Y020203K71500","T020407JLX100","P020403JLX100"]) tt["NAME"] = pd.np.where(tt["CC"][7].str.contains("J"),"JANICE", pd.np.where(tt["CC"][7].str.contains("K"),"KELVIN", pd.np.where(tt["CC"][7].str.contains("X"),"SPECIAL","NONE"))) ``` **Problem** : Apparently `[7]` is not a python practice **In R data.table :** ``` tt[grepl("J",str_sub(CC,8,8)), "NAME":="JANICE"] tt[grepl("K",str_sub(CC,8,8)), "NAME":="KELVIN"] # .... can achieve by doing like this ``` How can i do this in Python ?
2019/07/25
[ "https://Stackoverflow.com/questions/57200052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8935953/" ]
Use Regex. **Ex:** ``` import re s = "2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401" m = re.search(r"DDD=(.*?)%", s) #if you want it to be strict and get only ints use r"DDD=(\d+\.?\d*)%" if m: print(m.group(1)) ``` **Output:** ``` 1.08 ```
Here's an option which uses `split` twice rather than regex. It's not terribly flexible though and can easily break if the input format changes slightly. You can decide which option is best for your use case. ``` s = "2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401" print(s.split('DDD=')[1].split('%')[0]) ``` Results: ``` '1.08' ``` Depending on what you plan to do with the number, you might also want to cast it to a numeric type: ``` print(float(s.split('DDD=')[1].split('%')[0])) ``` Results: ``` 1.08 ```
57,200,052
**Target** : if the **8th (or n of )** of character in string **match condition**, **then update in new column** **By word in a single string :** ``` # if i want to check the 3rd character IN[0]: s = "apple" s[2] OUT[0]: 'p' ``` **Code** : ``` tt = pd.DataFrame({"CC":["T020203J71500","Y020203K71500","T020407JLX100","P020403JLX100"]) tt["NAME"] = pd.np.where(tt["CC"][7].str.contains("J"),"JANICE", pd.np.where(tt["CC"][7].str.contains("K"),"KELVIN", pd.np.where(tt["CC"][7].str.contains("X"),"SPECIAL","NONE"))) ``` **Problem** : Apparently `[7]` is not a python practice **In R data.table :** ``` tt[grepl("J",str_sub(CC,8,8)), "NAME":="JANICE"] tt[grepl("K",str_sub(CC,8,8)), "NAME":="KELVIN"] # .... can achieve by doing like this ``` How can i do this in Python ?
2019/07/25
[ "https://Stackoverflow.com/questions/57200052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8935953/" ]
Use Regex. **Ex:** ``` import re s = "2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401" m = re.search(r"DDD=(.*?)%", s) #if you want it to be strict and get only ints use r"DDD=(\d+\.?\d*)%" if m: print(m.group(1)) ``` **Output:** ``` 1.08 ```
To match *all the data between DDD= and %*: ``` import re test_str = "2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401" m = re.search(r"DDD=([^%]+)%", test_str) ddd = m.group(1) if m else m print(ddd) # 1.08 ```
57,200,052
**Target** : if the **8th (or n of )** of character in string **match condition**, **then update in new column** **By word in a single string :** ``` # if i want to check the 3rd character IN[0]: s = "apple" s[2] OUT[0]: 'p' ``` **Code** : ``` tt = pd.DataFrame({"CC":["T020203J71500","Y020203K71500","T020407JLX100","P020403JLX100"]) tt["NAME"] = pd.np.where(tt["CC"][7].str.contains("J"),"JANICE", pd.np.where(tt["CC"][7].str.contains("K"),"KELVIN", pd.np.where(tt["CC"][7].str.contains("X"),"SPECIAL","NONE"))) ``` **Problem** : Apparently `[7]` is not a python practice **In R data.table :** ``` tt[grepl("J",str_sub(CC,8,8)), "NAME":="JANICE"] tt[grepl("K",str_sub(CC,8,8)), "NAME":="KELVIN"] # .... can achieve by doing like this ``` How can i do this in Python ?
2019/07/25
[ "https://Stackoverflow.com/questions/57200052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8935953/" ]
Use Regex. **Ex:** ``` import re s = "2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401" m = re.search(r"DDD=(.*?)%", s) #if you want it to be strict and get only ints use r"DDD=(\d+\.?\d*)%" if m: print(m.group(1)) ``` **Output:** ``` 1.08 ```
Use string find operation: **Example** ``` my_string="2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401" fst = my_string.find("DDD=") snd = my_string.find("%") if fst >= 0 and snd >= 0 print(my_string[fst+4,snd]) ``` **Output** ``` 1.08 ``` Or you can use split: **Example** ``` my_string="2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401" (fst,snd) = my_string.split("DDD="); (trd,fourth) = snd.split("%"); print(trd) ``` **Output** ``` 1.08 ```
57,200,052
**Target** : if the **8th (or n of )** of character in string **match condition**, **then update in new column** **By word in a single string :** ``` # if i want to check the 3rd character IN[0]: s = "apple" s[2] OUT[0]: 'p' ``` **Code** : ``` tt = pd.DataFrame({"CC":["T020203J71500","Y020203K71500","T020407JLX100","P020403JLX100"]) tt["NAME"] = pd.np.where(tt["CC"][7].str.contains("J"),"JANICE", pd.np.where(tt["CC"][7].str.contains("K"),"KELVIN", pd.np.where(tt["CC"][7].str.contains("X"),"SPECIAL","NONE"))) ``` **Problem** : Apparently `[7]` is not a python practice **In R data.table :** ``` tt[grepl("J",str_sub(CC,8,8)), "NAME":="JANICE"] tt[grepl("K",str_sub(CC,8,8)), "NAME":="KELVIN"] # .... can achieve by doing like this ``` How can i do this in Python ?
2019/07/25
[ "https://Stackoverflow.com/questions/57200052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8935953/" ]
Use Regex. **Ex:** ``` import re s = "2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401" m = re.search(r"DDD=(.*?)%", s) #if you want it to be strict and get only ints use r"DDD=(\d+\.?\d*)%" if m: print(m.group(1)) ``` **Output:** ``` 1.08 ```
``` my_string="2019-07-25 15:23:13 [Thread-0] DEBUG - Serial : INFO: QQQ=00000D00001111 AAA=8 BBB=0 CCC=0 DDD=1.08% XXX=2401" output1 = print(my_string.split("DDD=")[1][:5]) #output1 =1.08% #output2 = print(my_string.split("DDD=")[1][:4]) #output2 =1.08 ```
420,361
My Exchange Server 2003 (running on Windows Server 2003) fails at around 04:54 on a regular basis, though not necessarily every day. By "fails" I mean that my colleagues try and check their emails and Outlook says "outlook is not connected to exchange." Since outlook tries to update the email every 3 minutes or so, and it records the time when the folder was last updated, it is possible to see the time of failure. It is impossible to download emails until the server is restarted. Thereupon everything works well. I have looked in Scheduled Tasks and can't see anything pertinent. Does anyone have any ideas?
2012/08/23
[ "https://serverfault.com/questions/420361", "https://serverfault.com", "https://serverfault.com/users/110917/" ]
**Question:** a) What version of exchange 2003 are you using ? Standard or Enterprise b) Is this part of SBS2003 or a stand alone exchange. **Suggestions:** 1) Can you navigate to this path in registry. HKEY\_LOCAL\_MACHINE\System\CurrentControlSet\Services\MSExchangeIS\Server name\Private-Mailbox Store GUID Check if you have a key called *Database Size Limit in Gb* and what's the value there. 2) Whats the DB size on disk? Default priv1.edb path is c:\Program Files\Exchsrvr\MDBDATA **Possible Causes:** a) Exchange 2003 DB is dismounting because of 18GB hard limit for Exchange 2003 standard. This is usually resolved by increasing the db size limit to 75GB for Ex03 Standard. ref: <http://support.microsoft.com/kb/912375> White-Space / Offline Defrag's etc, to reclaim space: <http://www.msexchange.org/tutorials/exchange-isinteg-eseutil.html>
Try looking in the Event Viewer if something occurs around the time it fails each time. Hit Start -> Run -> type eventvwr in the Run box to open the Event Viewer, check the events under System and Application logs. In addition, if you have a monitoring application such as HP openview or Centerity you can create a business service which will include all components that are required for the server to run, such as disk, cpu, memory monitors as well as networking, storage, application monitors, through that you will be able to identify the source for the server’s fail on that specific time when it fails.
420,361
My Exchange Server 2003 (running on Windows Server 2003) fails at around 04:54 on a regular basis, though not necessarily every day. By "fails" I mean that my colleagues try and check their emails and Outlook says "outlook is not connected to exchange." Since outlook tries to update the email every 3 minutes or so, and it records the time when the folder was last updated, it is possible to see the time of failure. It is impossible to download emails until the server is restarted. Thereupon everything works well. I have looked in Scheduled Tasks and can't see anything pertinent. Does anyone have any ideas?
2012/08/23
[ "https://serverfault.com/questions/420361", "https://serverfault.com", "https://serverfault.com/users/110917/" ]
Try looking in the Event Viewer if something occurs around the time it fails each time. Hit Start -> Run -> type eventvwr in the Run box to open the Event Viewer, check the events under System and Application logs. In addition, if you have a monitoring application such as HP openview or Centerity you can create a business service which will include all components that are required for the server to run, such as disk, cpu, memory monitors as well as networking, storage, application monitors, through that you will be able to identify the source for the server’s fail on that specific time when it fails.
Yeah, SP2 might do it. If you still have issues, Google for "exchange 2003 sp2 hotfix" and see if any of them are relevant to your problem. Another workaround is to set the Exchange Information Store to automatically restart after a failure in services.msc (if that's the service that's failing), but this doesn't fix the root cause of the problem.
420,361
My Exchange Server 2003 (running on Windows Server 2003) fails at around 04:54 on a regular basis, though not necessarily every day. By "fails" I mean that my colleagues try and check their emails and Outlook says "outlook is not connected to exchange." Since outlook tries to update the email every 3 minutes or so, and it records the time when the folder was last updated, it is possible to see the time of failure. It is impossible to download emails until the server is restarted. Thereupon everything works well. I have looked in Scheduled Tasks and can't see anything pertinent. Does anyone have any ideas?
2012/08/23
[ "https://serverfault.com/questions/420361", "https://serverfault.com", "https://serverfault.com/users/110917/" ]
**Question:** a) What version of exchange 2003 are you using ? Standard or Enterprise b) Is this part of SBS2003 or a stand alone exchange. **Suggestions:** 1) Can you navigate to this path in registry. HKEY\_LOCAL\_MACHINE\System\CurrentControlSet\Services\MSExchangeIS\Server name\Private-Mailbox Store GUID Check if you have a key called *Database Size Limit in Gb* and what's the value there. 2) Whats the DB size on disk? Default priv1.edb path is c:\Program Files\Exchsrvr\MDBDATA **Possible Causes:** a) Exchange 2003 DB is dismounting because of 18GB hard limit for Exchange 2003 standard. This is usually resolved by increasing the db size limit to 75GB for Ex03 Standard. ref: <http://support.microsoft.com/kb/912375> White-Space / Offline Defrag's etc, to reclaim space: <http://www.msexchange.org/tutorials/exchange-isinteg-eseutil.html>
Are you still able to ping the box after this happens or does it become completely unresponsive? Any backups running during that time? Is this server a dedicated Exchange server or does it have other functions? Otherwise, I agree witi Itai, you should cross reference the the event logs with the time in which your machine goes down. You may also need to get a dump of your system and post any pertinent information here. If it is just exchange that is failing and you still have access to your system, check Task Manager to gather what processes are running during that time.
420,361
My Exchange Server 2003 (running on Windows Server 2003) fails at around 04:54 on a regular basis, though not necessarily every day. By "fails" I mean that my colleagues try and check their emails and Outlook says "outlook is not connected to exchange." Since outlook tries to update the email every 3 minutes or so, and it records the time when the folder was last updated, it is possible to see the time of failure. It is impossible to download emails until the server is restarted. Thereupon everything works well. I have looked in Scheduled Tasks and can't see anything pertinent. Does anyone have any ideas?
2012/08/23
[ "https://serverfault.com/questions/420361", "https://serverfault.com", "https://serverfault.com/users/110917/" ]
Are you still able to ping the box after this happens or does it become completely unresponsive? Any backups running during that time? Is this server a dedicated Exchange server or does it have other functions? Otherwise, I agree witi Itai, you should cross reference the the event logs with the time in which your machine goes down. You may also need to get a dump of your system and post any pertinent information here. If it is just exchange that is failing and you still have access to your system, check Task Manager to gather what processes are running during that time.
Yeah, SP2 might do it. If you still have issues, Google for "exchange 2003 sp2 hotfix" and see if any of them are relevant to your problem. Another workaround is to set the Exchange Information Store to automatically restart after a failure in services.msc (if that's the service that's failing), but this doesn't fix the root cause of the problem.
420,361
My Exchange Server 2003 (running on Windows Server 2003) fails at around 04:54 on a regular basis, though not necessarily every day. By "fails" I mean that my colleagues try and check their emails and Outlook says "outlook is not connected to exchange." Since outlook tries to update the email every 3 minutes or so, and it records the time when the folder was last updated, it is possible to see the time of failure. It is impossible to download emails until the server is restarted. Thereupon everything works well. I have looked in Scheduled Tasks and can't see anything pertinent. Does anyone have any ideas?
2012/08/23
[ "https://serverfault.com/questions/420361", "https://serverfault.com", "https://serverfault.com/users/110917/" ]
**Question:** a) What version of exchange 2003 are you using ? Standard or Enterprise b) Is this part of SBS2003 or a stand alone exchange. **Suggestions:** 1) Can you navigate to this path in registry. HKEY\_LOCAL\_MACHINE\System\CurrentControlSet\Services\MSExchangeIS\Server name\Private-Mailbox Store GUID Check if you have a key called *Database Size Limit in Gb* and what's the value there. 2) Whats the DB size on disk? Default priv1.edb path is c:\Program Files\Exchsrvr\MDBDATA **Possible Causes:** a) Exchange 2003 DB is dismounting because of 18GB hard limit for Exchange 2003 standard. This is usually resolved by increasing the db size limit to 75GB for Ex03 Standard. ref: <http://support.microsoft.com/kb/912375> White-Space / Offline Defrag's etc, to reclaim space: <http://www.msexchange.org/tutorials/exchange-isinteg-eseutil.html>
Yeah, SP2 might do it. If you still have issues, Google for "exchange 2003 sp2 hotfix" and see if any of them are relevant to your problem. Another workaround is to set the Exchange Information Store to automatically restart after a failure in services.msc (if that's the service that's failing), but this doesn't fix the root cause of the problem.
58,507,602
Is it possible to limit the new widget Page Selector by a given page type? I know you can set it to load a specific path using EditingComponentProperty(nameof(PageSelectorProperties.RootPath) but can't see a way to limit by page type.
2019/10/22
[ "https://Stackoverflow.com/questions/58507602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417792/" ]
Currently there isn't, just by path i'm afraid. Not sure if Kentico is working on it, it would be nice to have as we have run into the same thing.
You could always add a new widget property **In your model properties class** ``` [EditingComponent(TextInputComponent.IDENTIFIER, Order = 0, Label = "Page Selector Class")] public string PageSelectorClass { get; set; } ``` **In your controller** ``` var pages = DocumentHelper.GetDocuments(GetProperties().PageSelector) //any other LINQ statements you need ```
56,060,579
Is there any way in which I can say, define a URI that will be used in different .yml files for different Artillery load tests? I am wanting to use the same URI within a number of .yml files to define the `target` within the `config` section. I saw the following on the [Artillery docs](https://artillery.io/docs/script-reference/): > > Values can be set dynamically via environment variables which are available under $processEnvironment template variable. > > > For example, to set a default HTTP header for all requests via the SERVICE\_API\_KEY environment variable > > > They show an example doc of: > > export SERVICE\_API\_KEY="012345-my-api-key" > > > artillery run my-test.yml > > > However I am unsure of how to implement this, as I am using the package.json file to run the `artillery run my-test.yml` command.
2019/05/09
[ "https://Stackoverflow.com/questions/56060579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3061047/" ]
Figured this out on my own: In package.json make a new script. Call it whatever you like, and do something similar to this: ``` "scripts": { "start": "set ENV=https://yoursite.com&&artillery run -k yourtest.yml" } ``` in the .yml file itself something like this: ``` config: target: "{{$processEnvironment.ENV}}" ``` call it like this: ``` npm run start ```
IDK why but for me export worked, I mean: ``` "scripts": { "start": "export ENV=https://yoursite.com&&artillery run -k yourtest.yml" } ```
56,060,579
Is there any way in which I can say, define a URI that will be used in different .yml files for different Artillery load tests? I am wanting to use the same URI within a number of .yml files to define the `target` within the `config` section. I saw the following on the [Artillery docs](https://artillery.io/docs/script-reference/): > > Values can be set dynamically via environment variables which are available under $processEnvironment template variable. > > > For example, to set a default HTTP header for all requests via the SERVICE\_API\_KEY environment variable > > > They show an example doc of: > > export SERVICE\_API\_KEY="012345-my-api-key" > > > artillery run my-test.yml > > > However I am unsure of how to implement this, as I am using the package.json file to run the `artillery run my-test.yml` command.
2019/05/09
[ "https://Stackoverflow.com/questions/56060579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3061047/" ]
Figured this out on my own: In package.json make a new script. Call it whatever you like, and do something similar to this: ``` "scripts": { "start": "set ENV=https://yoursite.com&&artillery run -k yourtest.yml" } ``` in the .yml file itself something like this: ``` config: target: "{{$processEnvironment.ENV}}" ``` call it like this: ``` npm run start ```
Something perhaps not very sophisticated but that works is this: ``` config: target: "https:/" ``` Then in the url you can put the rest of the URL for each cases ``` - get: url: "/myUrl1.com" - get: url: "/myUrl2.com" ```
30,273,712
I am using RadGrid with Nested Hierarchy of Master/Detail Tables. I want to Expand the Master Row when the detail Table inside the row has few rows. I am trying to achieve the same using below code ``` Private Sub RadGrid_ItemDataBound(ByVal sender As System.Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles dbgView.ItemDataBound If <considtion to check if row is expanded>Then e.Item.Expanded = True End If ``` However even after setting the Expanded flag as True, if I check the value of the state in QuickWatch, it still remains False. Can someone help me understand why state for that specific row is not getting changed? If this is not the right way in changing the state programmatically, can someone let me know the alternate way?
2015/05/16
[ "https://Stackoverflow.com/questions/30273712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2126643/" ]
You can do something like this: ``` foreach($a as $k1=>$ar1){ $text = ''; foreach($ar1 as $t){ $text .= "{$t['Name']}, "; } unset($a[$k1]); $a[$k1][0]['Name'] = substr($text,0,-2); } var_dump($a); ``` Output: ``` array (size=2) 0 => array (size=1) 0 => array (size=1) 'Name' => string 'kumar, siva' (length=10) 1 => array (size=1) 0 => array (size=1) 'Name' => string 'Arun, Prem' (length=9) ```
This can be solved succinctly with one loop and the implosion of the columnar values in each subarray. Code ([Demo](https://3v4l.org/MbG6A)) ``` $a = [ [['Name' => 'kumar'],['Name' => 'siva']], [['Name' => 'Arun'],['Name' => 'Prem']] ]; foreach ($a as $i => $group) { $result[$i][] = ['Name' => implode(', ', array_column($group, 'Name'))]; } var_export($result); ``` Output: ``` array ( 0 => array ( 0 => array ( 'Name' => 'kumar, siva', ), ), 1 => array ( 0 => array ( 'Name' => 'Arun, Prem', ), ), ) ```
673,903
We have a "test bed system" of 4 servers only (not 7). How do we get this to work with <http://www.ubuntu.com/download/cloud/install-ubuntu-openstack> using only 4 servers?
2015/09/14
[ "https://askubuntu.com/questions/673903", "https://askubuntu.com", "https://askubuntu.com/users/450673/" ]
Use the following command to edit the following file: ``` sudo nano /usr/share/glib-2.0/schemas/10_unity_greeter_background.gschema.override ``` Then copy and paste this into the file and replace `/foo/wallpaper.png` with the actual path to the actual file you would like to use for wallpaper (remember to put it in ' marks or this won't work!): ``` [com.canonical.unity-greeter] draw-user-backgrounds=false background='/foo/wallpaper.png' ``` alternatively, to set it to default, use this instead: ``` [com.canonical.unity-greeter] draw-user-backgrounds=true background='/usr/share/backgrounds/warty-final-ubuntu.png' ``` Press `CTRL` + `o` and then press `ENTER` to save the file. Press `CTRL` + `x` to exit nano. When you are finished, run the following command to apply the changes: ``` sudo glib-compile-schemas /usr/share/glib-2.0/schemas/ ``` [source](https://wiki.ubuntu.com/LightDM)
It was a permissions issue. Set the login screen to an image with permissions for only one user. Made it readable across all and now it works!
2,626,480
I have a bit of an issue with a site I maintain. I have been asked to add a report to a page that sits in a jsp page. The reporting information comes from a MySQL database. The problem is to connect the jsp to the database would require added functions to code that I do not have the original source of. I thought about redoing all the db connection again but thats a lot of time for something that will probably be rewritten in 3 weeks. Then I thought of just using PHP to display the report in the jsp as I have other pages connecting to the database using php (long story as to why were are using 2 languages). But the only way I know of is by using iFrames which is a bit of a no no. Using the object tag I've seen also has errors in IE. What would be the best way to do this?
2010/04/13
[ "https://Stackoverflow.com/questions/2626480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196420/" ]
You can use the JSTL ``` <c:import url="report.php"/> ``` to include the results of executing the PHP page.
``` <script language="php"> include_once ('report.php'); </script> ```
278,357
How can I set variables to be used in scripts as well? They don't have to be global / system-wide, just the current session is sufficient. But for some reason they seem gone even if I run a script right from my current terminal. Example: ```bash foo=bar echo "$foo" ``` output: `bar` However if test.sh contains `echo "$foo"` and I do: ``` foo=bar ./test.sh ``` The output is empty. How do I set a scope for temporary variables with a terminal session that remains valid when executing scripts from that same session?
2016/04/22
[ "https://unix.stackexchange.com/questions/278357", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/110067/" ]
`export foo=bar` will set the global variable $foo to bar. You can also use `foo=bar ./test.sh` as a single command to set foo to bar for test.sh.
You can run the assignment and echo test script in the same shell. ``` root@ijaz-HP-EliteBook-8560p:~# export foo=bar root@ijaz-HP-EliteBook-8560p:~# cat test.sh #!/bin/bash echo "$foo" root@ijaz-HP-EliteBook-8560p:~# ./test.sh bar ``` this is just one way of doing it.
278,357
How can I set variables to be used in scripts as well? They don't have to be global / system-wide, just the current session is sufficient. But for some reason they seem gone even if I run a script right from my current terminal. Example: ```bash foo=bar echo "$foo" ``` output: `bar` However if test.sh contains `echo "$foo"` and I do: ``` foo=bar ./test.sh ``` The output is empty. How do I set a scope for temporary variables with a terminal session that remains valid when executing scripts from that same session?
2016/04/22
[ "https://unix.stackexchange.com/questions/278357", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/110067/" ]
`export foo=bar` will set the global variable $foo to bar. You can also use `foo=bar ./test.sh` as a single command to set foo to bar for test.sh.
When you run your shell script, it executes in a new shell instance, and does not inherit any variables instantiated in the interactive shell instance. Specific variables can be inherited this way, called environment variables. You make a variable assignment an environment variable by using `export`, such as `export foo=bar`. This is the bash syntax, other shells may use `env` or some other method. You can also cause the shell script to execute in the same shell instance by 'sourcing' it. You can do this with `. test.sh` (note the period) or using `source test.sh`. You can do this in your interactive session, or you can do this from within a shell script. This is really handy for creating shell "libraries", where you source in a set of shell functions or variable definitions from an external file. Super handy. For instance: ``` #!/bin/bash . /path/lib.sh echo $foo # foo is instantiated in lib.sh do_something # this is a shell function from lib.sh ``` where lib.sh is: ``` foo="bar" do_something() { echo "I am do_something" } ```
278,357
How can I set variables to be used in scripts as well? They don't have to be global / system-wide, just the current session is sufficient. But for some reason they seem gone even if I run a script right from my current terminal. Example: ```bash foo=bar echo "$foo" ``` output: `bar` However if test.sh contains `echo "$foo"` and I do: ``` foo=bar ./test.sh ``` The output is empty. How do I set a scope for temporary variables with a terminal session that remains valid when executing scripts from that same session?
2016/04/22
[ "https://unix.stackexchange.com/questions/278357", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/110067/" ]
`export foo=bar` will set the global variable $foo to bar. You can also use `foo=bar ./test.sh` as a single command to set foo to bar for test.sh.
Another option could be to pass the variable to your script as an argument. ``` foo=bar ./test.sh $foo ``` The issue then becomes the contents of ./test.sh It would have to `echo $1` instead of `echo $foo` - the $1 indicating the first argument passed to the script.