qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
39,368,009
I have 3 network nodes running neutron-server .. Only one of these nodes is attached to the external network I use ml2 with openvswitch in the bridge mapping of the node connected to the external network - VIA FLOATING IPS - , i have external\_net mapped to the correct bridge .. On the other nodes i do not have this mapping defined and i do not have interfaces The issue i have is the following When i try to start a virtual machine that is connected to the external network , i have this error in the logs : neutron-server: 2016-09-07 12:33:00.975 57352 ERROR neutron.plugins.ml2.managers [req-def18170-5e45-4fef-9653-e008faa39913 - - - - -] Failed to bind port 035a58e1-f18f-428b-b78e-e8c0aaba7d14 on host node002 for vnic\_type normal using segments [{'segmentation\_id': None, 'phy sical\_network': u'external\_net', 'id': u'0d4590e5-0c48-4316-8b78-1636d3f44d43', 'network\_type': u'flat'}] neutron-server: 2016-09-07 12:33:00.975 57352 ERROR neutron.plugins.ml2.managers [req-def18170-5e45-4fef-9653-e008faa39913 - - - - -] Failed to bind port 035a58e1-f18f-428b-b78e-e8c0aaba7d14 on host node003 for vnic\_type normal using segments [{'segmentation\_id': None, 'phy sical\_network': u'external\_net', 'id': u'0d4590e5-0c48-4316-8b78-1636d3f44d43', 'network\_type': u'flat'}] on both nodes( node002 and node003 ) , because they DO NOT have this network defined ! so is this a bug or such a setup is not valid ? Thank you
2016/09/07
[ "https://Stackoverflow.com/questions/39368009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2924795/" ]
**Update**: Tim Biegeleisen's answer is more correct. You need to do a join on the two tables like that: ``` SELECT T1.id, T1.open, T1.receive+T2.receive, T1.close FROM T1 JOIN T2 USING (id); ``` **Edit**: If you want to update `T1`, you can do it like that: ``` UPDATE T1 SET receive=receive+coalesce((SELECT receive FROM T2 WHERE T1.id=T2.id),0); ```
``` SELECT T1.name, T1.open, T1.receive + COALESCE(T2.receive, 0) AS receive, T1.close - COALESCE(T2.receive, 0) AS close FROM T1 LEFT JOIN T2 ON T1.Id = T2.Id ``` If you want to `UPDATE` the first table, you can try this: ``` UPDATE T1 SET T1.recieve = T1.recieve + (SELECT COALESCE(T2.recieve, 0) FROM T2 WHERE T2.Id = T1.Id), T1.close = T1.close - (SELECT COALESCE(T2.recieve, 0) FROM T2 WHERE T2.Id = T1.Id) ```
12,807,539
I'm writing an application that takes arbitrary command line arguments, and then passes them onto a python function: ``` $ myscript.py --arg1=1 --arg2=foobar --arg1=4 ``` and then inside myscript.py: ``` import sys argsdict = some_function(sys.argv) ``` where `argsdict` looks like this: ``` {'arg1': ['1', '4'], 'arg2': 'foobar'} ``` I'm sure there is a library somewhere that does this, but I can't find anything. **EDIT:** argparse/getopt/optparse is not what I'm looking for. These libraries are for defining an interface that is the same for each invocation. I need to be able to handle arbitrary arguments. Unless, argparse/optparse/getopt has functionality that does this...
2012/10/09
[ "https://Stackoverflow.com/questions/12807539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118495/" ]
Here's an example using `argparse`, although it's a stretch. I wouldn't call this complete solution, but rather a good start. ``` class StoreInDict(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): d = getattr(namespace, self.dest) for opt in values: k,v = opt.split("=", 1) k = k.lstrip("-") if k in d: d[k].append(v) else: d[k] = [v] setattr(namespace, self.dest, d) # Prevent argparse from trying to distinguish between positional arguments # and optional arguments. Yes, it's a hack. p = argparse.ArgumentParser( prefix_chars=' ' ) # Put all arguments in a single list, and process them with the custom action above, # which convertes each "--key=value" argument to a "(key,value)" tuple and then # merges it into the given dictionary. p.add_argument("options", nargs="*", action=StoreInDict, default=dict()) args = p.parse_args("--arg1=1 --arg2=foo --arg1=4".split()) print args.options ```
If you really want to write something of your own instead of a proper command-line parsing library, for your input this should work: ``` dict(map(lambda x: x.lstrip('-').split('='),sys.argv[1:])) ``` You'll want to add something to catch arguments without an '=' in them.
3,815
I'm currently using the old Apple Mighty Mouse and I configured clicking on the trackball as a "middle click" that's been very handy for opening links in new tabs, closing tabs, etc. However, the mouse is starting to show its age and I've been looking at Apple's Magic Mouse and Magic Trackpad, and I'm wondering - do either of these support the "middle click" operation? If not, is there a gesture or a multi-finger click that can be used for the same things (i.e. opening new tabs, etc)?
2010/11/09
[ "https://apple.stackexchange.com/questions/3815", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/1570/" ]
Our friends over at [SuperUser have an answer for us](https://superuser.com/questions/62762/how-to-enable-middle-button-with-apples-new-magic-mouse): > > Here are two utilities that will allow you to customize gestures on the Magic Mouse, including adding middle click: > > > * [MagicPrefs](http://magicprefs.com/) > * [Better Touch Tool](http://blog.boastr.net/) > > >
[Multitouch](http://multitouch.app) is another option for adding "middle click" functionality to the Magic Mouse. (Disclaimer, I'm the developer.)
20,971,340
I am trying to make the black `div` (relative) above the second yellow one (absolute). The black `div`'s parent has a position absolute, too. ```css #relative { position: relative; width: 40px; height: 100px; background: #000; z-index: 1; margin-top: 30px; } .absolute { position: absolute; top: 0; left: 0; width: 200px; height: 50px; background: yellow; z-index: 0; } ``` ```html <div class="absolute"> <div id="relative"></div> </div> <div class="absolute" style="top: 54px"></div> ``` Expected Result: [![enter image description here](https://i.stack.imgur.com/gXSAS.png)](https://i.stack.imgur.com/gXSAS.png)
2014/01/07
[ "https://Stackoverflow.com/questions/20971340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1447267/" ]
This is because of the [Stacking Context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context), setting a z-index will make it apply to all children as well. You could make the two `<div>`s siblings instead of descendants. ``` <div class="absolute"></div> <div id="relative"></div> ``` <http://jsfiddle.net/P7c9q/3/>
I was struggling to figure it out how to put a div over an image like this: [![z-index working](https://i.stack.imgur.com/fHSWj.png)](https://i.stack.imgur.com/fHSWj.png) No matter how I configured z-index in both divs (the image wrapper) and the section I was getting this: [![z-index Not working](https://i.stack.imgur.com/QqhRn.png)](https://i.stack.imgur.com/QqhRn.png) Turns out I hadn't set up the background of the section to be `background: white;` so basically it's like this: ``` <div class="img-wrp"> <img src="myimage.svg"/> </div> <section> <other content> </section> section{ position: relative; background: white; /* THIS IS THE IMPORTANT PART NOT TO FORGET */ } .img-wrp{ position: absolute; z-index: -1; /* also worked with 0 but just to be sure */ } ```
15,095,756
I've thoroughly looked for an answer but everything seems to only give me half of what I need, which is how I managed to get this started. What I'm trying to do is enable a dropdown menu when a checkbox is checked, but keep it disabled otherwise. I'm not really sure how to call the function in the tag, but then again i'm not really sure it's working. ``` function .onCheckChange() { if ($("#partoption2").is(':checked')) { $("#parttwoqty").attr('disabled', 'disabled'); $("#partoption2").val("TRUE"); } else { $("#parttwoqty").attr('disabled'); $("#partoption2").val("FALSE"); } } ``` This is the fiddle: <http://jsfiddle.net/xjn3Q/1/> Thanks!
2013/02/26
[ "https://Stackoverflow.com/questions/15095756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2112319/" ]
I'm not 100% clear on your question, but it sounds like you want your substitute date evaluated in the `WHERE` clause, even though you have not included the `NVL()`. Have you tried this: ``` select a.id, title, body, NVL(a.to_date, to_date('9999-12-31 23:59:59', 'YYYY-MM-DD HH24:MI:SS')) as todate, cr_date from a, b where a.cust_id = 20 and a.body_id = b.body_id and a.from_date <= current and NVL(a.to_date, to_date('9999-12-31 23:59:59', 'YYYY-MM-DD HH24:MI:SS')) > current ```
The basic problem is that the 'display labels' or 'column aliases' are not available for use in the body of the query (the WHERE clause). You could get around this using a sub-query: ``` SELECT id, title, body, to_date, cr_date FROM (SELECT a.id, a.title, b.body, NVL(a.to_date, '9999-12-31 23:59:59') AS to_date, b.cr_date FROM a JOIN b ON a.body_id = b.body_id WHERE a.cust_id = 20 AND a.from_date <= CURRENT ) AS t WHERE to_date > CURRENT ``` This avoids repeating the NVL expression. Note that you had a conflict between `todate` in an AS and `to_date` in the WHERE. I also recommend identifying which table each column comes from when a query uses more than one table (as the inner query does, but the outer query does not). I usually use single-letter aliases for the tables; this time, the aliases were unnecessary since the table names given were single-letter names. The query plan for this is likely to be the same as for the single-level query. You could check using SET EXPLAIN, of course.
2,138,600
i have the following code: ``` function tryToDownload(url) { oIFrm = document.getElementById('download'); oIFrm.src = url; //alert(url); } function downloadIt(file) { var text = $("#downloaded").text(); setTimeout(function(){ $("#downloadBar").slideDown("fast") }, 700); setTimeout('tryToDownload("index.php?fileName='+file+'")', 400); setTimeout(function(){ $("#downloadBar").slideUp("fast") }, 5000); } ``` And there is a DIV with id "downloaded". So the code is ``` <div id="downloded">230</div> ``` 230 shows that the item is downloaded 230 times. What I want to do is that when some body clicks the download it updates 230 to 231. How can it be possible with jquery kindly help.
2010/01/26
[ "https://Stackoverflow.com/questions/2138600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259123/" ]
put this inside the **downloadIt()** function right after all the setTimeOuts are called ``` var curr_val = $('#downloaded').text(); var new_val = parseInt(curr_val)+1; $('#downloaded').text(new_val); ```
Something like this will do: ``` i = parseInt($("#downloaded").text()); $("#downloaded").text((i+1)); ```
67,651,665
I have a functions.py file with all my functions. I want to print a variable from the main.py file which was created in a funtions in the function.py file. How can i do that? functions.py: ``` from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys import time browser = webdriver.Firefox() def open_tradeview(): browser.get('https://www.tradingview.com/chart/') wait = WebDriverWait(browser, 10) wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[2]/div[3]/div/div/div/div"))).click() #Click on Hamburger menu wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[6]/div/span/div[1]/div/div/div[11]"))).click() #Click on sign in button wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[6]/div/div[2]/div/div/div/div/div/div/div[1]/div[4]/div/span"))).click() #Click on sign in with email button wait.until(EC.visibility_of_element_located((By.NAME, "username"))).send_keys("trading_view_bot@fastmail.com") #type in email wait.until(EC.visibility_of_element_located((By.NAME, "password"))).send_keys("2C3-cc9r" + Keys.RETURN) #type in password time.sleep(18) wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[2]/div[1]/div[3]/div/div/div/article/button"))).click() #Click ad away time.sleep(26) wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[2]/div[1]/div[3]/div/div/div/div/article/button"))).click() #Click ad away time.sleep(5) wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[6]/div[2]/div/div[2]/div/div/div[1]/button"))).click() #Click ad away wait.until(EC.element_to_be_clickable((By.ID, "header-toolbar-symbol-search"))).click() #Currency pair wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".search-Hsmn_0WX.upperCase-Hsmn_0WX.input-3n5_2-hI"))).send_keys("VETUSD") #type in currency pair wait.until(EC.element_to_be_clickable((By.XPATH, "//*[contains(text(), 'VeChain / US Dollar (calculated by TradingView)')]"))).click() #select new currency pair wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[2]/div[2]/div/div/div[1]/div[1]/div/div/div/div/div[2]/div/div"))).click() #click on time frame wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[6]/div/span/div[1]/div/div/div/div[12]/div"))).click() #select 30min time frame wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[2]/div[2]/div/div/div[1]/div[1]/div/div/div/div/div[5]/div/div"))).click() #click on indicators wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[2]/div[2]/div/div/div[1]/div[1]/div/div/div/div/div[5]/div/div"))).click() #click on indicators wait.until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[6]/div/div/div[1]/div/div[2]/div/input"))).send_keys("ATR Trailing Stoploss") #search for ATR indicator wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[6]/div/div/div[1]/div/div[3]/div[2]/div/div/div[2]/div[1]"))).click() #click on ATR indicator wait.until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[6]/div/div/div[1]/div/div[1]/span"))).click() #close search window def get_atr_price(): global atr global price atr = browser.find_element_by_xpath('/html/body/div[2]/div[1]/div[2]/div[1]/div/table/tr[1]/td[2]/div/div[1]/div[2]/div[2]/div[2]/div[2]/div/div[1]/div').text price = browser.find_element_by_xpath('/html/body/div[2]/div[1]/div[2]/div[1]/div/table/tr[1]/td[2]/div/div[1]/div[1]/div[2]/div[3]/span[2]').text ``` main.py: ``` from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys import time import yagmail from functions import * import functions functions.get_atr_price() open_tradeview() get_atr_price() print(atr) ``` when i want to print the variable atr i get an error that the variable atr is not defined So basically how can I access every variable from both files?
2021/05/22
[ "https://Stackoverflow.com/questions/67651665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15994222/" ]
Have your tried with something like this? ```py print(functions.atr) ``` Here is an example that works for me: main.py: ```py import functions print("hello from main!") print(functions.hello) functions.funky() # this changes the value print(functions.hello) ``` functions.py: ```py hello = 4 # here the global variable is declared def funky(): print("hello from functions.funky()") global hello hello = 10 # changes the value ``` Output: ```none hello from main 4 hello from functions.funky() 10 ``` EDIT: If you want to work without global variables, you could make the `get_atr_price()` function return the atr and price, like this: functions.py: ```py def get_atr_price(): atr = browser.find_element_by_xpath('/html/body/div[2]/div[1]/div[2]/div[1]/div/table/tr[1]/td[2]/div/div[1]/div[2]/div[2]/div[2]/div[2]/div/div[1]/div').text price = browser.find_element_by_xpath('/html/body/div[2]/div[1]/div[2]/div[1]/div/table/tr[1]/td[2]/div/div[1]/div[1]/div[2]/div[3]/span[2]').text return atr, price ``` Then, in your main.py file, you can use them like this: ```py atr, price = functions.get_atr_price(); ```
In your main function, you can take the result of any function in a variable then print ``` trade = open_tradeview() atr = get_atr_price() print(trade) print(atr) ```
1,237,590
In *Additional Drivers* under Software & Updates, the NVIDIA driver is stuck on *Continue using a manually installed driver*, and all other options are greyed out. I want to set the driver to proprietary driver(`nvidia-driver-390`), which was originally selected before I changed it to the open source driver, but now it is stuck. How can I resolve this issue? Should remove all NVIDIA drivers and install them again? If so , how to do it safely in Ubuntu 20.04? Additional info: 1. `cat /var/log/Xorg.0.log` output: <https://termbin.com/hqo3> 2. `lspci -k | grep -EA3 'VGA|3D|Display'` output: <https://termbin.com/bog0>
2020/05/09
[ "https://askubuntu.com/questions/1237590", "https://askubuntu.com", "https://askubuntu.com/users/311423/" ]
This problem should be fixed by running ``` sudo ubuntu-drivers install ``` after a reboot.
I also couldn't update to a newer Nvidia driver because a manual driver was installed, in my case from 470 to 510 driver on an Focal Desktop system of Canonical. My solution was: 1. Open a terminal and run the command: ``` sudo ubuntu-drivers autoinstall ``` The above will install the newest recommended driver. 2. Wait until all automatic commands are executed and reboot the system. 3. The Linux kernel loaded the 510 driver. 4. Checked *Additional Drivers* in Software & Updates, which points to Nvidia 510 driver. The accidentally selected manual driver option was removed.
39,629,786
I've whiteboarded this out, and cannot seem to understand why I am getting an out of memory error. The project is to create a linked list and some of its methods from scratch. My other functions are good to go, but this swap function is giving me a lot of trouble. When I run the debugger, the program crashes on the pj.nextNodeLink = p.nextNodeLink. The swap function is supposed to take two int inputs and swap their values. I was attempting to change the nextNodeLink pointers to do so, but clearly am failing. Any help would be much appreciated! ``` public void swapByIndex(int firstIndexValue, int secondIndexValue){ if(firstIndexValue<0 || secondIndexValue<0 || firstIndexValue>size-1 || secondIndexValue>size-1) { throw new ArrayIndexOutOfBoundsException(); } else if(head == tail){ // Case one - only one element in list System.out.println("The list only has one element. Nothing to swap. "); } else{ // Case Two - two or more elements //keep a pointer to the next element of head Node firstPointer = head; Node firstSwapElement = firstPointer; for(int k=0; k<firstIndexValue; k++){ firstSwapElement = firstPointer; // save the node P is on into 'previ' node firstPointer = firstPointer.nextNodeLink; // P iterates to next node } Node secondPointer = head; Node secondSwapElement = secondPointer; for(int k=0; k<secondIndexValue; k++){ secondSwapElement = secondPointer; secondPointer = secondPointer.nextNodeLink; } Node secondNodeSave = secondPointer; // save this so we have the correct next node link for second swap secondPointer.nextNodeLink = firstPointer.nextNodeLink; firstSwapElement.nextNodeLink = secondSwapElement; firstPointer.nextNodeLink = secondNodeSave.nextNodeLink; secondSwapElement.nextNodeLink = secondPointer; } } ```
2016/09/22
[ "https://Stackoverflow.com/questions/39629786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3545786/" ]
You just need to remove the dashes, do a loop over all the characters, parse them as integers, and add them up. ``` var s = "5246-9346-7341-8534"; var sum = 0; var i; s = s.replace(/-/g, ""); for (i = 0; i < s.length; i++) { sum += parseInt(s.substr(i, 1)); } console.log(s, "=", sum); // 74 ``` (I didn't just do your homework for you, did I?)
Replace the hyphens - iterate through the string and add the parsed Number to a total - display the total (74). Note that I added this to an input so that you could add a button and create a named function that allows you to add other numbers. ```js function addMe(){ var inputVal = document.getElementById('inputNumber').value.replace(/-/g,''); var newTotal = 0; for(i=0;i<inputVal.length;i++){ newTotal += parseInt(inputVal[i]); } console.log('total = ' + newTotal); //gives 74 in this instance } ``` ```html <input type="text" value="5246-9346-7341-8534" id="inputNumber"/> <button type = "button" onclick="addMe()"> Add Values</button> ```
261,539
Getting **Invalid Form Key. Please refresh the page** error not able to do any action after upgrade of **Magento 2.2.5 to Magento 2.3**.
2019/02/13
[ "https://magento.stackexchange.com/questions/261539", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/76119/" ]
Finally I got the solution I have a custom payment method that uses the cc-form to take credit card payments with and without 3dsecure. After placing order with 3dsecure, I am re-directing to 3dsecure page as normal, but on returning from 3dsecure, I am re-directed to the home page with "Invalid Form Key. Please refresh the page why because in Magento 2.3 core payment methods are using CsrfAwareActionInterface for each controller." So now i have implemented same thing in my custom payment method as below ``` use Magento\Framework\App\CsrfAwareActionInterface; use Magento\Framework\App\Request\InvalidRequestException; use Magento\Framework\App\RequestInterface; class CustomPaymentResponse extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface /** * @inheritDoc */ public function createCsrfValidationException( RequestInterface $request ): ?InvalidRequestException { return null; } /** * @inheritDoc */ public function validateForCsrf(RequestInterface $request): ?bool { return true; } ``` **Note :** you can get reference from core module. Here is the core file path **vendor\magento\module-authorizenet\Controller\Directpost\Payment\BackendResponse.php**.
``` use Magento\Framework\App\CsrfAwareActionInterface; use Magento\Framework\App\Request\InvalidRequestException; use Magento\Framework\App\RequestInterface; class CustomPaymentResponse extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface /** * @inheritDoc */ public function createCsrfValidationException( RequestInterface $request ): ?InvalidRequestException { return null; } /** * @inheritDoc */ public function validateForCsrf(RequestInterface $request): ?bool { return true; } /** * Dispatch request * * @return \Magento\Framework\Controller\ResultInterface|ResponseInterface * @throws \Magento\Framework\Exception\NotFoundException */ public function execute() { //your response check } ``` Your response controller should be like this, then only form key issue will fix. Referrence: <https://github.com/magento/magento2/issues/19712>
861,296
I understand that only one instance of any object according to .equals() is allowed in a Set and that you shouldn't "need to" get an object from the Set if you already have an equivalent object, but I would still like to have a .get() method that returns the actual instance of the object in the Set (or null) given an equivalent object as a parameter. Any ideas/theories as to why it was designed like this? I usually have to hack around this by using a Map and making the key and the value same, or something like that. EDIT: I don't think people understand my question so far. I want the exact object instance that is already in the set, not a possibly different object instance where .equals() returns true. As to why I would want this behavior, typically .equals() does not take into account all the properties of the object. I want to provide some dummy lookup object and get back the actual object instance in the Set.
2009/05/14
[ "https://Stackoverflow.com/questions/861296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106781/" ]
Well, if you've already "got" the thing from the set, you don't need to get() it, do you? ;-) Your approach of using a Map is The Right Thing, I think. It sounds like you're trying to "canonicalize" objects via their equals() method, which I've always accomplished using a Map as you suggest.
It's just an opinion. I believe we need to understand that we have several java class without fields/properties, i.e. only methods. In that case equals cannot be measured by comparing function, one such example is requestHandlers. See the below example of a JAX-RS application. In this context SET makes more sense then any data structure. ``` @ApplicationPath("/") public class GlobalEventCollectorApplication extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<Class<?>>(); classes.add(EventReceiverService.class); classes.add(VirtualNetworkEventSerializer.class); return classes; } } ``` To answer your question, if you have an shallow-employee object ( i.e. only EMPID, which is used in equals method to determine uniqueness ) , and if you want to get a deep-object by doing a lookup in set, SET is not the data-structure , as its purpose is different.
28,615,922
I am a web developer and do not have any experience with developing mobile friendly websites. When we are developing a mobile friendly website, do we need to create separate files for mobile version? Or can we use same files that we created for desktop version?
2015/02/19
[ "https://Stackoverflow.com/questions/28615922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2384770/" ]
If you are going to develop a big site like flipkart, ebay or facebook, then its better you do separate mobile version, because such type of websites will take more time to load in mobiles. You need to display only relevant content in mobiles. If its a simple website, better use Bootstrap.
Both you can make one file launch another, or have one big monster file. [How to detect Safari, Chrome, IE, Firefox and Opera browser?](https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser) But I think this might be more of what your looking for.
5,381,526
What are the generic cookie limits for modern browsers, as of 2011? I'm particularly interested in: * Max size of a single cookie * Max number of cookies per host/domain name + path * Max number of cookies per host/domain name * Max number / max total size of all cookies in a given browser I'm aware of [RFC 2109](http://www.ietf.org/rfc/rfc2109.txt) that specifies: * at least 300 cookies * at least 4096 bytes per cookie (as measured by the size of the characters that comprise the cookie non-terminal in the syntax description of the Set-Cookie header) * at least 20 cookies per unique host or domain name but what are real-world specs?
2011/03/21
[ "https://Stackoverflow.com/questions/5381526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/487064/" ]
Here's a handy tool to test it: <http://browsercookielimits.iain.guru/> It reveals quite a lot about the internal details regarding cookies. Click "Run Tests for Current Browser" for the results (it only takes a moment). For example, I ran all tests for Google Chrome 10.0.648.134 beta: ``` 22:23:46.639: Starting 22:23:47.345: Count: Max Cookie count with Character Length 3 and character "1": 180 22:23:50.131: Size: Max Cookie Character Length using character "1": 4096 22:23:52.347: Count: Max Cookie count with Character Length 4096 and character "1": 180 22:23:54.517: Size: Max Cookie Character Length using character "ÿ": 2049 22:23:57.450: Count: Max Cookie count with Character Length 2049 and character "ÿ": 180 22:23:59.41: Count: Max Cookie count with Character Length 100 and character "1": 180 22:24:0.535: Count: Max Cookie count with Character Length 10 and character "1": 180 22:24:2.88: Count: Max Cookie count with Character Length 5 and character "1": 180 22:24:2.886: Guessing Max Cookie Count Per Domain: 180 22:24:2.887: Guessing Max Cookie Size Per Cookie: 4096 bytes 22:24:2.887: Guessing Max Cookie Size Per Domain: NA ``` --- This answer is pretty old, but I just checked results for the latest Chrome version, and they're essentially the same. Edit: updated the answers for Chrome 54.0.2840.98 (64-bit).
In Firefox >= 63, the max number of cookies per domain is [180](https://bugzilla.mozilla.org/show_bug.cgi?id=1460251), cf pref "network.cookie.maxPerHost". When it reaches the limit, it will drop stale cookies, then drop [non secure cookies](https://bugzilla.mozilla.org/show_bug.cgi?id=1357676). If nothing works, it will simply refuse the cookie (cf netwerk/cookie/nsCookieService.cpp)
9,661,045
I have an HTML file and I want to take grab the text from this block, shown here: ``` <strong class="fullname js-action-profile-name">User Name</strong> <span>&rlm;</span> <span class="username js-action-profile-name"><s>@</s><b>UserName</b></span> ``` I want it to display as: ``` User Name @UserName ``` How would I do this using Beautiful Soup?
2012/03/12
[ "https://Stackoverflow.com/questions/9661045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1224640/" ]
``` from bs4 import BeautifulSoup html = '''<strong class="fullname js-action-profile-name">User Name</strong> <span>&rlm;</span> <span class="username js-action-profile-name"><s>@</s><b>UserName</b></span>''' soup = BeautifulSoup(html) username = soup.find(attrs={'class':'username js-action-profile-name'}).text fullname = soup.find(attrs={'class':'fullname js-action-profile-name'}).text print fullname print username ``` Outputs: ``` User Name @UserName ``` Two notes: 1. Use `bs4` if you're starting something new / just learning BS. 2. You will probably be loading your HTML from an external file, so replace `html` with a file object.
This assumes *index.html* contains the markup from the question: ``` import BeautifulSoup def displayUserInfo(): soup = BeautifulSoup.BeautifulSoup(open("index.html")) fullname_ele = soup.find(attrs={"class": "fullname js-action-profile-name"}) fullname = fullname_ele.contents[0] print fullname username_ele = soup.find(attrs={"class": "username js-action-profile-name"}) username = "" for child in username_ele.findChildren(): username += child.contents[0] print username if __name__ == '__main__': displayUserInfo() # prints: # User Name # @UserName ```
399,464
I spun up a Remote Desktop Server instance on Amazon's Virtual Private Cloud service... What's the best/easiest way to print from the VPC to local printers? The local printers are IP based, but not "cloud printers". I'm familiar with how Cloud Printing works for Chrome, but is there a way to install a cloud printer as a regular Windows printer on a Remote Desktop Server and "just have it work?"
2012/06/16
[ "https://serverfault.com/questions/399464", "https://serverfault.com", "https://serverfault.com/users/61373/" ]
There is a new [blog post from VMware](http://blogs.vmware.com/vsphere/2013/10/are-esxi-patches-cumulative.html?utm_source=dlvr.it&utm_medium=twitter) The relevant summary is: > > In short, the answer is yes, the ESXi patch bundles are cumulative. However, when applying patches from the command line using the ESXCLI command you do need to be careful to avoid getting into a situation where you could miss some updates. > > > The key is when applying patches from the command line you need to make sure you apply patches using the “esxcli software profile update …” command and not the “esxcli software vib update …” command. > > > ... > > Patches are essentially updates to VIBs and are distributed as ZIP archives. These archives can be loaded into Update Manager, or they can be copied to the host and used with the ESXCLI command. It’s important to note that along with the updated VIBs the patch archives also includes the latest version of all the other VIBs in the image profile. When you download a patch you aren’t just downloading the updates. You’re getting the complete ESXi software image. > > > So, yes. They are cumulative as long as you install them properly.
ewwhite, You may have already come across this article but I had it bookmarked awhile back: <http://blogs.vmware.com/vsphere/2012/02/understanding-esxi-patches-finding-patches.html> Hopefully this helps
28,702,372
By default if I am not logged and I try visit this in browser: ``` http://localhost:8000/home ``` It redirect me to `http://localhost:8000/auth/login` How can I change to redirect me to `http://localhost:8000/login`
2015/02/24
[ "https://Stackoverflow.com/questions/28702372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4207462/" ]
Just to extend @ultimate's answer: 1. You need to modify `App\Http\Middleware\Authenticate::handle()` method and change `auth/login` to `/login`. 2. Than you need to add `$loginPath` property to your `\App\Http\Controllers\Auth\AuthController` class. Why? See [Laravel source](https://github.com/laravel/framework/blob/22b248c48c6b094a51b9a8de8cd8fde56531db5b/src/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.php#L135). In result you'll have this in your middleware: ``` namespace App\Http\Middleware; class Authenticate { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($this->auth->guest()) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect()->guest('/login'); // <--- note this } } return $next($request); } } ``` And this in your AuthController: ``` namespace App\Http\Controllers\Auth; class AuthController extends Controller { protected $loginPath = '/login'; // <--- note this // ... other properties, constructor, traits, etc } ```
Authentication checks are made using middleware in Laravel 5. And the middleware for auth is `App\Http\Middleware\Authenticate`. So, you can change it in `handle` method of the middleware.
7,424,210
I'm building my first game in Java, from scratch. I've decided that the GameWorld class, that centralizes the main operations of the game (handling input, etc), would be best implemented as a singleton (using an enum). The relevant code for the enum is below. ``` public enum GameWorld { INSTANCE; private static InputController input = InputController.getInput(); public EntityPlayer player = new EntityPlayer(10, 10, 5, 5); public static GameWorld getWorld() { return INSTANCE; } public InputController getInputController() { return input; } } ``` The exception occurs in the constructor of EntityPlayer. The code and stack trace are below. ``` public class EntityPlayer implements Entity, InputListener { private int xPos; private int yPos; private int width; private int height; // Velocity of object // Determines where it sets itself on update private int xVel; private int yVel; private GameWorld world; private InputController input; private boolean solid; public EntityPlayer(int x, int y, int width, int height) { xPos = x; yPos = y; this.width = width; this.height = height; solid = true; xVel = 0; yVel = 0; world = getWorld(); input = world.getInputController(); input.registerKeyListener(this); } @Override public Graphics draw(Graphics g) { g.setColor(Color.yellow); g.fillRect(xPos, yPos - height, width, height); return g; } @Override public void update() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getXPos() { return xPos; } @Override public int getYPos() { return yPos; } @Override public Rectangle getRect() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isSolid() { return solid; } @Override public void kill() { } @Override public GameWorld getWorld() { return GameWorld.getWorld(); } @Override public void sendKeyPress(KeyEvent ke) { System.out.println(ke.getKeyChar()); } @Override public void sendMouseMove(MouseEvent me) { } } ``` The stack trace: ``` Exception in thread "main" java.lang.ExceptionInInitializerError at com.pvminecraft.gameworld.Main.<clinit>(Main.java:14) Caused by: java.lang.NullPointerException at com.pvminecraft.gameworld.entities.EntityPlayer.<init>(EntityPlayer.java:45) at com.pvminecraft.gameworld.GameWorld.<init>(GameWorld.java:15) at com.pvminecraft.gameworld.GameWorld.<clinit>(GameWorld.java:13) ... 1 more ``` Line 14 of Main.java is me getting another instance of GameWorld for testing. I'm not sure why this is throwing an Exception. If I remove references to GameWorld in EntityPlayer, it goes away. If you need the code for Main.java, tell me in the comments and I will post it. Thanks! **EDIT:** Line 45 in EntityPlayer is "input = world.getInputController();" I'm pretty sure that world is null, though I have no idea why.
2011/09/14
[ "https://Stackoverflow.com/questions/7424210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/599050/" ]
You are turning yourself in circles. You want to initialize the `GameWorld.INSTANCE` variable. Before you can do that, you have to initialize all the fields of the `GameWorld` class. After initializing all the field, the variable `INSTANCE` will be assigned. Before that happens, it still has the default value of `null`. During the initialization, the field `player` is initialized. And in that initialization, you already access the `INSTANCE` field. So you have a circular dependency. You really must decouple your classes, so that they become more independent of each other.
I didn't see any guarantee that the expression ``` InputController.getInput() ``` returns non-null. And since your code is very debugging-friendly (at least one NullPointerException per line) it should be trivial to see which variable is null. As I said, I suspect `input`.
21,302,623
I am rewriting my website URL with .htaccess but facing issues, I didnt know about rewrite URL, I just copy and paste the code from internet, ``` RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/\.]+)/?$ page.php? [L,QSA] ``` This works for me and redirects, **www.domain.com/page.php?id=1** to **www.domain.com/page?id=1**. But the problem is arised when I open **www.domain.com/someotherpage.php** then it redirects me to **page.php**. And also what ever I write in URL randomly its open **www.domain.com/page** for example ``` domain.com/any domain.com/thing domain.com/written ``` I did some researched for this issue but coudn't find any solution, then I asked my question here.
2014/01/23
[ "https://Stackoverflow.com/questions/21302623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2379039/" ]
again :), this domain class is generated by spring-security-plugin and its use isn't to be exposed directly to web. Normally grails scaffolding isn't applied to this domain class, but only to user and role domain class with some correction. If your need is to administrate roles,users and relations between users and roles you can use spring-security-ui-plugin. With this plugin you have a group of views/controllers that help you to manage spring-secuirity-plugin. At least if you want to create you personal web interface, whereas the plugin is opensource you could see how the controllers, which are used in this plugin, work. Bye
I think that in this case it should be something like (for show() method): ``` def show(Long secUserId, Long secRoleId) { def secUserSecRoleInstance = SecUserSecRole.get(secUserId, secRoleId) if (!secUserSecRoleInstance) { flash.message = message(code: 'default.not.found.message', args: [message(code: 'secUserSecRole.label', default: 'SecUserSecRole'), id]) redirect(action: "list") return } [secUserSecRoleInstance: secUserSecRoleInstance] } ```
263,092
I'm trying to build a simple low-power water level alarm such that it could run continuously for at least 4 months on just 3x AA batteries. I've found this schematic which uses the 555 timer: [![enter image description here](https://i.stack.imgur.com/hmYaY.jpg)](https://i.stack.imgur.com/hmYaY.jpg) However, the 555 timer has a minimum power consumption of around 30mW, which would be too much. Would it be a good idea to modify the circuit such that the water's conduction supplies power to the 555 like so: [![enter image description here](https://i.stack.imgur.com/LzVSy.jpg)](https://i.stack.imgur.com/LzVSy.jpg) Is water conductive enough for this to operate? Would it be a better idea to just use a low-power MCU like MSP430 and raise an interrupt when the probes short by water's conduction? Any thought appreciated.
2016/10/12
[ "https://electronics.stackexchange.com/questions/263092", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/80217/" ]
I assume that you are using BLE or similar. Be aware that RSSI is a very blunt instrument indeed and needs both understanding and a degree of magic to work well. There is only so much magic available in an office building and if you expect consistent fine precision you will be disappointed. If working in air (eg assuming that your office is not underwater or filled with solid rock or polystyrene beads or other dielectric) then n should be constant and determinate. The fact that they have given a typical range is a clue that things are less exact in practice than in theory. If you are doing this only theoretically and not with practical experiment as well then then the value of n used is not too important as it is almost certain to be wrong. RSSI (signal strength) readings can be affected by reflections, position of objects in the target space, object motion, line of site or not between nodes, number of nodes, presence of other unrelated signals on the allocated frequency band (or stronger ones out of band), directionality (or not) of antennas, front end overload and intermodulation performance, system signal to noise ratio, ... to give a far from complete list. RSSI distance measurements almost certainly need to be based on multiple signal attempts processed in some way. Having reference nodes of known distance can help. You can have fixed "beacons" with moving targets, or moving beacons with fixed targets, or some mix. There is a VERY large amount of information online on indoor distance determination using RSSI and some fairly basic searching will turn up more than you are liable to be able to assimilate in a sensible timespan. **\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_** **CLOSELY RELATED:** Here is an edited subset of some notes I wrote for somebody else a few months ago. Estimote are very active in this area and looking at what they are doing should be informative: **ESTIMOTE LOCATION development kit (!)** A must read. But, it starts like this: * Estimote Indoor Location SDK is a set of tools for building precise, blue-dot location services indoors. Just configure Estimote Beacons (no sweat, it’s fully automated), attach them to walls and you’re ready to set up your first location. From there, the location’s map is automatically uploaded to Estimote Cloud, and voila! You can now embed it in your own app. Location accuracy varies depending on location size, shape, and crowd density. In small rooms, it’s as good as 1 meter, in larger spaces it can be around 4 meters on average. Keep in mind that Indoor Location SDK is still work in progress: we’re constantly improving accuracy, adding new features, and optimizing for bigger venues. --- Estimote indoor location video 2m-12 <https://www.youtube.com/watch?v=wtBERi7Lf3c> Nearables video 2m (smaller, lower range, lower capability, lower cost.) <https://www.youtube.com/watch?v=JrRS8qRYXCQ> Estimote location (scroll down) Existing working install beacons, setup and go system Estimote You tube videos many many many <https://www.youtube.com/results?search_query=estimote> eg Estimote Beacons factory - posted December 2013 56s <http://estimote.com/indoor/> --- Building the next generation of context-aware mobile apps requires more than just iBeacon™ hardware. Developers need smarter software: tools that give them control over proximity and position within a given space, without unnecessary hassle. Estimote Indoor Location does just that. It makes it incredibly easy and quick to map any location. Once done, you can use our SDK to visualize your approximate position within that space in real-time, in your own app. Indoor Location creates a rich canvas upon which to build powerful new mobile experiences, from in-venue analytics and proximity marketing to frictionless payments and personalized shopping. What is Estimote Indoor Location SDK? Download software free. ``` http://developer.estimote.com/indoor/ ``` **\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_** **iBeacon and other RSSI position location:** While iBeacon is principally intended as an information promulgation system, a number of people have used the BLE transmitters as position/ triangulation based on RSSI and other methods. The Wikipedia page provides a good general overview. ``` https://en.wikipedia.org/wiki/IBeacon ``` BLE mesh networking ``` https://en.wikipedia.org/wiki/Scatternet ``` An experienced BLE position location developer and vendor. ``` https://locatify.com/blog/indoor-positioning-systems-ble-beacons/ ``` BLE - more re beacon based ``` http://estimote.com/ ``` Another <http://kontakt.io/> BLE in GEC lighting fixtures ``` http://9to5mac.com/2014/05/29/ge-integrates-ibeacons-in-new-led-lighting-fixtures-rolling-out-in-walmart-other-retailers/ ``` ' Google Scholar on ble position detection. ``` https://scholar.google.co.nz/scholar?q=ble+position+detection&hl=en&as_sdt=0&as_vis=1&oi=scholart&sa=X&ved=0ahUKEwiinMfLzqLNAhXkdqYKHWe4AOkQgQMIGjAA ``` 9783319226880-c2.pdf <- URL needed. ``` Indoor Position Detection Using BLE Signals Based on Voronoi Diagram ``` An Analysis of the Accuracy of Bluetooth Low Energy for Indoor Positioning Applications ``` http://www.cl.cam.ac.uk/~rmf25/papers/BLE.pdf ``` Indoor positioning with beacons and mobile devices ``` http://bits.citrusbyte.com/indoor-positioning-with-beacons/ ``` **OPEN BEACON PROJECT** ``` http://get.openbeacon.org/about.html ``` Development <http://get.openbeacon.org/source/#github> <http://www.openbeacon.org/> Bluetooth Proximity Tag Nordic BLS IC / modules <https://www.nordicsemi.com/eng/Products/Bluetooth-low-energy2/nRF51822> <http://get.openbeacon.org/source/#github> --- I have many many many variably related references if of interest - but, so does Mr Gargoyle. eg [Every picture tells a story](https://www.google.co.nz/search?q=ble+rssi+distance+position&num=100&espv=2&source=lnms&tbm=isch&sa=X&ved=0ahUKEwitnuz6ldXPAhVEilQKHQGnCQ8Q_AUICCgB&biw=1527&bih=836) and Most of these [many many many stories](https://www.google.co.nz/search?sourceid=chrome-psyapi2&ion=1&espv=2&ie=UTF-8&q=ble%20rssi%20distance%20position&oq=ble%20rssi%20distance%20position&aqs=chrome..69i57.11311j0j8) will be of high relevance.
If you want to calculate the path loss exponent 'n' you would first need to train the linear or straight line model. You can do this by determining the path loss for a range of distances within the region of interest. The path loss exponent can then be determined by fitting a straight line to the distance vs path loss data. This can either be done in MATLAB or if you are not good with coding using the linear regression model within excel. More the data used to find 'n' better it is. But remember that the linear model just gives you averaged out results. The results obtained by this approach may vary from reality quite appreciably.
6,441
If I try to open an MP4 file made by a Sony Webbie in Sony Vegas Platinum 6, it won't open. (Something made me think they would work together.) The Webbie files are H264. It will happily play MP4/H263. Is there a codec or something I can download?
2009/07/16
[ "https://superuser.com/questions/6441", "https://superuser.com", "https://superuser.com/users/1782/" ]
Youtube have a guide on ideal video settings for uploading: ["Getting Started: Optimizing your video uploads"](http://www.google.com/support/youtube/bin/answer.py?answer=132460&topic=16612&hl=en-US) > > Video > ----- > > > * **Resolution:** Recommended: 1280 x 720 (16x9 HD) and 640 x 480 (4:3 SD) > > > There is no required minimum resolution - in general the higher resolution the better and HD resolution is preferred. For older content, lower resolution is unavoidable. > * **Bit rate** - Because bit-rate is highly dependent on codec there is no recommended or minimum value. Videos should be optimized for resolution, aspect ratio and frame rate rather than bit rate. > * **Frame rate** - The frame rate of the original video should be maintained without re-sampling. In particular pulldown and other frame rate re-sampling techniques are strongly discouraged. > * **Codec** - `H.264`, `MPEG-2` or `MPEG-4` preferred. > > > Audio > ----- > > > * **Codec** - `MP3` or `AAC` preferred > * **Sampling rate** - 44.1kHz > * **Channels** - 2 (stereo) > > > Stick to that, and Youtube shouldn't do any further transcoding on your video, thus the quality should be the same as what you upload..
YouTube recommends MPEG4 compression. I'd try the mpeg4/improved profile (if you're using the export using quicktime option). iMovie also has a built in export to YouTube setting (at least it did in iMovie '08) which is probably more than adequate. YouTube is going to re-compress the video in any case, so you don't really have to worry about file size and compatibility, which are the two big hassles/tradeoffs when doing compression. <http://www.youtube.com/t/howto_makevideo>
63,994,870
I made a simple calculator with javascript , but when i want to validate input , it display Nan, and if statement not worked to validate empty input ? How to fix this and how to validate empty input by this form and how to remove the Nan Text displayed after empty input submit ? ```js let b = document.querySelector("#submit"); b.addEventListener("click", function() { let c = document.querySelector("#plus").value; let d = document.querySelector("#minus").value; let result = document.querySelector(".result"); let output = parseInt(c) + parseInt(d); result.innerHTML = output; if(c.value == "" && d.value == "") { console.log("Wrong"); } else { console.log("Well Typed"); } } ) ``` ```css body { display:flex; align-items:center; background-color:white; justify-content:center; font-family:"Montserrat",sans-serif; flex-direction:column; } button { background-color:#232324; border:none; color:white; padding:10px 17px; } .result { width:50%; min-height:50px; background-color:transparent; display:flex; align-items:center; justify-content:center; flex-direction:row; } input { margin: 20px 0; padding:10px; color:black; background-color:lightgray; border:none; } ``` ```html <body> <input type="number" placeholder = ""id = "plus"> <input type="number" id = "minus"> <div class="row"> <button id="submit"> + </button> <button id="submit"> - </button> <button id="submit"> x </button> <button id="submit"> ÷ </button> </div> <span class="result">1</span> </body> ```
2020/09/21
[ "https://Stackoverflow.com/questions/63994870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10687872/" ]
```js let b = document.querySelector("#submit"); b.addEventListener("click", function() { let c = document.querySelector("#plus").value; let d = document.querySelector("#minus").value; if(c !== "" && d !== ""){ let result = document.querySelector(".result"); let output = parseInt(c) + parseInt(d); result.innerHTML = output; console.log("Well Typed"); } else{ console.log("Wrong"); } } ) ``` ```css body { display:flex; align-items:center; background-color:white; justify-content:center; font-family:"Montserrat",sans-serif; flex-direction:column; } button { background-color:#232324; border:none; color:white; padding:10px 17px; } .result { width:50%; min-height:50px; background-color:transparent; display:flex; align-items:center; justify-content:center; flex-direction:row; } input { margin: 20px 0; padding:10px; color:black; background-color:lightgray; border:none; } ``` ```html <body> <input type="number" placeholder = ""id = "plus"> <input type="number" id = "minus"> <div class="row"> <button id="submit"> + </button> <button id="submit"> - </button> <button id="submit"> x </button> <button id="submit"> ÷ </button> </div> <span class="result">1</span> </body> ```
I made a else if statement for this code when the first input has value and the second input has no value Any suggestions? ```js if (c == "" && d == "") { console.log("Wrong"); error.innerHTML = "<h1>Write Number Please>/h1> "; } else if(c == "" && d >=0 || c>= 0 && d=="") { console.log("write value for all inputs"); } else { console.log("Well Typed"); result.innerHTML = output; } }) ```
31,513
It is true that $\phi(p) = (p-1)$ only if p is a prime. I had also proven (I am not sure if this is a trivial fact or not) that $\phi(pq) = (p-1)(q-1)$ only if p and q are distinct primes. However, I am having difficulty generalizing the result. It certainly seems true that if $\phi(p\_1\cdot p\_2\cdots p\_n) = (p\_1 - 1)(p\_2 - 1)\cdots (p\_n-1)$ then each $p\_i$ are distinct primes. What I had done in the initial proof for the case n = 2 was to use the the formula $\phi(pq) = \phi(p)\phi(q)\frac{d}{\phi(d)}$ where d = gcd(p,q) and the fact that if $a \mid b$ then $\phi(a) \mid \phi(b)$ to show that $d \mid 1$. The result follows quite easily after showing that p and q are coprime. However, this proof does not seem to be extendable to the general case. I hope that someone can help me with this.
2011/04/07
[ "https://math.stackexchange.com/questions/31513", "https://math.stackexchange.com", "https://math.stackexchange.com/users/9246/" ]
The general result sought is wrong. For example $$\phi(4 \times 4 \times 4 \times 9 \times 9)=\phi(64)\phi(81)=(32)(54)$$. Note that $$(4-1)(4-1)(4-1)(9-1)(9-1)=(27)(64)=(32)(54)$$ So in general $\phi(a\_1a\_2\cdots a\_n)=(a\_1-1)(a\_2-1)\cdots(a\_n-1)$ does not imply that the $a\_i$ are distinct primes. I expect that a little playing would give a counterexample with smaller $n$ than the 5 we have above.
The above-stated conjecture has infinitely many counterexamples. Namely $$\rm\phi(p\_1\cdot p\_2\cdots p\_n)\ =\ (p\_1 - 1)\ (p\_2 - 1)\cdots (p\_n-1)\ \ \Rightarrow\ \ p\_i\ distinct\ primes$$ is false for all primes $\rm\:p > 3\:$ in the following examples $$\rm\ \phi(3\cdot 3\cdot 4\cdot p)\ =\ 2\cdot 2\cdot 3\cdot (p-1)\ $$ $$\rm\ \phi(2\cdot 4\cdot 9\cdot p)\ =\ 1\cdot 3\cdot 8\cdot (p-1)\ $$
34,450
This has been bugging me for a while, and despite googling around, I cannot seem to even find an explanation as to why the "Create Application Shortcut" is disabled.
2011/12/22
[ "https://apple.stackexchange.com/questions/34450", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/15411/" ]
Unfortunately, the answer to your question is "you can't," and the reason is "because Google says so. <http://support.google.com/chrome/bin/answer.py?hl=en&answer=95710> says > > This feature is only available for Google Chrome on Windows and Linux. > > > but there is no real explanation as to why. Nor have I found one anywhere else. It seems like an oft-requested feature, but I've never seen Google even suggest that they are planning to add it (although I presume/hope that they will). **Alternative Solution:** If you are interested in creating site-specific browsers on Mac OS X, [Fluid.app](http://fluidapp.com/) works great, but (IIRC) it is based on Webkit, not Chrome. **2013-06-27:** *Turns out* there is a way to make Chrome SSBs on the Mac, although it's a little convoluted. The instructions are too long to replicate here, and there is a shell script and/or AppleScript involved. You can find both of them at <http://www.lessannoyingsoftware.com/blog/2010/08/149/Create+application+shortcuts+in+Google+Chrome+on+a+Mac> LifeHacker covered this as well, and created a video to go along with it. You can find that at: <http://lifehacker.com/5611711/create-application-shortcuts-in-google-chrome-for-mac-with-a-shell-script>
Or you can create an [electron](http://electron.atom.io) "app" from the website. Not nearly as simple as it should be with Chrome, but <https://github.com/jiahaog/nativefier> makes it a bit easier.
285,200
Was given a 2009 Macbook Pro after original owner attempted to hard reset. Reinstall of OS X unsuccessful from OS X Utilities. I get as far as agreeing to terms, and signing in to App Store with my Apple ID, and then get this message: "This item is temporarily unavailable. Try again later." I start school tomorrow and I am royally screwed if I can't figure this out. All data is clearly erased, as well as all Apps. Any info pointing me in the right direction is greatly appreciated.
2017/05/29
[ "https://apple.stackexchange.com/questions/285200", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/239639/" ]
Let me add this as a viable alternative for "if ya just gotta have it right now" Take it to an Apple Store - they'll do it for you.
Login with the original owners Apple ID - old copies of OS X are not available unless your Apple ID has a license for it.
6,030,071
``` UPDATE AggregatedData SET datenum="734152.979166667", Timestamp="2010-01-14 23:30:00.000" WHERE datenum="734152.979166667"; ``` It works if the `datenum` exists, but I want to insert this data as a new row if the `datenum` does not exist. UPDATE the datenum is unique but that's not the primary key
2011/05/17
[ "https://Stackoverflow.com/questions/6030071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/611116/" ]
Try using [this](http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html): > > If you specify `ON DUPLICATE KEY UPDATE`, and a row is inserted that would cause a duplicate value in a `UNIQUE index or`PRIMARY KEY`, MySQL performs an [`UPDATE`](<http://dev.mysql.com/doc/refman/5.7/en/update.html>) of the old row... > > > The `ON DUPLICATE KEY UPDATE` clause can contain multiple column assignments, separated by commas. > > > With `ON DUPLICATE KEY UPDATE`, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the `CLIENT_FOUND_ROWS` flag to [`mysql_real_connect()`](http://dev.mysql.com/doc/refman/5.7/en/mysql-real-connect.html) when connecting to [**mysqld**](http://dev.mysql.com/doc/refman/5.7/en/mysqld.html), the affected-rows value is 1 (not 0) if an existing row is set to its current values... > > >
This is not too bad, but we could actually combine everything into one query. I found different solutions on the internet. The simplest, but `MySQL only solution` is this: ``` INSERT INTO wp_postmeta (post_id, meta_key) SELECT ?id, ‘page_title’ FROM DUAL WHERE NOT EXISTS ( SELECT meta_id FROM wp_postmeta WHERE post_id = ?id AND meta_key = ‘page_title’ ); UPDATE wp_postmeta SET meta_value = ?page_title WHERE post_id = ?id AND meta_key = ‘page_title’; ``` [Link to documentation](https://remy.supertext.ch/2010/11/mysqlupdate-and-insert-if-not-exists/#:%7E:text=Often%20you%20have%20the%20situation,to%20do%20an%20insert%20first.&text=Unfortunately%2C%20this%20the%20%27ON%20DUPLICATE,PRIMARY%20KEY%20and%20UNIQUE%20columns.).
79,600
I've read all the bad things that can happen from garlic infused oil like homemade. How is this different than let's say Pizza Hut's garlic butter, or their (dry) breadstick seasoning with cheeses and dehydraded garlic? Do they in fact have a safer method that literally reduces the risk or what? I see the garlic butter has citric acid in it so that makes sense but what about the seasoning? That is just cheeses and dehydrated garlic as well as other things.
2017/04/02
[ "https://cooking.stackexchange.com/questions/79600", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/55741/" ]
What you are seeking are [natural food dyes](https://duckduckgo.com/?q=natural%20food%20dyes&t=ffnt&ia=web) (or [natural food colorings](https://duckduckgo.com/?q=natural%20food%20colorings&t=ffnt&ia=web)). These are commercially available and you may find them at a local health or natural foods store or even a quality grocers. They can be [homemade](http://nourishingjoy.com/homemade-natural-food-dyes/), if you have the time and can get the ingredients. Examples of their effects in buttercream: [![](https://i.stack.imgur.com/0syqU.jpg)](https://i.stack.imgur.com/0syqU.jpg) (from [Nourishing Joy](http://nourishingjoy.com/wp-content/uploads/2013/09/food-coloring.jpg)) **Be careful** not to end up with natural *fabric* dyes without careful checking, as many of these are toxic or bad tasting.
Suggestions: * Using a stencil, a seive and some icing sugar, you can create simple decorations known as [cake dusting](https://www.recipetips.com/kitchen-tips/t--1644/cake-dusting.asp) ![cake dusting](https://i.pinimg.com/originals/cd/c6/fc/cdc6fc33c85f956318dd1de4c11d007b.jpg) * Consider using chocolate icing * Fruit can be arranged on top to make wonderful toppings/decorations ![cake - fruit decorated](https://i.stack.imgur.com/2Gh02.jpg) (source: [stylemotivation.com](https://www.stylemotivation.com/wp-content/uploads/2013/07/Ideas-for-Fruit-decoration-4.jpg))
4,351,165
I have a `startDate` and an `endDate` as an input parameters. This parameters are used in the query say: ```sql SELECT * FROM patientRecords WHERE patientRecords.dateOfdischarge BETWEEN $P{startDate} AND $P{endDate} ``` Now, since the `startDate` and `endDate` are the parameters which are passed to the `JasperReports`. I have to ensure that they are in `mm/dd/yyyy` Date format. How do I go about converting the input parameter to this format using `iReport`?
2010/12/04
[ "https://Stackoverflow.com/questions/4351165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
U can try change the patern from propertise>textfield propertise or u can try this to\_char(tablename.fieldname, 'mm/dd/yyyy') as fieldname
Try this format it will work if you are using Mysql database date\_column\_name between date\_format($P{start\_date},'%Y-%m-%d') and date\_format($P{end\_date},'%Y-%m-%d') date\_column\_name between date\_format($P{start\_date},'%Y-%m-%d') and date\_format($P{end\_date},'%Y-%m-%d')
363,076
Does the sequence defined by $$x\_{n} =\left(\sqrt[n]{e}-1\right)\cdot n$$ converge. For finding the limit one has to solve for $\displaystyle\lim\_{x \to \infty} x\_{n}$ which I think I can solve, but how do I prove that it converges/diverges.
2013/04/16
[ "https://math.stackexchange.com/questions/363076", "https://math.stackexchange.com", "https://math.stackexchange.com/users/72792/" ]
Set $x=\frac{1}{n}$. Then the limit becomes $$\lim\_{n\to\infty}\dfrac{\sqrt[n]{e}-1}{\frac{1}{n}}=\lim\_{x\to0}\dfrac{e^x-1}{x}.$$ Can you proceed? Hint: Derivatives.
Here is an approach purely based on the ideas of sequences . Let $ x\_n=\bigg(1- \dfrac1n\bigg)^n$ , then $x\_{n+1}=\bigg(1- \dfrac1{n+1}\bigg)^{n+1}=\dfrac 1{\bigg(1+ \dfrac1n\bigg)^n\bigg(1+ \dfrac1n\bigg)}$ , so $(x\_{n+1})$ is convergent hence $(x\_n)$ is convergent and $\lim (x\_n)=\lim (x\_{n+1})=\dfrac1e$. Now it is easy to prove by A.M.-G.M. inequality that $\bigg(1- \dfrac1{n+1}\bigg)^{n+1}>\bigg(1- \dfrac1n\bigg)^n , \forall n>1$ , hence $(x\_n)$ is increasing so $\dfrac1e=\lim (x\_n)=$sup{ $x\_n : n \in \mathbb N$ }$ ≥ x\_{n+1}=\dfrac 1{\bigg(1+ \dfrac1n\bigg)^{n+1}} , \forall n\in \mathbb N$ i.e. $\bigg(1+ \dfrac1n\bigg)^{n+1}≥e \space, \forall n \in \mathbb N $ . Moreover , $ e=\lim \bigg(1+\dfrac1n\bigg)^n=$sup {$\bigg(1+\dfrac1n\bigg)^n: n\in \mathbb N$ }$≥\bigg(1+ \dfrac1{n+1}\bigg)^{n+1} , \forall n \in \mathbb N$ . So we get $\bigg(1+ \dfrac1n\bigg)^{n+1}≥e ≥\bigg(1+ \dfrac1{n+1}\bigg)^{n+1} , \forall n \in \mathbb N \implies \dfrac1n≥ \sqrt[n+1]{e}-1≥\dfrac1{n+1} , \forall n \in \mathbb N$ $\implies 1+\dfrac1n ≥ (n+1)(\sqrt[n+1]{e}-1)≥1 , \forall n \in \mathbb N $. So by squeeze theorem , $\lim \bigg((n+1)(\sqrt[n+1]{e}-1)\bigg)=1$ i.e. $\lim \bigg(n(\sqrt[n]{e}-1)\bigg)=1$
56,662,199
I have two lists that I will later use do determine on how many pages of a document I'm looking at. The first list (l\_name) contains the name of the document. The second list (l\_depth) contains the number of pages I will look at, always starting from the first one. The original lists look like this: ``` l_name = ['Doc_1', 'Doc_2', 'Doc_3'] l_depth = [1, 3, 2] ``` As I want to use a for loop to indicate each page I will be looking at ``` for d,p in zip(l_doc, l_page): open doc(d) on page(p) do stuff ``` I need the new lists to look like this: ``` l_doc = ['Doc_1', 'Doc_2', 'Doc_2', 'Doc_2', 'Doc_3', 'Doc_3'] l_page = [1, 1, 2, 3, 1, 2] ``` How can I multiply the names (l\_name --> l\_doc) based on the required depth and provide the range (l\_depth --> l\_page) also based on the depth?
2019/06/19
[ "https://Stackoverflow.com/questions/56662199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9092346/" ]
Try this : ``` l_name = ['Doc_1', 'Doc_2', 'Doc_3'] l_depth = [1, 3, 2] l_doc = [] for i,j in zip(l_name, l_depth): l_doc += [i]*j # ['Doc_1', 'Doc_2', 'Doc_2', 'Doc_2', 'Doc_3', 'Doc_3'] l_page = [k for _,j in zip(l_name, l_depth) for k in range(1,j+1)] # [1, 1, 2, 3, 1, 2] ```
``` l_name = ['Doc_1', 'Doc_2', 'Doc_3'] l_depth = [1, 3, 2] l_doc = [] l_page = [] for i, j in zip(l_name, l_depth): l_doc += [i] * j l_page += range(1, j + 1) print(l_doc) print(l_page) ```
68,737,526
I'm using [email-template](https://www.npmjs.com/package/email-templates) package for sending styled emails. Everything seems to work fine in preview of email (preview option is given in package itself. it renders sent email preview in tab if placed true). but when I get email in my gmail account images are not visible. I can tell that paths / images in the setting / code exists because in preview everything is placed just right. ```js smtpTransport = nodemailer.createTransport( smtpTransport({ host: 'smtp.gmail.com', port: 465, secure: true, jsonTransport: true, auth: { user: 'sender.example@gmail.com', pass: '123123', }, }) ); smtpTransport.use('compile', base64ToS3()); const templateWrapper = new Email({ transport: smtpTransport, send: true, preview: true, views: { options: { extension: 'ejs', }, root: path.join(__dirname, 'email/html/events'), }, juice: true, juiceSettings: { tableElements: ['TABLE'], }, juiceResources: { preserveImportant: true, webResources: { relativeTo: path.join(__dirname, 'email/assets'), images: true, }, }, }); ``` Here is my HTML template: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Efys - Welcome</title> <style> html { box-sizing: border-box; } *, *:before, *:after { box-sizing: border-box; } body { font-family: sans-serif; -webkit-font-smoothing: antialiased; font-size: 0.8rem; line-height: 1.4; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; } .bg-brand-color-blue-dark { background-color: #033e75; } .bg-brand-color-gold-light { background-color: #f0ede6; } .bg-brand-color-gold-dark { background-color: #d0a345; } .bg-white { background-color: #ffffff; } .brand-color-gold-dark { color: #d0a345; } .brand-color-gold-light { color: #f0ede6; } .brand-color-blue-dark { color: #033e75; } .text-color-white { color: #ffffff; } .text-color-black { color: #000000; } .display-block { display: block; } .margin-top-0rem { margin-top: 0; } .margin-top-1rem { margin-top: 1rem; } .margin-top-2rem { margin-top: 2rem; } .margin-bottom-2rem { margin-bottom: 2rem; } .padding-full-1rem { padding: 1rem; } .padding-full-2rem { padding: 2rem; } .padding-top-2rem { padding-top: 2rem; } .padding-bottom-5rem { padding-top: 5rem; } .border-solid-black { border: 1px solid #000000; } .border-radius-half { border-radius: 0.5rem; } .border-radius-1rem { border-radius: 1rem; } .whitespace { white-space: normal; } .font-size-x1 { font-size: 1rem; } .font-size-x2 { font-size: 2rem; } a, a:visited { color: blue; } .text-decoration-none { text-decoration: none; } ol { padding-left: 15px; } p { margin-top: 1rem; margin-bottom: 0; } .strong { font-weight: bold; } h3 { margin-bottom: 0; } h3 + p { margin-top: 0; } .inline-icon { margin-right: 5px; } .flexbox { display: flex; } .flex-row { flex-direction: row; } .flex-nowrap { flex-wrap: nowrap; } .flexbox .cell { width: 50%; } .flexbox .cell:nth-child(2) { text-align: right; } .maximum-width { width: 100%; max-width: 36.25rem; margin: 0 auto; } .logo { width: 100%; max-width: 36.25rem; margin: 0 auto; } .logo img { border: 0 none; outline: 0 none; width: 100%; height: auto; } @media only screen and (max-width: 480px) { .footer > .flexbox .cell { width: 100%; text-align: center; } .footer > .flexbox .cell:nth-child(2) { text-align: center; margin-top: 1rem; } .footer > .flex-nowrap { flex-wrap: wrap; } .inner-cell.flexbox { display: block; max-width: 100%; margin: 0 auto; } } </style> </head> <body> <div class="wrapper display-block bg-brand-color-blue-dark padding-full-1rem" > <!-- logo --> <div class="logo display-block" style="margin: 0 auto;"> <img class="display-block" src="efy-registration-header.jpg" alt="abc def" style="border-top-left-radius: 1rem; border-top-right-radius: 1rem;" /> </div> <!-- content --> <div class="content display-block maximum-width bg-white text-color-black padding-full-2rem" style="border-bottom-left-radius: 1rem; border-bottom-right-radius: 1rem;" > <p class="strong">Dear <%= clientName %>,</p> <p> You have successfully registered for <%= efyTitle %> on <%= efyDay %> at <%= startTime %> </p> <p>Your Reference ID is: <%= referenceId %></p> <% if (displayAddress) { %> <p>Zoom link: <%= address %></p> <% } else { %> <p> Zoom link: You should receive an email update with the link to the live efy </p> <% } %> <h3>Zoom Instructions</h3> <p>To join a Zoom meeting on a computer or mobile device:</p> <ol> <li> Download the Zoom app from their Download Center <a href="https://zoom.us/download" target="_blank" >https://zoom.us/download</a >. Otherwise, you will be prompted to download and install Zoom when you click a join link. </li> </ol> </div> <!-- footer --> <div class="footer maximum-width text-color-white" style="margin: 1rem auto 5rem;" > <div class="flexbox flex-row flex-nowrap" style="justify-content: center; align-items: flex-end;" > <div class="cell"> <div class="flexbox flex-row flex-nowrap inner-cell"> <div class="col" style="margin-right: 0.5em;"> <img src="logo_icon.png" alt="abc def" width="50" height="auto" /> </div> <div class="col"> Villa 1, Alwasl Rd. <br /> Alsafa 2 <br /> Dubai, United Arab Emirates </div> </div> <p> <span class="strong brand-color-gold-dark">T.</span> <a href="tel:+97143809298" class="text-decoration-none strong" style="color: #FFFFFF;" >+971 (0)4 380 9296</a > </p> <p class="margin-top-0rem"> <span class="strong brand-color-gold-dark">E.</span> <a href="mailto:info@example.com" class="text-decoration-none strong" style="color: #FFFFFF;" >info@example.com</a > </p> </div> <div class="cell"> <p> <span class="inline-icon" ><a href="#" ><img src="icon-facebook.png" width="40" height="auto"/></a ></span> <span class="inline-icon" ><a href="#" ><img src="icon-twitter.png" width="40" height="auto"/></a ></span> <span class="inline-icon" ><a href="#" ><img src="icon-instagram.png" width="40" height="auto"/></a ></span> <span class="inline-icon" ><a href="#" ><img src="icon-linkedin.png" width="40" height="auto"/></a ></span> </p> <p class="brand-color-gold-dark strong">@example.com</p> <p class="margin-top-0rem"> <span class="strong brand-color-gold-dark">W.</span> <a href="//example.com" class="text-decoration-none strong" style="color: #FFFFFF;" >example.com</a > </p> </div> </div> </div> </div> </body> </html> ```
2021/08/11
[ "https://Stackoverflow.com/questions/68737526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3728916/" ]
When you load an HTML page and use the image like below ``` <img src="icon-linkedin.png" width="40" height="auto" /> ``` It actually tells the browser that, load the image from the same directory from where you loaded the HTML page. Here comes the problem. When your email is loaded in the `Gmail` it will also tell browser the same and the browser will not be able to locate the image. **Solution:** If you are sending it from the backend. Then upload the image in any public url. You can upload the image in you frontend hosting and find the link. Then use the link directly. Your image need to be accessible publicly. If you do not have any other option or hosting. Upload the image in any public github/gitlab repo and use the link.
[According to the docs for `nodemailer-base64-to-s3`](https://github.com/forwardemail/nodemailer-base64-to-s3#options), you need to pass in some configuration options to the `base64ToS3` method. It says the `aws/params/Bucket` is required. I believe the following should give you a good start: ``` smtpTransport.use('compile', base64ToS3({ aws: { params: { Bucket: "bucket_name_here" } } })); ``` See <https://github.com/forwardemail/nodemailer-base64-to-s3/blob/master/example.js> for another example.
30,128,178
I'm trying to simulate a scroll event with ReactJS and JSDOM. Initially I tried the following: ``` var footer = TestUtils.findRenderedDOMComponentWithClass(Component, 'footer'); footer.scrollTop = 500; TestUtils.Simulate.scroll(footer.getDOMNode()); //I tried this as well, but no luck //TestUtils.Simulate.scroll(footer); ``` The scroll event is not propagated at all. Then, I've manually created the event and everything worked fine: ``` var evt = document.createEvent("HTMLEvents"); evt.initEvent("scroll", false, true); element.dispatchEvent(evt); ``` **Question**: Am I doing something wrong with the TestUtils? How can I make that to work?
2015/05/08
[ "https://Stackoverflow.com/questions/30128178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/510573/" ]
My situation may be different than the OP's, but I was struggling with the a similar problem and found my way here after lots and lots of searching. I realized the crux of my problem was that `TestUtils.Simulate.scroll()` only simulates a scroll event dispatched by a specific React component (e.g. when you have `overflow: scroll` set on that component) and not a scroll event dispatched by `window`. In particular, I was trying to test a scroll handler I'd set up in a React class like this: ``` componentDidMount: function () { window.addEventListener('scroll', this.onScroll); }, componentWillUnmount: function () { window.removeEventListener('scroll', this.onScroll); }, ``` To test `onScroll()`, I finally figured out that I had to simulate dispatching a scroll event from `window`, like this: ``` document.body.scrollTop = 100; window.dispatchEvent(new window.UIEvent('scroll', { detail: 0 })); ``` That worked great for me.
Judging from [this](https://stackoverflow.com/questions/26717499/testing-for-mouse-wheel-events) and [this](https://developer.mozilla.org/en-US/docs/Web/Events/wheel), I believe TestUtils simulates the scrolling via a `WheelEvent`, which means it needs a `deltaY` parameter to know how far to scroll. That would look like this: ``` TestUtils.Simulate.scroll(footer.getDOMNode(), { deltaY: 500 }); ```
51,842,493
I am already using [JsonSerializer](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonSerializer.htm) of [Newtonesoft Package](https://www.newtonsoft.com/) to convert strings to JSON format ,but it can't convert this string to JSON. ``` { "isSuccess": true, "elapsed": 54, "results": { "131351990802396920": "updated", "21034623651844830": "updated", "112201011402879160": "updated" }, "errors": { "105933291602523100": "Error", "106574790922078090": "Error", "114439941021395940": "Error", "123574814601457710": "Error" } } ``` The Class structure that i am trying to convert string to, is as follows: ``` public class UpdateResultSt { public bool isSuccess { get; set; } public int elapsed { get; set; } public List<SuccessfulUpdateResult> results = new List<SuccessfulUpdateResult>(); public List<FailedUpdateResult> errors = new List<FailedUpdateResult>(); } public class SuccessfulUpdateResult { public string id { get; set; } public string text { get; set; } } public class FailedUpdateResult { public string id { get; set; } public string text { get; set; } } ``` This is some of my code which is responsible for converting: ``` JsonSerializer json_serializer; json_serializer = new JsonSerializer { NullValueHandling = NullValueHandling.Ignore }; JsonReader jsonReader = new JsonTextReader(new StringReader(responseFromServer)); UpdateResultSt routes_list = json_serializer.Deserialize<UpdateResultSt>(jsonReader); ``` As you see both `the Results` and `the Errors` scopes have variable content. There are some other questions with the same issue but no one could resolve my problem. The error message is : > > 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) > into type > 'System.Collections.Generic.List`1[ConceptTaggerWinApp.UpdateResultSt]' > because the type requires a JSON array (e.g. [1,2,3]) to deserialize > correctly. To fix this error either change the JSON to a JSON array > (e.g. [1,2,3]) or change the deserialized type so that it is a normal > .NET type (e.g. not a primitive type like integer, not a collection > type like an array or List) that can be deserialized from a JSON > object. JsonObjectAttribute can also be added to the type to force it > to deserialize from a JSON object. Path 'isSuccess', line 1, position > 13.' > > > How do I change my classes structure to convert this string to JSON sucessfully?
2018/08/14
[ "https://Stackoverflow.com/questions/51842493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5516527/" ]
As you can't change the Json's format, I'd say the following class should work as expected: ``` public class UpdateResultSt { public bool isSuccess { get; set; } public int elapsed { get; set; } public Dictionary<string,string> results { get; set; } public Dictionary<string,string> errors { get; set; } } ``` You could then write something like: ``` routes_list.results["131351990802396920"] ``` to get the text `"updated"`. Or `routes_list.results.Keys` to get the list of the `id`s of the `results`. See [Deserializing dictionnaries](https://www.newtonsoft.com/json/help/html/SerializingCollections.htm#DeserializingDictionaries).
The format of SuccessfulUpdateResult and FailedUpdateResult are not correct. It should be like this: ``` { "isSuccess": true, "elapsed": 54, "results": [ 0: { "id" : "131351990802396920", "text" : "updated"}, 1: { "id" :"21034623651844830", "text" : "updated"}, 2: { "id" :"112201011402879160", "text" : "updated"} ], "errors": { // same than SuccessfulUpdateResult ... } } ```
424,775
sudo (Which I have configured to ask for a password) is rejecting my password (as if I mis-typed it) I am absolutely not typing it incorrectly. I have changed the password temporarily to alphabetic characters only, and it looks fine in plaintext, in the same terminal. I have my username configured thus: ``` myusername ALL=(ALL) ALL ``` I am using my password, NOT the root password, which are distinct. Just to be sure, I've tried both (even though I know the root password is not what I should use) - neither work. I have added myself to the group 'wheel' additionally, and included the following line: ``` %wheel ALL=(ALL) ALL ``` I'm kind of at the end of my rope here. I don't know what would cause it to act as though it was accepting my password, but then reject it. I have no trouble logging in with the same password, either at terminal shells, or through the X11 login manager.
2012/09/06
[ "https://serverfault.com/questions/424775", "https://serverfault.com", "https://serverfault.com/users/134857/" ]
Another possible cause is that systemd-homed is not running. Check it's status with ``` systemctl status systemd-homed ``` If it says something other than active, use ``` systemctl start systemd-homed ``` to start it again. Note that you need superuser privileges in order to run that command. As sudo is not working, you might try logging as root using ``` su root ``` and the correct password for root (usually not your regular user).
Oh what the heck, here was the issue, I guess? <https://bbs.archlinux.org/viewtopic.php?id=142720> ``` pacman -S pambase ``` fixes it.
10,132,556
I'm trying to start a Skype intent from my Android App, passing a phone number. So far, thanks to other people who ad similiar needs here on stackoverflow, I've managed to start skype, but still I can't pass the phone number. This is the code I'm using: ``` Intent sky = new Intent("android.intent.action.CALL_PRIVILEGED"); sky.setClassName("com.skype.raider", "com.skype.raider.Main"); sky.setData(Uri.parse("tel:" + number)); Log.d("UTILS", "tel:" + number); ctx.startActivity(sky); ``` What's happening is that skype starts, but gives me a toast saying that the number is not valid, and suggests me to add the international prefix. The Log.d gives me tel:+39........ (the number works, I'm using it also for ``` public static void call(String number, Context ctx) { try { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:" + number)); ctx.startActivity(callIntent); } catch (ActivityNotFoundException e) { Log.e("helloandroid dialing example", "Call failed", e); } } ``` In fact, when I go to the Skype's view for calling, I see it's been composed +0 So what it seems to me is that I'm passing the phone number in the wrong way, or to the wrong Activity....any help would be very appreciated! In the meantime, I just want to say that StackOverflow simply rocks.
2012/04/12
[ "https://Stackoverflow.com/questions/10132556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552260/" ]
See this answer: <https://stackoverflow.com/a/8844526/819355> Jeff suggests using a `skype:<user name>` instead of `tel:<phone number>` After some studing of the skype apk with apktool, as suggested in that answer, I came up with this code, for me it's working: ``` public static void skype(String number, Context ctx) { try { //Intent sky = new Intent("android.intent.action.CALL_PRIVILEGED"); //the above line tries to create an intent for which the skype app doesn't supply public api Intent sky = new Intent("android.intent.action.VIEW"); sky.setData(Uri.parse("skype:" + number)); Log.d("UTILS", "tel:" + number); ctx.startActivity(sky); } catch (ActivityNotFoundException e) { Log.e("SKYPE CALL", "Skype failed", e); } } ```
Refer this skype doc link [Skype URI tutorial: Android apps](https://learn.microsoft.com/en-us/skype-sdk/skypeuris/skypeuritutorial_androidapps) > > First need to check skype is installed or not using > > > ``` /** * Determine whether the Skype for Android client is installed on this device. */ public boolean isSkypeClientInstalled(Context myContext) { PackageManager myPackageMgr = myContext.getPackageManager(); try { myPackageMgr.getPackageInfo("com.skype.raider", PackageManager.GET_ACTIVITIES); } catch (PackageManager.NameNotFoundException e) { return (false); } return (true); } ``` > > initiate skype uri using > > > ``` /** * Initiate the actions encoded in the specified URI. */ public void initiateSkypeUri(Context myContext, String mySkypeUri) { // Make sure the Skype for Android client is installed. if (!isSkypeClientInstalled(myContext)) { goToMarket(myContext); return; } // Create the Intent from our Skype URI. Uri skypeUri = Uri.parse(mySkypeUri); Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri); // Restrict the Intent to being handled by the Skype for Android client only. myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main")); myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Initiate the Intent. It should never fail because you've already established the // presence of its handler (although there is an extremely minute window where that // handler can go away). myContext.startActivity(myIntent); return; } ``` > > if Skype is not installed then redirect to market place using > > > ``` /** * Install the Skype client through the market: URI scheme. */ public void goToMarket(Context myContext) { Uri marketUri = Uri.parse("market://details?id=com.skype.raider"); Intent myIntent = new Intent(Intent.ACTION_VIEW, marketUri); myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); myContext.startActivity(myIntent); return; } ```
32,423,636
There are countless questions here, how to solve the "could not initialize proxy" problem via eager fetching, keeping the transaction open, opening another one, `OpenEntityManagerInViewFilter`, and whatever. But is it possible to simply tell Hibernate to ignore the problem and pretend the collection is empty? In my case, not fetching it before simply means that I don't care. **This is actually an XY problem with the following Y:** I'm having classes like ``` class Detail { @ManyToOne(optional=false) Master master; ... } class Master { @OneToMany(mappedBy="master") List<Detail> details; ... } ``` and want to serve two kinds of requests: One returning a single `master` with all its `details` and another one returning a list of `master`s without `details`. The result gets converted to JSON by Gson. I've tried `session.clear` and `session.evict(master)`, but they don't touch the proxy used in place of `details`. What worked was ``` master.setDetails(nullOrSomeCollection) ``` which feels rather hacky. I'd prefer the "ignorance" as it'd be applicable generally without knowing what parts of what are proxied. Writing a Gson `TypeAdapter` ignoring instances of `AbstractPersistentCollection` with `initialized=false` could be a way, but this would depend on `org.hibernate.collection.internal`, which is surely no good thing. Catching the exception in the `TypeAdapter` doesn't sound much better. ### Update after some answers My goal is not to *"get the **data loaded** instead of the exception"*, but *"how to get **null** instead of the exception"* I [Dragan raises](https://stackoverflow.com/a/32481321/581205) a valid point that forgetting to fetch and returning a wrong data would be much worse than an exception. But there's an easy way around it: * do this for collections only * never use `null` for them * return `null` rather than an empty collection as an indication of unfetched data This way, the result can never be wrongly interpreted. Should I ever forget to fetch something, the response will contain `null` which is invalid.
2015/09/06
[ "https://Stackoverflow.com/questions/32423636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/581205/" ]
You could utilize [Hibernate.isInitialized](https://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/Hibernate.html#isInitialized%28java.lang.Object%29), which is part of the Hibernate public API. So, in the `TypeAdapter` you can add something like this: ``` if ((value instanceof Collection) && !Hibernate.isInitialized(value)) { result = new ArrayList(); } ``` However, in my modest opinion your approach in general is not the way to go. *"In my case, not fetching it before simply means that I don't care."* Or it means you forgot to fetch it and now you are returning wrong data (worse than getting the exception; the consumer of the service thinks the collection is empty, but it is not). I would not like to propose "better" solutions (it is not topic of the question and each approach has its own advantages), but the way that I solve issues like these in most use cases (and it is one of the ways commonly adopted) is using DTOs: Simply define a DTO that represents the response of the service, fill it in the transactional context (no `LazyInitializationException`s there) and give it to the framework that will transform it to the service response (json, xml, etc).
What you can try is a solution like the following. Creating an interface named `LazyLoader` ``` @FunctionalInterface // Java 8 public interface LazyLoader<T> { void load(T t); } ``` And in your Service ``` public class Service { List<Master> getWithDetails(LazyLoader<Master> loader) { // Code to get masterList from session for(Master master:masterList) { loader.load(master); } } } ``` And call this service like below ``` Service.getWithDetails(new LazyLoader<Master>() { public void load(Master master) { for(Detail detail:master.getDetails()) { detail.getId(); // This will load detail } } }); ``` And in Java 8 you can use Lambda as it is a Single Abstract Method (SAM). ``` Service.getWithDetails((master) -> { for(Detail detail:master.getDetails()) { detail.getId(); // This will load detail } }); ``` You can use the solution above with `session.clear` and `session.evict(master)`
31,369,916
I am using Kali linux 64 bit and I am trying to execute the following programs from Dr. Paul carter's website. The gcc command is giving errors. What should I use in the gcc command? ``` nasm -f elf32 array1.asm root@kali:assembly# gcc -o array1 array1.o array1c.c array1c.c:9:1: warning: ‘cdecl’ attribute ignored [-Wattributes] array1c.c:10:1: warning: ‘cdecl’ attribute ignored [-Wattributes] /usr/bin/ld: i386 architecture of input file `array1.o' is incompatible with i386:x86-64 output collect2: error: ld returned 1 exit status ```
2015/07/12
[ "https://Stackoverflow.com/questions/31369916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4277517/" ]
First install this: ``` sudo apt-get install gcc-multilib g++-multilib ``` then Assemeble and link in this way: ``` nasm -f elf array1.asm -o array1.o ``` And finaly, ``` gcc -m32 array1.o -o array1.out ``` and run, ``` ./array1.out ``` This should work......
(oops, I only skimmed the question, and thought you were making a standalone executable with just `ld`. See cad's answer for `gcc -m32`, for when you do want to link with libc and all that, rather than just try some little experiment as a standalone.) You have to tell `ld` what machine you want the output to be for. It defaults to the native type. ``` nasm -f elf32 array1.asm # or yasm ld -m elf_i386 array1.o -o 32bit-array1 ``` Unfortunately, a lot of asm guides / resources still have examples with 32bit x86 code.
1,018,078
Are there any good tools to easily test how HTML email will look across different email clients? I prefer something with instant feed back rather than a submit and wait service like <http://litmusapp.com> Or at the very least a way to test the Outlook 2007/MS Word rendering? I found this related question but it doesn't specifically address testing. [What guidelines for HTML email design are there?](https://stackoverflow.com/questions/127498/what-guidelines-for-html-email-design-are-there)
2009/06/19
[ "https://Stackoverflow.com/questions/1018078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796/" ]
Another thing you could try is to upload the html to a webpage and then open the webpage in word to test Outlook.
Direct Mail is an OS X desktop app that can show you previews of what your email will look like in a variety of email clients: <http://directmailmac.com/mac-email-design/> Full Disclosure: I work for the developers of Direct Mail
58,338,247
hello i get data in sqlite code : ``` getuserIDPW(String email) async{ final db = await database; var res = await db.query("person",columns: ['email', 'password'] ,where: "email = ?", whereArgs: [email]); return res.isNotEmpty? res : Null; } ``` code : ``` var useridpw = await DBHelper().getuserIDPW(_email); print(useridpw); ``` That's how I got the result of `[{email: kmail, password: 123123}]` But i want String like this : `var tmpEmail = 'kmail';` How to get String in map ? I'd be grateful if someone would help me.
2019/10/11
[ "https://Stackoverflow.com/questions/58338247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12061705/" ]
I had same issue but I resolved following below steps : I am on Windows server . Mongo DB shell version 3.0.4 . Error in below screen shot same as you mentioned [![enter image description here](https://i.stack.imgur.com/gqF1A.png)](https://i.stack.imgur.com/gqF1A.png) So I connect to Mongo shell switch to local . Use following command. Please note SIR is my replica set name ``` cfg = { _id:"SIR" , members: [{ _id:0,host:"localhost:27017"}] }; rs.initiate(cfg) ``` Result [![enter image description here](https://i.stack.imgur.com/nO7Op.png)](https://i.stack.imgur.com/nO7Op.png)
I'm using [bitnami/mongodb](https://github.com/bitnami/charts/tree/master/bitnami/mongodb) helm chart to deploy mongodb to our custom k8s cluster and got this error when forgot to override `clusterDomain` variable in my `values.yaml` file because by default it was **`cluster.local`** and lead to run `rs.initiate` eval with wrong cluster domain in host address: ``` mongodb 14:59:37.35 WARN ==> Problem initiating replica set request: rs.initiate({"_id":"rs0", "members":[{"_id":0,"host":"temp-mongo-0.temp-mongo-headless.default.svc.**cluster.local**:27017","priority":5}]}) response: MongoDB shell version v4.4.4 connecting to: mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("dc48d2bc-269b-4710-95b8-525b7768fa72") } MongoDB server version: 4.4.4 { "ok" : 0, "errmsg" : "No host described in new configuration with {version: 1, term: 0} for replica set rs0 maps to this node", "code" : 93, "codeName" : "InvalidReplicaSetConfig" } bye ```
47,508,790
I have the following JSON saved in a text file called test.xlsx.txt. The JSON is as follows: ``` {"RECONCILIATION": {0: "Successful"}, "ACCOUNT": {0: u"21599000"}, "DESCRIPTION": {0: u"USD to be accrued. "}, "PRODUCT": {0: "7500.0"}, "VALUE": {0: "7500.0"}, "AMOUNT": {0: "7500.0"}, "FORMULA": {0: "3 * 2500 "}} ``` The following is my python code: ``` f = open(path_to_analysis_results,'r') message = f.read() datastore = json.loads(str(message)) print datastore f.close() ``` With the json.loads, I get the error "*ValueError: Expecting property name: line 1 column 21 (char 20)*". I have tried with json.load, json.dump and json.dumps, with all of them giving various errors. All I want to do is to be able to extract the key and the corresponding value and write to an Excel file. I have figured out how to write data to an Excel file, but am stuck with parsing this json. ``` RECONCILIATION : Successful ACCOUNT : 21599000 DESCRIPTION : USD to be accrued. PRODUCT : 7500.0 VALUE : 7500.0 AMOUNT : 7500.0 FORMULA : 3 * 2500 ``` I would like the data to be in the above format to be able to write them to an Excel sheet.
2017/11/27
[ "https://Stackoverflow.com/questions/47508790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3163920/" ]
Your txt file does not contain valid JSON. For starters, keys must be strings, not numbers. The `u"..."` notation is not valid either. You should fix your JSON first (maybe run it through a linter such as <https://jsonlint.com/> to make sure it's valid).
As Mike mentioned, your text file is not a valid JSON. It should be like: ``` {"RECONCILIATION": {"0": "Successful"}, "ACCOUNT": {"0": "21599000"}, "DESCRIPTION": {"0": "USD to be accrued. "}, "PRODUCT": {"0": "7500.0"}, "VALUE": {"0": "7500.0"}, "AMOUNT": {"0": "7500.0"}, "FORMULA": {"0": "3 * 2500 "}} ``` Note: keys are within doube quotes as JSON requires double quotes. And, your code should be (without **str()**): ``` import json f = open(path_to_analysis_results,'r') message = f.read() print(message) # print message before, just to check it. datastore = json.loads(message) # note: str() is not required. Message is already a string print (datastore) f.close() ```
45,428,701
S3 bucket i want to save object such as image or video and want it to be protected and can access by authorised users only what should i do. One way is making url with token for particular time expired it after some time. Is any other way also to doing this.
2017/08/01
[ "https://Stackoverflow.com/questions/45428701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813659/" ]
Objects in Amazon S3 are private by default. If you wish to only grant access to specific files to authorized users, you have a couple of options: * Use AWS credentials, or * Use pre-signed URLs If you wish your application to be able to access the objects, you can give **AWS credentials** to your application. This could either be as an **IAM User** (applications can be *Users* too), or via an **IAM Role** that the application assumes (eg assign the Role to an EC2 instance and the application is then automatically provided with credentials). You would then **grant permissions** to the IAM User/Role to access a particular bucket, or a path within the bucket. Alternatively, if you wish to grant selective access to particular objects (eg a user's photos), you can use **pre-signed URLs**. These are time-limited credentials that provide access to an Amazon S3 object. An application can **generate the pre-signed URL with a couple of lines of code**. The URL can then be inserted into web pages (eg in `<img>` tags) to provide temporary access to private objects. When the time period **expires**, the URL will no longer function.
This is an example of a solution which allows your system to access an AWS S3 object's contents internally without the need to assign an access token to the object. ``` <?php if (!defined('MY_AWS_AUTOLOADER_FILE_LOCATION')) { // Replace /var/www/html/aws/aws-autoloader.php with wherever your actual file is // Make sure you've already downloaded and unzipped the aws-autoloader.php file // Can be found at http://docs.aws.amazon.com/aws-sdk-php/v3/download/aws.zip define('MY_AWS_AUTOLOADER_FILE_LOCATION', '/var/www/html/aws/aws-autoloader.php'); } if (!defined('MY_AWS_REGION_ID')) { // Replace us-west-2 with whatever your actual region ID is define('MY_AWS_REGION_ID', 'us-west-2'); } if (!defined('MY_AWS_ACCESS_KEY_ID')) { // Replace abcdefghijk with whatever your actual access key is define('MY_AWS_ACCESS_KEY_ID', 'abcdefghijk'); } if (!defined('MY_AWS_SECRET_ACCESS_KEY')) { // Replace lmnopqrstuvwxyz123456789 with whatever your actual secret key is define('MY_AWS_SECRET_ACCESS_KEY', 'lmnopqrstuvwxyz123456789'); } // Set the required environmental variables in case they // haven't already been set in .htaccess or elsewhere putenv('AWS_ACCESS_KEY_ID=' . MY_AWS_ACCESS_KEY_ID); putenv('AWS_SECRET_ACCESS_KEY=' . MY_AWS_SECRET_ACCESS_KEY); // Register the s3:// stream wrapper aws_register_stream_wrapper(); // Now, the URI of an S3 object can be accessed internally, without having assigned // a special access token to it. Assuming your bucket's name is my-bucket and the // object's file key inside that bucket is images/example.jpg you can build // the object's URI like so, which would assign a value of // s3://my-bucket/images/example.jpg // to $object_uri (making it internally accessible via that same URI): $object_uri = aws_render_s3_uri('my-bucket', 'images/example.jpg'); /** * Registers the s3:// stream wrapper */ function aws_register_stream_wrapper() { $region = MY_AWS_REGION_ID; // Simple security checks in case someone has messed with something // they shouldn't have if (!empty($region) && is_string($region)) { $client = aws_render_s3_client(); $client->registerStreamWrapper(); } } /** * @param $version (string) * The version of the AWS API to use * * @return (object) * An AWS S3 client */ function aws_render_s3_client($version = 'latest') { require_once(MY_AWS_AUTOLOADER_FILE_LOCATION); $s3_client = new Aws\S3\S3Client([ 'key' => MY_AWS_ACCESS_KEY_ID, 'secret' => MY_AWS_SECRET_ACCESS_KEY, 'region' => MY_AWS_REGION_ID, 'version' => $version, ]); return $s3_client; } /** * @param $bucket (string) * The name of the AWS bucket in which $file_key resides * * @param $file_key (string) * The name of the file to be retrieved, relative to the AWS bucket * * @return (string) * The URL to an AWS S3 object URL using the s3:// stream wrapper */ function aws_render_s3_uri($bucket, $file_key) { $uri = "s3://{$bucket}/{$file_key}"; return $uri; } ```
152,701
I heard about these dragons on this site and was curious to know, when do legendary dragons appear in the world? Is there a step-by-step guide to getting them to appear?
2014/01/28
[ "https://gaming.stackexchange.com/questions/152701", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/67678/" ]
There is a guaranteed spawn at Arcwind Point. [From Elder Scrolls Wikia](http://elderscrolls.wikia.com/wiki/Legendary_Dragon): > > A legendary dragon can also always be found at Arcwind Point perching > above a sarcophagus that contains either a Draugr Deathlord or a > Dragon Priest. > > > This spawning point still requires the The Elder Scrolls V: Dawnguard > DLC and level 78+. If the player dose not meet these requirements, > another type of dragon will spawn at Arcwind Point. > > >
You need dawnguard and to be lvl 78+
297,526
Here's a problem that i've seen for the first time and unfortunatley after trying everything I still couldn't fix the issue. Any suggestions will be a great help. The issue is that when we try to open greenworldinvestor.com it takes awful amount of time to load. The browser keeps on showing that its trying to find greenworldinvestor and when it finally finds it..it loads it in a snap. **few points** - * earlier it was on wpwebhost and I was using godaddy to manage the dns * Right now its on a shared account on bluehost with nameservers pointing to bluehost * happens with all the browsers and on all the OS - windows, linux, mac. **Here's what i've done from my end to fix the issue** --- Although, I understand that these points are not directly related to the issue however, just to be on safe side and to avoid assumptions - i'm listing everything that i did to try and fix the issue. * It's on wordpress - disabled all the plugins - no luck * used the default wordpress theme - no luck [confirms that the issue is not with the current theme] * even applied a CDN - no luck {all these steps definitely improved the page load time, but again that wasn't the issue in the first place - still, i thought that it may help somehow so listed them too} **Now here are some of the results of tests on tools.pingdom.com** - 1. Full page test - here's the [archived result](http://tools.pingdom.com/?url=www.greenworldinvestor.com&treeview=0&column=objectID&order=1&type=0&save=) 2. Ping test - archived ping result [tools.pingdom.com/ping/default.aspx?target=www.greenworldinvestor.com&o=2&id=5320266] 3. Traceroute - [archived traceroute result](http://tools.pingdom.com/ping/default.aspx?target=www.greenworldinvestor.com&o=1&id=5320272) **Dig result** - > > ; <<>> DiG 9.6.-ESV-R4-P3 <<>> www.greenworldinvestor.com ;; global > options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: > NOERROR, id: 29114 ;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: > 2, ADDITIONAL: 0 > > > ;; QUESTION SECTION: ;www.greenworldinvestor.com. IN A > > > ;; ANSWER SECTION: www.greenworldinvestor.com. 14400 > IN CNAME greenworldinvestor.com. > greenworldinvestor.com. 4311 IN A 66.147.244.226 > > > ;; AUTHORITY SECTION: > greenworldinvestor.com. 162711 IN NS ns1.bluehost.com. > greenworldinvestor.com. 162711 IN NS ns2.bluehost.com. > > > ;; **Query time: 67 msec** ;; SERVER: 71.252.219.43#53(71.252.219.43) ;; > WHEN: Thu Aug 4 05:39:14 2011 ;; MSG SIZE rcvd: 119 > > > **Result of HTTPFox** ![the first byte takes 17 sec. to load... crazy!](https://i.stack.imgur.com/CJ5mV.jpg)
2011/08/04
[ "https://serverfault.com/questions/297526", "https://serverfault.com", "https://serverfault.com/users/90480/" ]
From what I can see using the Chrome developer tools, your site is take a long time to serve the initial html of the page you request. I can say this isn't a DNS problem because, even if it were, only the first page requested would be slow. The client caches the DNS answer for a short time, so it wouldn't be slow on the second page request. I don't know much about wordpress, but I see similar behavior from Drupal when all server-side caching is disabled. You may want to check to make sure you have caching enabled, and there is no problem with the caching module you're using.
Not sure what may causing this, but it definitly is your main html page that is slow to load (not to render, only to load). Your problem might come from a misconfigured PHP handler. Could you try putting a simple HTML page (with the same content as your index page) and see if it loads faster (my guess is yes). Then, try a simple php file (with no more than a phpinfo()) and see if it loads faster (my guess is no).
3,183,064
> > **Possible Duplicates:** > > [For home projects, can Mercurial or Git (or other DVCS) provide more advantages over Subversion?](https://stackoverflow.com/questions/1218471/for-home-projects-can-mercurial-or-git-or-other-dvcs-provide-more-advantages-o) > > [What are the relative strengths and weaknesses of Git, Mercurial, and Bazaar?](https://stackoverflow.com/questions/77485/what-are-the-relative-strengths-and-weaknesses-of-git-mercurial-and-bazaar) > > > What are some of the differences between these source control system? Which one is the best for a small 2 people project?
2010/07/06
[ "https://Stackoverflow.com/questions/3183064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/375106/" ]
SVN is different from Git and Mercurial, in that it is a single repository that all users have to pull and commit to. Git and Mercurial have a distributed model. This means that there is a repository on every computer and there is usually an "Official" repository that people will choose to commit their changes to and pull from. Git and Mercurial are extremely similar. I prefer Mercurial because I found it much easier to use. For a 2 person team I would recommend Mercurial, but that is just my opinion. If you are not familiar with version control then you are still gonna have to spend your time learning to use any of the options, but Mercurial seemed the easiest for me. To start a Mercurial repository all you have to do is open a shell and cd to the directory you want to have version control in, and type `hg init`. That creates the repository. To add everything in the folder to the repository, type `hg add .`. Here are some other various commands: * To commit the local changes: `hg commit -m "Descriptions of changes"` * To pull to the latest version from the server: `hg pull` * To push the local changes: `hg push`
Git and Mercurial are quite similar (but different enough to warrant caution). SVN on the other hand is quite different: the first two are distributed VCSs, so they do not require a central server, while SVN does. In general many projects are moving toward distributed systems. For your small project, you're probably better off with Git or Mercurial. Which one you choose is essentially a matter of taste, although I prefer Git myself (and am far more familiar with it). You need not set up a server at all: you can push/pull changes through SSH or even email patches to each other (this can be done directly from the VCS but is sort of a hassle). You can set up a central server at any time, and all the changes will be there. You can use e.g. GitHub or Gitorious to host your project (if you're going with Git, I don't know about Mercurial).
156,500
How do I write an Excel workbook to a `MemoryStream` without first saving it to the file system? All options within the `Microsoft.Office.Interop.Excel.WorkBook` save options take a filename.
2008/10/01
[ "https://Stackoverflow.com/questions/156500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10830/" ]
I have done extensive work with the PIA and with storing Excel files in a document repository and streaming it out to the browser, and I have not been able to find a solution to using the PIA without first writing the contents to the file system first. I think that you are going to have to swallow the bullet and deal with the file system as an intermediary. The good news is that you can just give the file a unique name like a guid or use some other tempfilename method (not sure if one exists in .net) and just delete the contents when you are done.
The only way you could do this is if you were prepared to create a custom object that allowed you to store all the various bits and pieces of data/formulas/vba/links/ole objects that you wanted to keep, copy from your workbook to the object, and then persist that object to a memory stream. In affect using your proxy object as a go between. There is no way (as others have said) of writing an Excel file straight to memory. With Excel 2007 OpenXML format, you could use the BeforeSave event of the workbook to have a custom method that first sets the Cancel parameter of the BeforeSave event to True, and then instead serialises the resultant xml package (that represents the file) into an object in memory.
10,343,106
I've been using ``` mail -s "here is a log file" "person@example.com" < log/logfile.log ``` Which used to come through with headers: ``` User-Agent: Heirloom mailx 12.4 7/29/08 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit ``` But now the files are longer I'm getting noname attachments because with this: ``` User-Agent: Heirloom mailx 12.4 7/29/08 MIME-Version: 1.0 Content-Type: application/octet-stream Content-Transfer-Encoding: base64 ``` So if all else fails, check the manual `man mail` ... ``` NAME mailx - send and receive Internet mail SYNOPSIS mailx [-BDdEFintv~] [-s subject] [-a attachment ] [-c cc-addr] [-b bcc-addr] [-r from-addr] [-h hops] [-A account] [-S variable[=value]] to-addr . . . ``` None of these options seem useful so how can I force `Content-Type: text/plain`?
2012/04/27
[ "https://Stackoverflow.com/questions/10343106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/516748/" ]
The man page is a good place to start! Keep reading until you get to the `MIME TYPES` section, and pay close attention the following: > > Otherwise, or if the filename has no extension, the content types > text/plain or application/octet-stream are > used, the first for text or international text files, the second for any file that contains formatting char‐ > acters other than newlines and horizontal tabulators. > > > So, if your message contains "formatting characters" (which in general means control characters) other than newlines and tabs, it will automatically be classified as `application/octet-stream`. I bet that if you look closely at the data you'll find some control characters floating around. You can work around this by... * Including the log file as an attachment (using `-a`) instead of the main message body, and set up your `~/.mime.types` file to identify `*.log` files as text/plain. * Filter out control characters using something like `tr`. * Use another MUA such as `mutt` to send the mail. In fact, you could just craft a message yourself and send it directly to `sendmail`: ``` ( echo To: person@example.com echo From: you@example.com echo Subject: a logfile echo cat logfile.log ) | sendmail -t ```
I had some trouble to get my automatic email scripts to run after changing to Ubuntu Precise 12.04. I don't know, when Ubuntu (or Debian) exchanged bsd-mailx against heirloom-mailx, but the two "mail"-commands behave very differently. (E.g. heirloom uses -a for attachments, while it's used for additional headers in bsd.) In my case heirloom-mailx wasn't able to reliably determine the Mime type and kept sending text as attachments. Blame me for not weeding out control characters or whatever, but I don't see much point in changing scripts that did their job perfectly before the upgrade. So if you prefer setting the Mimetype yourself, bsd-mailx is a better solution. ``` sudo apt-get install bsd-mailx sudo apt-get remove heirloom-mailx ``` Solved it for me.
26,113,233
I have a build file in shell script which has a variable VAR, that has to be exported to a makefile. In the build file, ``` if [ "$arg" == "something" ]; then export VAR=$arg fi make ``` Now in the makefile, I need to use that variable in a conditional statement: ``` ifeq ( $(VAR),something) CONFIGURE_OPTIONS = abcdef else CONFIGURE_OPTIONS = ghijkl endif ``` But the condition is never checked in this manner. How can I use this exported variable?
2014/09/30
[ "https://Stackoverflow.com/questions/26113233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4091232/" ]
In shell script, ``` export VAR=hello make all ``` In makefile, ``` all : ifeq ($(VAR),hello) $(eval var1:="hello world in if block") else $(eval var1:="hello world in else block") endif @echo "$(var1)" ```
Your code does not work the way you expect, because you have an extra space before `$(VAR)`- it should be: ``` ifeq ($(VAR),something) ``` Spaces do matter in makefiles sometimes.
31,953
Proprietary software generally relies on the fact that in keeping the encryption algorithm private, it gets an extra layer of security implying "Security through Obscurity." Obviously this phrase has been hotly debated and surely is only acceptable if discovering the mechanics of a proprietary algorithm doesn't actually reduce it's security. Is there any other reason you would use a proprietary encryption since my research has proven there to be many more disadvantages than advantages!
2016/01/15
[ "https://crypto.stackexchange.com/questions/31953", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/28589/" ]
Generally speaking, using proprietary encryption is a major problem, because the algorithms which are used are not subject to the same amount of review they would be if public. But it is possible to gain some advantages this way, by taking advantage of public knowledge. Maurer & Massey (1993) prove that a cascade of ciphers with independent keys is at least as strong as its first cipher. So while PROPRIETARY(x) might not protect data as well as AES(x), and even AES(PROPRIETARY(x)) could be worse, PROPRIETARY(AES(x)) is at least as strong as AES(x). For example, suppose PROPRIETARY(x) takes a key of length log\_2((#x)!) bits and shuffles the bits according to the key. This is a weak cipher, subject (for example) to a known-plaintext attack. It seems unlikely that AES(PROPRIETARY(x)) would be weak, but it can be proven that PROPRIETARY(AES(x)) is at least as strong as AES itself. Of course nothing in this post should be taken as a reason to use proprietary encryption. In addition to taking resources to create and especially maintain, they can cause a false sense of security.
I think the answer is in some ways very obvious and in some ways less obvious. The advantage is that if it's proprietary, then that means you're almost certainly paying another party for it and therefore holding them responsible for reviewing, maintaining, and debugging the encryption library when problems arise. Contrast this with a library like OpenSSL, which turned out to have serious hidden flaws for prolonged periods of time due to the lack of sufficient manpower and funding for its maintenance and review. *(Note: I'm merely mentioning the advantages, not claiming that they outweigh the disadvantages or that there are no better alternatives.)*
2,313,925
I'm writing a program where each component has an inheritance structure has three levels... ui, logic, and data... where each of these levels has an interface of defined functionality that all components must implement. Each of these levels also has some functionality that could be written generically for the whole interface, rather than repeatedly for each component. In my mind, the best approach would be an abstract class in between the interface and the component implementation that does all the generic functionality (as in the linked [class diagram here](http://www.freeimagehosting.net/image.php?82759d7c7e.png))... but the inheritance rules for C# only let me have the multiple inheritance from unimplemented interfaces. What would be a best practices design to achieve this type of behavior?
2010/02/22
[ "https://Stackoverflow.com/questions/2313925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124034/" ]
Why not have each one of the components (UI, logic and data) in a different class and then have the UI using the logic class then have the logic class use the data class. That way you could have each class inherit from the appropriate generic class. Remember, you should [prefer composition over inheritance](https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance)
Each (abstract class & interface) offers their own set of advantages and disadvantages. While Russell is correct in suggesting *composition over inheritance*, using patterns suggests *program to an interface, not an implementation* (Head First Design Patterns). An abstract class offers tons of flexibility where you can implement methods *under the covers* so to speak, enforce implementation, etc. Both interfaces offer polymorphism if that is a concern. But abstract classes take a base inheritance slot.
876,775
Can data be recovered from a "broken SSD" in a similar manner as from an HDD? Or once the drive is "broken" is the data "toast"? EDIT: I don't mean using the same methods. I am just trying to find out if data is generally recoverable or not.
2015/02/11
[ "https://superuser.com/questions/876775", "https://superuser.com", "https://superuser.com/users/11546/" ]
NAND chips are typically standardized parts with datasheets available. All the ones I've seen on flash drives are BGA mounted, which is difficult to remove and work with, but not impossible. So it's not impossible for someone to pull chips off the board and read them in another device. Getting meaningful data off of them (i.e. what was written by an operating system) without intimate knowledge of how the controller is distributing data to them exactly is extremely difficult. However, it is likely the developer of the controller has utilities available for this or similar purposes, or could perform such an operation if desired. It's also possible some SSD boards have UART pins or pads where you can talk to the controller over the serial port and perform low-level operations, such as raw dumping of the flash chips. I don't know this for sure, though. You could on this [SSD development kit](http://www.openssd-project.org/wiki/Jasmine_OpenSSD_Platform) I believe.
Unlike an HDD, an SSD has no separate electronics board that controls/reads/writes to platters inside the capsule -- which is one of the biggest tricks to recovering data from a physically damaged or electronically "fried" HDD: you can plug in a good controller board and the data inside the capsule is usually (mostly) okay. With an SSD, it's all electronics, and there isn't any practical way to replace the microcontroller that levels wear and handles reads and writes (surface mount chips as opposed to a complete board with connectors and cables). On a national security level, it might well be possible to disassemble the device and individually read out the data from the flash RAM chips -- but on a practical basis, if an SSD won't detect on multiple computers, or won't read back data, or won't hold a format (indicative that it won't write), it's done and everything on it is gone. Yet another good reason to have good backup habits for your SSD (though most modern SSDs will outlast the user, barring electircal surges, static damage, or physical destruction).
13,468,248
I have a list of type object as follows, `List<object>` recordList which will contain database record(integer,string) as follows, ``` [[1,AAAAAAAA],[2,BBBBBB]] ``` I need to split the data in the list and put into `Hashmap<Integer,String>` as follows, I do knw how to split the data form the object list and poplualte the hashmap. How to populate the Hashmap with the data from list?
2012/11/20
[ "https://Stackoverflow.com/questions/13468248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1321824/" ]
``` List<String> l = new ArrayList<String>(); Map<Integer,String> m = new HashMap<Integer, String>(); Iterator<String> ite = l.iterator(); while(ite.hasNext()) { String sTemp[] =ite.next().split(","); m.put(Integer.parseInt(sTemp[0]), sTemp[1]); } ```
``` package listHashMap; import java.util.*; public class MyList { public static void main(String [] args) { List<String> aList=new ArrayList<String>(); Map<Integer,String> aMap = new HashMap<Integer, String>(); aList.add("AAAA"); aList.add("BBBB"); for(int i=0;i<aList.size();i++){ aMap.put(i+1,aList.get(i)); } System.out.println(aMap.toString()); } } ```
19,304,597
I am using Codeigniter and as much as possible i don't want to use the $\_GET method. What are the other ways to get the value of a button tag? Here's my button code: ``` <button id="first" name="first" type="submit" value="Php3000"></button> ``` I just want to get the value of the button to be able to pass it to my controller. I am a beginner, please enlighten me. Thank you. **EDIT** Sorry for not making it clear to you guys, actually i have three buttons ``` <button id="first" name="first" type="submit" value="Php3000"></button> <button id="second" name="second" type="submit" value="Php2000"></button> <button id="third" name="third" type="submit" value="Php2500"></button> ``` The user must choose among those three buttons and I should get the value of the chosen button. Example of what i want to do : <http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_button_value2> There it displayed the value of the button, i want to get it and pass it to my controller
2013/10/10
[ "https://Stackoverflow.com/questions/19304597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2144219/" ]
Sorry for the additional answer.. HTML Buttons in forms are treated as input fields, but only the value of the pressed button will actually be submitted. So you should rewrite your buttons as follows or similiar: ``` <button id="first" name="selected_button" value="Php3000">Choose php 3000 label</button> <button id="second" name="selected_button" value="Php2000">Choose php 2000 label</button> <button id="third" name="selected_button" value="Php2500">Choose php 2500 label</button> ``` The value of the selected button will then be available as $\_POST['selected\_button'], or in CodeIgniter ``` $selected_button = $this->input->post('selected_button'); switch($selected_button){ ... } ``` If you give your buttons separate names you will have to check each one, but like this you can just get get the value, and decide how to go on from there. In that aspect Buttons are also much more developer-friendly than Inputs of type submit. I would not rely on javascript if it's not guaranteed to be available on all client machines. Although it's a nice way of doing it. Edit: If you are using some fancy CSS you wouldn't even have to rely on buttons/forms but could use links directly. Assuming you'd be using the pretty twitter bootstrap, it might look as follows: ``` <a href="<?php echo site_url('controller/method/Php3000'); ?>" class="btn btn-info">Choose php 3000 label</a> ... ``` If you don't need any additional data submitted at the same time, this approach would have the least overhead.
I don't use CodeIgniter, but according to <http://ellislab.com/codeigniter/user-guide/libraries/input.html> you should be able to just grab the values from the input handler inside your controller: ``` if( $this->input->post('first') ) { // First button was pressed; } ```
21,757,179
I have the following problem with a small Spring MVC project I'm trying to create. I'd like to create the DispatcherServlet, but the wizard list is empty. ![enter image description here](https://i.stack.imgur.com/y7ewC.png) I believe I have all the necessary dependencies covered: * spring-core * spring-beans * spring-context * spring-jdbc * spring-web * spring-webmvc I read on similar questions that the wizard can only be used on Dynamic Web projects. I checked the Project Facets and it seems to be OK. * Dynamic Web Module v3.0 * Java v1.6 * JavaScript v1.0 Also, web.xml has been created and the project has been updated with the Maven dependencies. As far as I know this should work, but it doesn't. Any help would be much appreciated.
2014/02/13
[ "https://Stackoverflow.com/questions/21757179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3306409/" ]
Found the solution. I just had to select a **Target runtime** when creating the Dynamic Web Project. Once I did that the New Servlet list worked properly and I could add the DispatcherServlet. Of course, it can also be done manually on web.xml (that's what I did), but I was worried since the other method was supposed to work as well.
You should set server runtime in your project. To do that, Right click project -> Click properties -> Java Build Path ->Add Library –> Click Next -> Select server and add it.
2,746,750
When debugging the following console program: ``` class Program { static void Main(string[] args) { Console.WriteLine(DoIt(false)); Console.WriteLine(DoIt(true)); } private static Boolean DoIt(Boolean abort) { try { throw new InvalidOperationException(); } catch(Exception ex) { if (abort) { return true; } Console.WriteLine("Got here"); return false; } } } ``` Why does the IDE land on the second return statement during the second call to DoIt()? The results of the execution is correct but the debugging experience is misleading. Is this a known issue? Is the behavior in VS 2010 the same?
2010/04/30
[ "https://Stackoverflow.com/questions/2746750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32588/" ]
**edit** - Looks like I was wrong, but leaving my original answer here anyway: Are you sure that it works with a `List<Integer>`? It shouldn't. The method `subList()` returns a separate `List`. If you remove elements from that list, it shouldn't affect the original list. The API docs for `List.subList()` say this: > > Returns a view of the portion of this list between the specified `fromIndex`, inclusive, and `toIndex`, exclusive. (If `fromIndex` and `toIndex` are equal, the returned list is empty.) The returned list is backed by this list, so **non-structural changes** in the returned list are reflected in this list, and vice-versa. > > > Clearing a list is not a non-structural change; only changing the elements in the list are non-structural changes. This has nothing to do with whether your POJO has `equals` or `hashCode` methods or not. **edit** - I just tried it out with an `ArrayList` and it does work (not only with `Integer`, but also with my own object as a list element).
Two things I can think of are: 1. `list.sublist(0, 5)` returns an empty list, therefore `.clear()` does nothing. 2. Not sure of the inner workings of the List implementation you're using (ArrayList, LinkedList, etc), but having the `equals` and `hashCode` implemented may be important. I had a simiarl issue with Maps, where HashMap definitely needs the hashCode implementation.
49,635,495
I have a text in a .txt file and there are some paragraphs,and you can see this structure: ``` name:zzzz,surnames:zzzz,id:zzzz,country:zzzz ... name:zzzz,surnames:zzzz,id:zzzz,country:zzzz ... name:zzzz,surnames:zzzz,id:zzzz,country:zzzz ... name:zzzz,surnames:zzzz,id:zzzz,country:zzzz ... ``` And I would know how to compare all the 'id' and if there are paragrafs with the same id, eliminate one of them. Some idea? Thank you. I have already gotten the first id :/
2018/04/03
[ "https://Stackoverflow.com/questions/49635495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9590852/" ]
Enable Hyper V as following: Run a command prompt as administrator and execute: ``` dism /Online /Disable-Feature:Microsoft-Hyper-V ``` reboot and ``` bcdedit /set hypervisorlaunchtype off ```
After following the answer left by Bub Espinja, these were my steps. --- Run Powershell/CMD as Administrator and enter ```bsh dism /Online /Disable-Feature:Microsoft-Hyper-V ``` Reboot, then enter ```bsh bcdedit /set hypervisorlaunchtype off ``` However, I ran into some difficulty so I came back here and followed an additional step left by Prakash. --- Go to Control Panel [Category View] -> Programs -> Turn Windows features on or off Ensure 'Windows Hypervisor Platform' is not checked. Expand 'Hyper-V' and enable 'Hyper-V Platform' [![Ensure 'Windows Hypervisor Platform' is not checked. Expand 'Hyper-V' and enable 'Hyper-V Platform'](https://i.stack.imgur.com/eoHV4.png)](https://i.stack.imgur.com/eoHV4.png) After rebooting, I was able to run 'Docker Quickstart Terminal' and subsequently `docker run hello-world`. [![Demonstration of Result](https://i.stack.imgur.com/hJfqJ.png)](https://i.stack.imgur.com/hJfqJ.png)
39,490,201
I don't know how to explain,what I want but from examples I think you know. Momently my registration link is: ``` example.com/pages/registration.php ``` but I want to open my registration.php on this link: ``` example.com/registration ``` How can I do this? Or where can I learn about it,and how to call this? Thanks
2016/09/14
[ "https://Stackoverflow.com/questions/39490201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6740538/" ]
I know them as pretty URL's/clean URL's. You can create them using a .htaccess file. <http://www.desiquintans.com/cleanurls>
You can achieve that using normal Header Redirect. Open the file... ``` `example.com/pages/registration.php` ``` At the top of that file simply add the lines: ``` <?php header('location: example.com/registration'); exit; ```
16,055,915
I have a file in which first row contains the number and second row contains a statement associated with it and so on like the below example ``` 12 stat1 18 stat2 15 stat3 ``` But i need to print the output like sorting reversely as per numbers and so the statement related to it and print like this ``` Time = 18 Stat = stat2 Time = 15 Stat = stat3 Time = 12 Stat = stat1 ```
2013/04/17
[ "https://Stackoverflow.com/questions/16055915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2194036/" ]
From Sql Server 2008 onwards you can use `Merge` syntax ``` MERGE user target USING user_new source ON taget.ID = source.ID WHEN MATCHED THEN UPDATE SET target.Column= source.Column1,target.column2=source.column2 WHEN NOT MATCHED BY TARGET THEN INSERT (ID,Column1,Column2) VALUES (source.ID,source.column1,source.column2); ``` or you can use the below query ``` INSERT INTO user(ID,column1,column2) SELECT ID,column1,column2 FROM user_new AS source WHERE NOT EXISTS (SELECT * FROM user WHERE ID = source.ID); UPDATE target SET ... FROM user AS target INNER JOIN user_new AS source ON target.ID = source.ID; ```
You can't do `insert` and `update` in a single query you have to do in seperate ``` select * from user where user_id not in (select user_new.user_id from user_new ) ``` this query results the data for insert query similarly u have to update by replacing `not in` to `in`
64,399,585
In my **register** screen, part of the content(at the bottom) is hidden by the phone's bottom navbar. The content is only visible when I close the bottom navbar. What I want to achieve is, whenever the bottom navbar is displayed on the phone, I want content that is hidden by it to be pushed upwards for visibility and whenever the navbar is removed from sight, I want the content to remain at it's position. Here is my code. ``` class Body extends StatelessWidget { @override Widget build(BuildContext context) { return SafeArea( child: SizedBox( width: double.infinity, child: Padding( padding: EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(20)), child: SingleChildScrollView( child: Column( children: [ Text( "Register Account", style: headingStyle, ), Text( "Complete your details or continue \nwith social media.", textAlign: TextAlign.center, ), SizedBox(height: SizeConfig.screenHeight * 0.04), // 4% SignUpForm(), SizedBox(height: SizeConfig.screenHeight * 0.03), // 3% Row(mainAxisAlignment: MainAxisAlignment.center, children: [ SocialCard( icon: "assets/icons/google-icon.svg", press: () {}, ), SocialCard( icon: "assets/icons/facebook-2.svg", press: () {}, ), SocialCard( icon: "assets/icons/twitter.svg", press: () {}, ) ]), SizedBox(height: getProportionateScreenHeight(15)), Text( <--- HIDDEN FROM VIEW "By continuing you confirm that you agree with our Term and Condition", textAlign: TextAlign.center, ), ], ), ), ), ), ); } } // Get Screen Size class SizeConfig { static MediaQueryData _mediaQueryData; static double screenWidth; static double screenHeight; static double defaultSize; static Orientation orientation; void init(BuildContext context) { _mediaQueryData = MediaQuery.of(context); screenWidth = _mediaQueryData.size.width; screenHeight = _mediaQueryData.size.height; orientation = _mediaQueryData.orientation; } } // Get the proportionate height as per screen size double getProportionateScreenHeight(double inputHeight) { double screenHeight = SizeConfig.screenHeight; // 812 is the layout height that designer use return (inputHeight / 812.0) * screenHeight; } ``` Visual of the problem [![enter image description here](https://i.stack.imgur.com/PLoxn.jpg)](https://i.stack.imgur.com/PLoxn.jpg)
2020/10/17
[ "https://Stackoverflow.com/questions/64399585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10617728/" ]
Any special requirement for using a `SingleChildScrollView`? If not can you please try the code below, if this works for you, here's what it does 1. Replace `SigleChildScrollView` with `Container` 2. Wrap your `SignupForm()` inside an `Expanded()` widget. Here is the code - ``` class Body extends StatelessWidget { @override Widget build(BuildContext context) { return SafeArea( child: SizedBox( width: double.infinity, child: Padding( padding: EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(20)), child: Container( child: Column( children: [ Text( "Register Account", style: headingStyle, ), Text( "Complete your details or continue \nwith social media.", textAlign: TextAlign.center, ), SizedBox(height: SizeConfig.screenHeight * 0.04), // 4% Expanded(child: SignUpForm()), SizedBox(height: SizeConfig.screenHeight * 0.03), // 3% Row(mainAxisAlignment: MainAxisAlignment.center, children: [ SocialCard( icon: "assets/icons/google-icon.svg", press: () {}, ), SocialCard( icon: "assets/icons/facebook-2.svg", press: () {}, ), SocialCard( icon: "assets/icons/twitter.svg", press: () {}, ) ]), SizedBox(height: getProportionateScreenHeight(15)), Text( "By continuing you confirm that you agree with our Term and Condition", textAlign: TextAlign.center, ), ], ), ), ), ), ); } } // Get Screen Size class SizeConfig { static MediaQueryData _mediaQueryData; static double screenWidth; static double screenHeight; static double defaultSize; static Orientation orientation; void init(BuildContext context) { _mediaQueryData = MediaQuery.of(context); screenWidth = _mediaQueryData.size.width; screenHeight = _mediaQueryData.size.height; orientation = _mediaQueryData.orientation; } } // Get the proportionate height as per screen size double getProportionateScreenHeight(double inputHeight) { double screenHeight = SizeConfig.screenHeight; // 812 is the layout height that designer use return (inputHeight / 812.0) * screenHeight; } ```
Use SafeArea Widget to avoid the bottom navigation bar. To know more about SafeArea widget click [here](https://stackoverflow.com/questions/49227667/using-safearea-in-flutter)
523,933
I need to process the following text to get rid of the strange symbols such as: `â<80><99> â<80><9c> â<80>?` Example text: > > With the mystery unexplained, the Hyatt tried to give its guests a sense of security by posting a guard in its lobby. But Wolf couldnâ<80><99>t shake the notion that a thief could re-enter her room at any time. â<80><9c>I had dreams about it for many nights,â<80>?says Wolf, a 66-year-old Dell IT services consultant traveling in Houston for business. > > > Can anyone help me with it? I hope to either manually delete it with some command in Vi or do it with script.
2012/12/24
[ "https://superuser.com/questions/523933", "https://superuser.com", "https://superuser.com/users/-1/" ]
Just so that other people too can have an answer - Try installing ["European Union Expansion Font Update"](https://www.microsoft.com/en-us/download/confirmation.aspx?id=16083) from Microsoft. This solution is what I found at [Google Forums](http://productforums.google.com/forum/#!msg/chrome/wt4k-H-_s8Q/-oWZ5uC5rOkJ) and it helped me and I didn't needed to format my PC Hope it helps others too.
So partial thanks to some answers, but instead of closing chrome, I copied all my helvetica fonts (i'm a designer, i had 50+) into another folder. Since it detects which is in use... I decided I'd rather delete that one instead to at least get rid of the boldness which was fine by me. So, closed chrome and as I guessed i was able to delete the Helvetica Bold font (it's a system font, but it'll overwrite as another font if needed) So, opened Chrome and all was fixed (although it did go to the next font after helvetica... But better than that bold font!)
9,790,665
On fan pages, tab apps used to be displayed on the left side of the page, and their order was controlled by the "position" value they have (which is described on the api). On the new Facebook layout for profiles, tab applications are now displayed at the top of the profile, with the description, the profile pic, etc. as "favorites". They're displayed as a list of icons and only a handful of them are visible at the time, and, the position value has no longer any effect on the order, no matter how you set it with the api, the apps do not change their order now. Does anyone know how to change the order of the apps on the new layout for a fan page by calling the javascript api? (I know how to do it on the Facebook ui, not interested in that).
2012/03/20
[ "https://Stackoverflow.com/questions/9790665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1272933/" ]
Here is a solution for doing it in C#: <http://leeontech.wordpress.com/2012/03/01/customizing-gridview-items-in-metro-app-4/>
I am not sure about C# and XMAL code of doing this. But in Javascript, instead of creating the template in HTML, you can create the item template in javascript by doing something like this ``` function MyItemTemplate(itemPromise) { return itemPromise.then(function (currentItem) { var result = document.createElement("div"); //use source data to decide what size to make the //ListView item and apply different css class to it result.className = currentItem.data.type; result.style.overflow = "hidden"; // Display image var image = document.createElement("img"); image.className = "regularListIconTextItem-Image"; image.src = currentItem.data.picture; result.appendChild(image); var body = document.createElement("div"); body.className = "regularListIconTextItem-Detail"; body.style.overflow = "hidden"; // Display title var title = document.createElement("h4"); title.innerText = currentItem.data.title; body.appendChild(title); // Display text var fulltext = document.createElement("h6"); fulltext.innerText = currentItem.data.text; body.appendChild(fulltext); result.appendChild(body); return result; }); } ``` Source of this code is in the ListView Item Templates sample of the [consumer preview sample package](http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-Samples). Unfortunately, I was not able to find the C# version of it. Hope this helps to some degree.
26,650,456
look at the following snippet: ``` class C val c1 = new C { def m1 = "c1 has m1" } val c2 = new C { def m2 = "c2 has m2" } c1.m1 c2.m2 //c2.m1 //c1.m2 ``` run it in the REPL, then you know what I mean. My limited java knowledge tells me that in java, objects of same class will have the same methods signagure, and as far as OO concerned, there is no much difference between java and scala under the hood. (correct me, if I'm wrong), so I'm very surprised to see the snippet is sound scala code. so why?
2014/10/30
[ "https://Stackoverflow.com/questions/26650456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157300/" ]
You're extending `C` with traits, so `c1` and `c2` are anonymous classes : ``` scala> c1.getClass res0: java.lang.Class[_ <: C] = class $anon$1 scala> c2.getClass res1: java.lang.Class[_ <: C] = class $anon$2 ``` Looking at the java code, you'll see (`O` being a surrounding object to get it to compile) : ``` public final class O$$anon$1 extends O$C { public java.lang.String m1(); public O$$anon$1(); } public final class O$$anon$2 extends O$C { public java.lang.String m2(); public O$$anon$2(); } ```
The Java equivalent is ``` C c1 = new C { public String m1() { ... } } C c2 = new C { public String m2() { ... } } ``` Now, you can't call `c1.m1()` directly, but you can do it using reflection: ``` c1.getClass().getMethod("m1").invoke(c1) ``` Scala just allows you to do it with a simpler syntax.
7,991,425
I need to see if a specific image exists on my cdn. I've tried the following and it doesn't work: ``` if (file_exists(http://www.example.com/images/$filename)) { echo "The file exists"; } else { echo "The file does not exist"; } ``` Even if the image exists or doesn't exist, it always says "The file exists". I'm not sure why its not working...
2011/11/03
[ "https://Stackoverflow.com/questions/7991425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804992/" ]
Here is the simplest way to check if a file exist: ``` if(is_file($filename)){ return true; //the file exist }else{ return false; //the file does not exist } ```
`file_exists($filepath)` will return a true result for a directory and full filepath, so is not always a solution when a filename is not passed. `is_file($filepath)` will only return true for fully filepaths
68,449,461
I want to install Openstack on CentOS 8(single node). I am having single machine (physical machine) where I want to install all nodes of Openstack. This setup I required for simulation only not production use. I have tried to install Openstack using packstac 3 times but couldn't success. I got different issues during installation: 1.In first attempt After installation, I tried to create instance, but not getting console of instances even after it got created successfully. 2. In second attempt, during deployment of instance, network not getting allocated. 3. In third attempt, it got stuck at packstack, puppet testing only. I have followed below 2 links: <https://computingforgeeks.com/install-openstack-victoria-on-centos/> <https://www.google.com/amp/s/www.linuxtechi.com/install-openstack-centos-8-with-packstack/amp/> I followed each and every steps mention in the likns. I want to create two Ubuntu VMs on Openstack. Can someone provide me some links/video, where I can get everything which is required to install Openstack on single node and create two Ubuntu VMs and assign network to them and test the connectivity between these two VMS. Thanks in advance.
2021/07/20
[ "https://Stackoverflow.com/questions/68449461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9891377/" ]
I would use official [Packstack documentation](https://www.rdoproject.org/install/packstack/). Note that you should start with a totally fresh Centos installation; i.e. don't try to install Packstack on a server where a previous installation failed (or succeeded). You can also try [Devstack](http://docs.openstack.org/devstack). Its default configuration requires a smaller machine than Packstack (in my experience, 8GB RAM should be sufficient). Same remark: Start with a fresh installation of Centos or Ubuntu. [Microstack](https://microstack.run/) is another alternative. Its advantage is a very simple and quick installation; its disadvantage is a very strange (in my opinion) configuration and not a lot of documentation. However, it is suitable for your purpose. It claims to work on any Linux, Windows and MacOS; it does require *snap*.
I tried to install Openstack several times last week (october 2021): a) with CentOS 8 Stream to metal hardware (real server) with devstack - no one version was installed (neither Master nor Xena & Wallaby, version Viktoria & below are not for Stream OS); b) Virtual machine with CentOS 8 Stream installed with packstack - installation was clearly successful (!), quite easy for install (according to official RDO project and its homepage), however there is the real problem with virtual and actual networking: no external network is accessible, router created was OK with external connection (router IP was detected successfully from outside) but no connection was possible from and to instance. So I conclude the Openstack package is not completely documented to resolve problems, however its installation can be quite easy (when successfully finish ;) ) Addition: Of coarse, there are resources with an information how network can be configured, official Openstack docs describes different network configurations as well (however it is difficult to find it for one click and being newbie), but anyway this system requires a lot of time to study before usage.
17,027,759
I deleted a project in my workspace, then tried to create a new project with the same name. Eclipse told me that it overlaps the location of another project (the one I just deleted). How do I fix this?
2013/06/10
[ "https://Stackoverflow.com/questions/17027759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Go to Window >> Preferences >> General >> startup and shutdown >> workspace theen select Recent work space then click Remove and close the program and open it again ![screenshot](https://i.stack.imgur.com/wBhNx.png)
go to the folder and delete the file *.project*. This worked for me.
11,696,327
After installing OS X Mountain Lion and XCode, I'm getting this error: ``` Jonathans-MacBook-Air:fme jong$ npm install bcrypt npm http GET https://registry.npmjs.org/bcrypt/0.7.0 npm http 304 https://registry.npmjs.org/bcrypt/0.7.0 npm http GET https://registry.npmjs.org/bindings/1.0.0 npm http 304 https://registry.npmjs.org/bindings/1.0.0 > bcrypt@0.7.0 install /Users/jong/Workspace/fme/node_modules/bcrypt > node-gyp rebuild CXX(target) Release/obj.target/bcrypt_lib/src/blowfish.o make: c++: No such file or directory make: *** [Release/obj.target/bcrypt_lib/src/blowfish.o] Error 1 gyp ERR! build error gyp ERR! stack Error: `make` failed with exit code: 2 gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:215:23) gyp ERR! stack at ChildProcess.EventEmitter.emit (events.js:91:17) gyp ERR! stack at Process._handle.onexit (child_process.js:674:10) gyp ERR! System Darwin 12.0.0 gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" gyp ERR! cwd /Users/jong/Workspace/fme/node_modules/bcrypt gyp ERR! node -v v0.8.4 gyp ERR! node-gyp -v v0.6.1 gyp ERR! not ok npm ERR! bcrypt@0.7.0 install: `node-gyp rebuild` npm ERR! `sh "-c" "node-gyp rebuild"` failed with 1 npm ERR! npm ERR! Failed at the bcrypt@0.7.0 install script. npm ERR! This is most likely a problem with the bcrypt package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node-gyp rebuild npm ERR! You can get their info via: npm ERR! npm owner ls bcrypt npm ERR! There is likely additional logging output above. npm ERR! System Darwin 12.0.0 npm ERR! command "node" "/usr/local/bin/npm" "install" "bcrypt" npm ERR! cwd /Users/jong/Workspace/fme npm ERR! node -v v0.8.4 npm ERR! npm -v 1.1.45 npm ERR! code ELIFECYCLE npm ERR! npm ERR! Additional logging details can be found in: npm ERR! /Users/jong/Workspace/fme/npm-debug.log npm ERR! not ok code 0 ``` I have a feeling that it doesn't know which compiler to use. How do I fix this?
2012/07/27
[ "https://Stackoverflow.com/questions/11696327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/927092/" ]
Apparently I just need to install the Command Line Tools from the downloads panel in XCode
The problem may be that your Node.Js is version 0.10 and some modules only work with the previous 0.8.22 version which you can get here: <http://blog.nodejs.org/2013/03/06/node-v0-8-22-stable/>
34,720
I used to duplicate layers such as watermarks or adjustment layers from one document to another in Photoshop all the time. Layers are mostly put in a group. Now, I am starting to use Photoshop CS6 and I've fallen in love with the new Color Lookup adjustment layers. I found that whenever I have a Color Lookup layer in a group, I can't duplicate that group to another open document any more. All I can do is to duplicate it to a new document which is no use because from that new document I can't duplicate it to the document I want anyway. I can still duplicate other layers to another document as I always did but just that Color Lookup Layers that I can't copy. Can anyone explain why I can't do that or am I missing anything? updated\* I have tried to right click on the group and click Duplicate Group and in the Document list of Destination document, there are only two options which are the same document and New. When I tried to drag and drop the group I am getting the following error message. I have tried to do all those with just a single color lookup layer and it failed for the same reason as well. "Could not complete your request because an adjustment or fill layer cannot be converted to the destination document mode". Both documents have RGB, 8 bits mode. Any possible causes? Thanks.
2013/02/15
[ "https://photo.stackexchange.com/questions/34720", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/11384/" ]
This appears to be a bug within the type of Color Lookup profile. The abstract profiles can be duplicated, while the 3DLUT and Device Link fail. You will also notice that the Color Lookup layer will persist across changes to the document bit depth only when it is an abstract profile. The layer will be removed with either of the other profile types. The process I used to test: 1. Create new document **A** (clean slate) 2. Paint something (just for visual reference) 3. Duplicate document **B** (to have identical parameters) 4. In doc **A** create and group Curve and Color Lookup adj layers * note that the behavior of the Color Lookup layer in this testing was consistent whether grouped or not 5. Set doc **A** Color Lookup profile to a 3DLUT preset * Try duplicating to doc **B** + No option to duplicate using right click option (no destination for doc **B**) + Drag/Drop produces the "Could not complete your request because an adjustment or fill layer cannot be converted to the destination document mode" error * Change bit depth of doc **A** + Color Lookup layer is removed 6. Repeat step 6 with Color Lookup profile set to a Device Link preset * Same results as step 6 7. Repeat step 6 with Color Lookup profile set to an Abstract preset * Duplicates fine using either context menu (Destination for doc **B** is present), or via drag/drop * Changing bit depth works fine, Color Lookup layer persists across the edit Even if this is an expected limitation for those profile types, still looks like a bug due to the lack of feedback to the user (e.g. silently removing the Color Lookup layer when changing bit depth). I'm guessing the difference between your results and MikeW can be attributed to the inconsistency across the Color Lookup profile types. Perhaps some others can test as above to confirm, if confirmed it probably warrants a topic at <http://feedback.photoshop.com/photoshop_family/problems/common>
Drag and drop your layer from layers toolbar to another window: ![drag and drop](https://i.stack.imgur.com/ei6zv.jpg)
1,284,904
SQLite first timer, and I want to use Linq for data access. I made a SQLite database with sqliteadmin, and added it as a data source in VS2008. The problem is that when i try to drag&drop a table from the server explorer to the .dbml file, i get the error: > > "The selected object(s) use an > usupported data provider." > > > I used .NET Framework Data Provider for SQLite when i defined the data connection.
2009/08/16
[ "https://Stackoverflow.com/questions/1284904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64999/" ]
One way to deal with this is to : * First, create the site, without any javascript * Then, when every works, add javascript enhancements where suitable This way, if JS is disabled, the "first" version of the site still works. You can do exactly the same with CSS, naturally -- there is even one "[CSS Naked Day](http://naked.dustindiaz.com/)" each day, showing what websites look like without CSS ^^ One example ? * You have a standard HTML form, that POSTs data to your server when submitted, and the re-creation of the page by the server displays a message like "thanks for subscriving" * You then add some JS + Ajax stuff : instead of reloading the whole page while submitting the form, you do an Ajax request, that only send the data ; and, in return, it displays "thanks for subscribing" without reloading the page In this case, if javascript is disabled, the first "standard" way of doing things still works. This is (part of) what is called [Progressive enhancement](http://en.wikipedia.org/wiki/Progressive_enhancement)
What you're aiming for is [progressive enhancement](http://en.wikipedia.org/wiki/Progressive_enhancement). I'd go about this by first designing the site without the JavaScript and, once it works, start adding your JavaScript events via a library such as jQuery so that the behaviour of the site is completely separate from the presentation. This way you can provide a higher level of functionality and polish for those who have JavaScript enabled in their browsers and those who don't.
6,629,686
I am trying to learn Unix C and doing some exercises for practice. I am currently working on writing my own shell that works similar to the linux bash shell. The code I have below provides for a fairly basic shell. It now provides I/O redirection. I am trying to add support for piping. Initially, I just want to add support for a single pipe. I have tried to go through some tutorials online but can't quite figure out where to start. Currently, the shell below can handle commands commands such as the following. ls > abc, cat< file1 > file2, etc. ``` #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <string.h> #include <sys/wait.h> #include <fcntl.h> #define TRUE 1 int main(void) { char *arg_list[10]; int status; int counter = 0; int counter2 = 0; pid_t pid; char buf[100]; char inFile[10]; char outFile[10]; int fdIn, fdOut; while(TRUE) { printf("> "); if (!fgets(buf, 100, stdin)) return 0; pid = fork(); switch(pid) { case -1: return 1; case 0: { arg_list[counter] = strtok(buf, " \n"); counter = 0; while(arg_list[counter] != NULL) { counter++; arg_list[counter] = strtok(NULL, " \n"); } counter2 = 0; while(arg_list[counter2] != NULL) { if(!strcmp(arg_list[counter2], "<")) { if(arg_list[counter2+1] != NULL) { fdIn = open(arg_list[counter2+1], O_RDONLY); dup2(fdIn, STDIN_FILENO); } else { printf("No input file specified"); } arg_list[counter2] = 0; } else if(!strcmp(arg_list[counter2], ">")) { if(arg_list[counter2+1] != NULL) { fdOut = open(arg_list[counter2+1], O_CREAT | O_WRONLY | O_TRUNC, 0666); dup2(fdOut, STDOUT_FILENO); } else { printf("No output file specified"); } arg_list[counter2] = 0; } counter2++; } execvp(arg_list[0], arg_list); break; } default: waitpid(-1, &status, 0); break; } } return 0; } ``` If somebody can point me in the right direction, that would be appreciated.
2011/07/08
[ "https://Stackoverflow.com/questions/6629686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/695752/" ]
After you use `dup2()` (successfully), you have two file descriptors open for the one file. You need to close the original file descriptor; the executed process should not have the extra file descriptors open. You are also going to need to open the files in the appropriate way before using `dup2()`. Amongst other things, that means `strtok()` is not a good choice because it blats out the delimiter but you need to know which file to open for reading and which for writing). You are also going to need to fettle the argument list; it should contain just the command name and a null pointer, not the two file names.
Why do you need to check the type of command? Unix shells don't treat any commands specially; all redirections, including pipes, are handled the same way. One thing to watch out for is that redirections can happen *anywhere* in a command, so you should parse them out first; try ``` >foo ls <bar -la ``` in a shell sometime. (Pipes are an obvious exception to this, since they also delimit commands; syntactically `|` is the same as `;`, although semantically there is redirection involved in addition.)
110,081
I am having a hard time identifying different principles of design in action. It is hard for me to identify the relationship between different elements on a page and to know what approach was used to create that particular relationship. How can I identify and understand which principles were used in a design?
2018/06/01
[ "https://graphicdesign.stackexchange.com/questions/110081", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/118300/" ]
A good way to identify principles of design is to study each of them in isolation with a definition, an explanation, and examples of the principle. Graphic Design studies include areas in different specialties: Human Visual Perception, Applied Behavioural Psychology, and Anthropology. A cross-subject web search will help you find/sort-out individual concepts. Many of the references of interest to us fall into "Marketing." One reference I stumbled across was/is (in revisions) a kind of dictionary, cross-referenced by design principles, many (not all) of them of interest to us. It is not complete; but, it is an excellent start. I was so impressed that I bought a dozen/case and gave them to colleagues. **Universal Principles of Design** - A cross-disciplinary reference; William Lidwell, Kritina Holden, Jill Butler; 2003, Rockport pub. A second recommendation is a comprehensive, organized, and well-written **Principles of Form and Design**; Wucius Wong; 1993, John Wiley & sons pub. This and **Principles of Color Design**, also by him, influenced Graphic Design courses taught at Concordia University, LaSalle and Dawson Colleges - Montreal, Canada among others. It presents the visual language of graphic design. David B. Berman wrote **do good -design-**, How Designers Can Change The World; 2009, New Riders; which gives us our ethical principles to guide our designs to be truthful, ethical, and sustainable design. It is sponsored by the AIGA and others. The message is, "Don't just do good design, do good." I wish I could put these three books into your hands.
**How to identify principles of design more easily.** Everyone immediately responds to the subject matter in a composition. Harder to understand after-the-fact is the design (as in plan or scheme) behind the finished piece. After the work is complete, deconstructing it to reveal the principle behind it can be difficult. The principle may be non-obvious because the subject matter gets in the way. Graphic design is not a means of self-expression. Rather, it is a means of communication used to illuminate, demonstrate, tell, sell, or explain an idea or product. Knowing the purpose could make deconstruction easier. The theory being; Once you know what the “message” is, you can figure out what visual technique the designer used to communicate that message—the dominant principle is in use. As graphic designers, we use design principles applied to visual elements like a visual grammar. The way we communicate the subject using our style of expressing visual ideas becomes the artwork we create. Not everyone agrees what the simple elements of design are. A good start would list them. … **The Elements of Two-Dimensional Design**—the basic visual material used to construct the graphic design • Conceptual Elements: Space, Point, Line, Area • Visual Elements as they take form (aspects of elements): Shape, Size/scale, Colour/tone, Texture, Field/frame • Relational Elements as they are placed into the layout: Position, Direction, Depth, Weight • Functional Elements we manipulate: Illustration, Photograph, Text, Rules, **Visual Effects** Elements of design (often together with subject matter) create visual effects. When you see a visual effect, it means that some sort of organizing principle is working. The Visual Elements and Subject Matter are used separately and together to create all kinds of relationships, motion, transition, contrasts, conflicts, variations, themes, feelings, meanings, depth effects, space effects, and so on. **If you can find a relationship that creates a visual effect, you have discovered a principle.** For example, repetition (repeating something) tends to insist on being seen and it can give the effect of motion. When you discover principles, you can use them and you will understand how to make and understand artwork better. For example, a combination of red and orange has a different effect than a combination of red and green. By looking at these color combinations next to each other, you might discover a principle of design. When you see a big shape combined with another big shape it has a different effect than combining a small shape with a big shape. By looking at size examples, you might see another principle of design suggested. There are many general principles that work to produce effects, feelings, and meanings. There is an unlimited number of ways to use the elements, subject matter, and design principles to produce effects, feelings, and meanings. This is why, when we solve problems in art, we are **not** looking for one correct answer, but we are looking one or more solutions out of many unknown possible solutions. There are different kinds of design principles. Start with a list of the principles you know. Add ones you discover. When one known by an alternate name turns up, combine them. (Rather than an exhaustive glossary of terms, the interested person is invited to do a web search of the terms for definitions, and illustrative examples) Here’s a start: **Principles of Two-Dimensional Graphic** Visual **Design** - Alignment - Balance (Symmetry) - Symmetrical, Asymmetrical, Radial - Tone & Color - Contrast, variation, variety - Direction (Hierarchy) - Emphasis: “Centre of Interest,” Focus, Hierarchy, Dominance - Harmony/Unity: - Opposition - Movement/Motion/Gradation - Proximity - Repetition, rhythm, pattern - Similarity - Framing (Space) - Transparency - Variety/variation … You may even wish to include general **Principles of Composition** - Format - Viewpoint - Layout Do a search on each one in turn. Note its definition, relevant description and actual example to illustrate the principle(s) being used. Pull-up the images in your search to isolate the specific examples to illustrate the term Here are important additions **Cognitive Behavioural Graphic Design Principles** Gestalt Law – The law of simplicity **Gestalt principles of design** (Grouping) Theories of visual perception - Proximity – closer objects are related to each other - Similarity – objects that look similar as seen related or part of the same group. When there is something that doesn’t seem to fit or doesn’t resemble its neighbours, it is called an anomaly and according to the Von Restorff effect, it gets noticed and remembered. - Closure/Convexity – occurs when an incomplete shape is seen as a whole - Continuity/Good Continuation – occurs as the eye moves naturally from one part of the design to the next. It leads to the Pragnanz Effect where complex objects appear in their simplest form. - Figure & Ground – the subject and background appear to exchange dominance. The design alternates its position or characteristics in a random fashion. The difference between the two is vague as there is no dominance of one over the other. - Common Region Connectedness There are more… **Principles of Colour Association** – The Psychology of Color - Blue; secure, calm, honest, trustworthy, strong, caring - Red; love, excitement, action, boldness, passionate. - Etc. **Principles of Shape Association** – The Psychology of Shapes - Circles, ellipses, and curves have a strong femininity - Vertical lines are seen as exciting and motivating - Horizontal lines are perceived as tranquil and static - Etc. **Principles of Social Influence** – The Psychology of Marketing and Sales - Reciprocation - Authority - Commitment / Consistency - Scarcity - Liking - Social proof **Principles of Perception** - Constancy - Space - Depth - Motion - Colour **Principles of Typography** - Legibility - Readability - Weight/Colour - Alignment - Emphasis
889,663
What do I need to do in order to produce PDF invoices with a file size smaller than 20kb? [Example PDF](https://drive.google.com/file/d/0B6HXMKHljcfYV1d5Yl9YNzd4TWM/view?usp=sharing) I create invoices for a small business and I have 60,000+ invoices stored as PDFs (non scanned) that are about 108kb per page on average. I generate these invoices from an Excel spreadsheet and save them as PDFs. I've noticed documents from other companies, or even my own bank statement as PDFs that are less than 20kb per page on average. (UPDATED 3/17) I've used the Acrobat Audit tool (accessible in the "Save as" window when selecting "Optimized PDF" from the drop-down and then clicking the settings button, on Acrobat XI). Here is the result: ``` Content Streams 3.48145 KB Fonts 91.98340 KB Structure Info 11.72852 KB Document Overhead 0.64453 KB ----------------------------- TOTAL 107.8379 KB ``` What I've tried: * I attempted to use Acrobat XI's "Optimize Scanned PDF" settings, but I get "Page contains renderable text." * I attempted to "Save as" choosing the file type of "Adobe PDF Files, Optimized (\*.pdf)". The results were slightly smaller, but not less than 20kb or even less than 90kb. * I've tried Web apps that have about the same effect as the aforementioned "Save as" attempt.
2015/03/14
[ "https://superuser.com/questions/889663", "https://superuser.com", "https://superuser.com/users/318312/" ]
From the result of Acrobat Audit tool, **the biggest part of your PDF is due to Fonts** inclusion (91kb) , not to real PDF content (3kb+11kb). So you can try some of the following: * **use a single font** for the whole document * while using a single font, **try out different fonts** to see which on give you the smallest size (I've had the same problem years ago, bay using different font the document size varied wildly from 13kb to 150kb) * some software that generate PDF have an **option to include only the used characters** of a font, instead of the whole font character set, maybe this could reduce the file size a bit ([PDF Creator](http://www.pdfforge.org/pdfcreator) comes to mind) * some software that generate PDF have an option to **render the text as vector graphics**, so it wont need to include the fonts. If the text contents of the PDF is small, this could reduce the file size (I've seen this options somewhere, but I can't remind in which software...)
You could create the PDF using PHP write commands. I just did a quick search for PHP PDF and came up with several ways to produce pdfs. such as... "TCPDF is a PHP class for generating PDF documents without requiring external extensions. TCPDF Supports UTF-8, Unicode, RTL languages, XHTML, Javascript, digital signatures, barcodes and much more." Its been a while but i got involved in web based document creation and i remember the pdf's produced were remarkably small.
54,371
I frequently use and edit config files inside /etc on OS X Lion. I would like to be able to access this dir in Finder easily, but don't want to unhide hidden files system-wide using `defaults write com.apple.Finder AppleShowAllFiles`. Anyone know how?
2012/06/21
[ "https://apple.stackexchange.com/questions/54371", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/19162/" ]
Enable ShowAllFiles one more time, long enough to drag `/etc` onto your Finder sidebar. From then on, `/etc` will be available in Finder and in Open and Save As dialogs, regardless of ShowAllFiles.
Although its not exactly what you want, you could make an *Application* with **Automator**. To do so: * Open **Automator**. * Select **Work Flow**. * Select **Run Shell Script** and type `open /etc`. * Hit *Save* and choose **Application** as the format. You will, then, be able to open the **etc** folder by double clicking the *Application* you've just created.
19,638,473
``` System.Threading.ThreadPool.SetMaxThreads(50, 50); File.ReadLines().AsParallel().WithDegreeOfParallelism(100).ForAll((s)->{ /* some code which is waiting external API call and do not utilize CPU */ }); ``` I have never got threads count more than CPU count in my system. Can I use PLINQ and get more than one thread per CPU?
2013/10/28
[ "https://Stackoverflow.com/questions/19638473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/655310/" ]
If you're calling external web API, you might be hitting the limit of concurrent simultaneous connections, which is set to 2. In the begining of your application do the following: ``` System.Net.ServicePointManager.DefaultConnectionLimit = 4096; System.Net.ServicePointManager.Expect100Continue = false; ``` Try if that helps. If not, there might be some other bottleneck within the routine you're trying to parallelize. Also, just like other responders said, ThreadPool decides how many threads to spin up based on load. In my experience with TPL I've seen that thread cound increases by time: longer the app runs, and heavier load gets, more threads are spun up.
PLINQ does not fit in this case. I have found next article useful for me. <http://msdn.microsoft.com/en-us/library/hh228609(v=vs.110).aspx>
1,742
I'd heard that some people have a custom not to give knives as a gift (as knives are a sign of shortening life, not extending it); I asked one rabbi who said he hadn't heard of such a custom, but it seemed reasonable. Does anyone have a source for this custom? Would it therefore be advisable not to register for kitchen knives as part of a bridal registry?
2010/06/09
[ "https://judaism.stackexchange.com/questions/1742", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/21/" ]
"[Rabbi Nachman of Breslev said] in the name of the Ba'al Shem Tov, one should not give his fellow a knife as a gift" ([Sichot Haran no. 9](https://he.wikisource.org/wiki/%D7%A9%D7%99%D7%97%D7%95%D7%AA_%D7%94%D7%A8%22%D7%9F/%D7%90-%D7%A0#%D7%98), first printed in 1815. Maaglei Tzedek pg. 3a. This tradition is also found in Baal Shem Tov al Hatorah, Parshas Re’ah in the Mekor Mayim Chaim, no. 6.). There is an in depth article about this issue by Bency Eichorn on [the Sefarim blog](http://seforim.blogspot.com/2009/09/knife-is-it-dangerous-gift-for-rosh.html). In there he says that the earliest Jewish source is the aforementioned Sichot Haran. The non-Jewish sources for this custom predate the Jewish source by over 300 years. He also brings other students of the Ba'al Shem Tov who would give knives as gifts.
Rav Bentzion Mutzafi says there is no source for the custom of not handing someone a knife, but then he says "maybe for being careful for a good (cause)." *שאלה* - 2673 שלום לכבוד הרב הגאון האם יש מקור לדבר שאסור להעביר סכין מיד ליד אלה להניח על השולחן ולקחת או שזה סתם שטות והמצאה? *תשובה* **אין לזה מקור, ואולי זה ענין של זהירות טובה** Translation: Hello to the honorable Rabbi-Scholar. My question is: is there a source that it is forbidden to pass a knife from a hand to another hand but rather to set it down onto the table and pick it up, or is this just nonsense and an invention (i.e., a new custom)? Response: There is no source to this, and maybe this is a concern for exercising appropriate caution.
46,035
People often tag their questions with the words from the question title. Other times they use some syntactic keywords or classes. Examples: * `[arraylist]` * `[extends]` * `[properties]` * `[stringbuffer]` * `[break]` * etc, etc. From time to time I remove those tags, because they do not *categorize* the question. In my view tags are used by users to watch (and answer). And I will be surprised if someone has chosen to watch the `[extends]` tag. So, am I right to do so? ([Related question](https://meta.stackexchange.com/questions/32401/good-idea-to-remove-uncommon-tags-from-questions)) **See Also** <https://blog.stackoverflow.com/2010/08/the-death-of-meta-tags/>
2010/04/09
[ "https://meta.stackexchange.com/questions/46035", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/141771/" ]
The SO community *does* have a lot of power, but the with exception of the moderators, no one user has power to do more than downvote a question, flag it, and vote to close. Ignoring moderators, voting to close requires 5 people, flagging requires 5 people, downvoting takes off just 2 rep, and you need 3 10k users to vote to delete - but that can only happen after 3 days. Of these, only being flagged several times by the community can seriously affect your reputation - and no one person has the power to do that. All the marketing tag meant was that questions there are based around marketing with respect to programming - like any question on SO, it has to be about programming. No exceptions, not even for the likes of Jon Skeet, he with more-rep-than-atoms-in-the-universe. The system tries it's best to not allow such elitism.
What's your stackoverflow account? Anyways as you see from [the list of questions tagged marketing](https://stackoverflow.com/questions/tagged/marketing) all of them are very programming related or closed. **EDIT**: it appears that one of your posts was flagged as offensive or spam by a large number of people, and that made you lose 100 reputation.
4,753,372
Typically interfaces that let you add listeners also include a remove method something like the following. ``` interface SomeInterface { addListener( Listener) removeListener( Listener ); } ``` This however suck for several reasons. * It is possible to pass a Listener that has not yet been removed to SomeInterface.removeListener(). * It is also possible to call SI.removeListener() when no Listeners haven registered. One should not be able to call remove before even doing an add. * It also means one has to keep a handle of both the Listener and the SI reference in order to remove at some later stage. I have a proposal which I believe works solves the those three problems, however I want to hear from others to learn from their ideas and proposals which might be more elegant than my own solution.
2011/01/20
[ "https://Stackoverflow.com/questions/4753372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56524/" ]
My proposal would be to have the AddListener method return an object of type ISubscriptionCanceller with one method: CancelSubscription and possibly a SubscriptionActive property. This object would contain all information necessary to cancel a given subscription, whether subscriptions are stored in an array, linked list, or some new data structure yet to be invented. It would naturally be impossible to attempt to cancel a subscription that had not yet been requested, since one would not have the necessary ISubscriptionCanceller to do so.
I think a lot of your underlying assumptions are wrong. Lets consider the alternative in Java, that removeListener is not a method on the class until a listener has been registered. 1. This isn't possible in Java; Java is not a dynamic language (ignoring reflection) 2. Even if it was possible, as it is in javascript, how would you deal with the fact that you can add listeners of different types? Do you propose a remove method for each type? Typically if you pass in a listener that has not been registered to some sort of observing class, the method will do nothing and perhaps return a boolean indicating success or failure. Which is fine, well understood. I utterly reject this statement: "It is also possible to call SI.removeListener() when no Listeners haven registered. One should not be able to call remove before even doing an add."
14,003
[Is it ever correct to have a space before a question or exclamation mark?](https://english.stackexchange.com/questions/4645/a-space-before-a-question-or-an-exclamation-mark-can-it-be-correct) is affirming what I always use, but now some translators I know said that I always need a space before. I am sure they are French or something but before I answer them, I would like to see some British source confirming it. UPDATE: No, Wikipedia is not authoritative unless it has a link to a publication that is. The people I need to correct are likely native English speakers who sat too long next to French translators or something. I need some heavy tome to throw at them :) UPDATE: The translators ate their words. All is well in the world.
2011/02/24
[ "https://english.stackexchange.com/questions/14003", "https://english.stackexchange.com", "https://english.stackexchange.com/users/2022/" ]
As far as authority goes, I'd put my money with Fowler's *[Modern English Usage](http://en.wikipedia.org/wiki/A_Dictionary_of_Modern_English_Usage)*. In the first edition (1926), Fowler uses what seem to be half-spaces before colons, semicolons, question marks, and exclamation marks, but not before full stops or commas. These 'half-spaces' seem similar in length to regular spaces, or slightly narrower, but half as wide as those spaces he uses after colons etc. and full stops. The second edition (1965), edited by Gowers, look similar. The third edition (1996), by Burchfield (another authority in the field), doesn't have any space before semicolons etc. Frankly, spaces do look a bit old fashioned to me. My advice would be to not use spaces any more; however, if you should decide to use them after all, it would still be correct—just uncommon. I believe it is still common in languages like French.
Do you trust Microsoft? When you type a question in Microsoft Word and leave a space before the question mark. It says you have a grammar mistake and puts a green line under it. I know you're looking for a book or something though.
575,364
Recently I noticed that there are some sentences which contain "can't" that sound wrong when you replace "can't" with "cannot." Here's one example. The sentence > > Why can't I do it? > > > sounds correct. But replacing "can't" with "cannot" yields this sentence > > Why cannot I do it? > > > I don't know if this sentence is breaking any formal grammatical rule but it just sounds very "wrong" to me (and searching for the phrase on google seems to back up the idea that it's very rarely used). I was fairly surprised when I realized this. I think I had previously assumed that if I take any sentence containing a contraction and expand the contraction then the sentence should remain valid. But that does not seem to be the case in this example. So here's my question: *Why is this? Did sentences like "Why cannot I do it?" used to sound more normal but they eventually died out while "Why can't I do it?" survived? Is it that "Why can I not do it?" is the proper expansion of the contraction? If so, how did the "not" end up jumping over the "I" to form the contraction? More generally I would appreciate any explanation about the origin of this phenomenon.*
2021/09/21
[ "https://english.stackexchange.com/questions/575364", "https://english.stackexchange.com", "https://english.stackexchange.com/users/433699/" ]
I would second the answer to [this question](https://english.stackexchange.com/questions/82982/why-does-why-doesnt-it-work-become-why-does-it-not-work) that points out that constructions analogous to "why cannot I" were common through the 18th century and beyond, so though they sound old-fashioned today, they haven't always been ungrammatical. But there's no real reason to insist that contemporary English and 18th-century English have to have identical grammar rules. In fact, *Cambridge Grammar of the English Language* (p. 91) argues that in contemporary English, *can't* and *won't* are independent words that are "negative inflections" of *can* and *will*, not true contractions. This argument is based largely on the observation that *can't* and *won't* can be used in places where *cannot* and *will not* are obsolete. (Negative inflections are uncommon in European languages but exist in other languages such as Japanese: *arimasu* = "to exist" and *arimasen* = "to be nonexistent"). > > Forms like *won't* are commonly regarded as 'contractions' of *will* + *not*, and so on, but there are compelling reasons for analysing them differently from cases like *she'll* (from *she* + *will*), *they've* (*they* + *have*), etc. *Won't* is, by every criterion, a single grammatical word, an inflectional form of ***will***. *She'll* is not a single grammatical word, hence not an inflectional form. Rather, *'ll* (pronounced /l/) is a **clitic** form of *will*, i.e. a reduced form that is joined phonologically (and orthographically) to an independent word called its **host**. The host in the case of *she'll* is the pronoun *she*. The written forms *she'll*, *they've*, etc., are pronounced as single monosyllabic words phonologically but correspond to two-word sequences syntactically. > > > Evidence for this analysis is seen in: > > > [i] *Won't/\*Will not she be glad?* [not replaceable by *will not*] > > > [ii] *He says she'll read it, but she WON'T/will NOT.* > > > Example [i] shows that *won't* is not always replaceable by *will not* (as *she'll* always is by *she will*), and in such cases a contraction analysis is not viable. In [ii] the [...] capitals indicate contrastive negation marked by stress. A clitic cannot bear stress (cliticisation is an extreme case of the phonological reduction that is available only for words that are unstressed). Note, for example, that in *He says she won't read it, but she WILL*, the stress prevents the reduction of *she WILL* to *SHE'LL*: if *won't* involved cliticisation like *she'll*, therefore, it would not occur with emphatic negation. > > >
Before we start, think of how "gonna" and "wanna" arose in English - they are phonetic corruptions of "going to" and "want to". They are relatively common even in writing in which the writer does not intend to mimic speech. The history of can't/cannot is much the same. New Fowler's Modern English Usage (2000) states > > The reduced form can't, which now seems so natural, is relatively recent in origin. It does not occur in the works of Shakespeare, for example, and the earliest example of it given in the OED is one of 1706 > > > In "Negation in English and other Languages" by Jespersen, he comments > > In writing the forms in n't make their appearance about 1660 and are already frequent in Dryden's, Congreve's, and Farquhar's comedies. Addison in the Spectator nr. 135 speaks of mayn't, can't, sha'n't, won't, and the like as having "very much untuned our language, and clogged it with consonants". Swift also (in the Tatler nr. 230) brands as examples of "the continual corruption of our English tongue" such forms as cou'dn't, ha'n't, can't, shan't; but nevertheless he uses some of them very often in his Journal to Stella. > > > You will see the parallel with "gonna" and "wanna" Jespersen continues: > > Cannot becomes can't with a different vowel, long [a:]; Otway 288 writes cannot, **but pronounces it in one syllable** *[to add - can't]*. Congreve 268 has can't. In the same way, with additional dropping of [l], shall not becomes [sha'nt] *[to add - also with a long vowel]*. The spelling was not, and is not yet, settled ; NED. records sha'nt from 1664, shan't from 1675, shann't from 1682 (besides Dryden's shan'not 1668); now both shan't and sha'n't are in use. > > > (Out of interest, Jespersen then goes on to refer to the lengthened "a" in the tag of "I'm angy, an't I?" in which the "m" is dropped and has given rise to the incorrect "I'm angry, **aren't** I?"... because that is what it sounds like...) So, in short, cannot became can't because that is how the majority of people spoke and heard it. However, two spellings and two pronunciations are now accepted. The battle for "correctness" has ended in a compromise. From the above, and in your example "Why cannot I do it?" I surmise that the "cannot" would have been popularly pronounced "can't" from somewhere in the early 1600s, yet spelled "cannot" and pronounced that way by teachers (who, by-and-large, are conservative.) You will note that there are no circumstances in which **can't** may not replace "**cannot**", but "cannot" looks and sounds more "educated/formal" and may not replace "can't" in all circumstances. This is based on 400 years of pronunciation.
2,359,537
Using the HTML5 `<canvas>` element, I would like to load an image file (PNG, JPEG, etc.), draw it to the canvas completely transparently, and then fade it in. I have figured out how to load the image and draw it to the canvas, but I don't know how to change its opacity. Here's the code I have so far: ``` var canvas = document.getElementById('myCanvas'); if (canvas.getContext) { var c = canvas.getContext('2d'); c.globalAlpha = 0; var img = new Image(); img.onload = function() { c.drawImage(img, 0, 0); } img.src = 'image.jpg'; } ``` Will somebody please point me in the right direction like a property to set or a function to call that will change the opacity?
2010/03/01
[ "https://Stackoverflow.com/questions/2359537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18986/" ]
This suggestion is based on pixel manipulation in canvas 2d context. From MDN: > > You can directly manipulate pixel data in canvases at the byte level > > > To manipulate pixels we'll use two functions here - `getImageData` and `putImageData`. `getImageData` usage: ``` var myImageData = context.getImageData(left, top, width, height); ``` The `putImageData` syntax: ``` context.putImageData(myImageData, x, y); ``` Where `context` is your canvas 2d context, and `x` and `y` are the position on the canvas. So to get red green blue and alpha values, we'll do the following: ``` var r = imageData.data[((x*(imageData.width*4)) + (y*4))]; var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1]; var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2]; var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3]; ``` Where `x` is the horizontal offset, `y` is the vertical offset. The code making image half-transparent: ``` var canvas = document.getElementById('myCanvas'); var c = canvas.getContext('2d'); var img = new Image(); img.onload = function() { c.drawImage(img, 0, 0); var ImageData = c.getImageData(0,0,img.width,img.height); for(var i=0;i<img.height;i++) for(var j=0;j<img.width;j++) ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255] c.putImageData(ImageData,0,0);//put image data back } img.src = 'image.jpg'; ``` You can make you own "shaders" - see full MDN article [here](https://developer.mozilla.org/En/HTML/Canvas/Pixel_manipulation_with_canvas)
You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity. If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.
13,592,786
I have a query where I am doing an `INNER JOIN` on couple sub-queries. In this query I use a similar `WHERE` clause which has a `LIKE` statement; `WHERE bookName LIKE '%INTERVIEWS%'`. But there are about five different variations of a `bookName` which has the word "INTERVIEWS". So would the query perform better if I did an `OR` statement for each variation, or should I do one `LIKE` statement for all the variations? ------------------ EDIT ------------------ Here is an example of what the query looks like with only a `LIKE` statement: ``` SELECT * FROM books WHERE bookName LIKE '%INTERVIEWS%'; ``` Here is an example of what the query looks like with `OR` statements: ``` SELECT * FROM books WHERE bookName = 'INTERVIEWS WITH CELEBRITIES' OR bookName = 'ONGOING INTERVIEWS WITH STUDENTS' OR bookName = 'POLITICIAN INTERVIEWS' OR bookName = 'INTERVIEWS WHICH FAILED' OR bookName = 'INTERVIEWS WITH PROGRAMMERS'; ```
2012/11/27
[ "https://Stackoverflow.com/questions/13592786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/830545/" ]
There is multiple aspects to consider: * You do not have an `index` on the bookName column: in this context that does not matter, the query is going to perform the same way by executing a clustered index scan or a table scan. * You do have a `non clustered index` on the bookName column + this is a `non covering index` (scenario 1): in the second use case with the `OR` statement, you are likely to hit the `index tipping point`, where the query optimizer will decide **not** to use the `non clustered index`. In this context the `LIKE` will perform better by using an index scan. Read more on the [Kimberly Tripp's blog](http://www.sqlskills.com/BLOGS/KIMBERLY/category/The-Tipping-Point.aspx). + this is a `covering index` (scenario 2): there is no tipping point for covering indexes. In this case, the second query will perform drastically better by using an `index seek` where the `LIKE` query will still have to do an `Index Scan`. So if performance is critical, use a covering index Here are the details, using [Adventure Works](http://msftdbprodsamples.codeplex.com/releases/view/93587) Scenario 1 ``` SELECT * FROM Production.Product AS p WHERE Name LIKE '%mountain seat%' SELECT * FROM Production.Product AS p WHERE Name = 'LL Mountain Seat Assembly' OR Name = 'ML Mountain Seat Assembly' OR Name = 'HL Mountain Seat Assembly' OR Name = 'LL Mountain Seat/Saddle' OR Name = 'ML Mountain Seat/Saddle' OR Name = 'HL Mountain Seat/Saddle' ``` ![enter image description here](https://i.stack.imgur.com/CPB1K.png) Scenario 2 ``` SELECT Name FROM Production.Product AS p WHERE Name LIKE '%mountain seat%' SELECT Name FROM Production.Product WHERE Name = 'LL Mountain Seat Assembly' OR Name = 'ML Mountain Seat Assembly' OR Name = 'HL Mountain Seat Assembly' OR Name = 'LL Mountain Seat/Saddle' OR Name = 'ML Mountain Seat/Saddle' OR Name = 'HL Mountain Seat/Saddle' ``` ![enter image description here](https://i.stack.imgur.com/nj3TS.png)
If the bookName column is indexed and the table has a substantial number of columns, the second option will definitely run more quickly because it will be ab index scan instead of a table scan. If there is no index then they will be approximately the same because they will both require a table scan. As for the idea of adding full text indexing, that is best for long columns of text, not short names like this. I would stick with indexing the column if you need performance and doing a series of exact matches.
24,536
I'm planning on building a small model turbofan engine for a bit of fun but I thought I'd better get a better understanding of how they work first. I understand the majority of it at the moment but I'm struggling to see what the bypass air actually does, to my mind it seems like a waste of air and energy if its just going straight out of the engine without compression...could someone explain this to me?
2016/01/22
[ "https://aviation.stackexchange.com/questions/24536", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/13120/" ]
The bypass air is actually what gives the jet engine most of its thrust. As the air enters the engine, some of it goes to the turbine core and runs the whole engine. But most of the air goes through and is sped up by the large fan giving it the thrust. Doing it this way increases the efficiency because the engine moves more air, although at a slightly lower velocity, than just a low-bypass engine which moves some air with high velocity.
Jet planes like fighter planes have their geometry designed for supersonic speed which is usually achieved with high velocity combusted jet exhaust from the jet engine. This consumes a lot of fuels in the high pressure compressor section. Passenger planes on other hand are not designed to fly at supersonic speed so high velocity jet exhaust with high fuel consumption rate are not desired. The fuel optimal way to achieve this is to extract the kinetic energy from the combusted jet exhaust and transform it back into mechanical energy. This energy is used to drive the turbo fan which only compresses bypass air through the bypass section of the engine to the exhaust to achieve all the benefits of bypass jet engine as described in many other comments or articles. Note there is no fuel consumption here in the bypass section but only the excess kinetic energy of the hot exhaust is extracted and is used to run the bypass fan(s). It is possible to design different engine mechanism to do the same thing as (high) bypass jet engine here, but it may be more complicated and has the penalty of heavier engine; therefore, less efficient than the current implementation.
7,403,457
been researching this a while and not sure entirely what to do. I want to allow users to switch debug mode either on or off. With debug mode on NSLogs will be printed to console. currently I can set debug mode on or off in the build settings using a preprocessor (DEBUG) and I use the following code to "block" NSLogs. ``` #ifdef DEBUG NSLog(@"If you can see this then debug is on"); #endif ``` I have created a toggle switch in the settings page to get input from the user but I don't know how to use this input to then undefined/redefine DEBUG. Any ideas? I am not sure if this is even possible so any alternate solutions would also be appreciated. Many Thanks :)
2011/09/13
[ "https://Stackoverflow.com/questions/7403457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/529432/" ]
You should not use preprocessor directives: using `#ifdef DEBUG` means that, if `DEBUG` is not defined, that piece of code doesn't get compiled at all. You should instead replace preprocessor directives with a simple if statement that check a global variable (or, at least, that may be a solution).
I believe your code block would only check if you are building for debug or release and will build accordingly. You can build it on a device it will be on release mode , I don't think it is possible to run the simulator in release mode otherwise. Maybe manually building the application for simulator and moving the packed file to run only on simulator without running xcode, but it will not be reasonable I guess.
33,813
The Galleons, Sickles, and Knuts are described as the currency of wizards. I don't remember seeing anything about any other currency used by wizards. Is there such currency? Are Galleons, Sickles, and Knuts universal, or do wizards outside of Britain/Commonwealth/English speaking world use different currency?
2013/04/03
[ "https://scifi.stackexchange.com/questions/33813", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/4004/" ]
There is almost certainly some kind of different currencies, though there's not enough canon info to know if they are some rare outlier country's coin, or every country has it own coins. From ***Goblet of Fire*, Chapter 7 - BAGMAN AND CROUCH** > > "You foreign?" said Mr. Roberts as Mr. Weasley returned with the correct notes. > "Foreign?" repeated Mr. Weasley, puzzled. > > "You're not the first one who's had trouble with money," said Mr. Roberts, scrutinizing Mr. > > Weasley closely. "**I had two try and pay me with great gold coins the size of hubcaps ten minutes ago**." > > > * Neither Galleons, Sickles, or Knuts are even remotely close to the size of hubcaps * On the other hand, Galleons aren't very much bigger than muggle money, so Mr Roberts wouldn't be calling them "great gold coins size of hubcaps" if they were simply Galleons. + British [2 pound coin](http://en.wikipedia.org/wiki/Two_pounds_%28British_coin%29) is 1.12" + Wikia says Galleons are the size of [American Silver Eagles](http://en.wikipedia.org/wiki/American_Silver_Eagle), ~1.6" (mere 50% bigger). No cite, but seems about right given they were carried in kids' pockets. + hubcaps are at least 10x the size of a Galleon, 15x size of 2quid ([Toyota RAV4's is 16"](http://rads.stackoverflow.com/amzn/click/B00BOEZOF2)) Therefore we almost certainly can infer that they were something else (and I know of no Muggle currency of that size). But there's no additional info on the topic I'm aware of in HP books, interviews or podcasts (however, there's a chance future post 4/2013 data on Pottermore would add some extra details). --- NOTE: in the interest of fairness, there exists a legitimate opinion (voiced on both on HP Wikia's talk page and in comments below) that Mr. Roberts was given typical Galleons and merely used "hyberbole" when he compared the slightly-larger Galleon coins to "hubcaps". I personally don't see it as a plausible interpretation (see above), but there's no unambiguous proof it's wrong.
There's a different currency in America at least: the dragot. It's mentioned in [this passage](https://www.wizardingworld.com/writing-by-jk-rowling/rappaports-law-en) on new-Pottermore. > > In brief, the catastrophe involved the daughter of President Rappaport’s trusted Keeper of Treasure and Dragots (the Dragot is the American wizarding currency and the Keeper of Dragots, as the title implies, is roughly equivalent to the Secretary of the Treasury). > > *Rappaport's Law, Wizarding World* > > > As for other countries, there isn't much canon evidence (other than the discussion above about *GoF*). If the same currency was used throughout Europe, I suspect the coins might have other names in other languages — "galleon", "sickle" and "knut" are very much suited to an anglophone! (Interestingly though, they don't alter the names in the Spanish translation, I've just checked.) One completely speculative point: Muggle banks make quite a lot of commission on currency exchange — goblins are fairly mercenary, so would probably like to do the same!
27,745,456
In the python, the `if` statement can have parentheses or not like this: ``` if True: pass if (True): pass ``` Is there any difference at all, even a performance difference, between these?
2015/01/02
[ "https://Stackoverflow.com/questions/27745456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2968663/" ]
In Python, parenthesis are not required. You usually use them to group long complex expressions.
As in most languages, extra parentheses are ignored. In Python the `if` statement doesn't require any at all. Both statements are identical.
2,129,642
Let $E$ is a splitting field of a polynomial over $K$ then $E/K$ is finite normal extension. Now the polynomial is of finite degree and will have finitely many roots, so the extension $E/K$ is finite and also since $E$ is the splitting field of the polynomial over $K$ so it contains all the roots of the polynomial and hence a normal extension. Is the reasoning correct?
2017/02/05
[ "https://math.stackexchange.com/questions/2129642", "https://math.stackexchange.com", "https://math.stackexchange.com/users/98414/" ]
Your reasoning that $E$ is finite over $K$ is correct. For normality, it depends on what definition of a normal extension you are using. There are a few equivalent ones, and from your proof it is not clear to me which definition you are using. Here is one definition we can take for $E$ to be normal over $K$ (from wikipedia). Let $\overline{K}$ be an algebraic closure of $K$ containing $E$. Then $E$ is normal over $K$ if every embedding, $\sigma$, of $E$ into $\overline{K}$ that fixes $K$ (means $\sigma\rvert\_K = id\rvert\_K$), sends $E$ to $E$, that is, $\sigma(E) = E$. Let's say that $E$ is the splitting field of the polynomial $f\in K[x]$. Then $E = K(\alpha\_1,\alpha\_2,\ldots,\alpha\_n)$, where the $\alpha\_i$ are the roots of $f$. One way to write the proof would be to argue as follows. Let $\sigma$ be an embedding of $E$ into $\overline{K}$ that fixes $K$. Then $\sigma$ permutes the roots of $f$, so for all $i$, $\sigma(\alpha\_i) = \alpha\_j$ for some $j$. The $\alpha\_j$'s are in $E$, so $\sigma$ sends $E$ to $E$. Thus $E$ is normal over $K$.
> > **Theorem:** Let be $K$ field extension of $k$, the the following are equivation: > > > $(1)$ $K$ normal extension of $k$ and finite > > > $(2)$ $K$ splitting fields of $k$ for $f\in k[x]$ > > > proof $2) \to 1)$ Let be $\alpha\_1,..,\alpha\_n $ roots of polynomial $f(x)$ then $K=k(\alpha\_1,..,\alpha\_n)$ and let $g(x)$ irreducible polynomial in $k[x]$ and have root $\beta \in K$ and $L$ splitting field $g(x)$ and $\beta'\in L$ onther root of $g(x)$ , then exitst isomorphism $\sigma: k(\beta) \to k(\beta'); \sigma(\beta)=\beta' $, and we note that $K$ is spilliting field of $f(x)$ over $k(\beta) $ and $K(\beta')=k(\alpha\_1,..,\alpha\_n,\beta')$ is spilliting field of $f(x)$ over $k(\beta')$, then exists isomorphism $\tau:K \to K(\beta') ; \tau(a)=a ; a\in k(\beta) , \tau(\beta)=\beta'$, then $\tau(\alpha\_1),..,\tau(\alpha\_n)$ are roots of $f(x)$ in $K(\beta')$. and $\beta \in K; \beta=h(\alpha\_1,..,\alpha\_n)$, then $\beta'=\tau(\beta)=\tau(h(\alpha\_1,..,\alpha\_n))=h(\tau(\alpha\_1),..,\tau(\alpha\_n))\in K$, so all roots of $g(x)$ in $K$ then splitting in $K[x]$ and $K$ normal extension of $k$. we note that $K$ finite extension of $k$
2,933,029
I have two image swap functions and one works in Firefox and the other does not. The swap functions are identical and both work fine in IE. Firefox does not even recognize the images as hyperlinks. I am very confused and I hope some one can shed some light on this for me. Thank you very much in advance for any and all help. FYI: the working script swaps by onClick via DIV elements and the non-working script swaps onMouseOver/Out via "a" elements. Remember both of these work just fine in IE. Joshua Working Javascript in FF: ``` <script type="text/javascript"> var aryImages = new Array(); aryImages[1] = "/tires/images/mich_prim_mxv4_profile.jpg"; aryImages[2] = "/tires/images/mich_prim_mxv4_tread.jpg"; aryImages[3] = "/tires/images/mich_prim_mxv4_side.jpg"; for (i=0; i < aryImages.length; i++) { var preload = new Image(); preload.src = aryImages[i]; } function swap(imgIndex, imgTarget) { document[imgTarget].src = aryImages[imgIndex]; } ``` ``` <div id="image-container"> <div style="text-align: right">Click small images below to view larger.</div> <div class="thumb-box" onclick="swap(1, 'imgColor')"><img src="/tires/images/thumbs/mich_prim_mxv4_profile_thumb.jpg" width="75" height="75" /></div> <div class="thumb-box" onclick="swap(2, 'imgColor')"><img src="/tires/images/thumbs/mich_prim_mxv4_tread_thumb.jpg" width="75" height="75" /></div> <div class="thumb-box" onclick="swap(3, 'imgColor')"><img src="/tires/images/thumbs/mich_prim_mxv4_side_thumb.jpg" width="75" height="75" /></div> <div><img alt="" name="imgColor" src="/tires/images/mich_prim_mxv4_profile.jpg" /></div> ``` Not Working in FF: ``` <script type="text/javascript"> var aryImages = new Array(); aryImages[1] = "/images/home-on.jpg"; aryImages[2] = "/images/home-off.jpg"; aryImages[3] = "/images/services-on.jpg"; aryImages[4] = "/images/services-off.jpg"; aryImages[5] = "/images/contact_us-on.jpg"; aryImages[6] = "/images/contact_us-off.jpg"; aryImages[7] = "/images/about_us-on.jpg"; aryImages[8] = "/images/about_us-off.jpg"; aryImages[9] = "/images/career-on.jpg"; aryImages[10] = "/images/career-off.jpg"; for (i=0; i < aryImages.length; i++) { var preload = new Image(); preload.src = aryImages[i]; } function swap(imgIndex, imgTarget) { document[imgTarget].src = aryImages[imgIndex]; } ``` ``` <td> <a href="home.php" onMouseOver="swap(1, 'home')" onMouseOut="swap(2, 'home')"><img name="home" src="/images/home-off.jpg" alt="Home Button" border="0px" /></a> </td> ```
2010/05/28
[ "https://Stackoverflow.com/questions/2933029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/353310/" ]
Both your examples work for me, though they're pretty unappealing examples of ancient Netscape 3-era coding. ``` var aryImages = new Array(); aryImages[1] = "/tires/images/mich_prim_mxv4_profile.jpg"; ``` Arrays are `0`-indexed. Currently your loop will try to access `aryImages[0]` and get an `undefined`, which is will try (and fail) to preload. There is very rarely any use for the `new Array` constructor today. Instead use array literals: ``` var images= [ '/tires/images/mich_prim_mxv4_profile.jpg', '/tires... ]; ``` also: ``` document[imgTarget].src = aryImages[imgIndex]; ``` We don't do that, or `<img name>` any more. In preference, give the image an `id` attribute and access it with `document.getElementById()`. Otherwise this causes all sorts of problems when image names clash with document properties and other named items on the page. Maybe you've got a name clash problem, something else called “home” in part of the document we can't see. Though if “does not even recognize the images as hyperlinks” means you aren't getting the pointer changing over the links or showing the link address, I suspect what you've actually got is a layout problem in code we can't see here, where you've accidentally positioned another element over the top of the nav so it can't be clicked on. Anyway, it's poor for manageability, usability and accessibility to be loading images into an element like this. Use normal links to the images (so they work without JavaScript) and add progressive-enhancement JS on top, eg.: ``` <style type="text/css"> .thumb { display: block; } .thumb img { width: 75px; height: 75px; border: none; vertical-align: top; } </style> <a class="thumb" href="/tires/images/mich_prim_mxv4_profile.jpg"> <img src="/tires/images/thumbs/mich_prim_mxv4_profile_thumb.jpg" alt="" /> </a> <a class="thumb" href="/tires/images/mich_prim_mxv4_tread.jpg"> <img src="/tires/images/thumbs/mich_prim_mxv4_tread_thumb.jpg" alt="" /> </a> <a class="thumb" href="/tires/images/mich_prim_mxv4_side.jpg"> <img src="/tires/images/thumbs/mich_prim_mxv4_side_thumb.jpg" alt="" /> </a> <img id="thumbshow" src="/tires/images/mich_prim_mxv4_profile.jpg" alt="" /> <script type="text/javascript"> // Bind to links with thumb class // for (var i= document.links.length; i-->0;) { if (document.links[i].className==='thumb') { // Preload main image // var img= new Image(); img.src= document.links[i].href; // When clicked, copy link address into image source // document.links[i].onclick= function() { document.getElementById('thumbshow').src= this.href; return false; } } } </script> ``` Similarly, most people do simple rollovers with CSS background images these days. If you use [CSS Sprites](http://www.alistapart.com/articles/sprites), you don't even need two separate images, so no preloading or JavaScript of any kind is necessary.
Just checked up on this. If you are using XHTML, it may not be the JavaScript that is corrupt, but your markup: XHTML needs tags and attributes to be specified in lowercase. I assume, that IE in its much-to-desire standards support perhaps partially ignores this, and evaluates your latter example as you think it should. But Firefox, which, you know, is much more standards compliant, may treat this as an improperly formatted attribute and ignores it. Like: ``` <div onclick="swap(1, 'imgColor')"></div> <!-- Should work --> <a onMouseOver="swap(1, 'home')"></a> <!-- May not work --> ``` Note, that this may not be the solution at all, just a possible issue.
8,543
I remember a rumour from my youth in the late seventies / early eighties, that there was supposedly cadmium in older (relative to that time) LEGO bricks. Searching for `LEGO cadmium` yields quite a lot of hits, but so far, nothing conclusive. I also note that LEGO has never recalled any old bricks, which I admit would be next to impossible: how would the general public be able to distinguish between older and newer bricks? **Has cadmium ever been used in LEGO bricks? If so, in what quantities?** How about other toxic metals?
2017/01/28
[ "https://bricks.stackexchange.com/questions/8543", "https://bricks.stackexchange.com", "https://bricks.stackexchange.com/users/3176/" ]
I asked Gary Istok on your behalf in [this Brickset Forum thread](http://bricksetforum.com/discussion/comment/498950), who is an expert on LEGO's history. He said the following: > > When LEGO replaced the Cellulose Acetate bricks circa 1963 with ABS > plastic for non-trans parts, and polycarbonate for the trans ones, > they had a problem with the red and yellow parts. For some reason > (I'm not a chemical engineer)... red and yellow ABS parts were more > difficult to color to TLG standards. So Bayer and Borg-Warner (the > chemical companies that produced the ABS and other plastic pellets > worldwide) added Cadmium, a heavy metal, as an additive to those 2 > LEGO colors to help in the coloring process. > > > Although Cadmium will not leach out of the LEGO bricks of that era (kids could safely chew on those LEGO parts), the longer term landfill > issues of Cadmium laced LEGO getting into the ground, did become an > issue with environmentalists. So TLG had their plastics makers > Borg-Warner (for USA, Canada, Britain, Ireland and Australia) and > Bayer (for continental Europe and Asia) work on removing the cadmium > from the red and yellow elements of that era. I don't know the > chemical specifics of that action, but by 1973 LEGO parts were Cadmium > free... and have remained so. > > > Next question.... can you tell Cadmium parts (1963-72) from Cadmium free parts? Generally yes... but it's easier for red bricks, which > are a darker red color with Cadmium. Yellow LEGO parts with Cadmium > are also a darker color, but the difference between Cadmium and > Cadmium free yellow parts is less noticeable... especially with used > or dirty yellow elements. > > >
Even in early 1980s there were some patches having Cadmium. I should link to the study but lost it now. Here is somewhat proper reference: <https://www.thesun.co.uk/news/5436922/second-hand-plastic-toys-including-lego-could-harm-children-with-toxic-chemicals/> Eating is something to avoid. Hand-to-mouth (hand skin licked) behaviour is not as fatal.
12,298,237
I am new to java language and have been reading over the API documentations. I was wondering if someone could help me with what some of the symbols mean? For example, in PriorityQueue there is: ``` Constructor Summary ... PriorityQueue(Collection<? extends E> c) ... Method Summary ... <T> T[] ... ``` My problem is around '?', 'E', 'c' and 'T'. I think I have worked out a few, like 'T' I think is Type. If someone could help with understanding I would be much greatful. A link to website that describes would be great! Thank you!
2012/09/06
[ "https://Stackoverflow.com/questions/12298237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You're right that `T` is a type parameter. In this case it can be replaced by any type, since it does not have constraints. This constructor has a type constraint: ``` PriorityQueue(Collection<? extends E> c) ``` and should be read as: create a new `PriorityQueue` instance using a `Collection` taking as type parameter any type that extends the type `E` (including `E` itself), where `E` is the type parameter of the `PriorityQueue`. Example: ``` List<String> list = new ArrayList<String>(); PriorityQueue<String> pq = new PriorityQueue<String>(list); ``` In this case `E` (the type parameter of `pq`) is `String` and the type parameter of `list` matches the predicate `? extends E`, since it is also `String`. This would also work: ``` List<String> list = new ArrayList<String>(); PriorityQueue<Object> pq = new PriorityQueue<Object>(list); ``` since `String` is a subclass of `Object`, but this would fail at compilation: ``` List<String> list = new ArrayList<String>(); PriorityQueue<Integer> pq = new PriorityQueue<Integer>(list); ``` I suggest you read more about Java generics [here](http://docs.oracle.com/javase/tutorial/java/generics/).
You should learn some basic java concepts.Stack Overflow's [java tag](https://stackoverflow.com/tags/java/info) has many information. The tag's `<? extends E>` means Wildcard generic parameter that the parameter can be any generic Collection where the parametrized type extends the collection. The "parameter" E is replaced by the programmer when using the class, e.g. `ArrayList<String>` `<T>` is Generic class declaration. `T[]` is Array. `c` is variable declaration.
50,127,362
The below API is called from the UI, as well as it wants to be redirected to, by other APIs. ``` @RequestMapping(value = "/showAbc", method = RequestMethod.POST) public ModelAndView showAbc(@RequestBody Abc abcInstance) { //doSomething } ``` The below API is also called from the UI end, but it fetches an instance of Abc class using a repository call and now wants to call the above API using redirect, and also wants to pass the instance as an argument. ``` @RequestMapping(value = "/showBcd", method = RequestMethod.POST) public ModelAndView showBcd(@RequestParam String bcdId){ Abc abc = abcRepository.findByBcdId(bcdId); /* How to pass the instance of Abc, when redirecting to /showAbc */ return new ModelAndView("redirect:/showAbc"); } ``` Now, in the above redirect I also want to pass the instance of Abc, when redirecting to /showAbc from /showBcd.
2018/05/02
[ "https://Stackoverflow.com/questions/50127362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9602278/" ]
I wouldn't recommend calling one API to another if it's in the same application. This way you are tightly coupling API to API. Either leave the API contract to be called to UI or handle the delegation via plain java service calls. ``` @RequestMapping(value = "/showAbc", method = RequestMethod.POST) public ModelAndView showAbc(@RequestBody Abc abcInstance) { return new ModelAndView("abc",abcService.get()); } @RequestMapping(value = "/showBcd", method = RequestMethod.POST) public ModelAndView showBcd(@RequestParam String bcdId){ // You should move this repo call to bcdService.java Abc abc = abcRepository.findByBcdId(bcdId); //Use a normal service call to get the instance instead of a API call return new ModelAndView("abc",abcService.getViaInstance(abc)); } ``` However, to have a model passed to the view(**Forward the request**), you need to add to the model as : ``` ModeAndView m = new ModelAndView("forward:/showAbc"); Abc abc = getAbcInstance(); m.addObject("abc",abc); return m; ```
Please try this ``` ModeAndView m = new ModelAndView("redirect:/showAbc"); Abc abc = abcRepository.findByBcdId(bcdId); m.addObject("abc",abc); return m; ```
28,282
Let $G$ be a simple algebraic group over a field $k$, and let $U$ be the unipotent radical of a Borel subgroup $B$. Because $B$ normalises $U$, the group $H = B/U$ acts on the coordinate ring $\mathcal{O} = k[X]$ of the basic affine space $X = G/U$ via $(h.f)(x) = f(xh)$. We get a decomposition of $\mathcal{O}$ into a direct sum $\mathcal{O} = \oplus\_{\lambda \in \Lambda^+} \mathcal{O}^\lambda$ where the Weyl module $\mathcal{O}^\lambda$ is the set of all $f \in \mathcal{O}$ such that $h.f = \lambda(h)f$ for all $h \in H$. Because the action of $H$ commutes with the action of $G$ on $k[X]$ given by $g.f(x) = f(g^{-1}x)$, each $\mathcal{O}^\lambda$ is a $G$-submodule of $\mathcal{O}$. We can also identify $\mathcal{O}^\lambda$ with the space of global sections $H^0(G/B, \lambda)$. Next, multiplication in $\mathcal{O}$ induces a $G$-module map $\mathcal{O}^\lambda \otimes \mathcal{O}^\mu \to \mathcal{O}^{\lambda + \mu}$ for any $\lambda, \mu \in \Lambda^+$. Since $\mathcal{O}$ has no zero-divisors, this map is non-zero. Now if the base field $k$ has characteristic zero, it is well-known that the $G$-modules $\mathcal{O}^\lambda$ for $\lambda \in \Lambda^+$ are irreducible, so the multiplication map above must be surjective. Does this remain true when the characteristic of $k$ is positive, when the Weyl modules $\mathcal{O}^\lambda$ are no longer irreducible in general?
2010/06/15
[ "https://mathoverflow.net/questions/28282", "https://mathoverflow.net", "https://mathoverflow.net/users/6827/" ]
The question has an affirmative answer and a fairly long history as well, but the proof uses some nontrivial ideas. The notation used here is nonstandard relative to that found in Jantzen's book *Representations of Algebraic Groups* (second edition, AMS, 2003). Also, a "Weyl module" (in the usual sense) of a given highest weight is the dual of the module of global sections for a related line bundle on the flag variety, using Kempf's vanishing theorem (1976). The term "Weyl module" was coined by Carter and Lusztig in their paper on special linear groups, partly because the formal character is given by Weyl's formula. A Weyl module has a unique simple quotient, while the corresponding module has this module as its unique simple submodule. There was a series of papers by Lakshmibai-Musili-Seshadri on the geometry of flag varieties in prime characteristic, in which they stated along the way that the tensor product of these dual Weyl modules maps onto the one specified by the sum of highest weights. (Their proof may not be rigorous. In any case, Kempf's theorem comes into play here.) A focused reference is the paper in J. Algebra 27 (1982) by Jian-pan Wang, "Sheaf cohomology on $G/B$ and tensor product of Weyl modules". That paper followed up a suggestion of mine that such a tensor product should have a filtration with appropriate Weyl modules as subquotients. The paper by Olivier Matthieu in Duke Math. J. 59 (1989) used Frobenius splitting techniques to prove this in full generality after the partial results by Wang and then by Steve Donkin in Springer Lecture Notes 1140 (1985). Eventually all of this gets folded into the general theory of "tilting modules" for reductive algebraic groups (Chapter G in Jantzen). [ADDED] As Ekedahl just pointed out, a treatment is given in the more recent and more extensive book by Brion and Kumar along with history.
Yes, it is true in general. I found it as Thm 3.1.2 of *Brion, Michel(F-GREN-IF); Kumar, Shrawan(1-NC) Frobenius splitting methods in geometry and representation theory. Progress in Mathematics, 231. Birkhäuser Boston, Inc., Boston, MA, 2005. x+250 pp. ISBN: 0-8176-4191-2*. The result itself is earlier (see historical remarks at the end of Chapter 3).
11,321,001
I kind of suck at recursion (which is why im working on this) and I'm having trouble figuring out how to do this: `("Hello" foldLeft(1))((x, y) => x * y.toInt)` recursively. Any thoughts?
2012/07/04
[ "https://Stackoverflow.com/questions/11321001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479180/" ]
``` scala> def r(s : String) : Int = { | s match { | case "" => 1 | case _ => s.head.toInt * r(s.tail) | } | } r: (s: String)Int scala> r("hello") res4: Int = 714668928 ```
Here's a tail recursive version using an accumulator. This version has a clean API too. ``` import scala.annotation.tailrec def unicodeProduct(string: String): Int = { @tailrec def unicodeProductAcc(string: String, acc: Int): Int = { string match{ case "" => acc case _ => unicodeProductAcc(string.tail, string.head.toInt * acc ) } } unicodeProductAcc(string, 1) } scala> :load unicodeProduct.scala Loading unicodeProduct.scala... import scala.annotation.tailrec unicodeProduct: (string: String)Int scala> unicodeProduct("hello") res0: Int = 714668928 ```
30,787
We have already discussed why $e^{(\pi\sqrt{163})}$ is an almost integer. [Why are powers of $\exp(\pi\sqrt{163})$ almost integers?](https://mathoverflow.net/questions/4775/why-are-powers-of-exppisqrt163-almost-integers) Basically $j(\frac{1+\sqrt{-163}}{2} ) \simeq 744 - e^{\pi\sqrt{163}}$, where $j(\frac{1+\sqrt{-163}}{2} )$ is a rational integer. But $j(\sqrt {\frac{-232}{2}})$ and $j(\sqrt {\frac{-232}{4}})$ are not integers. They are algebraic integers of degree $2$, but they are also almost integers themselves. The same phenomenon happens with Class $2$ numbers $88$ and $148$. Is there another modular function that explains why these numbers are almost integers?
2010/07/06
[ "https://mathoverflow.net/questions/30787", "https://mathoverflow.net", "https://mathoverflow.net/users/6769/" ]
The standard reason why $e^{\pi\sqrt{N}}$ is a near integer for some $N$ is that there is some modular function $f$ with $q$-expansion $q^{-1} + O(q)$, such that substituting $\tau = \frac{1 + i\sqrt{N}}{2}$ (or perhaps $\frac{i\sqrt{N}}{2}$) and $q = e^{2 \pi i \tau}$ into the $q$-expansion of $f$ yields a rational integer. If $N$ is sufficiently large, positive powers of $q$ are very small, so the initial term $q^{-1} = e^{-\pi i (1 + i\sqrt{N})} = -e^{\pi\sqrt{N}}$ is large and very close to the rational integer. We usually see the phenomenon with $f$ as the $j$-function, but as Frictionless Jellyfish pointed out, there are other choices. You might ask why a modular function would yield an integer when fed a quadratic imaginary input, and the answer seems to come from the theory of complex multiplication, i.e., elliptic curves whose endomorphism rings are strictly larger than the integers. I'll start by outlining the usual picture with the $j$ function, and then switch to moduli of symmetrized diagrams of curves. **Class number one** Given an elliptic curve $E$ over the complex numbers, we can choose a lattice $\Lambda \subset \mathbf{C}$ such that $E \cong \mathbf{C}/\Lambda$ as a complex manifold (and as an analytic group). $\Lambda$ is uniquely determined by this property up to complex rescaling, also known as homothety. The endomorphism ring of $E$ is therefore isomorphic to the endomorphism ring of $\Lambda$, which is a discrete subring of $\mathbf{C}$ and is either $\mathbf{Z}$ or the integers in a quadratic imaginary extension $K$ of $\mathbf{Q}$. In the latter case, $E$ is said to have complex multiplication (or "$E$ is a CM curve"), and $\Lambda$ is a complex multiple of a fractional ideal in $K$. Two fractional ideals in $K$ yield isomorphic curves if and only if they are related by a rescaling, i.e., by a principal ideal. This yields a bijection between isomorphism classes of elliptic curves with complex multiplication by the ring of integers in $K$, and elements of the ideal class group of $K$. These sets are finite. For any complex elliptic curve $E$ and any ring-theoretic automorphism $\sigma$ of $\mathbf{C}$, we can define $E^\sigma$ as the curve you get by applying $\sigma$ to the coefficients of the Weierstrass equation defining $E$. Since the $j$-invariant is a rational function in the coefficients of the Weierstrass equation, $j(E^\sigma) = j(E)^\sigma$. Since $E^\sigma$ and $E$ have isomorphic endomorphism rings, the conclusion of the above paragraph implies the automorphism group of $\mathbf{C}$ acts on the set of CM curves, and their $j$-invariants, with finite orbits. In particular, $[\mathbf{Q}(j(E)):\mathbf{Q}]$ is bounded above by the class number of $K$ (and with more work, we find that we have equality). The fact that $j(E)$ is an algebraic integer can be proved in several different ways: see section II.6 of Silverman's *Advanced Topics in the Arithmetic of Elliptic Curves*. My preferred method is showing that $j$ is the solution to lots of modular equations (which yield monic polynomials). We are left with the problem of finding CM elliptic curves whose endomorphism rings have class number one, but this is equivalent to finding lattices $\Lambda \subset \mathbf{C}$ that are the rings of integers of class number one imaginary quadratic fields. By work of Heegner, Stark, and Baker, we get the usual list: $N = 163, 67, 43, 19, \dots$, and the first few terms yield near-integers. **Symmetrized diagrams** For any prime $p$, there is an affine curve $Y\_0(p)$ roughly parametrizing triples $(E, E', \phi)$, where $\phi: E \to E'$ is a degree $p$ isogeny of elliptic curves. Equivalently, points on this space correspond to pairs of (homothety classes of) lattices, such that one is an index $p$ sublattice of the other. I use the term "roughly" because the presence of extra automorphisms prevents the formation of a universal family over the parameter space, so the affine curve is only a coarse moduli space. The Fricke involution switches $E$ with $E'$, and sends $\phi$ to its dual isogeny. The quotient is the curve $Y\_0^+(p)$, roughly parametrizing unordered pairs of elliptic curves, with dual degree $p$ isogenies between them. It is possible to consider level structures with more complicated automorphisms, but I'll stick with primes for now. Based on the class number one discussion above, we want a function $f$ that attaches to each such unordered pair a complex number such that: 1. $f$ has $q$-expansion $q^{-1} + O(q)$. 2. For any ring-theoretic automorphism $\sigma$ of $\mathbf{C}$, we have the compatibility: $$f(\{E,E'\},\{\phi, \bar{\phi} \})^\sigma = f(\{E^\sigma,{E'}^\sigma \},\{\phi^\sigma, \bar{\phi}^\sigma \}).$$ This implies the value of $f$ is algebraic when $E$ and $E'$ are CM. 3. $f$ should satisfy enough modular equations (or some other condition that yields integrality). By a theorem of Cummins and Gannon, these conditions taken together imply that $f$ is a normalized Hauptmodul for a genus zero curve. In particular, $p$ must be one of the fifteen [supersingular primes](https://mathoverflow.net/questions/1269/what-does-supersingular-mean): 2,3,5,7,11,13,17,19,23,29,31,41,47,59,71. Now, suppose we have a class number two field, such as $\mathbf{Q}(\sqrt{-58})$. We want a supersingular prime $p$, and an unordered pair of fractional ideals in the field, one index $p$ in the other, that is stable (up to simultaneous homothety) under the action of the automorphism group of $\mathbf{C}$ on the Weierstass coefficients of the quotient elliptic curves. Ideally, we would like there to be only one homothety class of unordered pairs, so $\operatorname{Aut} \mathbf{C}$ will automatically act trivially. For the case at hand, the fractional ideal $(2,-i\sqrt{58})$ has index 2 in the ring of integers, its square is $(2)$, and it is the only index 2 fractional ideal. If we take $p=2$, we find that the unordered pair $\{ 1, (2,-i\sqrt{58}) \}$ represents the only homothety class of pairs of fractional ideals of index 2. This yields the result that Frictionless Jellyfish pointed out, that if $f\_{2A} = q^{-1} + 4372q + 96256q^2 + \dots$ is the normalized Hauptmodul of $X\_0^+(2)$, then $f\_{2A}(\frac{1+i\sqrt{58}}{2}) \in \mathbf{Z}$. When $q=e^{-\pi \sqrt{58}}$, the terms with positive powers of $q$ in the expansion of $f\_{2A}$ are small enough to make $q^{-1}$ close to an integer. **Powers** We still need to figure out why $e^{\pi\sqrt{232}}$, the square of $e^{\pi \sqrt{58}}$, is also near an integer. The easy answer is: if we square $f\_{2A}$, we get $q^{-2} + 8744 + O(q)$, which is an integer when $q=e^{-\pi \sqrt{58}}$. The $O(q)$ terms here are still small enough to make $q^{-2} = e^{\pi \sqrt{232}}$ very close to an integer. You get a similar phenomenon with 88 and 148. If you want to ask about $e^{3\pi \sqrt{58}}$, which is an integer minus $1.5 \times 10^{-4}$, a more sophisticated answer can be extracted from Alison Miller's answer to [this question](https://mathoverflow.net/questions/4775/why-are-powers-of-exppisqrt163-almost-integers). The normalized Hauptmodul for $X\_0^+(2)$ is a replicable function, meaning its coefficients satisfy a certain infinite collection of recurrences, introduced by Conway and Norton when studying monstrous moonshine. These recurrences are equivalent to the existence of certain modified Hecke operators $T\_n$, such that $n \cdot T\_nf\_{2A}$ is an integer-coefficient polynomial in $f\_{2A}$ with $q$-expansion $q^{-n} + O(q)$. The coefficients in the $O(q)$ part get big as $n$ increases, so powers of $e^{\pi \sqrt{58}}$ eventually drift away from integers. (N.B.: The 2A in $f\_{2A}$ refers to a conjugacy class in the monster simple group. There is a distinguished graded representation of the monster for which the trace of identity is $j-744$ and the trace of a 2A element is $f\_{2A}$.)
Frictionless Jellyfish deleted his useful (but snide) answer, so here is some elaboration. Define $r[q] = f2[q]^{24} + 2^{12}/f2[q]^{24} = q^{-1} - 24 + 4372q + O(q^{2})$, where f2[.] is a Weber function. Weber functions satisfy quadratic polynomials for Class 2 numbers such as 232: $r[e^{-\pi \sqrt{58}}] = 64(((5 + \sqrt{29})/2)^{12} + 2^{12}/(5 + \sqrt{29})^{12}) = 24591257728 = e^{\pi \sqrt{232}} - 24 + ...$. Note that r[q] is specifically engineered to cancel square-roots and be an exact rational integer. Alternatively we could work directly with $2^{12}/f2[q]^{24} = q^{-1} - 24 + 276q + O(q^{2})$: $2^{12}/f2[e^{-\pi \sqrt{58}}]^{24} = 64(((5 + \sqrt{29})/2)^{12}$. The number $(5 + \sqrt{29})/2)$ is a Pisot number because its conjugate is less than unity, so the twelfth power is approximately a rational integer.
3,857
I want to create an automated process, that will trigger/create the Export Service * <https://eu1.salesforce.com/ui/setup/export/DataExportPage/d> ![enter image description here](https://i.stack.imgur.com/BG2G8.jpg) And once complete, will upload all the resulting files to an FTP. The files are 512MB in size each. Is this supported in any way? I thought of parsing the resulting page once I get the confirmation mail, but that seems so '90s'
2012/10/30
[ "https://salesforce.stackexchange.com/questions/3857", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/260/" ]
The FREE Jitterbit data loader lets you query all fields, export to an FTP site, and to schedule that process. Only downside is spending an hour or two setting up the query for each object (custom and system). On the plus side, it exports a lot of objects that the salesforce data export doesn't.
For future visitors, you can try this solution to [upload data on FTP server using Command line dataloader.](http://www.jitendrazaa.com/blog/salesforce/using-dataloader-and-ant-to-backup-salesforce-data-on-ftp-server-video/)
8,089,125
When i ran PMD on my Java Code , one of the Error Message it is showing is "The class STWeb has a Cyclomatic Complexity , of 20 " . Typically my java class is of this way ``` public class STWeb implements STWebService { public String getData(RequestData request) { validate(request); } public boolean validate(Data[] formdata) { if(formdata.length==1) //do this else if(formdata.length==3) //do this else if(formdata.length==4) //do this else if(formdata.length>4) //do this else if(formdata.length==2) { if(formdata[0].getName.equals("OIY")) { } / And many more if else here } } } ``` As you can see , as per my business requirements , i need to code the class with many if's and if else so the reason the cyclocomplexity has ncreased , please tell me what is feasible approach as per the standard for this ??
2011/11/11
[ "https://Stackoverflow.com/questions/8089125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784597/" ]
It helps if you have something like this: ``` if (a) { return true; } else if (b) { return true; } else if (c) { return true; } else { return false; } ``` then, you replace it with this: ``` return a || b || c; ```
If this is mandatory - yes this happens despite it's futil - you can often reduce the class cyclomatic complexity by introducing base classes and move distribute the functions into the base classes until the per class cyclomatic complexity is ok. Or simpler: add // NOPMD to your class: ``` public class VeryComplexStuff { // NOPMD ... ```
37,798,690
I'm using the leaflet library in R, which is a wrapper to the leaflet.js library. I'm wondering if it is possible to add a query or search button using the R interface (or some hack to the underlying code)? There are search plug-ins to the javascript library here <http://leafletjs.com/plugins.html#search--popups>, but I can't figure out how to get them to work with the javascript that comes out from the R library. As a minimal example, I want to add to the following the ability to search for "location 1" in the following map, and have it display the popup: ``` library(leaflet) df = read.csv(textConnection( 'Name, Lat, Long <b>location 1</b>,42.3401, -71.0589 <b>location 2</b>,42.3501, -71.0689')) leaflet(df) %>% addTiles() %>% setView(lng=-71.0589,lat=42.3301, zoom=12) %>% addMarkers(~Long, ~Lat, popup = ~Name ) ```
2016/06/13
[ "https://Stackoverflow.com/questions/37798690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2615477/" ]
It appears that there is a search plugin for the R leaflet package: <https://github.com/byzheng/leafletplugins>
[Check out](https://owi.usgs.gov/blog/inlmiscmaps/) the `inlmisc` package and `AddSearchButton` ``` df = read.csv(textConnection( 'Name, Lat, Long <b>location 1</b>,42.3401, -71.0589 <b>location 2</b>,42.3501, -71.0689')) map=leaflet(df) %>% addTiles() %>% setView(lng=-71.0589,lat=42.3301, zoom=12) %>% addMarkers(~Long, ~Lat, popup = ~Name, group="marker") map=inlmisc::AddSearchButton(map, group = "marker", zoom = 15, textPlaceholder = "Search here") ```
92,869
I am going to be starting up a new project at work and want to get into unit testing. We will be using Visual Studio 2008, C#, and the ASP.NET MVC stuff. I am looking at using either NUnit or the built-in test projects that Visual Studio 2008 has, but I am open to researching other suggestions. Is one system better than the other or perhaps easier to use/understand than the other? I am looking to get this project set up as kind of the "best practice" for our development efforts going forward.
2008/09/18
[ "https://Stackoverflow.com/questions/92869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13593/" ]
I have been using NUnit for two years. All is fine, but I have to say that the unit testing system in Visual Studio is pretty nice, because it's inside the GUI and can more easily do a test for private function without having to mess around. Also, the unit testing of Visual Studio lets you do covering and other stuff that NUnit alone can't do.
I got messages that "NUnit file structure is richer than VSTest"... Of course, if you prefer the NUnit file structure, you can use this solution to the other way, like this (NUnit → Visual Studio): ``` #if !MSTEST using NUnit.Framework; #else using Microsoft.VisualStudio.TestTools.UnitTesting; using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute; using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute; #endif ``` Or any other conversion... :-) This use here is just an alias to the compiler.
1,617,524
I plan on writing a Java 3D game that will work both on PC and Android. Unfortunately it looks like there is no common OpenGL API for both platforms. Do the APIs differ significantly? Is there a way I could use the same 3D code in both versions? Is it a good idea?
2009/10/24
[ "https://Stackoverflow.com/questions/1617524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78145/" ]
Android supports OpenGL ES 1.0 which overlaps with OpenGL 1.3 so this should be possible, but it is not as simple a just replacing the jar files at runtime. It is a good idea to try to reuse as much as possible of you application across both platforms. Anyway it is generally good practice to isolate the rest of you code from external dependencies such OpenGL even if you don't specifically need OpenGL ES support. You never know what API/platform you may want to port your application to in the future. There are 2 options that are available. The first is to hide the OpenGL implementation behind an interface that the rest of your application uses and then provide separate Jogl and Androide implementations. Depending on which platform you are running on you can then choose to instanciate the correct implemenation at runtime using the factory pattern. As OpenGL ES and OpenGL are very similar the effort required to maintain this should not be too high providing you stick to the common functions. The other option is to try and use Jogl2 which has support for profiles. These appear to provide exactly what you need but Jogl2 is still in beta. The bottom this page talks a little about profiles: <http://kenai.com/projects/jogl/pages/FAQ> > > Profiles allow Java applications to be written in a way which allows compatibility with multiple OpenGL versions at the same time. Since OpenGL ES (GL for embedded systems) has overlapping functionality with OpenGL itself it opened the opportunity to add even Profiles which bridge desktop and embedded implementations. > > > You might want to read this <http://michael-bien.com/mbien/entry/jogl_2_opengl_profiles_explained> for more information about profiles.
There is actually quite a bit of difference between java3d and the android opengl api. First java3d is a higher level abstraction on 3d. And even if you were to use something like JOGL there would be some differences in the api's. Your best bet would be to abstract out the actually 3d drawing implementation in the code base, you could share the rest of the logic, but then have platform specific code to handle the opengl/3d drawing.
50,933,364
I am new to VueJS and web development in general. I am working on a project that displays my Vue components as cards. I was hoping to make this web app a SPA with only 1 card ever appearing at a time. Is it possible to put something such as a search field where I can type (say a name or some text found within the card) and have that card appear. Sorry in advance if I'm unclear. Also is this the best way about creating multiple instances of this card? Thanks! ``` Vue.component('blog-card', { template: '#blog-card', data: function data() { return { name: 'LeBron James', category: 'Slasher', image: 'http://ak-static.cms.nba.com/wp- content/uploads/headshots/nba/latest/260x190/2544.png', author: '99', desc: '23 Badges' }; } }); Vue.component('blog-card2', { template: '#blog-card', data: function data() { return { name: 'Steph Curry', category: 'Shot Creator', image: 'http://ak-static.cms.nba.com/wp-content/uploads/headshots/nba/latest/260x190/201939.png', author: '96', desc: '15 Badges' }; } }); new Vue({ el: '#container' }); ```
2018/06/19
[ "https://Stackoverflow.com/questions/50933364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9841091/" ]
Using `str_detect` from the `stringr` pacakge: ``` library(stringr) str_detect(df1$column1, df1$column2) [1] TRUE FALSE TRUE ``` or using only base R combining `grepl` with apply: ``` apply(df1,1, function(x){ grepl(x[2], x[1]) }) [1] TRUE FALSE TRUE ```
We can do this using `stringr`. First, let's create a data frame: ``` df <- data.frame(column1 = c("Target_US_Toy", "Target_CA_Toy"), column2 = c("_US_", "_NZ_"), stringsAsFactors = FALSE) ``` Next, we create a new column called `result`: ``` library(stringr) df$result = str_detect(string = df$column1, pattern = df$column2) ```
6,248,814
We created a few applications targeting iPhone 3 and iPhone 4. When we tested these apps on iPad, they worked well. We thought we do not need to create separate apps targeting iPad. We went with that decision. A few months later, we realized that the graphics are not looking as good as are on the iPhone. Even the text is not that sharp. Now we are wondering whether to create these apps targeting iPad as well. Do people usually create separate apps for iPhad and iPhone or they just create one for these two platforms? If we need to create separate apps, what is the best way to do?
2011/06/06
[ "https://Stackoverflow.com/questions/6248814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186148/" ]
You just need to change the images and size for ipad. A few changes in xibs that are for ipad. you can make same app work on iphone as well as ipad... Check out this Link that convert iphone app to universal ipad apps [Link here](http://iphonedevelopment.blogspot.com/2010/04/converting-iphone-apps-to-universal.html) You can place this condition `if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)` and then load the respective xibs. Hope you are getting my point.
The iPad uses "pixel doubling" to expand an iPhone app to completely fill its screen in 2x mode. That is usually why it won't look as sharp as a native iPad app. The best way to answer whether or not you should make an native iPad app is a matter of customer base and funds for R&D. Do you think your customers will demand (and pay for) a separate app? Is it worth the additional costs to design, develop, support and maintain it? Also, do the activities involved in your app scale to the iPad platform? When I say this I mean are they complex enough where they would benefit from redesigning to accommodate the extra screen space and UI elements the iPad offers?
723,380
Today i've faced with loggin loop on my Ubuntu 14.04.3 LTS again. I've started with most popular scenarios to fix but everything fails. All articles on the first 4-5 pages of google search are read but no success. For now i can login to Guest, to tty with my user, to my new user using GUI, but my old user via GUI is unreachable. Could you please point me somewhere how i can fix it??
2016/01/20
[ "https://askubuntu.com/questions/723380", "https://askubuntu.com", "https://askubuntu.com/users/327741/" ]
I had the same query when I had updated some systems installed with the 14.04.1 installation medium, that had been updated to 14.04.3 without pushing the kernel onto one of the HWE releases. The thing that made sense of it in my mind is that the installation medium (CD release) for 12.04.5 will use the Trusty HWE kernel (3.13.xx) by default. 12.04.5 as a release, just refers to having all of your packages upgraded to a certain point. **The kernel version is not explicitly tied to the point release.** So it's fine to have a 12.04.5 release of Ubuntu, which uses the original kernel for 12.04. Having a look at the [Kernel Support Schedule](https://wiki.ubuntu.com/Kernel/LTSEnablementStack) is also informative, and helped my comprehension greatly.
You can find out exactly which version Ubuntu version you are using by typing > > cat /etc/issue > > > or with the command > > lsb\_release -a > > > as indicated by other answers (you need to install it first, as it doesn't come with Ubuntu by default)
10
If magic were to manifest in the modern (present) age, how would first world governments attempt to classify and regulate its usage? To be more specific (and an example), if the USA created a Department of Magical Affairs, what would the primary and secondary concerns of such an agency be? Further clarification, let's assume that magic is a field of study that anyone can learn with proper research, time, and dedication, but innate talent will cause variations in the extent/limits of power.
2014/09/16
[ "https://worldbuilding.stackexchange.com/questions/10", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/10/" ]
This is a rather more complicated subject than the question would make it. There's an old saying about how there are two things you would not want to see the making of: sausage and legislation. This issue is further clouded by the unique political landscape of the US, in as far as there are quite a few people who dead set against the use of magic in any form. So there is really no practical way to judge what language the chartering legislation of such an agency might contain, and thus, what it's concerns *would* be. However, I don't think it too difficult to judge what the concerns of such an agency *should* be. First and foremost, it would need to take a look at how magic, in whatever form it manifested, would affect the enforcement of existing law - and most urgently and especially laws regarding violent crimes such as murder. Considering the depth and breadth of federal, state, and local laws, this would require considerable resources as well as inter-agency cooperation. The second most important area, from a regulatory perspective, would be the effect on commerce. This would include things like licensing, workplace safety, and environmental impact. This aspect is also far reaching and would require considerable resources and more inter-agency cooperation.
Probably the primary concerns would be that people did not use magic for illicit purposes (putting curses on people, etc.). A secondary concern might be something like encouraging education about magic, or if magic is an inborn rather than learned ability, seeking out and identifying magic-users. It would probably issue magic licenses to those who could pass a basic competency test, and fine those who used magic in certain ways without having a license.
9,982,433
I'm developing an application for my final thesis on computer science, and I need to collect and log accelerometer data. I need to acquire it for a whole day long, so there are serious battery constraints (for instance, I cannot leave the screen on). Also, this isn't a market targeted application, so it is pretty acceptable to do some serious hacking, even low level C/C++ coding, if required. It is well known that on many devices the listeners for accelerometer events stop generating events when screen goes off (some links regarding this problem: <http://code.google.com/p/android/issues/detail?id=3708> , [Accelerometer stops delivering samples when the screen is off on Droid/Nexus One even with a WakeLock](https://stackoverflow.com/questions/2143102/accelerometer-stops-delivering-samples-when-the-screen-is-off-on-droid-nexus-one)). I have thoroughly searched for some alternatives, some of them include workarounds that do not work for my device (LG P990, stock ROM). So what happens is this: When you register an event listener for android accelerometer sensor in a Service, it works fine until the screen is turned off. I have already tried to register the eventListener on a Service, on an IntentService, tried to acquire WakeLocks. Regarding wakelocks, I can verify that the service is still running watching the LOGcat output, but it seems the accelerometer is put into sleep mode. One of the workarounds presented in some of the links is to unregister and re-register the event listener periodically using the thread of an IntentService like in this code snippet bellow ``` synchronized private static PowerManager.WakeLock getLock(Context context) { if (lockStatic==null) { PowerManager mgr=(PowerManager)context.getSystemService(Context.POWER_SERVICE); lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,NAME); lockStatic.setReferenceCounted(true); } return(lockStatic); } @Override protected void onHandleIntent(Intent intent) { sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE); sensorManager.unregisterListener(this); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); synchronized (this) { boolean run = true; while (run){ try { wait(1000); getLock(AccelerometerService.this).acquire(); sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE); sensorManager.unregisterListener(this); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); Log.d("Accelerometer service", "tick!"); } catch (Exception e) { run = false; Log.d("Accelerometer service", "interrupted; cause: " + e.getMessage()); } } } } @Override public void onSensorChanged(SensorEvent event) { Log.d("accelerometer event received", "xyz: "+ event.values[0] + "," + event.values[1] + "," + event.values[2]); } ``` which indeed makes the onSensorChange be called every time we unregister/register the listener. The problem is that the event received contains always the same values, regardless of me shaking the device. So, basically my questions are: ( bear with me, I'm almost finishing :P ) 1. is it possible to have low level access (C/C++ approach) to the accelerometer hardware WITHOUT registering to an event listener? 2. is there any other workaround or hack? 3. could anyone with a more up-to-date phone kindly test if the problem persists in firmware 3.0 and above? **[UPDATE]** **Unfortunately, it seems to be a bug with some cellphones. More details in my answer.**
2012/04/02
[ "https://Stackoverflow.com/questions/9982433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1308680/" ]
Basically, it is a problem with my phone. Other users have reported this also happens with their phones, from different brands but same Android version. Other persons have no problem at all - strongly indicating that this is not a problem with the stock version of android but from the implementations of each company for their hardware drivers. I need constant accelerometer data delivered and cannot have a dongle measure this data for me - I have an Arduino with Bluetooth and accelerometer, so I could have implemented this solution. So I decided that the temporary solution for my cellphone was to let the screen on (dimmed) and ignore battery consumption. Later on I will perform the tests for battery usage using another android phone which works with the screen turned off. **More information about the bug** I've researched some more and found reports from other Android users and I think maybe I understand what is happening. The library libsensors.so which has the drivers for the phone sensors is not developed by Google but by each cellphone vendor - of course, because each cellphone has its own specific hardware. Google only provides a C header file so that the developers know what they have to implement. On some implementations for these drivers, the developers simply turn the accelerometer off when the screen goes off, thus preventing the sensor event listener to receive new events. I also tested this with CyanogenMod RC7.2 but it did not work either, because accelerometer drivers are original from LG. **E-mails exchanged with HR department of LG** I sent an e-mail to the developers of the LG P990 and finally got some concrete answers! This may be of great help to some people like me that are experiencing these issues with Android. I wrote the following question > > Hello! I am developing my thesis in computer science and currently I > am fetching data from accelerometer hardware. As of now, I found out > that the accelerometers do not send events when the screen is off, so > even when I grab a wakelock from within one of my programs, I can > verify that my program is still running (through LOGcat output) but no > accelerometer event comes out. I have to dim my screen on (which I > cannot afford, the battery drains too fast) to start receiving > accelerometer events again. I also tried accessing it through native C > code, registering on the accelerometer events but the result was the > same, the accelerometer did not throw any values, even though I was > rotating my device. So I was wondering if I could have direct access > to the hardware, with native code, without having to register to a > listener. Is this possible? If so, could you kindly give some further > advice? I would appreciate very much any help! Martin > > > For what I received this response: > > Dear Martin, We received the answer from Dev. Team. They said that you > can’t get accelerometer event while your phone screen is off. Because > HAL layer didn’t implement sysFS path to get H/W event such as > accelerometer and there is no public API to get event. Thank you. Best > Regards. (Sean Kim) > > > I then sent an e-mail back, saying among other things, that I considered this a bug, since one should have access to all the hardware when acquiring a wake lock: > > [...] I asked this question because I have some friends that also have > Android phones with the same gingerbread version but from other > cellphone brands, and some of them reported they receive events from > the accelerometers when the screen is turned off. I read on some > forums that this bug - I consider it a bug, since when I acquire a > Wakelock I would expect to have some processing going on - depends on > the sensor drivers that the vendors implement for their cellphones. Is > there any possibility that these drivers can be updated or will this > bug be corrected at some point? This would help me enormously with my > ongoing work [...] > > > And then I received this answer: > > In my knowledge from Dev. Team, That isn’t bug. That is a limitless of > this phone because of H/W architecture. We need to redesign the HAL > architecture and device driver to support your request. But, as you > know that is too difficult due to lack of resource. We are trying to > help you with our all efforts but we cannot support your request as I > mentioned. (Sean Kim) > > > So they apparently know about this but are not trying to correct this because either they don't think it is a bug - which I still strongly believe is a logical flaw - or they don't have the time/resources to correct it. **Bottom line** If you have a cellphone that does not send accelerometer events with the screen off, try updating your firmware. If this does not solve and you really want to do some serious hacking, re implement your hardware layer - hint: it's probably something to do with libsensors.so.
I've ran into similar problems with the Samsung Nexus running *Android 4.0.2* using other system services that stop/pause while the screen is off even though a `PARTIAL_WAKE_LOCK` is acquired. My solution was to use a `SCREEN_DIM_WAKE_LOCK` as in: ``` lockStatic = mgr.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,NAME); ``` It would be far better to have the screen fully off, but at least this solution works although it would be even better if I could limit using a `SCREEN_DIM_WAKE_LOCK` to only those devices/OSes that require it.