qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
73,286,085
I want to create a simple plotly chart from a .csv file that I fetched from an API. I import the library, pass the dataframe, and get the error: ```none TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class ``` code: ``` import plotly.express as px df=pd.read_csv('file.csv') ``` What might be the problem, and what does this error mean? Full error traceback: ```none TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_9952/1054373791.py in <module> 1 from dash import Dash, dcc, html, Input, Output ----> 2 import plotly.express as px 3 import pandas as pd ~\anaconda3\lib\site-packages\plotly\express\__init__.py in <module> 13 ) 14 ---> 15 from ._imshow import imshow 16 from ._chart_types import ( # noqa: F401 17 scatter, ~\anaconda3\lib\site-packages\plotly\express\_imshow.py in <module> 9 10 try: ---> 11 import xarray 12 13 xarray_imported = True ~\anaconda3\lib\site-packages\xarray\__init__.py in <module> ----> 1 from . import testing, tutorial 2 from .backends.api import ( 3 load_dataarray, 4 load_dataset, 5 open_dataarray, ~\anaconda3\lib\site-packages\xarray\testing.py in <module> 7 import pandas as pd 8 ----> 9 from xarray.core import duck_array_ops, formatting, utils 10 from xarray.core.dataarray import DataArray 11 from xarray.core.dataset import Dataset ~\anaconda3\lib\site-packages\xarray\core\duck_array_ops.py in <module> 24 from numpy import where as _where 25 ---> 26 from . import dask_array_compat, dask_array_ops, dtypes, npcompat, nputils 27 from .nputils import nanfirst, nanlast 28 from .pycompat import cupy_array_type, dask_array_type, is_duck_dask_array ~\anaconda3\lib\site-packages\xarray\core\npcompat.py in <module> 70 List[Any], 71 # anything with a dtype attribute ---> 72 _SupportsDType[np.dtype], 73 ] 74 except ImportError: ~\anaconda3\lib\typing.py in inner(*args, **kwds) 273 except TypeError: 274 pass # All real errors (not unhashable args) are raised below. --> 275 return func(*args, **kwds) 276 return inner 277 ~\anaconda3\lib\typing.py in __class_getitem__(cls, params) 997 else: 998 # Subscripting a regular Generic subclass. --> 999 _check_generic(cls, params, len(cls.__parameters__)) 1000 return _GenericAlias(cls, params) 1001 ~\anaconda3\lib\typing.py in _check_generic(cls, parameters, elen) 207 """ 208 if not elen: --> 209 raise TypeError(f"{cls} is not a generic class") 210 alen = len(parameters) 211 if alen != elen: TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class ```
2022/08/09
[ "https://Stackoverflow.com/questions/73286085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15299852/" ]
I got the same error, it is dependency issue, plotly.express (5.9.0) is not working with numpy==1.20, if you upgrade numpy==1.21.6 it will solve your error. ``` pip install numpy==1.21.6 ```
41,354,972
my MYSQL table is as below: ``` id record_nr timestamp 1 931 2014-02-15 6:21:00 2 577 2013-05-03 0:19:00 3 323 2012-08-07 11:26:00 ``` in PHP I tried to retrieve a record by comparing time as below: ``` $dateTimeString = "2013-07-28 7:23:34"; $query = "SELECT * FROM mytable "; $query .= "WHERE timestamp <= STR_TO_DATE('".$dateTimeString."', '%H:%i:%s')"; $query .= " ORDER BY timestamp DESC LIMIT 1"; ``` This didn't work. How to retrieve the record #577? Timestamp is not the time the record was created. Rather, it is a date and time associated with that record.
2016/12/28
[ "https://Stackoverflow.com/questions/41354972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2109581/" ]
You are sending an ajax request to update the record. So, you should not try to `render` a view or `redirect` user as the response of this request. Instead, you can send back a JSON object with some properties e.g. "status". Then on client side, you check the returned JSON response and based on "status" parameter ( or any other you chose ), you can either update your data or reload the page using `window.reload` on client side.
27,025,827
In this code with pyshark ``` import pyshark cap = pyshark.FileCapture(filename) i = 0 for idx, packet in enumerate(cap): i += 1 print i print len(cap._packets) ``` `i` and `len(cap._packets)` give two different results. Why is that?
2014/11/19
[ "https://Stackoverflow.com/questions/27025827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/464277/" ]
Don't know if it works in Python 2.7, but in Python 3.4 `len(cap)` returns 0. The FileCapture object is a generator, so what worked for me is `len([packet for packet in cap])`
402,484
i have csv as below ``` col1,col2,col3,col4,col5 1,val1,57,val1,TRUE ,val2,,val2, ,val3,,val3, ,val4,,val4, ,val5,,val5, 2,val1,878,val1,FALSE ,val2,,val2, ,val3,,val3, ,val4,,val4, ,val5,,val5, ``` i need to display the output using awk as below ``` col1,col2,col3,col4,col5 1,val1#val2#val3#val4#val5,57,val1#val2#val3#val4#val5,TRUE 2,val1#val2#val3#val4#val5,878,val1#val2#val3#val4#val5,FALSE ```
2017/11/04
[ "https://unix.stackexchange.com/questions/402484", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/258950/" ]
Keeping it simple, readable and portable (mostly a function of my not having that much `awk` experience, hehe): ``` BEGIN { FS=","; OFS="," } NR < 3 { print # just echo header and separator lines } /^[0-9]/ { if (NR > 3) { # concatenate all parts (note: csv because of OFS not the commas here) print part1,part2,part3 } part1 = $1 OFS $2 part2 = $3 OFS $4 part3 = $5 } /^,/ { part1 = part1 "#" $2 part2 = part2 "#" $4 } END { print part1,part2,part3 } ``` Result: ``` col1,col2,col3,col4,col5 1,val1#val2#val3#val4#val5,57,val1#val2#val3#val4#val5,TRUE 2,val1#val2#val3#val4#val5,878,val1#val2#val3#val4#val5,FALSE ```
31,962
I am using this program. However, I am getting garbage values only. Do revert as to how can I get proper values over my arduino. ``` /*****************************************************************************/ * PrinterCapturePoll.ino * ------------------ * Monitor a parallel port printer output and capture each character. Output the * character on the USB serial port so it can be captured in a terminal program. * * By............: Paul Jewell * Date..........: 29th January 2015 * Version.......: 0.1a *-------------------------------------------------------------------------- - ---- * Wiring Layout * ------------ - * * Parallel Port Output Arduino Input * -------------------- ------------ - * Name Dir. Pin Name Pin * ---- -- - ---- -- - * nSTROBE > 1..........................2 * DATA BYTE > 2 - 9.......................3 - 10 * nACK < 10.........................11 * BUSY < 11.........................12 * OutofPaper < 12................GND * Selected < 13.................5v * GND <> 18 - 25................GND *------------------------------------------------------------------------------ - ******************************************************************************** / int nStrobe = 2; int Data0 = 3; int Data1 = 4; int Data2 = 5; int Data3 = 6; int Data4 = 7; int Data5 = 8; int Data6 = 9; int Data7 = 10; int nAck = 11; int Busy = 12; int led = 13; // use as status led void setup() { // Configure pins pinMode(nStrobe, INPUT_PULLUP); for (int n = Data0; n < (Data7 + 1); n++) pinMode(n, INPUT_PULLUP); pinMode(nAck, OUTPUT); pinMode(Busy, OUTPUT); pinMode(led, OUTPUT); Serial.begin(9600); while (!Serial) { Serial.println("Waiting to Initialise"); } //State = READY; delay(1000); Serial.println("Initialised"); delay(1000); } void loop() { while (digitalRead(nStrobe) == HIGH) { digitalWrite(Busy, LOW); digitalWrite(nAck, HIGH); digitalWrite(led, HIGH); ProcessChar(); } digitalWrite(Busy, HIGH); digitalWrite(led, LOW); digitalWrite(nAck, LOW); delay(5); //milliseconds. Specification minimum = 5 us } void ProcessChar() { byte Char; Char = digitalRead(Data0) + (digitalRead(Data1) << 1) + (digitalRead(Data2) << 2) + (digitalRead(Data3) << 3) + (digitalRead(Data4) << 4) + (digitalRead(Data5) << 5) + (digitalRead(Data6) << 6) + (digitalRead(Data7) << 7); Serial.print(char(Char)); } ```
2016/12/06
[ "https://arduino.stackexchange.com/questions/31962", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/20151/" ]
I think I can see the problem - although I have no way to test it. According to [Wikipedia](https://en.wikipedia.org/wiki/Parallel_port): > > When the data was ready, the host pulled the STROBE pin low, to 0 V. The printer responded by pulling the BUSY line high, printing the character, and then returning BUSY to low again. > > > That's not what you're doing - you are repeatedly reading while the strobe is HIGH. Here's my attempt at your loop() which I hope will at least get you started: ``` void loop() { // Wait for strobe to go LOW, indicating a character is ready while (digitalRead(nStrobe) == LOW) { delay(1) }; // Strobe is now LOW - a character is ready. // Pull BUSY to high // (NB: I don't know what you're doing with nAct and led) digitalWrite(Busy, HIGH); digitalWrite(led, LOW); digitalWrite(nAck,LOW); // Print the character ProcessChar(); // Return BUSY to low again // (NB: I don't know what you're doing with nAct and led) digitalWrite(Busy, LOW); digitalWrite(led, HIGH); digitalWrite(nAck,HIGH); // Wait for the strobe to go HIGH again while (digitalRead(nStrobe) == LOW) { delay(1) }; } ``` You should also probably consider setting the initial values of your outputs (BUSY and nAck) rather than relying on them defaulting to some particular state. I don't know what (n)Ack is for in this case -- Wikipedia doesn't mention it.
20,730,665
I want use a common WebDriver instance across all my TestNG tests by extending my test class to use a base class as shown below but it doesn't seem to work : ``` public class Browser { private static WebDriver driver = new FirefoxDriver(); public static WebDriver getDriver() { return driver; } public static void open(String url) { driver.get(url); } public static void close() { driver.close(); } } ``` I want to use the WebDriver in my test class as shown below, but I get the error message : **The method getDriver() is undefined for the type GoogleTest**: ``` public class GoogleTest extends Browser { @Test public void GoogleSearch() { WebElement query = getDriver().findElement(By.name("q")); // Enter something to search for query.sendKeys("Selenium"); // Now submit the form query.submit(); // Google's search is rendered dynamically with JavaScript. // Wait for the page to load, timeout after 5 seconds WebDriverWait wait = new WebDriverWait(getDriver(), 30); // wait.Until((d) => { return d.Title.StartsWith("selenium"); }); //Check that the Title is what we are expecting assertEquals("selenium - Google Search", getDriver().getTitle().toString()); } } ```
2013/12/22
[ "https://Stackoverflow.com/questions/20730665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2850361/" ]
The problem is that your `getDriver` method is **static**. Solution #1: Make method non-static (this will either need to make the `driver` variable non-static as well, or use `return Browser.getDriver();` ) ``` public WebDriver getDriver() { return driver; } ``` **Or,** call the `getDriver` method by using `Browser.getDriver` ``` WebElement query = Browser.getDriver().findElement(By.name("q")); ```
60,823,571
I have a background image and a box with a title in it. How would I blur part of the image in the box? I tried using web kit filter but it blurred the title [![Example](https://i.stack.imgur.com/yWjPZ.png)](https://i.stack.imgur.com/yWjPZ.png) ``` .title { height: 90px; margin: auto; margin-top: 90px; margin-left: 250px; margin-right: 250px; display: flex; justify-content: center; align-items: center; border-width: 1px; border-style: solid; filter: blur(8px); -webkit-filter: blur(8px); } ``` ``` .bgimage { width: 100%; height: 540px; background-size: 100%; background-repeat: no-repeat; background-image: url("img"); } ``` ``` <div className="bgimage"> <div className="title">Title</div> </div> ```
2020/03/24
[ "https://Stackoverflow.com/questions/60823571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7559119/" ]
You may need **[backdrop-filter](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter)** > > The backdrop-filter CSS property lets you apply graphical effects such as blurring or color shifting to the area behind an element. Because it applies to everything behind the element, to see the effect you must make the element or its background at least partially transparent. > > > ```css backdrop-filter: blur(20px); ``` An amazing online demo: <https://codepen.io/alphardex/pen/pooQMVp> ```css body { display: flex; justify-content: center; align-items: center; height: 100vh; /* background: URL(); */ background-size: cover; background-position: center; } .bgimage { display: flex; justify-content: center; align-items: center; width: 72vw; height: 36vh; /* box-shadow: ; */ backdrop-filter: blur(20px); transition: 0.5s ease; &:hover { /* box-shadow: ; */ } .title { padding-left: 0.375em; font-size: 3.6em; font-family: Lato, sans-serif; font-weight: 200; letter-spacing: 0.75em; color: white; @media (max-width: 640px) { font-size: 2em; } } } ``` [![enter image description here](https://i.stack.imgur.com/rdx6i.jpg)](https://i.stack.imgur.com/rdx6i.jpg)
2,619,042
Here's what i have so far... I have yet to figure out how i'm going to handle the 11 / 1 situation with an ace, and when the player chooses an option for hit/stand, i get segfault. HELP!!! **updated code** ``` #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #define DECKSIZE 52 #define VALUE 9 #define FACE 4 #define HANDSIZE 26 typedef struct { int value; char* suit; char* name; }Card; /*typedef struct { int value; char* suit; char* name; }dealerHand; typedef struct { int value; char* suit; char* name; }playerHand;*/ //trying something different Card cards[DECKSIZE]; /*dealerHand deal[HANDSIZE]; //trying something different playerHand dealt[HANDSIZE];*/ char *faceName[]={"two","three", "four","five","six", "seven","eight","nine", "ten", "jack","queen", "king","ace"}; char *suitName[]={"spades","diamonds","clubs","hearts"}; Card *deal[HANDSIZE]; Card *dealt[HANDSIZE]; void printDeck(){ int i; for(i=0;i<DECKSIZE;i++){ printf("%s of %s value = %d\n ",cards[i].name,cards[i].suit,cards[i].value); if((i+1)%13==0 && i!=0) printf("-------------------\n\n"); } } void shuffleDeck(){ srand(time(NULL)); int this; int that; Card temp; int c; for(c=0;c<10000;c++){ //c is the index for number of individual card shuffles should be set to c<10000 or more this=rand()%DECKSIZE; that=rand()%DECKSIZE; temp=cards[this]; cards[this]=cards[that]; cards[that]=temp; } } /*void hitStand(i,y){ // I dumped this because of a segfault i couldn't figure out. int k; printf(" Press 1 to HIT or press 2 to STAND:"); scanf("%d",k); if(k=1){ dealt[y].suit=cards[i].suit; dealt[y].name=cards[i].name; dealt[y].value=cards[i].value; y++; i++; } } */ int main(){ int suitCount=0; int faceCount=0; int i; int x; int y; int d; int p; int k; for(i=0;i<DECKSIZE;i++){ //this for statement builds the deck if(faceCount<9){ cards[i].value=faceCount+2; }else{ //assigns face cards as value 10 cards[i].value=10; } cards[i].suit=suitName[suitCount]; cards[i].name=faceName[faceCount++]; if(faceCount==13){ //this if loop increments suit count once cards[i].value=11; //all faces have been assigned, and also suitCount++; //assigns the ace as 11 faceCount=0; } //end building deck } /*printDeck(); //prints the deck in order shuffleDeck(); //shuffles the deck printDeck(); //prints the deck as shuffled This was used in testing, commented out to keep the deck hidden!*/ shuffleDeck(); x=0; y=0; for(i=0;i<4;i++){ //this for loop deals the first 4 cards, dealt[y]=&cards[i]; //first card to player, second to dealer, as per standard dealing practice. i++; y++; deal[x]=&cards[i]; x++; } printf(" Dealer's hand is: %s of %s and XXXX of XXXX. (Second card is hidden!)\n",deal[0]->name,deal[0]->suit,deal[1]->name,deal[1]->suit); printf(" Player's hand is: %s of %s and %s of %s.\n",dealt[0]->name,dealt[0]->suit,dealt[1]->name,dealt[1]->suit); printf(" the current value of the index i=%d\n",i); //this line gave me the value of i for testing d=deal[0]->value+deal[1]->value; p=dealt[0]->value+dealt[1]->value; if(d==21){ printf(" The Dealer has Blackjack! House win!\n"); }else{ if(d>21){ printf(" The dealer is Bust! You win!\n"); }else{ if(d>17){ printf(" Press 1 to HIT or 2 to STAND: "); scanf("%d",&k); if(k==1){ dealt[y]=&cards[i]; y++; i++; } }else{ if(d<17){ printf(" Dealer Hits!"); deal[x]=&cards[i]; x++; i++; } } } } return 0; } ```
2010/04/11
[ "https://Stackoverflow.com/questions/2619042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314116/" ]
To fix your segfault, use `scanf("%d",&k);` instead of `scanf("%d",k);` (note the ampersand that I added. You need that because `scanf`'s second argument is a pointer to the location where it should store what gets read in. `k` by itself isn't a pointer--adding the `&` gets a pointer to `k`. For handling aces, under what conditions do the aces go from valued at 11 to valued at 1? What line(s) in your code do you expect to have to touch to enable that? I can think of a way to implement it involving a variable that keeps track of how many aces went into computing a player's total score, or another way would be to recompute a score just in time to use it.
630,249
I am working on a multi-threaded app. I'm processing reports and keeping track of the number of reports in the current batch as well as the total number of reports processed. Whenever I update the counters, I also need to update a label on the GUI which, since the process is on a separate thread, requires a call to a delegate. Which one of these is the better way to go? ``` private void UpdateTotalCount(int newValue) { totalCount = newValue; if (labelTotalCount.InvokeRequired) BeginInvoke((MethodInvoker) delegate() { labelTotalCount.Text = "Total reports:" + totalcount; }); else labelTotalCount.Text = "Total reports:" + totalcount; } ``` or ``` private int totalCount; public int TotalCount { get { return totalCount; } set { totalCount = value; if (labelTotalCount.InvokeRequired) BeginInvoke((MethodInvoker) delegate() { labelTotalCount.Text = "Total reports:" + totalcount; }); else labelTotalCount.Text = "Total reports:" + totalcount; } } ``` **Edit:** Ok, third option. ``` private void UpdateTotalCountLabel() { if (labelTotalCount.InvokeRequired) BeginInvoke((MethodInvoker) delegate() { labelTotalCount.Text = "Total reports:" + totalcount; }); else labelTotalCount.Text = "Total reports:" + totalcount; } // code elsewhere would look like this totalCount++; UpdateTotalCountLabel(); //or totalCount+= curBatch.Length; UpdateTotalCountLabel(); ```
2009/03/10
[ "https://Stackoverflow.com/questions/630249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19038/" ]
I think using the public accessors is better since it allows more maintanable code in case later on you need to change the way the total value is calculated. In that way, the users of the TotalValue property will not need to worry about your changes since these changes will not affect their code in any way.
17,610,594
I'm developing an application to send SMS via AT commands, that part is OK. I have a list of contacts and I want to send a file (which changes in time) to all of my contacts. In order to do that I need to repeat the sending part every 30 minutes. I found this code using a timer, but I'm not sure if it's useful in my case and how I can use it. Please help, any idea is appreciated. ``` private void btntime_Click(object sender, EventArgs e) { s_myTimer.Tick += new EventHandler(s_myTimer_Tick); int tps = Convert.ToInt32(textBoxsettime.Text); // 1 seconde = 1000 millisecondes try { s_myTimer.Interval = tps * 60000; } catch { MessageBox.Show("Error"); } s_myTimer.Start(); MessageBox.Show("Timer activated."); } // Méthode appelée pour l'évènement static void s_myTimer_Tick(object sender, EventArgs e) { s_myCounter++; MessageBox.Show("ns_myCounter is " + s_myCounter + "."); if (s_myCounter >= 1) { // If the timer is on... if (s_myTimer.Enabled) { s_myTimer.Stop(); MessageBox.Show("Timer stopped."); } else { MessageBox.Show("Timer already stopped."); } } } ```
2013/07/12
[ "https://Stackoverflow.com/questions/17610594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2335219/" ]
Whether this code is useful or not depends entirely what you want to do with it. It shows a very basic usage of the Timer-class in .NET, which is indeed one of the timers you can use if you want to implement a repeating action. [I suggest you look at the MSDN-guidance on all timers in .NET](http://msdn.microsoft.com/en-us/magazine/cc164015.aspx) and pick the one that best fits your requirements.
4,607,039
We have around 3 people working on a project in TFS. Our company set our TFS project to single checkout. But Sometimes, we have 1 person checking out certain files, solution files, etc. Is it bad practice to have multiple checkout enabled and let the merging or diff tool handle the problem if we both accidentally overwrote someone else code? I've read this somewhere that its all about good communication and allowing the diff tool to handle these problems but our employers suggest using single checkout. 2 questions. Should we enable multiple checkout? If so, how do we enable multiple checkout?
2011/01/05
[ "https://Stackoverflow.com/questions/4607039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400861/" ]
It is true that having multiple checkout disabled is simpler to work with, and it safeguards you against having to do manual merges and perhaps overwrite work. However, it can also hinder productivity and development, especially on medium to large teams. If John can't get his feature done before Susan checks her version of a file in; some time is going to be wasted. In my experience, multiple checkout with TFS works really well, and you should not be afraid to use it. The built-in merge tool sucks, but you can get a nice one such as [DiffMerge](http://www.sourcegear.com/diffmerge/) for free. If you make sure to communicate what each other is working on, and each of you make sure to Get Latest after each feature (or every morning), to avoid the possibility of working on stale versions, you should be fine.
9,183
I managed to get all traffic routed through tor using the following this [documentation](https://trac.torproject.org/projects/tor/wiki/doc/TransparentProxy). I want now to know if it's possible to turn this on and off on command. I've tried reversing it with the following to no avail: ``` #!/bin/sh iptables -P INPUT ACCEPT iptables -P OUTPUT ACCEPT iptables -P FORWARD ACCEPT iptables -F INPUT iptables -F OUTPUT iptables -F FORWARD ``` Does anyone know how this would be possible?
2015/12/07
[ "https://tor.stackexchange.com/questions/9183", "https://tor.stackexchange.com", "https://tor.stackexchange.com/users/10009/" ]
1. You need to flush the NAT table too, as dingensundso suggests: `iptables -t nat -F` 2. You probably don't want to just `ACCEPT` all `INPUT`, `OUTPUT`, and `FORWARD` traffic, this would disable packet-filtering (your "firewall") entirely. 3. Just switching Tor on and off is a terrible plan for anonymity. Your applications will keep state between your usage inside and outside of Tor and this state will potentially link your Tor usage to your non-Tor usage, deanonymizing you.
12,234,050
For the last 3 weeks we have been testing Nginx as load balance. Currently, we're not succeeding to handle more than 1000 req/sec and 18K active connections. When we get to the above numbers, Nginx starts to hang, and returns timeout codes. The only way to get a response is to reduce the number of connection dramatically. I must note that my servers can and does handle this amount of traffic on a daily basis and we currently use a simple round rubin DNS balancing. We are using a dedicated server with the following HW: * INTEL XEON E5620 CPU * 16GB RAM * 2T SATA HDD * 1Gb/s connection * OS: CentOS 5.8 We need to load balance 7 back servers running Tomcat6 and handling more than 2000 req/sec on peek times, handling HTTP and HTTPS requests. While running Nginx's cpu consumption is around 15% and used RAM is about 100MB. My questions are: 1. Has any one tried to load balance this kind of traffic using nginx? 2. Do you think nginx can handle such traffic? 3. Do you have any idea what can cause the hanging? 4. Am I missing something on my configurations? Below are my configuration files: nginx.conf: ----------- ```sh user nginx; worker_processes 10; worker_rlimit_nofile 200000; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 10000; use epoll; multi_accept on; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; #access_log /var/log/nginx/access.log main; access_log off; sendfile on; tcp_nopush on; keepalive_timeout 65; reset_timedout_connection on; gzip on; gzip_comp_level 1; include /etc/nginx/conf.d/*.conf; } ``` servers.conf: ------------- ```sh #Set the upstream (servers to load balance) #HTTP stream upstream adsbar { least_conn; server xx.xx.xx.34 max_fails=2 fail_timeout=15s; server xx.xx.xx.36 max_fails=2 fail_timeout=15s; server xx.xx.xx.37 max_fails=2 fail_timeout=15s; server xx.xx.xx.39 max_fails=2 fail_timeout=15s; server xx.xx.xx.40 max_fails=2 fail_timeout=15s; server xx.xx.xx.42 max_fails=2 fail_timeout=15s; server xx.xx.xx.43 max_fails=2 fail_timeout=15s; } #HTTPS stream upstream adsbar-ssl { least_conn; server xx.xx.xx.34:443 max_fails=2 fail_timeout=15s; server xx.xx.xx.36:443 max_fails=2 fail_timeout=15s; server xx.xx.xx.37:443 max_fails=2 fail_timeout=15s; server xx.xx.xx.39:443 max_fails=2 fail_timeout=15s; server xx.xx.xx.40:443 max_fails=2 fail_timeout=15s; server xx.xx.xx.42:443 max_fails=2 fail_timeout=15s; server xx.xx.xx.43:443 max_fails=2 fail_timeout=15s; } #HTTP server { listen xxx.xxx.xxx.xxx:8080; server_name www.mycompany.com; location / { proxy_set_header Host $host; # So the original HTTP Host header is preserved proxy_set_header X-Real-IP $remote_addr; # The IP address of the client (which might be a proxy itself) proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://adsbar; } } #HTTPS server { listen xxx.xxx.xxx.xxx:8443; server_name www.mycompany.com; ssl on; ssl_certificate /etc/pki/tls/certs/mycompany.crt; # Path to an SSL certificate; ssl_certificate_key /etc/pki/tls/private/mycompany.key; # Path to the key for the SSL certificate; location / { proxy_set_header Host $host; # So the original HTTP Host header is preserved proxy_set_header X-Real-IP $remote_addr; # The IP address of the client (which might be a proxy itself) proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass https://adsbar-ssl; } } server { listen xxx.xxx.xxx.xxx:61709; location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } } ``` sysctl.conf: ------------ ```sh # Kernel sysctl configuration file for Red Hat Linux # # For binary values, 0 is disabled, 1 is enabled. See sysctl(8) and # sysctl.conf(5) for more details. # Controls IP packet forwarding net.ipv4.ip_forward = 0 # Controls source route verification net.ipv4.conf.default.rp_filter = 1 # Do not accept source routing net.ipv4.conf.default.accept_source_route = 0 # Controls the System Request debugging functionality of the kernel kernel.sysrq = 1 # Controls whether core dumps will append the PID to the core filename # Useful for debugging multi-threaded applications kernel.core_uses_pid = 1 # Controls the use of TCP syncookies net.ipv4.tcp_syncookies = 1 # Controls the maximum size of a message, in bytes kernel.msgmnb = 65536 # Controls the default maxmimum size of a mesage queue kernel.msgmax = 65536 # Controls the maximum shared segment size, in bytes kernel.shmmax = 68719476736 # Controls the maximum number of shared memory segments, in pages kernel.shmall = 4294967296 fs.file-max = 120000 net.ipv4.ip_conntrack_max = 131072 net.ipv4.tcp_max_syn_backlog = 8196 net.ipv4.tcp_fin_timeout = 25 net.ipv4.tcp_keepalive_time = 3600 net.ipv4.ip_local_port_range = 1024 65000 net.ipv4.tcp_rmem = 4096 25165824 25165824 net.core.rmem_max = 25165824 net.core.rmem_default = 25165824 net.ipv4.tcp_wmem = 4096 65536 25165824 net.core.wmem_max = 25165824 net.core.wmem_default = 65536 net.core.optmem_max = 25165824 net.core.netdev_max_backlog = 2500 net.ipv4.tcp_tw_recycle = 1 net.ipv4.tcp_tw_reuse = 1 ``` Any help, guidance, ideas will be highly appreciated.
2012/09/02
[ "https://Stackoverflow.com/questions/12234050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1520931/" ]
Here are some good references: <http://dak1n1.com/blog/12-nginx-performance-tuning> Server fault: <https://serverfault.com/questions/221292/tips-for-maximizing-nginx-requests-sec> A very well documented config from the dak1n1 link: ``` # This number should be, at maximum, the number of CPU cores on your system. # (since nginx doesn't benefit from more than one worker per CPU.) worker_processes 24; # Number of file descriptors used for Nginx. This is set in the OS with 'ulimit -n 200000' # or using /etc/security/limits.conf worker_rlimit_nofile 200000; # only log critical errors error_log /var/log/nginx/error.log crit # Determines how many clients will be served by each worker process. # (Max clients = worker_connections * worker_processes) # "Max clients" is also limited by the number of socket connections available on the system (~64k) worker_connections 4000; # essential for linux, optmized to serve many clients with each thread use epoll; # Accept as many connections as possible, after nginx gets notification about a new connection. # May flood worker_connections, if that option is set too low. multi_accept on; # Caches information about open FDs, freqently accessed files. # Changing this setting, in my environment, brought performance up from 560k req/sec, to 904k req/sec. # I recommend using some varient of these options, though not the specific values listed below. open_file_cache max=200000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on; # Buffer log writes to speed up IO, or disable them altogether #access_log /var/log/nginx/access.log main buffer=16k; access_log off; # Sendfile copies data between one FD and other from within the kernel. # More efficient than read() + write(), since the requires transferring data to and from the user space. sendfile on; # Tcp_nopush causes nginx to attempt to send its HTTP response head in one packet, # instead of using partial frames. This is useful for prepending headers before calling sendfile, # or for throughput optimization. tcp_nopush on; # don't buffer data-sends (disable Nagle algorithm). Good for sending frequent small bursts of data in real time. tcp_nodelay on; # Timeout for keep-alive connections. Server will close connections after this time. keepalive_timeout 30; # Number of requests a client can make over the keep-alive connection. This is set high for testing. keepalive_requests 100000; # allow the server to close the connection after a client stops responding. Frees up socket-associated memory. reset_timedout_connection on; # send the client a "request timed out" if the body is not loaded by this time. Default 60. client_body_timeout 10; # If the client stops reading data, free up the stale client connection after this much time. Default 60. send_timeout 2; # Compression. Reduces the amount of data that needs to be transferred over the network gzip on; gzip_min_length 10240; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml; gzip_disable "MSIE [1-6]\."; ``` Also more info on linux system tuning for sysctl.conf: ``` # Increase system IP port limits to allow for more connections net.ipv4.ip_local_port_range = 2000 65000 net.ipv4.tcp_window_scaling = 1 # number of packets to keep in backlog before the kernel starts dropping them net.ipv4.tcp_max_syn_backlog = 3240000 # increase socket listen backlog net.core.somaxconn = 3240000 net.ipv4.tcp_max_tw_buckets = 1440000 # Increase TCP buffer sizes net.core.rmem_default = 8388608 net.core.rmem_max = 16777216 net.core.wmem_max = 16777216 net.ipv4.tcp_rmem = 4096 87380 16777216 net.ipv4.tcp_wmem = 4096 65536 16777216 net.ipv4.tcp_congestion_control = cubic ```
10,438,034
So, I'm writing a menu and I want it to stay a certain color based upon it being on that page. I've added "class = 'active'" onto the page, and I've tried adding it to CSS, but it's not working. Any ideas? PHP code: ``` <?php $currentPage = basename($_SERVER['REQUEST_URI']); print "<div id = 'submenu-container'>"; print "<div id = 'submenu'>"; print "<ul class = 'about'>"; print " <li><a href='about.php#about_intro.php'if($currentPage=='about.php#about_intro.php' || $currentPage=='about.php') echo 'class='active''>About</a></li>"; print " <li><a href='about.php#about_team.php'if($currentPage=='about.php#about_team.php') echo 'class='active''>Team</a></li>"; print " <li><a href='about.php#about_services.php' if($currentPage=='about.php#about_services.php') echo 'class='active'>Services</a></li>"; print " </ul>"; print "</div>"; print"</div>"; ?> ``` CSS: ``` #submenu ul li a .active { background:#FFF; } ```
2012/05/03
[ "https://Stackoverflow.com/questions/10438034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1340238/" ]
I think instead of ``` $memberDisplayList = '<a href= (...etc) ``` you meant to type ``` $memberDisplayList .= '<a href= (...etc) ``` which would append the new links to your string. Also you don't seem to be echoing your `$user_pic` and `$memberDisplayList` strings anywhere.
13,740,912
i have simple chrome extension that opens JQuery dialog box on each tab i open , the problem is when web page has iframe in it , the dialog box opens as many iframes are in the page . i want to avoid this , all i need it open only and only 1 instance of the Dialog box for each page . how can i avoid the iframes in the page ? this is my content script : ``` var layerNode= document.createElement('div'); layerNode.setAttribute('id','dialog'); layerNode.setAttribute('title','Basic dialog'); var pNode= document.createElement('p'); console.log("msg var: "+massage); pNode.innerHTML = massage; layerNode.appendChild(pNode); document.body.appendChild(layerNode); jQuery("#dialog").dialog({ autoOpen: true, draggable: true, resizable: true, height: 'auto', width: 500, zIndex:3999, modal: false, open: function(event, ui) { $(event.target).parent().css('position','fixed'); $(event.target).parent().css('top', '5px'); $(event.target).parent().css('left', '10px'); } }); ```
2012/12/06
[ "https://Stackoverflow.com/questions/13740912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/63898/" ]
How about wrapping all this with ``` if(window==window.top) { // we're not in an iframe // your code goes here } ```
101,759
I was wondering if there are any ledgers to make such entries. I trade regularly and I would like to make a good record of it.
2018/11/03
[ "https://money.stackexchange.com/questions/101759", "https://money.stackexchange.com", "https://money.stackexchange.com/users/78593/" ]
Have a look at the Asset functionality of common accounting packages. It allows you to record prices and quantities of 'things' at purchase and sale. For shares, each stock code can be considered a separate 'thing' with buy and sell prices and quantities held in 'inventory'. Each accounting package has its own processes and it takes awhile to become familiar with them. Here are some steps to get you started with gnucash, which is "[personal and small-business financial-accounting software, freely licensed under the GNU GPL](https://www.gnucash.org/)". (Disclaimer: I've starting using the software fairly recently, but I'm not otherwise knowingly affiliated with gnucash.) 1. Download and install [gnucash](https://www.gnucash.org/docs/v3/C/gnucash-guide/invest-setup1.html). 2. Open gnucash and Select menu item File -> New File. If a dialog pops up asking you to save changes to the (default) file, select "Continue Without Saving". This brings up the New Account Hierarchy Setup dialog. 3. Fill in whatever you like until you reach "Choose accounts to create". Here, select "Investment Accounts" for some defaults to start you off. Carry on with the rest of the dialog. 4. You'll be asked to save the file. Pick a filename you like, such as "Shares 2018". Pick a location (directory or folder), but be aware that gnucash will save lots of temporary and backup files in the same location. The filename you pick will be the main file, and once you quit gnucash, the rest can usually be safely deleted. However, you might want to keep them as backups. Make sure you click "Save" often (see the menu ribbon below the "File" menu) to ensure that your main gnucash file is up to date. 5. After saving, you'll see the chart of accounts. Here's a [link](https://www.gnucash.org/docs/v3/C/gnucash-guide/chapter_invest.html) to the gnucash manual for the chapter called "Investments". Follow [the instructions](https://www.gnucash.org/docs/v3/C/gnucash-guide/invest-setup1.html) to set up your investment portfolio, then use the manual for further instructions about buying and selling shares, recording dividends, and so on. Have fun!
31,173,307
What are the differences between this: ``` if(a && b) { //code } ``` and this: ``` if(a) { if(b) { //code } } ``` From what I know `b` will only get evaluated in the first code block if `a` is true, and the second code block would be the same thing. Are there any benefits of using one over the other? Code execution time? memory? etc.
2015/07/01
[ "https://Stackoverflow.com/questions/31173307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4714970/" ]
They get compiled to the same bytecode. No performance difference. Readability is the only difference. As a huge generalization, short-circuiting looks better but nesting is slightly clearer. It really boils down to the specific use case. I'd typically short-circuit. --- I tried this out. Here's the code: ``` public class Test { public static void main(String[] args) { boolean a = 1>0; boolean b = 0>1; if (a && b) System.out.println(5); if (a) if (b) System.out.println(5); } } ``` This compiles to: ``` 0: iconst_1 1: istore_1 2: iconst_0 3: istore_2 4: iload_1 5: ifeq 19 8: iload_2 9: ifeq 19 12: getstatic #2 15: iconst_5 16: invokevirtual #3 19: iload_1 20: ifeq 34 23: iload_2 24: ifeq 34 27: getstatic #2 30: iconst_5 31: invokevirtual #3 34: return ``` Note how this block repeats twice: ``` 4: iload_1 5: ifeq 19 8: iload_2 9: ifeq 19 12: getstatic #2 15: iconst_5 16: invokevirtual #3 ``` Same bytecode both times.
403,709
I have a map $f(t,g,h)$ where $f:[0,1]\times C^1 \times C^1 \to \mathbb{R}.$ I want to define $$F(t,g,h) = \frac{d}{dt}f(t,g,h)$$ where $g$ and $h$ have no $t$-dependence in them. So $g(x) = t^2x$ would not be admissible if you want to calculate what $F$ is. How do I write this properly? Is it correct to write instead > > Define $F$ by $F(t,\cdot,\cdot) = \frac{d}{dt}f(t,\cdot,\cdot)$. > > > But there is some ambiguity in the arguments. What is the best way to write it?
2013/05/27
[ "https://math.stackexchange.com/questions/403709", "https://math.stackexchange.com", "https://math.stackexchange.com/users/61615/" ]
Without words... Well, nearly without words... ![enter image description here](https://i.stack.imgur.com/la68x.png)
65,618,221
Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java. Isn't different compilers and JVM doing same thing and achieving platform independence.
2021/01/07
[ "https://Stackoverflow.com/questions/65618221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11815436/" ]
> > Isn't different compilers and JVM doing same thing and achieving platform independence. > > > Not really. Your Java program is running *within* the JVM, which acts as a translation layer between the Java byte code and the native machine code. It *hides* the platform-specific details from the Java application code. This is not the case with C. C code (typically) runs natively, so there is no translation layer isolating it from platform-specific details. Your C code can be directly affected by platform-specific differences (word sizes, type representations, byte order, etc.). A *strictly conforming* C program, which uses nothing outside of the standard library and makes no assumptions about type sizes or representation beyond the minimums guaranteed by the language standard, should exhibit the same behavior on any platform for which it is compiled. All you need to do is recompile it for the target platform. The problem is that most useful real-world C and C++ code *isn't* strictly conforming; to do almost anything interesting you have to rely on third-party and system-specific libraries and utilities, and as soon as you do you lose that platform independence. I *could* write a command-line tool manipulates files in the local file system that would run on Windows and MacOS and Linux and VMS and MPE; all I would need to do is recompile it for the different targets. However, if I wanted to write something GUI-driven, or something that communicated over a network, or something that had to navigate the file system, or anything like that, then I'm reliant on system-specific tools and I *can't* just rebuild the code on different platforms.
3,816,331
I have 3 ways I want to filter: 1. by name 2. by list 3. and show all I'm using ASP.NET 3.5 and SQL Server 2008. Using ADO.NET and stored procs. I'm passing my list as a table valued parameter (but I'm testing with a table variable) and the name as a nvarchar. I have "show all" as ISNULL(@var, column) = column. Obviously the way I'm querying this is not taking advantage of short circuiting or my understanding of how WHERE clauses work is lacking. What's happening is if I make @var = 'some string' and insert a null to the table variable, then it filters correctly. If I make @var = null and insert 'some string' to the table variable, then I get every record, where I should be getting 'some string'. The code: ``` declare @resp1 nvarchar(32) set @resp1 = null declare @usersTable table (responsible nvarchar(32)) --insert into @usersTable (responsible) values (null) insert into @usersTable (responsible) values ('ssimpson') insert into @usersTable (responsible) values ('kwilcox') select uT.responsible, jsq.jobnumber, jsq.qid, aq.question, aq.section, aq.seq, answers.* from answers inner join jobno_specific_questions as jsq on answers.jqid = jsq.jqid inner join apqp_questions as aq on jsq.qid = aq.qid left join @usersTable as uT on uT.responsible = answers.responsible where answers.taskAction = 1 and (uT.responsible is not null or ISNULL(@resp1, Answers.responsible) = Answers.responsible) order by aq.section, jsq.jobnumber, answers.priority, aq.seq ``` This is what I've come up with. It's ugly though.... ``` declare @resp1 nvarchar(32) set @resp1 = 'rrox' declare @filterPick int declare @usersTable table (responsible nvarchar(32)) insert into @usersTable (responsible) values (null) --insert into @usersTable (responsible) values ('ssimpson') --insert into @usersTable (responsible) values ('kwilcox') if @resp1 is null begin set @filterPick = 2 end else begin set @filterPick = 1 end select uT.responsible, jsq.jobnumber, jsq.qid, aq.question, aq.section, aq.seq, answers.* from answers inner join jobno_specific_questions as jsq on answers.jqid = jsq.jqid inner join apqp_questions as aq on jsq.qid = aq.qid left join @usersTable as uT on uT.responsible = answers.responsible where answers.taskAction = 1 and (case when uT.responsible is not null then 2 when ISNULL(@resp1, Answers.responsible) = Answers.responsible then 1 end = @filterPick ) order by aq.section, jsq.jobnumber, answers.priority, aq.seq ``` Ok. I think I've got it. I've removed @resp1 because it wasn't necessary and am just using the table valued parameter @usersTable (but here I'm using a table variable for testing). I've added a flag @filterPick so I can show only values in @usersTable or every record where answers.taskAction = 1. The code: ``` declare @filterPick bit declare @usersTable table (responsible nvarchar(32)) insert into @usersTable (responsible) values (null) --insert into @usersTable (responsible) values ('ssimpson') --insert into @usersTable (responsible) values ('kwilcox') if exists (select * from @usersTable where responsible is not null) begin set @filterPick = 1 end else begin set @filterPick = 0 end select * from answers inner join jobno_specific_questions as jsq on answers.jqid = jsq.jqid inner join apqp_questions as aq on jsq.qid = aq.qid left join @usersTable as uT on answers.responsible = uT.responsible where answers.taskAction = 1 and (uT.responsible is not null or (isnull(uT.responsible, answers.responsible) = answers.responsible and @filterPick = 0)) order by aq.section, jsq.jobnumber, answers.priority, aq.seq ```
2010/09/28
[ "https://Stackoverflow.com/questions/3816331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428757/" ]
I'm a bit confused by your question but I'll give it a shot. First off i suspect your issues with the incorrect records being returned have to do with your comparison of a null value. To demonstrate what I am talking about query any table you want and add this to the end: ``` WHERE null = null ``` no records will be returned. In your code I would change: ``` where answers.taskAction = 1 and (uT.responsible is not null or ISNULL(@resp1, Answers.responsible) = Answers.responsible) ``` to ``` where answers.taskAction = 1 and (uT.responsible is not null or @resp1 is null) ``` And see if that returns the desired result.
49,815,229
i've been trying to authenticate user input using the mysqli\_fetch\_assoc function, though it works i.e redirects user to the home page when the username and password is correct, but it doesn't display the error message(s) when the inputs are incorrect however it displays the username error message when the username is incorrect case wise. pls how do i fix it? here is the code ``` $username = $password = ""; $username_err = $password_err = ""; //testing input values if ($_SERVER["REQUEST_METHOD"] == "POST") { //processing username input if (empty($_POST['username'])) { $username_err = " *username is required!"; }else{ //if field is not empty $username = test_input($_POST['username']); } //processing password input if (empty($_POST['password'])) { $password_err = " *password is required!"; }elseif (strlen($_POST['password']) < 8) { $password_err = " *password must not be less than 8 characters!"; }else{ //if field is not empty $password = md5($_POST['password']); } //comparing user input with stored details $sql = "SELECT * FROM users_log WHERE Username = '$username' AND Password = '$password'"; $result = mysqli_query($dbconn, $sql); $row = mysqli_fetch_assoc($result); if ($row) { if ($row['Username'] != $username ) { $username_err = "Incorrect Username"; }elseif ($row['Password'] != $password ) { $password_err = "Incorrect Password"; }else{ header("location:../home/homeIndex.php"); } } } function test_input($input){ $input = trim($input); $input = stripslashes($input); $input = htmlspecialchars($input); return $input; } ``` the html output ``` <span><?php echo "$username_err<br>"; ?></span> <input type="text" name="username" class="form-control" placeholder="Username" size="30"> </div><br> <?php echo "$password_err<br>"; ?></span> <input type="password" name="password" class="form-control" placeholder="Password" size="30" > </div><br> ```
2018/04/13
[ "https://Stackoverflow.com/questions/49815229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9602904/" ]
``` if ($row) { if ($row['Username'] != $username ) { $username_err = "Incorrect Username"; }elseif ($row['Password'] != $password ) { $password_err = "Incorrect Password"; }else{ header("location:../home/homeIndex.php"); } } ``` data inside the $row will execute when condition is true. So use if condition like this, ``` if ($row) { header("location:../home/homeIndex.php"); }else{ $username_err = "Incorrect Username Or Password"; } ``` Hope this will resolve your issue
68,146,659
Is it possible to achive authentication with email and password in flutter without using firebase? I have searched around Stackoverflow and internet in general and found nothing about this. I am creating a simple authentication class this is what I have done at the moment: ``` class User { bool isAuthenticated = false; late String userid; late String username; late String email; late DateTime expireDate; // this variable is used to make the user re-authenticate when today is expireDate User(bool isAuthenticated, String userid, String username, String email) { this.isAuthenticated = isAuthenticated; this.userid = userid; this.username = username; this.email = email; this.expireDate = new DateTime.now().add(new Duration(days: 30)); } } class Authentication { Future<User> signin(String email, String password) {} void signup(String username, String email, String password) {} } ``` EDIT #1: I know how to setup a cookie/token based authentication server I have my own repos on that topic: [cookie authentication](https://github.com/datteroandrea/cookieauth), [token authentication](https://github.com/datteroandrea/jwtauth) but I don't know how to handle the tokens/cookies in flutter.
2021/06/26
[ "https://Stackoverflow.com/questions/68146659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10457357/" ]
This answer is based of #edit1. Since you mentioned that you already know how to set up tokens on the server side you're half way done. Here's a few assumptions I'm making, you already know js/php and worked with JSON output, The database already has a column and table that keeps track of sessions and user\_id. Since you know how Cookies are built this should be relatively easy cause i built it around similar architecture. We has to use the local memory that app's provide access to. There are two packages in flutter that allow u to do this, you can use either: * shared\_preferences [package link](https://pub.dev/packages/shared_preferences) * flutter\_secure\_storage [package link](https://pub.dev/packages/flutter_secure_storage) The main difference is if you want to store 'tokens' or data you want secure you would obviously use flutter\_secure\_storage. I'm going to use this for code example. And yes the data is saved even after the app is closed. Setting up Tokens(flutter): --------------------------- 1. Setting up User Class When using firebase we generally take for granted the user class that comes with flutter\_auth but that is basically what we have to build. A user class with all the data u want to store and then a function called authenticate. ``` class AppUser{ final _storage = new FlutterSecureStorage(); //below class is mentioned in the next part AuthApi api = new AuthApi(); //constructor AppUser(){ //ur data; }; Future<bool> authenticate(email, password) async { //this is the api mentioned in next part http.Response res = await api.login(email, password); Map<String, dynamic> jsonRes = jsonDecode(res.body); if (jsonRes["error"]) { return false; } _setToken(jsonRes["token"]); _setUID(jsonRes["user-id"].toString()); _setAuthState(true); return true; } Future<void> _setToken(String val) async { //how to write to safe_storage await _storage.write(key: 'token', value: val); } Future<void> _setUID(String val) async { await _storage.write(key: 'user_id', value: val); } //you can stream this or use it in a wrapper to help navigate Future<bool> isAuthenticated() async { bool authState = await _getAuthState(); return authState; } Future<void> _getAuthState() async { //how to read from safe_storage u can use the same to read token later just replace 'state' with 'token' String myState = (await _storage.read(key: 'state')).toString(); //returns boolean true or false return myState.toLowerCase() == 'true'; } Future<void> _setAuthState(bool liveAuthState) async { await _storage.write(key: 'state', value: liveAuthState.toString()); } } ``` and assuming ur going to authenticate on a button press so it would look like ``` onPressed(){ AuthUser user = new AuthUser(); if(user.authenticate(email, password)){ //if logged in. Prolly call Navigator. }else{ //handle error } } ``` 2. Setting up api calls Oka so this is calling a Node express API, and the json output looks like ``` //if successful {"status":200, "error": false, "token": "sha256token", "user-id": "uid"} ``` we need to create a class that will give us an output for making this call hence the AuthApi class ``` class AuthApi { //this is the login api and it returns the above JSON Future<http.Response> login(String email, String password){ return http.post( Uri.parse(ip + '/api/auth/login'), headers: <String, String>{ 'Content-Type': 'application/json', }, body: jsonEncode(<String, String>{ "email": email, "password": password, }), ); } } ``` Thank you for clarifying what u needed, it helped answer better.
8,713
another user recommend to me in another post [this page](http://www.bricklink.com/) to buy miniatures for my growing collection of minifigures of LEGO Star Wars. My question regarding the page is simple, there is a large assortment of minifigures of all the years, but why no one includes their accessories? For example, laser sheets or blasters ... Can the originals be obtained in any way within the page or is there any other method to obtain them? I've been looking at Amazon, but the prices are very high ... But they do include the minifigures accessories. Any ideas?
2017/03/15
[ "https://bricks.stackexchange.com/questions/8713", "https://bricks.stackexchange.com", "https://bricks.stackexchange.com/users/8450/" ]
As you've noticed, the [Starwars Minifigs](https://www.bricklink.com/catalogList.asp?catType=M&catString=65) don't come with accessories - this probably makes it easier for the sellers and buyers in terms of sorting: for example the battle packs often came with 3 or 4 different characters along with 2 different weapon styles - there's no definitive "this character has this style of weapon". The weapons can be found using the [Parts - Minifig, Weapon](https://www.bricklink.com/catalogList.asp?pg=2&catLike=W&sortBy=N&sortAsc=A&catType=P&catID=19) category - there are (at present) 4 guns tagged with `(SW)`, as well as the various different lightsaber hilts (listed as `Weapon Lightsaber Hilt`), various generic weapons (pikes/spears) and the newer "Shooter Mini with [...] Trigger" that is appearing for more play value over authentic weapon styles (another reason why you might want to buy the weapons separately). In terms of lightsabers, the beams themselves are listed as `Bar 4L (Lightsaber Blade / Wand)` under the [Bars category](https://www.bricklink.com/catalogList.asp?catType=P&catString=46) (there's also Kylo Ren's `Bar 4L / 2L Crossed`). If you're after more "realistic" weapons, then third party producers may be what you're after. BrickArms do a nice line in [Sci-Fi weapons](http://www.brickarms.com/scifi.php) that include Han's DL-44 and the Imperial issued EL-11, DC-15, DC-15S and D9-AR.
8,585,380
My code gives me segfault error: which I don't understand,the debugger says error comes from printing the value from stored\_ ``` char *stored_ = NULL; char testMessage[15]; //strcpy(stored_, testMessage); for (int a = 0;a < 10; a++) { sprintf(testMessage,"Message::%i\n",a); printf("string is:%s;length is %i\n",testMessage,strlen(testMessage)); stored_ = (char*) realloc (stored_, sizeof(char) * (strlen(testMessage) * (a+1) )); strcpy(&stored_[a], testMessage); } for (int b = 0;b < 10; b++) { printf("inside:|%s|\n",stored_[b]); } ```
2011/12/21
[ "https://Stackoverflow.com/questions/8585380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1051003/" ]
Fist up, `sizeof(char)` is *always* 1, you don't need to multiply by it. Secondly, when you're allocating room for a string, you have to use: ``` malloc (strlen (string) + 1); ``` In other words, you need room for the null byte at the end. Thirdly, you appear to be confused between character pointers and character *pointer* pointers. `stored_` is a single block of characters and `stored_[1]` is only one byte beyond `stored_[0]`, meaning you won't have enough room to store the string. ``` stored_[n], n=: 0 1 2 3 +---+---+---+---+ | | | | |... +---+---+---+---+ each of these cells is a single byte. ``` You'll either have to manage the single block of characters yourself, leaving enough room for each element (by using sparse indexes), or have a block of character pointers with indexes 0, 1, 2 and so on, but you'll then have to manage the string allocations separately. The following code shows how to do this latter one: ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main (void) { // An array of char pointers (C strings). char **stored_ = NULL; char testMessage[15]; int i; // Populate them. for (i = 0; i < 10; i++) { sprintf (testMessage,"Message::%i",i); printf ("string is:%s;length is %i\n",testMessage,strlen(testMessage)); // Reallocate array of char *, allocate room for string, then store it. stored_ = realloc (stored_,sizeof (char*) * (i + 1)); stored_[i] = malloc (strlen (testMessage) + 1); strcpy (stored_[i], testMessage); } ``` That's the meat of it, the allocation of the array of character pointers *separate* from the actual arrays of characters forming the C strings. Then the code below prints them and cleans up. ``` // Print them. for (i = 0; i < 10; i++) { printf("inside:|%s|\n",stored_[i]); } // Free all memory and return. for (i = 0; i < 10; i++) { free (stored_[i]); } free (stored_); return 0; } ``` The output being, as expected: ``` string is:Message::0;length is 10 string is:Message::1;length is 10 string is:Message::2;length is 10 string is:Message::3;length is 10 string is:Message::4;length is 10 string is:Message::5;length is 10 string is:Message::6;length is 10 string is:Message::7;length is 10 string is:Message::8;length is 10 string is:Message::9;length is 10 inside:|Message::0| inside:|Message::1| inside:|Message::2| inside:|Message::3| inside:|Message::4| inside:|Message::5| inside:|Message::6| inside:|Message::7| inside:|Message::8| inside:|Message::9| ``` With this method, each cell is a pointer to an array of characters, separately allocated (which holds the C string): ``` stored_[n], n=: 0 1 2 3 +---+---+---+---+ | | | | |... +---+---+---+---+ | | | | +----------------------+ | | | +---> | character array here | | | | +----------------------+ | | | +----------------------+ | | +-------> | character array here | | | +----------------------+ | | +----------------------+ | +-----------> | character array here | | +----------------------+ | +----------------------+ +---------------> | character array here | +----------------------+ ```
17,787,603
This is code to perform the delete operation. The four images appear, but the alert box for delete operation is not appearing by giving the onload functionality. Please guide me...here is the code. ``` // script for deletedelete operation $(document).ready(function(){ $('a.delete').on('click',function(e){ e.preventDefault(); imageID = $(this).closest('.image')[0].id; alert('Now deleting "'+imageID+'"'); $(this).closest('.image') .fadeTo(300,0,function(){ $(this) .animate({width:0},200,function(){ $(this) .remove(); }); }); }); }); ``` HTML ``` //four images being given with delete link <div id="container"> <div class="image" id="image1" style="background-image:url(http://lorempixel.com/100/100/abstract);"> <a href="#" class="delete">Delete</a> </div> <div class="image" id="image2" style="background-image:url(http://lorempixel.com/100/100/food);"> <a href="#" class="delete">Delete</a> </div> <div class="image" id="image3" style="background-image:url(http://lorempixel.com/100/100/people);"> <a href="#" class="delete">Delete</a> </div> <div class="image" id="image4" style="background-image:url(http://lorempixel.com/100/100/technics);"> <a href="#" class="delete">Delete</a> </div> </div> ```
2013/07/22
[ "https://Stackoverflow.com/questions/17787603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605662/" ]
I'd use a function like this one, where `range` is the string you gave ``` function highlightDivs(range) { var lower = range.split(" ")[0].slice(1); var upper = range.split(" ")[2].slice(1); $('.section-link').hide(); $('.section-link').children('.price').each(function() { if (lower <= $(this).val() && upper >= $(this).val()){ $(this).parent().show(); } }); } ```
122,741
We are traveling from Tbilisi to Ataturk airport and then with a transit to Antalya; both legs were sold under a single ticket by Turkish Airlines. * Do they automatically put luggage for transit? * How far is the second terminal, and where we should go for passport control?
2018/09/23
[ "https://travel.stackexchange.com/questions/122741", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/84484/" ]
For International to Domestic connections on Turkish Airlines, your bags will be automatically transferred to the domestic flight IF (and only if!) the domestic destination you are travelling to has customs facilities at the airport. In the case of Antalya, they DO have such facilities, so your bags will be automatically transferred to your domestic flight. Shortly before landing into Istanbul an announcement will be made on the flight, and they will direct you to the back of the in-flight SkyLife magazine to confirm which locations do and do not have customs facilities, so you can use this to confirm what I've said above. Upon landing in Istanbul you will need to proceed through Passport Control (just follow the signs), through baggage claim and customs (WITHOUT collecting your bags), and then make an immediate LEFT turn and follow the signs to the domestic terminal which is a 5-10 minute walk away.
34,666,777
I am creating a simple program that takes some input and turns it into an output to .txt file. I have been trying to use if-else statements to make it so that after it has received a name ; ``` //user enters name and then moves to next line System.out.println("Enter Your Name"); gamerName = Scan.nextLine(); ``` it will either move onto the next part (if a name is entered) or break. How and where will i properly add and format these if-else statements? thanks you ``` import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.nio.file.*; public class JavaProject { private static char[] input; public static void main(String[] args) { for(int b = 1; b < 100; b++ ) { //this is making the code loop 100 times //variables int[] minutesPlayed = new int [100]; String gamerName, gamerReport; //Main data storage arrays String[] gameNames = new String[100]; int[] highScores = new int[100]; @SuppressWarnings("resource") Scanner Scan = new Scanner(System.in); //formatting for output and input System.out.println("////// Game Score Report Generator \\\\\\\\\\\\"); System.out.println(" "); //user enters name and then moves to next line System.out.println("Enter Your Name"); gamerName = Scan.nextLine(); //user is given an example of input format System.out.println("FALSE DATA FORMAT WILL CAUSE ERROR - Input Gamer Information " + "Using Format --> Game : Achievement Score : Minutes Played"); System.out.println(" "); //another data input guide which is just above where data input is in console System.out.println("Game : Achievement Score : Minutes Played"); gamerReport = Scan.nextLine(); String[] splitUpReport; // an array of string splitUpReport = gamerReport.split(":"); // split the text up on the colon int i = 0; //copy data from split text into main data storage arrays gameNames[i] = splitUpReport[0]; highScores[i] = Integer.parseInt(splitUpReport[1].trim() ); minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim()); //output to file using a PrintWriter using a FileOutPutStream with append set to true within the printwriter constructor // try { PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data", true)); writer.println("Player : " + gamerName); writer.println(); writer.println("--------------------------------"); writer.println(); String[] report = gamerReport.split(":"); writer.println("Game: " + report[0] + ", score= " +report[1] + ", minutes played= " +report[2]); writer.println(); writer.close(); } catch (IOException e) { System.err.println("File does not exist!"); } } } public static char[] getInput() { return input; } public static void setInput(char[] input) { JavaProject.input = input; } } ```
2016/01/07
[ "https://Stackoverflow.com/questions/34666777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5517288/" ]
In this case, the problem turned out to be because my project in Eclipse depended on downstream project. When I went into my project's build path and removed the downstream project, my test went from red to green. The difference was spotted by contrasting output from the correct Maven CLI execution and the incorrect Eclipse execution. By diff'ing command line output between Maven CLI and Eclipse I spotted the following line in the Maven CLI console output: ``` <org.springframework.core.io.support.PathMatchingResourcePatternResolver><main><org.springframework.core.io.support.PathMatchingResourcePatternResolver.doFindPathMatchingJarResources(?:?):Looking for matching resources in jar file [file:/Users/jthoms/.m2/repository/com/acme/teamnamespace/downstream-project/0.0.2/downstream-project-0.0.2.jar]> ``` This corresponded to a line in Eclipse's console output: ``` <org.springframework.core.io.support.PathMatchingResourcePatternResolver><main><org.springframework.core.io.support.PathMatchingResourcePatternResolver.doFindMatchingFileSystemResources(?:?):Looking for matching resources in directory tree [/git/cloned/downstream-project/target/classes/com/acme/teamnamespace]> ``` In the Maven CLI output the source from a JAR file but in Eclipse it was in a project directory tree. After that line, all logged output started to become very different until the exception occurred.
23,936
I have the following setup: There is a collection of items I and a collection of partial rankings V. That is, an element of V is a total ordering on a subset of I. There is no expectation of consistency among the elements of V: it may be that x < y for one element and y < x for another. I would like to assign a score $s : I \to \mathbb{R}$ which in some sense captures these rankings. That is, I would like s(x) < s(y) to mean "x tends to be less than y for elements of V which have both in their domain". I'm not sure of what a good way to do this is. [Arrow's impossibility theorem](http://en.wikipedia.org/wiki/Arrow%27s_impossibility_theorem) puts some constraints on what can be achieved here, because given a set of votes and a scoring function like this we could use the scoring function to define a total order on the items, which is then constrained by the theorem. I suppose I'm really looking for references rather than an answer to this question (although both would be appreciated): I'm sure there's a body of theory around this, but I have no idea what it is like or what it's called, so I'm at a bit of a loss as to where to start looking for a solution.
2010/05/08
[ "https://mathoverflow.net/questions/23936", "https://mathoverflow.net", "https://mathoverflow.net/users/4959/" ]
Here is a list biased towards what is remarkable in the complex case. (To the potential peeved real manifold: I love you too.) By "complex" I mean holomorphic manifolds and holomorphic maps; by "real" I mean $\mathcal{C}^{\infty}$ manifolds and $\mathcal{C}^{\infty}$ maps. * Consider a map $f$ between manifolds of *equal* dimension. In the complex case: if $f$ is injective then it is an isomorphism onto its image. In the real case, $x\mapsto x^3$ is not invertible. * Consider a holomorphic $f: U-K \rightarrow \mathbb{C}$, where $U\subset \mathbb{C}^n$ is open and $K$ is a compact s.t. $U-K$ is connected. When $n\geq 2$, $f$ extends to $U$. This so-called Hartogs phenomenon has no counterpart in the real case. * If a complex manifold is compact or is a bounded open subset of $\mathbb{C}^n$, then its group of automorphisms is a Lie group. In the smooth case it is always infinite dimensional. * The space of sections of a vector bundle over a compact complex manifold is finite dimensional. In the real case it is always infinite dimensional. * To expand on Charles Staats's excellent answer: few smooth atlases happen to be holomorphic, but even fewer diffeomorphisms happen to be holomorphic. Considering manifolds up to isomorphism, the net result is that many complex manifolds come in continuous families, whereas real manifolds rarely do (in dimension other than $4$: a compact topological manifold has at most finitely many smooth structures; $\mathbb{R}^n$ has exactly one). On the theme of *zero subsets* (i.e., subsets defined locally by the vanishing of one or several functions): * *One* equation always defines a *codimension one* subset in the complex case, but {$x\_1^2+\dots+x\_n^2=0$} is reduced to one point in $\mathbb{R}^n$. * In the complex case, a zero subset isn't necessarily a submanifold, but is amenable to manifold theory by Hironaka desingularization. In the real case, *any* closed subset is a zero set. * The image of a proper map between two complex manifolds is a zero subset, so isn't too bad by the previous point. Such a direct image is hard to deal with in the real case.
11,289,905
I can't understand what is happening in my code: ``` for (NSMutableDictionary *dict in jsonResponse) { NSString *days = [dict objectForKey:@"dayOfTheWeek"]; NSArray *arrayDays = [days componentsSeparatedByString:@" "]; NSLog(@"la var %@ size %lu", days, sizeof(arrayDays)); for(int i = 0; i<sizeof(arrayDays); i++){ NSLog(@"el dia %@",[arrayDays objectAtIndex:i]); } } ``` What I get in log: ``` 2012-07-02 10:06:57.191 usualBike[1342:f803] var M T W T F size 4 2012-07-02 10:06:57.191 usualBike[1342:f803] day M 2012-07-02 10:06:57.192 usualBike[1342:f803] day T 2012-07-02 10:06:57.192 usualBike[1342:f803] day W 2012-07-02 10:06:57.193 usualBike[1342:f803] day T 2012-07-02 10:06:57.193 usualBike[1342:f803] var S S size 4 2012-07-02 10:06:57.194 usualBike[1342:f803] day S 2012-07-02 10:06:57.194 usualBike[1342:f803] day S ``` And crashes, because position 3 doesn't exist. Why the size is not changing the second time? it should be 1. Thank you in advance
2012/07/02
[ "https://Stackoverflow.com/questions/11289905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256477/" ]
Regex! ``` re.sub('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}','CENSORED_IP',data) ``` Worthy of note, this also matches things like 999.999.999.999. If that's a problem, you will have to get a regex that is a little more complicated. Furthermore, this only works on IPv4 Addresses. On only valid IP's: ``` re.sub('(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)','CENSORED_IP',data) ``` Source: [Regex Source](https://stackoverflow.com/questions/4011855/regexp-to-check-if-an-ip-is-valid)
394,250
Here's a snippet of code: An inlined function: ``` inline void rayStep(const glm::vec3 &ray, float &rayLength, const glm::vec3 &distanceFactor, glm::ivec3 &currentVoxelCoordinates, const glm::ivec3 &raySign, const glm::ivec3 &rayPositive, glm::vec3 &positionInVoxel, const int smallestIndex) { rayLength += distanceFactor[smallestIndex]; currentVoxelCoordinates[smallestIndex] += raySign[smallestIndex]; positionInVoxel += ray * glm::vec3(distanceFactor[smallestIndex]); positionInVoxel[smallestIndex] = 1 - rayPositive[smallestIndex]; } ``` It's usage: ``` glm::ivec3 distanceFactor = (glm::vec3(rayPositive) - positionInVoxel) / ray; if (distanceFactor.x < distanceFactor.y) { if (distanceFactor.x < distanceFactor.z) { rayStep(ray, rayLength, distanceFactor, currentVoxelCoordinates, raySign, rayPositive, positionInVoxel, 0); } else { rayStep(ray, rayLength, distanceFactor, currentVoxelCoordinates, raySign, rayPositive, positionInVoxel, 2); } } else { if (distanceFactor.y < distanceFactor.z) { rayStep(ray, rayLength, distanceFactor, currentVoxelCoordinates, raySign, rayPositive, positionInVoxel, 1); } else { rayStep(ray, rayLength, distanceFactor, currentVoxelCoordinates, raySign, rayPositive, positionInVoxel, 2); } } ``` I really dislike the way the usage of the function looks like. One way I could fix it is to calculate the index of the smallest component and then just use the body of the function directly in the code: ``` int smallestIndex = (distanceFactor.x < distanceFactor.y) ? (distanceFactor.x < distanceFactor.z ? 0 : 2) : (distanceFactor.y < distanceFactor.z ? 1 : 2); rayLength += distanceFactor[smallestIndex]; currentVoxelCoordinates[smallestIndex] += raySign[smallestIndex]; positionInVoxel += ray * glm::vec3(distanceFactor[smallestIndex]); positionInVoxel[smallestIndex] = 1 - rayPositive[smallestIndex]; ``` This looks much cleaner to me. So why haven't I done that, if it bothers me so much? The benefit of the above code is that value of the `smallestComponentIndex` of the function is know at compile time - the value is given as a constant and the function is inlined. This enables the compiler to do some optimizations which it wouldn't be able to do if the value were unknown during the compile time - which is what happens in the example with double ternary operator. The performance hit in my example is not small, the code goes from 30ms to about 45ms of execution time - that's 50% increase. This seems negligible, but this is a part of a simple ray tracer - if I want to scale it to do more complex calculations, I need this part to be as fast as possible, since it's done once per ray intersection. This was run on low resolution with a single ray per pixel, with no light sources taken into account. A simple ray cast, really, hence the runtime of 30ish ms. Is there any way I can have both the code expression and speed? Some nicer way to express what I want to do, while making sure that value of the `smallestComponentIndex` is known at compile time?
2019/07/04
[ "https://softwareengineering.stackexchange.com/questions/394250", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/247488/" ]
This is going to be a frame challenge answer. > > It is possible to design base class in a way that I have to pass connection string only once and not for each of the 4 concrete classes? > > > You *shouldn't* try to achieve what you want to with a base class. Why not? ======== Basically, if you use a base class for this, it might work fine now. Over time, your code will get more and more complex. The older code is, the more difficult it is to change it. And then when at some point one of your repos needs a different connection string, you will have to untangle everything and it. will. be. PAIN. So having to provide the connection string to each repo is actually *a good thing*. In the end. At the moment it seems like just more work, but it's worth it going forward. What instead? ============= This is a situation where [favoring composition over inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance) is actually easier then messing around with inheritance in a way it isn't really supposed to be used. "Switching over" won't actually be a lot of work for you, because you already have the common functionality in your base class. In order to adjust it just * give it a more fitting name, `RepoConnector` or something like that * make it non-abstract * make the constructor public or internal Then you can *inject* it into your repos, store it in a field and use it from there. For example, your `RegionRepo` would look something like this: ``` internal class RegionRepo { private readonly RepoConnector _repoConnector ; public RegionRepo(RepoConnector repoConnector, int variantId) { _repoConnector = repoConnector; VariantId = variantId; } public int GetRegionIdByVariantId() { string query = ""; List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@id", VariantId)); return _repoConnector.ExecuteScalar(query, parameters); } } ``` Admittedly, this isn't exactly what you wanted. Now the connection string is only provided once, but instead the `RepoConnector` is being passed to all the repos. However, passing the info to each repo is the "proper" way to do it that won't give you headaches later on. Also, you do still get "the best of both worlds": If you want to change the connection string, there's only one place to change now, PLUS you won't have to rewrite common functionality for each repo. "Dirty logic"? ============== The same advice does not really apply for this bit: ``` List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@TestId", TestId)); parameters.Add(new SqlParameter("@VariantId", VariantId)); ``` It's not *that* dirty. However, you say "*I have to do this at so many places*". If it's really bad enough, you *might* want to add a little helper method to the `RepoConnector`, something like this: ``` internal void ExecuteQuery(string query, string name1, int value1, string name2, int value2) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter(name1, value1)); parameters.Add(new SqlParameter(name2, value2)); ExecuteQuery(query, parameters); } ``` As is probably obvious, this only helps if you're really doing the same thing (as in the example, "calling ExecuteQuery with 2 int parameters") multiple times. Another alternative might be using `params`: ``` void ExecuteQuery(string query, params SqlParameter[] parameters) { // Everything else can stay the same here because foreach still works on arrays } // You can now call it this way: ExecuteQuery(query, new SqlParameter("@TestId", TestId), new SqlParameter("@VariantId", VariantId)); // You can put as many "new SqlParameter()" as you want, or even without any: ExecuteQuery(query); ``` But again, this doesn't give you *a lot*, so it's only worth it in some cases. If you're always doing slightly different things, it's probably easier to do that by writing slightly different code for each.
1,271,166
I am looking for help to achieve the following The Diagram represents a car, users can add engine and colour when I view the XML it looks like this: ``` <Car> <Engine>BigEngine</Engine> <Colour>Pink</Colour> </Car> ``` What I would like to do is to wrap the car inside 'vehicle', i.e ``` <Vehicle> <Car> <Engine>BigEngine</Engine> <Colour>Pink</Colour> </Car> </Vehicle> ``` I am not sure of the best way to achieve this. I want the model explorer and the generated XML to be wrapped in 'vehicle' but for all other intents and purposes the user is working with a car only Info: Visual Studio 2010, C# and DSL SDK for 2010
2009/08/13
[ "https://Stackoverflow.com/questions/1271166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76581/" ]
not sure how to do it in Jquery ``` window.onbeforeunload = function (e) { var e = e || window.event; // For IE and Firefox if (e) { e.returnValue = 'Any string'; } // For Safari return 'Any string'; }; ``` <https://developer.mozilla.org/en/DOM/window.onbeforeunload>
23,600
Any idea how to write this code better."the html is nested tabs" Two selectors and two similar events, in a function would be better or a pattern to reduce lines. [eg .jsbin](http://jsbin.com/utaxot/3/edit) ``` $(function() { var $items = $('#vtab>ul>li'), $items2 = $('#vtab2>ul>li'); $items.mouseover(function() { var index = $items.index($(this)); $items.removeClass('selected'); $(this).addClass('selected'); $('#vtab>div').hide().eq(index).show(); }).eq(1).mouseover(); $items2.mouseover(function() { var index = $items2.index($(this)); $items2.removeClass('selected'); $(this).addClass('selected'); $('#vtab2>div').hide().eq(index).show(); }).eq(1).mouseover(); }); ```
2013/03/08
[ "https://codereview.stackexchange.com/questions/23600", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/22919/" ]
First of all, your code has a bug: You did not follow the [rule of three](http://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29). Code such as `myStack1 = myStack2;` will cause the pointer to be deleted twice - which is undefined behavior. --- ``` int storedElements; ``` This seems kind of misleading. This variable doesn't hold the *stored elements*. It holds the *number of stored elements*. Perhaps `storedElementsCount` or something like that would be better? --- ``` myStaticIntStack( int aNumber ); ``` Why did you call the variable `aNumber` here? `aNumber` is a *terrible* name. It tells me essentially *nothing*. Later you used `stackSize` which is a **FAR** better name. Why didn't you use it here too? And, by the way, consider using `size_t` to store sizes and capacities instead of ints. This would apply to `stackSize` and `storedElements`. --- ``` myStaticIntStack::myStaticIntStack() { this->stackSize = 1; this->elements = new int(0); this->storedElements = 0; } ``` Seriously? The default behavior for the stack is to create a stack with maximum size 1? That is kind of... worthless. It's OK to allow this in the myStaticIntStack(int) constructor, but as a *default* it just seems odd. Consider not even allowing a default constructor. --- ``` myStaticIntStack::myStaticIntStack( int stackSize ) { this->stackSize = stackSize; this->elements = new int[ stackSize ]; this->storedElements = 0; } ``` Can the stackSize be zero? Can it be negative? Consider adding an assertion. By the way, if you make stackSize be a size\_t, the negative case becomes impossible, since size\_t is unsigned. But you'll still need to handle the "stackSize == 0" case. A size of 0 might be acceptable. If that is the case, add a comment stating that and why it is so. Consider declaring this constructor `explicit`. --- ``` myStaticIntStack::~myStaticIntStack() { if( this->elements != NULL ) { if( stackSize > 1 ) delete[] this->elements; else delete this->elements; } } ``` Why do you need a NULL check? Are you expecting the destructor to be called with `elements == NULL`? If this merely defensive programming and this case is never supposed to happen, then leave it as an assertion. Also, that whole `delete` vs `delete[]` is weird. What if I use the constructor `myStaticIntStack(1)`? Then you'll be `delete`ing something created with `new[]`. I'd change the code (from the constructors) so that `new[]` - not `new` - is always used and, therefore, `delete[]` is always the right thing to do in the destructor. --- ``` void myStaticIntStack::push( int newElement ) { if( this->storedElements == this->stackSize ) cout << "Stack is full, you must POP an element before PUSHing a new one!" << endl; else { this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement; this->storedElements++; } } ``` This is improper error handling that violates the single responsibility principle. Your function should either throw an exception, merely assert the condition or return an error code. Printing to the command line should be done elsewhere - probably *outside* this class. --- ``` this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement; ``` I'm pretty sure you could simplify this. For a stackSize=16, the first position is at index 15. Why 15? Why not 0? That'd simplify the code to just `elements[storedElements] = newElement;`. Just remember to also fix the pop/peek code. Just because the stack is Last-in-first-out doesn't mean you have to fill the last indexes in the internal array first. That's an implementation detail. --- > > it's confusing that pop() returns a value even if Stack is empty. > > > Then *don't* return a value if the Stack is empty. Throw an exception or abort with an assertion. Problem solved. Next. As I stated before, your `cout`s are in the wrong place. If you fix that the "Pop return" problem might just naturally go away. If you decide to keep it like that (return -1), then consider making `-1` a named constant since [magic numbers](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) are bad. ``` return ERROR_STACK_IS_EMPTY; ``` --- ``` int myStaticIntStack::peek() ``` Same thing about `cout`. Also, `peek()` doesn't change anything, does it? Then consider making it `const`. ``` int myStaticIntStack::peek() const ``` --- Consider splitting your myStaticIntStack in two files: `myStaticIntStack.hpp` and `myStaticIntStack.cpp`. Your main function would be in a third file. --- Some extra thoughts: * I suspect the "better way" might be to just use a vector internally. This would painlessly solve your "rule of three" problem. Bonus points since it'd make it easier to "resize" the stack after being created if you ever wanted to add that feature. * Personally, I'd uppercase the first letter of the class name, but that's just personal preference. Nothing wrong with your particular style. * Consider adding a `bool empty()` function, that checks if the stack is empty. * Consider adding a `bool full()` function, that checks if the stack is full. * Those two functions above could make your error detection code easier to understand. If your assignment forbids adding extra functions, consider adding them as private functions. * Consider adding a `int size()` function, that returns storedElements. * Consider adding a `int capacity()` function, that returns stackSize * Normally, a class like this would be implemented as a template since it's useful to have stacks for more than just integers. Not sure if you've learned about templates yet. If you follow QuentinUK's suggestion of removing the `this->`, beware. There is one case that might cause you trouble. In the constructor, `this->stackSize = stackSize;` is correct, but `stackSize = stackSize;` would not be. To work around this issue, you could use something like this: ``` /*optionally add "explicit" here*/ myStaticIntStack::myStaticIntStack( int stackSize ) : stackSize(stackSize) { elements = new int[ stackSize ]; storedElements = 0; } ``` This is all I can think of right now. Hope this helps.
93,285
I apologize if this is a duplicate, I can't find anything up-to-date that really helps answer my question. I know this is nitpicky, but it's been a long battle and I am losing it. For some time, I have been annoyed with the fact that you can't customize the android camera app's naming convention. My workaround, since the dawn of Dropbox camera upload, has been to use dropbox to upload and rename my photos (yyyy-mm-dd HH.nn.ss.jpg) and then use dropsync to overwrite the original file in my camera photo. The problem I'm facing at the moment is that the camera in the hangouts app does not follow the same rules as the default camera app for my phone (Sony Xperia z3) so I end up with duplicates in my gallery of any image I happened to capture using hangouts instead of the camera. I could use the camera to take a picture and then share it using hangouts, but I decided instead to play around with Tasker and try to automate consolidating my images. (Another gripe I have is that Dropbox won't let me exclude folders, so I'd like to get rid of Camera Upload altogether and not have every screenshot I've ever taken backed up forever). The directory for the default camera is [internal storage]/DCIM/100ANDRO and for hangouts it is [internal storage]/DCIM/Camera I have a profile (below) triggered by the "file modified" event that will move the new file in the "Camera" folder into the "DCIM" folder. However, there is often a race condition, so Dropbox will upload the image before it is moved and again after. So my problem of duplicate images is not yet solved. [![tasker profile to move newly created image](https://i.stack.imgur.com/Ur5vOt.png) (click for larger version)](https://i.stack.imgur.com/Ur5vO.png) I'd like to forgo the Dropbox/Dropsync combo and instead use Tasker to rename a file as it is added to either of the camera folders. I'd like to use the same naming convention that Dropbox uses, but I can't figure out how Tasker can access the EXIF data from the image to rename the photo to something like "2014-12-30 10.23.56.jpg". So, as a tl;dr: I am using Tasker to move images captured from different apps into a common folder. Can anyone help me add a step to rename the file I am moving based on the date and time the image was captured?
2014/12/30
[ "https://android.stackexchange.com/questions/93285", "https://android.stackexchange.com", "https://android.stackexchange.com/users/87069/" ]
Use Tasker's native Java calls ============================== Java code --------- Use [ExifInterface.getAttribute](http://developer.android.com/reference/android/media/ExifInterface.html#getAttribute(java.lang.String)) to solve this problem. ``` exif = new ExifInterface( %filename ) %datetime = exif.getAttribute(exif.TAG_DATETIME) ``` Implementation overview ----------------------- 1. Getting path of a .JPG from `%filename` Tasker variable 2. Construct a new `ExifInterface` class instance into `exif` Java variable 3. Get date & time by `exif.getAttribute` Java function, and store results into `%datetime` Tasker variable 4. Free `exif` Java variable 5. Check `%datetime` is set *(this is not set when .JPG is not contains EXIF info)* [![](https://i.stack.imgur.com/0DRB7.png)](https://i.stack.imgur.com/0DRB7.png) Step by step solution in Tasker ------------------------------- 1. Add a new **Code > Java Function** action a. Set `ExifInterface` to **Class Or Object** *(or select by magnifying glass button)* b. Write `new \\ {ExifInterface} (String)` to **Function** *(or select by magnifying glass button)* c. Write `%filename` to **Param (String)** d. Write `exif` to **Return {ExifInterface}** [![](https://i.stack.imgur.com/JQwNs.png)](https://i.stack.imgur.com/JQwNs.png) 2. Add a new **Code > Java Function** action a. Write `exif` to **Class Or Object** *(or select by coffee button)* b. Write `getAttribute \\ {String} (String)` to **Function** *(or select by magnifying glass button)* c. Write `exif.TAG_DATETIME` to **Param (String)** d. Write `%datetime` to **Return {String}** [![](https://i.stack.imgur.com/8WSGb.png)](https://i.stack.imgur.com/8WSGb.png) 3. Add a new **Code > Java Object** action a. Left **Mode** on `Delete` b. and write `exif` to **Name** [![](https://i.stack.imgur.com/DrHrr.png)](https://i.stack.imgur.com/DrHrr.png) 4. Check `%datetime` is set *- I added a conditional Flash for show `%datetime`* **Done!**
50,179,858
I've been having issues regarding this narrowing conversion error > > Overload resolution failed because no accessible 'Show' can be called without a narrowing conversion: > > > 'Public Shared Function Show(owner As System.Windows.Forms.IWin32Window, text As String, caption As String, buttons As System.Windows.Forms.MessageBoxButtons) As System.Windows.Forms.DialogResult': Argument matching parameter 'owner' narrows from 'String' to 'System.Windows.Forms.IWin32Window'. > > > 'Public Shared Function Show(owner As System.Windows.Forms.IWin32Window, text As String, caption As String, buttons As System.Windows.Forms.MessageBoxButtons) As System.Windows.Forms.DialogResult': Argument matching parameter 'caption' narrows from 'Microsoft.VisualBasic.MsgBoxStyle' to 'String'. > > > 'Public Shared Function Show(owner As System.Windows.Forms.IWin32Window, text As String, caption As String, buttons As System.Windows.Forms.MessageBoxButtons) As System.Windows.Forms.DialogResult': Argument matching parameter 'buttons' narrows from 'System.Windows.Forms.MessageBoxIcon' to 'System.Windows.Forms.MessageBoxButtons'. > > > 'Public Shared Function Show(text As String, caption As String, buttons As System.Windows.Forms.MessageBoxButtons, icon As System.Windows.Forms.MessageBoxIcon) As System.Windows.Forms.DialogResult': Argument matching parameter 'buttons' narrows from 'Microsoft.VisualBasic.MsgBoxStyle' to 'System.Windows.Forms.MessageBoxButtons'. > > > I did some research and the generic solution for "Overload resolution failed because no accessible '' can be called without a narrowing conversion: " errors is to Specify Option Strict Off according to Microsoft. I tried changing this manually in the Project Properties but it didn't seem to work. This is the code where the error is occurring: ``` If MessageBox.Show("Please Enter a value for ESD (rad)", "ESD (rad) Value", MsgBoxStyle.OkCancel, MessageBoxIcon.Information) = DialogResult.OK Then txtCal_USE_Radio.Focus() ``` I've also checked several other forums where they talk about this error but specifically related to the 'New' function and they don't seem to help. Any help on this would be great!
2018/05/04
[ "https://Stackoverflow.com/questions/50179858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9742443/" ]
You've invoking `Show({string}, {MsgBoxStyle}, {MessageBoxIcon})`, so the last overload in the error message is the closest: > > 'Public Shared Function Show(text As String, caption As String, buttons As System.Windows.Forms.MessageBoxButtons, icon As System.Windows.Forms.MessageBoxIcon) As System.Windows.Forms.DialogResult': Argument matching parameter 'buttons' narrows from 'Microsoft.VisualBasic.MsgBoxStyle' to 'System.Windows.Forms.MessageBoxButtons'. > > > That's `Show({String}, {String}, {MessageBoxButtons}, {MessageBoxIcon})` - you're missing a `caption` argument, and instead of `MsgBoxStyle` you should use the `MessageBoxButtons` enum. Sounds like you have `Option Strict On` - that's ~~good~~ excellent - but it seems you also have `Imports Microsoft.VisualBasic`, which is essentially polluting your *IntelliSense* with VB6 back-compatibility stuff, which `MsgBoxStyle` is part of; that enum means to work with the legacy `MsgBox` function, which `MessageBox` is a more .NET-idiomatic replacement for. Switching off `Option Strict` would be the single worst thing to do - you're passing a bad parameter and the compiler is telling you "I can't convert the supplied type to the expected one"; last thing to do is to make it say "hey don't worry, just implicitly convert all the things and blow up at run-time instead". *IntelliSense*/autocomplete should be telling you what to do *as you type the arguments into the function call*; re-type the opening parenthese `(` and watch *IntelliSense* highlight the parameters and their respective types as you use the arrow keys to move the caret across the arguments you're supplying.
28,235,744
I am trying to start an external executable file via Groovy but got some problems with it! I just want to start the `rs.exe` with several parameters to create a PDF-file using the SSRS. But as soon as I try to get the return value/exit-code it doesn't work anymore! But I want to grab the generated file and add it to a database, so I need a return value to know when its generated. This works totally fine for generating: ``` def id = 1 def cmd = """ C://Program Files (x86)//...//rs.exe -i C:\\export.rss -s http://localhost/ReportServer_SQLEXPRESS -v ID=${id} -e Exec2005 """ def proc = cmd.execute() ``` But I don't get any return value/exit-code. I already tried different way, e.g. ``` proc.waitFor() ``` but I or ``` cmd.execute().value ``` but nothing worked. When I start the `rs.exe` with all my provided data in Windows I get the return "Process succesfully ended". Any Groovy-specialists here that can help me out?
2015/01/30
[ "https://Stackoverflow.com/questions/28235744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4511347/" ]
Try executing command when it's defined in the following way: ``` def cmd = ['cmd', '/c', 'C://Program Files (x86)//...//rs.exe', '-i', 'C:\\export.rss', '-s', 'http://localhost/ReportServer_SQLEXPRESS', '-v', "ID=${id}", '-e', 'Exec2005'] def proc = cmd.execute() ```
31,758,853
I'm currently working on a Node.js stack application used by over 25000 people, we're using Sails.js framework in particular and we got MongoDB Application is running at a EC2 instance with 30GB of RAM, databse is running on a Mongolab AWS based cluster in same zone the EC2 is. We even got an Elastic Cache Redis instance with 1.5GB for storage. So the main and huge problem we're facing is **LATENCY**. When we reach a peak of concurrent users requesting application we're getting multiple timeouts and sails application reaching over 7.5GB of RAM, HTTP requests to API take longer than 15 seconds (which is unacceptable) and when even get 502 and 504 responses sent by nginx. I can notice Mongo write operations as our main latency issue, however even GET requests take long when a demand peak is present. I can't access production servers, I only got a keymetrics monitoring tool by pm2 (which is actually great) and New Relic alerts. So, I'd like to know some roadmap to cope these issues, maybe more detailed information should be offered, so far I can say application seems stable when not much users are present. What are main factors and setup to consider? So far I know *what I should do*, but I'm not sure about details or the *hows*. IMHO: 1. Cache as much as possible. 2. Delay MongoDB write operations. 3. Separate Mongo databases with higher write demand. 4. Virtualize? 5. Tune up node setups. On optimising code, I've posted another stackoverflow question with one example of [code patterns I'm following](https://codereview.stackexchange.com/questions/98815/). **What are your advise and opinion for production applications?**
2015/08/01
[ "https://Stackoverflow.com/questions/31758853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742560/" ]
Basically most of main points are already present in answers. I'll just summarise them. To optimize your application you could do several main things. 1. Try to move form `node.js` to `io.js` it still have a bit better performance and latest cutting edge updated. (But read carefully about experimental features). Or at least from `node.js` `v10` to `v12`. There was lot of performance optimisations. 2. Avoid using synchronous functions that uses I/O operations or operating with big amount of data. 3. Switch from one node process to [clustering](https://nodejs.org/api/cluster.html) system. 4. Check your application to memory leaks. I'm using [memwatch-next](https://github.com/marcominetti/node-memwatch) for `node.js v12` and [memwatch](https://github.com/lloyd/node-memwatch) for `node.js v10` 5. Try to avoid saving data to global variables 6. Use caching. For data that should be accessible globally you could use `Redis` or `Memcached` is also a great store. 7. Avoid of using `async` with `Promises`. Both libs are doing same things. So no need to use both of them. (I saw that in your code example). 8. Combine `async.waterfall` with `async.parallel` methods where it could be done. For example if you need to fetch some data from mongo that is related only to user, you could fetch user and then in parallel fetch all other data you need. 9. If you are using `sails.js` make sure that it's in `production` mode. (I assume you already did this) 10. Disable all hooks that you don't need. In most cases `grunt` hook is useless.And if you don't need `Socket.io` in your application - disable it using `.sailsrc` file. Something like: { "generators": { "modules": {} }, "hooks": { "grunt": false, "sockets": false } } Another hooks that could be disabled are: `i18n`, `csrf`, `cors`. BUT only if you don't use them in your system. 11. Disable useless globalisation. In `config/globals.js`. I assume `_`, `async`, `services` could be disabled by default. Just because `Sails.js` uses old version of `lodash` and `async` libraries and new versions has much better performance. 12. Manually install `lodash` and `async` into `Sails.js` project and use new versions. (look point 11) 13. Some "write to mongo" operations could be made after returning result to user. For example: you can call `res.view()` method that will send response to user before `Model.save()` BUT code will continue running with all variables, so you could save data to mongo DB. So user wouldn't see delay during write operation. 14. You could use queues like [RabbitMQ](https://www.rabbitmq.com/) to perform operations that require lot of resources. For example: If you need to store big data collection you could send it to `RabbitMQ` and return response to user. Then handle this message in "background" process ad store data. It will also can help you with scaling your application.
42,850,428
We are currently use the oob page types for Blog, News and Event. We have one page for each of these types that includes a repeater to show a list of the pages of that type. We would also like to have a page that includes a repeater that shows all blog, news and event pages in one spot, sorted by their created date. I have seen some old comments ([here](https://devnet.kentico.com/questions/using-two-page-types-in-a-repeater), [here](https://devnet.kentico.com/questions/columns-content-filter-over-multiple-page-types)) on devnet saying that although a repeater can render multiple page types, the fields rendered must be identical across each of those page types. The workarounds suggested are either to create the same fields in each page type, or to create a custom SQL query and use a query repeater to render the data. I've done this and it works just fine, but it was pretty cumbersome to create and will be difficult to maintain. (If we want to add other page types, for example.) Can anyone suggest a more out-of-the-box method available in Kentico 10? **Update:** I'm trying to accomplish this as Brenden described, but am running into trouble. My page structure is as follows: ``` Root .RollupPage (CMS.MenuItem) ..BlogPosts (CMS.Blog) ...January 2017 (CMS.BlogMonth) ....blog post 1 (CMS.BlogPost) ...February 2017 (CMS.BlogMonth) ....blog post 2 (CMS.BlogPost) ..Events (CMS.MenuItem) ...Event1 (CMS.BookingEvent) ...Event2 (CMS.BookingEvent) ``` I've attempted to use a universal viewer, but failed to get it to return any data. I configured it with: ``` Path: /RollupPage/% Page types: CMS.BlogPost;CMS.BookingEvent Hierarchical Transformation: CMS.MenuItem.HierTrans1 ``` HierTrans1 has the following transformations: ``` CMS.BlogPost.Default (Item transformation for type CMS.BlogPost) CMS.BookingEvent.EventCalendarItem (Item transformation for type CMS.BookingEvent) ``` These aren't customized at all; they are standard OOB transformations just so I can see it work. When I view the RollupPage, the universal viewer displays nothing. I attempted to use a Hierarchical Viewer with the same settings as I did with the Universal Viewer. It kind-of worked. It displayed my booking events but did not display any blog posts. Yet using the same blog post transformation (CMS.BlogPost.default) with hierarchical viewer whose `Path` was set to `/RollupPage/BlogPosts/%` displayed my blog posts correctly but, obviously, did not display my booking events. The results I've gotten so far makes me think a) something about the way I've created my pages is stopping the universal viewer from traversing the whole tree and/or b) the hierarchical viewer either only goes a couple of levels deep, or maybe it is being blocked from traversing the tree too... No events are recorded when I edit or view these web parts. Any idea what I may be doing wrong?
2017/03/17
[ "https://Stackoverflow.com/questions/42850428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6683608/" ]
You can use the **Hierarchical viewer** or the **Universal viewer**, as Brenden Kehren mentioned, to achieve the goal you are describing. When configuring the web part you must select all the **Page types** that are included in the hierarchy, in your case: **CMS.MenuItem, CMS.Blog, CMS.BlogMonth, CMS.BlogPost** and **CMSBookingEvent**. Create a **Hierarchical transformation** to be used with your viewer and add an **Item transformation** for each of the items you wish to display. Also make sure the **Level** setting for each transformation is configured properly (-1 applies the transformation to all levels). For **Universal viewer** it is necessary to check the property **Load hierarchical data** in the section **Extended settings** of the configuration. As an additional note, you can leave the path property empty in case you are viewing the child documents of the current page. For reference there is also an example on the **Corporate Site** example site in the content tree path **Examples > Web Parts > Listings and viewers > Pages > Hierarchical viewer** (or **Universal viewer**). Hope this helps!
1,617,855
The question is basically it but here's the background of the story if curious: My eyes woulld ache since I spend 12+ hours a day looking at a computer screen, so I decided to give night light a try and turned it to 70% strength. The colors were uglier than normal but I used it for about a year (always on) and now when I turn it off it looks like I'm looking at the sun when I look at my computer screen. Anyway, my concern is, is leaving night light on long periods of time bad for my computer? And a follow-up question if someoone knows: is always using night light bad for the eyes?
2021/01/15
[ "https://superuser.com/questions/1617855", "https://superuser.com", "https://superuser.com/users/1233850/" ]
> > is leaving night light on long periods of time bad for my computer? > > > What night light setting does is just to decrease light of display, and maybe not equally all colours, but blue is reduced a bit more then the others. So the answer for your question is **NO**, using night light will not cause any negative effect for your display (it could even be a little beneficial for it, but I don't think that would be measurable). > > is always using night light bad for the eyes? > > > Having less eye strain with night light settings is definitely a good sign, that's the feedback from your eyes that it prefers those settings.
774,809
I'd like to make a tool bar with icons that get's bigger when you mouse over them. I don't mind reinventing the wheel, but if anyone can suggest a good: 1. Image Format (not sure bitmaps'll work here and not sure how to do Vectors) 2. Existing Control (pay or free, so long as I can use it in a close source app) 3. Container class (is TPanel sufficient?)
2009/04/21
[ "https://Stackoverflow.com/questions/774809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
I've not used it yet personally, but maybe check out TMS TAdvSmoothDock rather than reinventing wheel..? <http://www.tmssoftware.com/site/advsmoothdock.asp>
15,430,684
I have searched on this subject and am just getting more confused. We have a Forms Authentication web application. I have changed the old FormsAuthentication.SetCookie statement to instead create a GenericPrincipal containing a FormsIdentity, then I have added a couple of custom claims, then I write a sessionsecuritytokentocookie using SessionAuthenticationModule. I am getting slightly confused with FederatedAuthentication - I am using FederatedAuthentication.SessionAuthenticationModule to write the token but I think this is the same as just using Modules("SessionAuthenticationModule") in my case? Anyway, the authentication works fine but my custom claims are not being recreated. I am not using membership providers or role providers - does that matter? I have read about SessionAuthenticationModules, ClaimsAuthenticationManagers, ClaimsTransformationModules but I am no longer certain which of these I should be using or how? Currently I just add my claims where the old login code was (I haven't got time to rewrite the whole login process) and I was expecting these claims to be recreated automatically on each request. What do I need to do - obviously I do not want to have to go to the database every time to rebuild them - I thought they were being stored in the cookie and recreated automatically.
2013/03/15
[ "https://Stackoverflow.com/questions/15430684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2047485/" ]
Your approach is fine - you create a ClaimsPrincipal with all the claims you need and write out the session cookie. No need for a claims authentication manager. possible gotchas: * make sure you set the authentication type when creating the ClaimsIdentity - otherwise the client will not be authenticated * by default session cookies require SSL (the browser won't resend the cookie over plain text). This can be changed but is not recommended.
34,517,581
> > Note: I already went through the below SO Question and 7 Answers (as of now) about [Symbols](https://github.com/zenparsing/es-private-fields), WeekMaps and Maps, Please read the full question before you vote: [Private properties in JavaScript ES6 classes](https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes) > > Article: <https://esdiscuss.org/topic/es7-property-initializers> > > > Below is my `Simple Class` which contains Private, Public and Protected Properties and Methods. ```js 'use strict'; class MyClass { constructor () { this.publicVar = 'This is Public Variable'; this.privateVar = 'This is Private Variable'; this.protectedVar = 'This is Protected Variable'; } // Public Constructor Method. publicMethod () { console.log(' Accessing this.publicVar: ', this.publicVar); console.log(' Accessing this.privateVar: ', this.privateVar); console.log(' Accessing this.protectedVar: ', this.protectedVar); return 'Its Public Method' } // Public Method. privateMethod () {return 'Its Private Method'} // Private Method. protectedMethod () {return 'Its Protected Method'} // Protected Method. foo () { this.publicMethod(); this.privateMethod(); this.protectedMethod(); } // Public Method } // end class ``` I'm instantiating the Object and calling the public method which is working as expected. ``` let MyObject = new MyClass; MyObject.foo(); // Works fine. console.log( MyObject.publicVar ); // Works console.log( MyObject.publicMethod() ); // Works ``` > > Working as expected. > > > Now my question. I'm aware few things like Symbol are in the ES6 specification, what is the current workaround to get protected and private variables/methods working on ES6 classes. ``` console.log( MyObject.privateVar ); // Works console.log( MyObject.privateMethod() ); // Works ``` > > I want this property and method to be visible only in its own class. > > > ``` console.log( MyObject.protectedVar ); // Works console.log( MyObject.protectedMethod() ); // Works ``` > > I want this property and method to be visible in its own class and inside classes extending it. > > > Workaround / better solution to achieve this behavior is appreciated
2015/12/29
[ "https://Stackoverflow.com/questions/34517581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5696335/" ]
**Private properties** In ES6 (and before), all private property implementations rely on [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures). People [have been doing it](http://javascript.crockford.com/private.html) even before JavaScript has versions. WeakMap is just a variation that removes the need of new scope and new functions for each new object, at cost of access speed. Symbol is a ES6 variation that hides the attribute from common operations, such as simple property access or `for in`. ```js var MyClass; ( () => { // Define a scoped symbol for private property A. const PropA = Symbol( 'A' ); // Define the class once we have all symbols MyClass = class { someFunction () { return "I can read " + this[ PropA ]; // Access private property } } MyClass.prototype[ PropA ] = 'Private property or method'; })(); // function in the closure can access the private property. var myObject = new MyClass(); alert( myObject.someFunction() ); // But we cannot "recreate" the Symbol externally. alert( myObject[ Symbol( 'A' ) ] ); // undefined // However if someone *really* must access it... var symbols = Object.getOwnPropertySymbols( myObject.__proto__ ); alert( myObject[ symbols[ 0 ] ] ); ``` As seen above, it can be worked around by [Object.getOwnPropertySymbols()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols). Despite its existence, I always choice symbol over WeakMap. The code is cleaner, simpler, less gc work, and (I think) more efficient. > > I personally avoid `class`, too. `Object.create` is much simpler. But that is out of scope. > > > --- **Protected properties** Protected properties, by its nature, requires executing function to know the object of the calling code, to judge whether it should be granted access. This is impossible in JS, not because ES6 has [no real class](https://www.quora.com/Are-ES6-classes-bad-for-JavaScript), but because caller *context* is [simply unavailable](https://stackoverflow.com/questions/28260389/can-you-get-the-property-name-through-which-a-function-was-called/28314301#28314301). Due to [various](https://en.wikipedia.org/wiki/Prototype-based_programming) [special](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) [natures](https://en.wikipedia.org/wiki/First-class_function) of JavaScript, for the foreseeable future protected properties shall remain impossible. [ Update ] Three years later, thanks to widespread support of module, it is possible to emulate most benefits of protected properties, see the answer below by Twifty. They are still public, but you need to go extra to access them, which means it is difficult to accidentally access or override them. [ /Update ] Alternatively... --- **Package properties** Some languages have semi-protected properties, sometimes called "package private", where the method / property is accessible to members in the same module / package. ES6 can implement it with closure. It is exactly the same as the private property code above - just share the scope and its symbols with multiple prototypes. But this is impractical, since this requires that the whole module be defined under same closed scope, i.e. in a single file. But it is an option nonetheless.
155,882
I have a simple echo server program running on CentOS 7. If I run both the client and the server in the VM, I can connect to the server. I'm using VirtualBox with the "bridged" network configuration. Using the IP of my Linux VM (found using ifconfig), I can successfully ssh into the Linux VM from Cygwin in Windows. However when I try to connect to the server using putty from my Windows 7 host PC the connection won't work. I don't understand why the server doesn't see a connection request from the host PC. What could be causing this? The windows Firewall is disabled.
2014/09/16
[ "https://unix.stackexchange.com/questions/155882", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/84370/" ]
I suggest you capture the packets and write them to a file with the `<file>.pcap` extension, and then open with `wireshark`. For example, in CentOS, to capture the packets: ``` $ tcpdump -i eth0 -s 1500 -w /root/<filename.pcap> ```
33,550,852
Here i'm trying to do a fastest method to save 3 matrix(R, G and B) into a BufferedImage. I've found this method here at StackExchange, but it doesn't work for me because the image it's being saved in a grayscale color. If I'm doing something wrong or if there's a way of doing this faster than `bufferimage.setRGB()`, please help me. Thanks! ```java public static BufferedImage array_rasterToBuffer(int[][] imgR, int[][]imgG, int[][] imgB) { final int width = imgR[0].length; final int height = imgR.length; int numBandas = 3; int[] pixels = new int[width*height*numBandas]; int cont=0; System.out.println("max: "+width*height*3); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { for (int band = 0; band < numBandas; band++) { pixels[(((i*width)+j)*numBandas +band)] =Math.abs(( (imgR[i][j] & 0xff) >> 16 | (imgG[i][j] & 0xff) >> 8 | (imgB[i][j] & 0xff))); cont+=1; } } } BufferedImage bufferImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); WritableRaster rast = (WritableRaster) bufferImg.getData(); rast.setPixels(0, 0, width, height, pixels); bufferImg.setData(rast); return bufferImg; } ```
2015/11/05
[ "https://Stackoverflow.com/questions/33550852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5530314/" ]
I think you are getting grey because the expression ``` Math.abs(( (imgR[i][j] & 0xff) >> 16 | (imgG[i][j] & 0xff) >> 8 | (imgB[i][j] & 0xff))); ``` does not depend on `band`, so your rgb values are all the same. The expression looks dodgy anyway because you normally use the left shift operator `<<` when packing rgb values into a single `int`. I don't know for sure, as I'm not familiar with the classes you are using, but I'm guessing something like this might work ``` for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { pixels[(((i*width)+j)*numBandas)] = imgR[i][j] & 0xFF; pixels[(((i*width)+j)*numBandas + 1)] = imgG[i][j] & 0xFF; pixels[(((i*width)+j)*numBandas + 2)] = imgB[i][j] & 0xFF; } } ```
50,588,967
I am trying to solve a problem given to me and it involves using basic loops, functions and conditions. I have been given the below: ``` // TODO: complete program console.log(calculate(4, "+", 6)); // Must show 10 console.log(calculate(4, "-", 6)); // Must show -2 console.log(calculate(2, "*", 0)); // Must show 0 console.log(calculate(12, "/", 0)); // Must show Infinity ``` and this is my attempt (not working of course). Can anyone give me a nudge of a pointer as to what I am doing wrong? ```js function calculate(n1, n2, n3) { let calc if n2 = "+" { (calc = +) }; else if n2 = "-" { (calc = -) }; else if n2 = "*" { (calc = * ) }; else { (calc = /) }; let acalc = (n1 + n2 + n3); return acalc; } console.log(calculate(4, "+", 6)); // Must show 10 console.log(calculate(4, "-", 6)); // Must show -2 console.log(calculate(2, "*", 0)); // Must show 0 console.log(calculate(12, "/", 0)); // Must show Infinity ```
2018/05/29
[ "https://Stackoverflow.com/questions/50588967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9865551/" ]
You can't set variables equal to operators. Your `if` blocks should look like this instead: ``` if (n2 == "+") { return parseInt(n1) + parseInt(n3); }; ``` Use `parseInt` if you are passing in strings instead of numbers
13,856,436
I'm developing a Java project using Eclipse, and Ant as a build tool. When I run "ant all" from the command line, my project builds without any errors, but on Eclipse I get many compilation errors. So I thought I'd copy Ant's Classpath onto my Eclipse Project's Build Path. Is there an Ant task/command to show that? Like "ant just show me your assembled classpath" or something?
2012/12/13
[ "https://Stackoverflow.com/questions/13856436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1264138/" ]
If you run Ant with the -verbose and -debug flags, you'll see all gory details of what javac is doing, including the classpath.
20,983,535
``` /* result 1 */ select Id, Name from Items /* result 2 */ select Id, Alias from ItemAliases where Id in ( select Id, Name from table abc ) ``` We use SQL Server 2008. Using the above example, it should be pretty straightforward what I'm trying to do. I need to return the results of query 1... and return the results of query 2. Query 2 however, needs to filter to only include records from result 1. Here is my attempt to show what I would like to end up with. ``` VAR A = ( select Id, Name from Items ) /* result 1 */ select A.* /* result 2 */ select Id, Alias from ItemAliases where Id in ( A.Id ) ```
2014/01/07
[ "https://Stackoverflow.com/questions/20983535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/704238/" ]
I think you just want to store Result1 and use it to compose Result2: ``` declare @Result1 table (Id int primary key, Name varchar(100)); insert into @Result1 -- store Result1 select Id, Name from Items --return Result1 select Id, Name from @Result1; --return Result2 using stored Result1 select Id, Alias from ItemAliases where Id in (select Id from @Result1); ```
38,464,876
When I update my Google Play dependencies in my Gradle file from version 8.4.0 to 9.2.1, I get the following error: > > Error:Failed to resolve: com.google.android.gms:play-services-measurement:9.2.1 > > > This was not an issue when using version 8.4.0. I tried to include it as an explicit dependency but makes no difference. The specific dependencies I’m using are: ``` compile 'com.google.android.gms:play-services-maps:9.2.1' compile 'com.google.android.gms:play-services-auth:9.2.1' compile 'com.google.android.gms:play-services-plus:9.2.1' ``` I would be grateful for any pointers on why this is happening.
2016/07/19
[ "https://Stackoverflow.com/questions/38464876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2815375/" ]
Try update google-services plugin in main `build.gradle` file ``` buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.0.0' classpath 'com.google.gms:google-services:3.0.0' } } ```
14,367,906
I trying to deploy an app to Heroku, but when I push my config.ru file I've got errors. Follow Heroku's log: ``` 2013-01-16T21:04:14+00:00 heroku[web.1]: Starting process with command `bundle exec rackup config.ru -p 29160` 2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:51:in `initialize' 2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/bin/rackup:19:in `<main>' 2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:51:in `instance_eval' 2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:137:in `start' 2013-01-16T21:04:16+00:00 app[web.1]: from /app/config.ru:in `new' 2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:304:in `wrapped_app' 2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/bin/rackup:4:in `<top (required)>' 2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:40:in `parse_file' 2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:200:in `app' 2013-01-16T21:04:16+00:00 app[web.1]: from /app/config.ru:in `<main>' 2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:40:in `eval' 2013-01-16T21:04:16+00:00 app[web.1]: /app/config.ru:1:in `block in <main>': undefined method `require' for #<Rack::Builder:0x0000000281d6a0 @run=nil, @map=nil, @use=[]> (NoMethodError) 2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:254:in `start' 2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/bin/rackup:19:in `load' 2013-01-16T21:04:17+00:00 heroku[web.1]: State changed from starting to crashed 2013-01-16T21:04:17+00:00 heroku[web.1]: Process exited with status 1 2013-01-16T21:04:18+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes= 2013-01-16T21:04:19+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/favicon.ico host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes= 2013-01-16T21:04:20+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/favicon.ico host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes= 2013-01-16T21:04:37+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes= 2013-01-16T21:04:06+00:00 heroku[web.1]: Unidling ``` Follow my config.ru file: ``` require './app' run Sinatra::Application ``` my main file is `app.rb` Any help?
2013/01/16
[ "https://Stackoverflow.com/questions/14367906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1472317/" ]
Regular expressions for HTML can be brittle to change, but a regex for this exact case would be; [`<A HREF="\(.*\)" .*>\(.*\)</A>`](http://refiddle.com/gjv)
1,853,771
Find the probability that the birth days of 6 different persons will fall in exactly two calendar months. Ans.is 341/(12^6) Here each person has 12 option So there are 6 persons .total no. Of ways 12^6 And out of 12 months 2 are randomly selected ..so $12$C$2$ B'day of 6 persons fall in 2 months in 2^6 ways. Therefore requird probability is ($12$C$2$ × 2^$6$)/12^$6$ But not geting appropriate ans.
2016/07/09
[ "https://math.stackexchange.com/questions/1853771", "https://math.stackexchange.com", "https://math.stackexchange.com/users/351895/" ]
I'm assuming you mean How do we find the derivative of $y= \frac{(4x^3 +8)^{\frac{1}{3}}}{(x+2)^5}$? The quotation rule: $\frac{f(x)}{g(x)}=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$ The chain rule: $f(g(x))=f'(g(x))g'(x)$ So to solve the question, we apply the quotation rule first Letting $$(4x^3 +8)^{\frac{1}{3}}=f(x)$$ $$(x+2)^5=g(x)$$ By applying the quotation rule, we get $y'=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$ You can use the chain rule to differentiate both $f(x)$ and $g(x)$ $f'(x)=\frac{1}{3}(4x^3+8)^{-\frac{2}{3}}12x^2$ $g'(x)=5(x+2)^4$ You can plug all of these into $y'=\frac{f'(x)g(x)-g'(x)f(x)}{g^2(x)}$ to get the derivative
55,356,622
I am trying to make a POST request to the Microsoft cognitive translate service, but get the following error: ``` Access to XMLHttpRequest at 'https://api.cognitive.microsofttranslator.com/post' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. core.js:15723 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "https://api.cognitive.microsofttranslator.com/post", ok: false, …} ``` I made a similar api POST request in node.js from the docs provided by Microsoft: <https://learn.microsoft.com/en-us/azure/cognitive-services/translator/quickstart-nodejs-translate> This worked totally fine, but when I tried in Angular I kept facing the same error since this morning. My end product will be a option to translate 90% of the page. Now I only want to translate a word to work it out further. If there is anything simpler to translate some specific text on the website I'm more than happy to switch to something else. My code so far: ``` import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { TranslatedText } from './TranslatedText'; import { v4 as uuid } from 'uuid'; @Injectable({ providedIn: 'root' }) export class TranslateService { readonly request = Request; readonly uuidv4 = uuid(); readonly subscriptionKey: string = 'MYTRANSLATIONKEY'; constructor(private http: HttpClient) { } options = { method: 'POST', baseUrl: 'https://api.cognitive.microsofttranslator.com/', url: 'translate', qs: { 'api-version': '3.0', 'to': 'de', }, headers: { 'Ocp-Apim-Subscription-Key': this.subscriptionKey, 'Content-type': 'application/json', 'X-ClientTraceId': this.uuidv4.toString() }, body: [{ 'text': 'Hello World!' }], json: true, }; readKey() { if (!this.subscriptionKey) { throw new Error('Environment variable for your subscription key is not set.') }; } getTranslation() { console.log("api call gelukt"); return this.http.post('https://api.cognitive.microsofttranslator.com/post', this.options.body, this.options); } } ``` ``` import { Component, OnInit } from '@angular/core'; import { TranslateService } from '../translate.service'; @Component({ selector: 'app-translate', templateUrl: './translate.component.html', styleUrls: ['./translate.component.css'] }) export class TranslateComponent implements OnInit { constructor(private translateService: TranslateService) { } ngOnInit() { } getTranslation() { return this.translateService.getTranslation().subscribe( (data ) => console.log(data)) } } ``` My expecting result was to get a json Something like this in the console: ``` [ { "detectedLanguage": { "language": "en", "score": 1.0 }, "translations": [ { "text": "Hallo Welt!", "to": "de" }, ] } ] ``` But I'm getting the error showed earlier
2019/03/26
[ "https://Stackoverflow.com/questions/55356622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11109765/" ]
Please check with the backend team to handle CORS origin. They need to enable CORS to avoid this error. It's not recommended to handle it in the browser or http level.
58,831,853
``` print("Please enter integers (then press enter key twice to show you're done):") s = input() #whatever you're inputting after the print first = True #What does this mean??? while s != "": #What does this mean??? lst = s.split() #split all your inputs into a list for x in lst: if first: #If its in ur lst? maxV = int(x) #then the max value will be that input as an integer first = False #What does this mean? else: if maxV < int(x): maxV = int(x) s= input() print(maxV) ``` I'm confused as to what first=True and first= False in this code, what does it mean to set a variable equal to true or false? Also confused as to what while s != "": means. Sorry, I'm a complete beginner, would be forever grateful if someone could help me
2019/11/13
[ "https://Stackoverflow.com/questions/58831853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12364974/" ]
I don't really know what programming language this is but with basic knowledge I can kinda tell you what these things mean. I hope it helps: ``` print("Please enter integers (then press enter key twice to show you're done):") s = input() #Here s becomes your input first = True #Here you set first as a boolean which can have the state true or false. In this example it gets the value True assigned while s != "": #While repeats a certain process and in this example it keeps this process going while s isn't empty lst = s.split() #splits all your inputs into a list <- you got that right for x in lst: if first: #It checks if first is true. If it is true it keeps going with the code right after the if maxV = int(x) #then the max value will be that input as an integer first = False #this sets a new value to first. which is false in this case else: if maxV < int(x): maxV = int(x) s= input() print(maxV) ``` Additionally you said you didn't understand the `!=`. `!=` is like `==` but the opposite. It means unequal. Therefore if you say something like `1 == 1` this is true, because 1 equals 1. If you say `1 != 2` this is true because 1 is **not** the same as 2.
44,320,604
I have a view like this: ``` Year | Month | Week | Category | Value | 2017 | 1 | 1 | A | 1 2017 | 1 | 1 | B | 2 2017 | 1 | 1 | C | 3 2017 | 1 | 2 | A | 4 2017 | 1 | 2 | B | 5 2017 | 1 | 2 | C | 6 2017 | 1 | 3 | A | 7 2017 | 1 | 3 | B | 8 2017 | 1 | 3 | C | 9 2017 | 1 | 4 | A | 10 2017 | 1 | 4 | B | 11 2017 | 1 | 4 | C | 12 2017 | 2 | 5 | A | 1 2017 | 2 | 5 | B | 2 2017 | 2 | 5 | C | 3 2017 | 2 | 6 | A | 4 2017 | 2 | 6 | B | 5 2017 | 2 | 6 | C | 6 2017 | 2 | 7 | A | 7 2017 | 2 | 7 | B | 8 2017 | 2 | 7 | C | 9 2017 | 2 | 8 | A | 10 2017 | 2 | 8 | B | 11 2017 | 2 | 8 | C | 12 ``` And I need to make a new view which needs to show average of value column (let's call it avg\_val) and the value from the max week of the month (max\_val\_of\_month). Ex: max week of january is 4, so the value of category A is 10. Or something like this to be clear: ``` Year | Month | Category | avg_val | max_val_of_month 2017 | 1 | A | 5.5 | 10 2017 | 1 | B | 6.5 | 11 2017 | 1 | C | 7.5 | 12 2017 | 2 | A | 5.5 | 10 2017 | 2 | B | 6.5 | 11 2017 | 2 | C | 7.5 | 12 ``` I have use window function, over partition by year, month, category to get the avg value. But how can I get the value of the max week of each month?
2017/06/02
[ "https://Stackoverflow.com/questions/44320604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8091329/" ]
Assuming that you need a month average and a value for the max week not the max value per month ``` SELECT year, month, category, avg_val, value max_week_val FROM ( SELECT *, AVG(value) OVER (PARTITION BY year, month, category) avg_val, ROW_NUMBER() OVER (PARTITION BY year, month, category ORDER BY week DESC) rn FROM view1 ) q WHERE rn = 1 ORDER BY year, month, category ``` or more verbose version without window functions ``` SELECT q.year, q.month, q.category, q.avg_val, v.value max_week_val FROM ( SELECT year, month, category, avg(value) avg_val, MAX(week) max_week FROM view1 GROUP BY year, month, category ) q JOIN view1 v ON q.year = v.year AND q.month = v.month AND q.category = v.category AND q.max_week = v.week ORDER BY year, month, category ``` Here is a [dbfiddle](http://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=b3e36972ff6b186c0c3c82e4a627dc4b) demo for both queries
39,931,342
I have got a string ``` $key1={331015EA261D38A7} $key2={9145A98BA37617DE} $key3={EF745F23AA67243D} ``` How do i split each of the keys based on "$" and the "next line" element? and then place it in an Arraylist? The output should look like this: Arraylist[0]: ``` $key1={331015EA261D38A7} ``` Arraylist[1]: ``` $key2={9145A98BA37617DE} ``` Arraylist[2]: ``` $key3={EF745F23AA67243D} ```
2016/10/08
[ "https://Stackoverflow.com/questions/39931342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6659196/" ]
If you just want to split by new line, it is as simple as : ``` yourstring.split("\n"): ```
1,486,009
I have the following norms: $$ \|f\|\_1=\int\_{t\_0}^{t\_1}\|f(t)\|\_2dt $$ $$ \|f\|\_2=\sqrt{\int\_{t\_0}^{t\_1}\|f(t)\|\_2^2dt} $$ I need to show their non-equivalence, i.e. that there do not exist numbers $a,b\in\mathbb R$, $a\ge b>0$ such that $b\|f\|\_2\le\|f\|\_1\le a\|f\|\_2$. I would like to do the proof by myself (don't show the full proof please). I am almost sure this has to be a proof by contradiction, so I somehow need to write a few inequalities that give something like this: $$ \begin{array}{rll} \|f\|\_1 & = & \int\_{t\_0}^{t\_1}\|f(t)\|\_2dt \\ & \le & ??? \\ & \vdots & \\ & \le & \text{something}\cdot\|f\|\_2 \\ \end{array} $$ and show that this "something" can take a value that would contradict the assumption that an $a$ exists. However, I do not know how to make the journey from $\|f\|\_1$ to $\|f\|\_2$ using inequalities, primarily due to the presence of the square root. Could you please help me get started? Thanks a lot!
2015/10/18
[ "https://math.stackexchange.com/questions/1486009", "https://math.stackexchange.com", "https://math.stackexchange.com/users/218257/" ]
**Hint**: Try to construct a sequence of functions $f\_n$ in the vector space you work in such that $\frac{||f\_n||\_1}{||f\_n||\_2} < \frac{1}{n}$. This will show that a constant $b > 0$ such that $b ||f||\_2 \leq ||f||\_1$ for **all** $f$ does not exist.
25,446,685
I have a simple tab system but I'm a bit stuck on exactly how to make this work. I'm using ng-repeat to spit out the tabs and the content and so far this is working fine. Here are my tabs: ``` <ul class="job-title-list"> <li ng-repeat="tab in tabBlocks"> <a href="javascript:;" ng-click="activeTab($index)">dummy content</a> </li> </ul> ``` And here's the repeated content which needs to match up to the tabs: ``` <div ng-repeat="content in contentBlocks"> <p>more dummy content</p> </div> ``` And finally, my function (the console log returns the correct indexes from the tabs) ``` $scope.activeTab = function(i) { $scope.selectedTab = i console.log($scope.selectedTab) } ``` Any suggestions on how I should go about this? I've looked into ng-show, ng-switch and ng-if to show and hide the appropriate content but I've been stuck on this for a while... Many thanks!
2014/08/22
[ "https://Stackoverflow.com/questions/25446685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768250/" ]
``` jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); ``` Now for a bit of explanation. The closest equivalent to as seen in the question is.. ``` jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ``` But that kills the entire JRE irrespective of other non-daemon threads that are running. If they are running, they should be shut down or cleaned up explicitly. If there are no other non-daemon threads running, `DISPOSE_ON_CLOSE` will dispose the current `JFrame` and end the virtual machine.
64,687,848
I have a data frame that includes comments from different people (so it can be written in any form they want). The sample data frame is shown below (this is only a sample and my original data set has more than 50000 rows): ``` structure(list(comment = c("3.22%-1ST $100K/1.15% BAL", "3.25% ON 1ST $100,000/1.1625% ON BAL", "3.225% 1ST 100K/1.1625 ON BAL", "3.22% 1ST 100K/1.15% ON BAL", "3.255% 1ST 100K/1.1625% ON BAL", "3.2% 1ST 100K/1.15% ON BAL", "3.22% ON 1ST 100K & 1.15% ON BALANCE", "3.255% 1ST 100K/1.1625% ON BAL", "3.22% ON 1ST 100K / 1.1625% ON BAL", "3.2% 1ST 100K/1.15% ON BAL", "3.2% 1ST 100K/1.15% ON BAL", "3.2% 1ST $100K + 1.1625% BALANCE", "3.255% ON 1ST $100K & 1.1625% ON BALANCE", "3.225% ON 1ST $100,000 AND 1.16% ON BALANCE", "3.255% ON FIRST $100,000 AND 1.1625% ON BALANCE", "$4000", "$7,500", "$6,000", "$5,000", "$6000.00", "$10,000 PLUS BONUS $10,000", "4-100/1.1625", "3.2% 1ST 100K/1.15% ON BAL", "3.2% ON 1ST $100,000 + 1.15% ON BAL", "THE GREATER $3,000 OR .5% OF SALE PRICE", "**3.255% ON THE 1ST $100,000 AND 1.1625% ON THE BALANCE" ), a = c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE)), row.names = c(NA, -26L), class = c("tbl_df", "tbl", "data.frame")) 1 3.22%-1ST $100K/1.15% BAL TRUE 2 3.25% ON 1ST $100,000/1.1625% ON BAL TRUE 3 3.225% 1ST 100K/1.1625 ON BAL TRUE 4 3.22% 1ST 100K/1.15% ON BAL TRUE 5 3.255% 1ST 100K/1.1625% ON BAL TRUE 6 3.2% 1ST 100K/1.15% ON BAL TRUE 7 3.22% ON 1ST 100K & 1.15% ON BALANCE TRUE 8 3.255% 1ST 100K/1.1625% ON BAL TRUE 9 3.22% ON 1ST 100K / 1.1625% ON BAL TRUE 10 3.2% 1ST 100K/1.15% ON BAL TRUE 11 ............................ .... ``` As you can see this data frame has no specific format and that makes it difficult to work with. **What I want to do:** I want to change all number like 3.255%, 3.2%, 3.22%, 4, etc (basically, numbers in a range of 0 to 5 in each of the comments to the same format like `x.yz%` format. **What are the challenges?** the main challenge here is that some rows don't start with numbers like $4000 or "THE GREATER $3,000 OR .5% OF SALE PRICE" which are obviously in a different format. One approach is to separate rows that start with a digit and label them with "TRUE" or "FALSE" for now. I wrote the command below(**not sure if this is a good idea, though!**): ``` df_com$a <- str_detect(df_com$comment, pattern = "^\\d") ``` However, using this we may miss a line like "THE GREATER $3,000 OR .5% OF SALE PRICE". This line should be changed to "THE GREATER $3,000 OR **.50**% OF SALE PRICE". Also, in order to replace number and round them, I followed the answer explained here: [round all float numbers in a string](https://stackoverflow.com/questions/38204034/round-all-float-numbers-in-a-string) and modified it in the form shown below to do the task: ``` gsubfn("(\\d\\w{1:3})", ~format(round(as.numeric(x), 2), nsmall=2), x) ``` However, this expression doesn't work. The expected result is something in this form: ``` 1 3.22%-1ST $100K/1.15% BAL TRUE 2 3.25% ON 1ST $100,000/1.16% ON BAL TRUE 3 3.23% 1ST 100K/1.16 ON BAL TRUE 4 3.22% 1ST 100K/1.15% ON BAL TRUE 5 3.26% 1ST 100K/1.16% ON BAL TRUE 6 3.20% 1ST 100K/1.15% ON BAL TRUE 7 3.22% ON 1ST 100K & 1.15% ON BALANCE TRUE 8 3.26% 1ST 100K/1.16% ON BAL TRUE 9 3.22% ON 1ST 100K / 1.16% ON BAL TRUE 10 3.20% 1ST 100K/1.15% ON BAL TRUE 11 ............................ .... ``` Any advice on how I can do this task?
2020/11/04
[ "https://Stackoverflow.com/questions/64687848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676462/" ]
In base R, this is a great place to use `gregexpr` and `regmatches`: ```r gre <- gregexpr("\\b?[0-9]*\\.[0-9]*(?=%)", df_com$comment, perl = TRUE) str(regmatches(df_com$comment, gre)) # List of 26 # $ : chr [1:2] "3.22" "1.15" # $ : chr [1:2] "3.25" "1.16" # $ : chr "3.23" # $ : chr [1:2] "3.22" "1.15" # $ : chr [1:2] "3.25" "1.16" # $ : chr [1:2] "3.20" "1.15" # $ : chr [1:2] "3.22" "1.15" # $ : chr [1:2] "3.25" "1.16" # $ : chr [1:2] "3.22" "1.16" # $ : chr [1:2] "3.20" "1.15" # $ : chr [1:2] "3.20" "1.15" # $ : chr [1:2] "3.20" "1.16" # $ : chr [1:2] "3.25" "1.16" # $ : chr [1:2] "3.23" "1.16" # $ : chr [1:2] "3.25" "1.16" # $ : chr(0) # $ : chr(0) # $ : chr(0) # $ : chr(0) # $ : chr(0) # $ : chr(0) # $ : chr(0) # $ : chr [1:2] "3.20" "1.15" # $ : chr [1:2] "3.20" "1.15" # $ : chr(0) # $ : chr [1:2] "3.25" "1.16" regmatches(df_com$comment, gre) <- lapply(regmatches(df_com$comment, gre), function(nums) { format(round(as.numeric(nums), 2), nsmall=2) }) ``` The result: ```r df_com # # A tibble: 26 x 2 # comment a # <chr> <lgl> # 1 3.22%-1ST $100K/1.15% BAL TRUE # 2 3.25% ON 1ST $100,000/1.16% ON BAL TRUE # 3 3.23% 1ST 100K/1.1625 ON BAL TRUE # 4 3.22% 1ST 100K/1.15% ON BAL TRUE # 5 3.25% 1ST 100K/1.16% ON BAL TRUE # 6 3.20% 1ST 100K/1.15% ON BAL TRUE # 7 3.22% ON 1ST 100K & 1.15% ON BALANCE TRUE # 8 3.25% 1ST 100K/1.16% ON BAL TRUE # 9 3.22% ON 1ST 100K / 1.16% ON BAL TRUE # 10 3.20% 1ST 100K/1.15% ON BAL TRUE # # ... with 16 more rows ``` I used the literal of `x.yz%`, which explains why there is a single `1.1625` unchanged in row 3.
17,635,381
I am new to triggers i have two tables with names ArefSms And tblSalesProd i want after an insert my trigger update ArefSms where tblSalesProd.SalesID=ArefSms.SalesID for this propose i write below code ``` USE [ACEDB] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER TRIGGER [dbo].[areftblSalesProd] ON [dbo].[tblSalesProd] AFTER INSERT AS Begin Try Update ArefSms set qt=inserted.ProdQty where ArefSms.SalesID=inserted.SalesID End Try Begin Catch End catch ``` but now i have error ``` Msg 4104, Level 16, State 1, Procedure areftblSalesProd, Line 9 The multi-part identifier "inserted.SalesID" could not be bound. ``` What can I do?
2013/07/14
[ "https://Stackoverflow.com/questions/17635381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2304094/" ]
You need to specify `inserted` in the `update` statement. It is a table reference: ``` Update ArefSms set qt=inserted.ProdQty from inserted where ArefSms.SalesID=inserted.SalesID; ```
9,071,174
As part of strengthening session authentication security for a site that I am building, I am trying to compile a list of the best ways to register a user's computer as a second tier of validation - that is in addition to the standard username/password login, of course. Typical ways of registering a user's computer are by setting a cookie and or IP address validation. As prevalent as mobile computing is, IP mapping is less and less a reliable identifier. Security settings and internet security & system optimization software can make it difficult to keep a cookie in place for very long. Are there any other methods that can be used for establishing a more reliable computer registration that doesn't require the user to add exceptions to the various cookie deleting software?
2012/01/30
[ "https://Stackoverflow.com/questions/9071174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/708034/" ]
Simply calling read doesn't guarantee that you will receive all the 63 bytes or that you receive the 63 bytes you were hoping for.. I would suggest that you somehow determine how much data you need to receive(send the data length first) and then put the recv function in a loop until you have all the data.. The send function(from the client) should be checked also.
43,985,851
If I'm using webpack, I can create a program using CommonJS module syntax ``` #File: src-client/entry-point.js helloWorld1 = require('./hello-world'); alert(helloWorld1.getMessage()); #File: src-client/hello-world.js var toExport = {}; toExport.getMessage = function(){ return 'Hello Webpack'; } module.exports = toExport; ``` I can also create a program using ES6/ES2015 module syntax. ``` #File: src-client/entry-point.js import * as helloWorld2 from './hello-world2'; alert(helloWorld2.getMessage()); #File: src-client/hello-world2.js var getMessage = function(){ return 'Hello ES2015'; }; export {getMessage}; ``` Both of the above programs compile and run (in browser) without issue. However, if I try to mix and match the syntax ``` #File: src-client/entry-point.js helloWorld1 = require('./hello-world'); import * as helloWorld2 from './hello-world2'; alert(helloWorld1.getMessage()); alert(helloWorld2.getMessage()); ``` Webpack itself will happily compile the program ``` $ ./node_modules/webpack/bin/webpack.js src-client/entry-point.js pub/bundle.js Hash: 1ce72fd037a8461e0509 Version: webpack 2.5.1 Time: 72ms Asset Size Chunks Chunk Names bundle.js 3.45 kB 0 [emitted] main [0] ./src-client/hello-world.js 110 bytes {0} [built] [1] ./src-client/hello-world2.js 80 bytes {0} [built] [2] ./src-client/entry-point.js 155 bytes {0} [built] ``` but when I run the program in my browser, I get the following error ``` Uncaught ReferenceError: helloWorld1 is not defined at Object.<anonymous> (bundle.js:101) at __webpack_require__ (bundle.js:20) at toExport (bundle.js:66) at bundle.js:69 ``` I didn't expect this to work (I'm not a monster), but it does raise the question of what, exactly, is going on. When webpack encounters conflicting module syntax like this -- what happens? Does the presence of an `import` keyword put webpack into "parse ES2015" mode? Is there a way to force webpack to treat certain files as ES2015 and others as CommonJS? i.e. is there a way for webpack to seamlessly handle a project with modules using multiple standards? Or is the general feeling that you shouldn't do this?
2017/05/15
[ "https://Stackoverflow.com/questions/43985851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4668/" ]
The presence of `import` automatically puts the module in [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode), as defined in the [Spec](https://www.ecma-international.org/ecma-262/6.0/#sec-strict-mode-code). In strict mode you're not allowed to use a variable that hasn't been defined, whereas in regular mode the variable will implicitly become a global variable. You try to assign the result of `require` to `helloWorld1` which was not previously defined. You need to declare that variable: ``` const helloWorld1 = require('./hello-world'); ``` Instead of `const` you may also use `let` or `var`.
1,439,713
I want to build an ant script that does exactly the same compilation actions on a Flash Builder 4 (Gumbo) project as the `Project->Export Release Build...` menu item does. My ant-fu is reasonably strong, that's not the issue, but rather I'm not sure exactly what that entry is doing. Some details: * I'll be using the 3.x SDK (say, 3.2 for the sake of specificity) to build this. * I'll be building on a Mac, and I can happily use ant, make, or some weird shell script stuff if that's the way you roll. * Any useful optimizations you can suggest will be welcome. * The project contains a few assets, MXML and actionscript source, and a couple of .swcs that are built into the project (not RSL'd) Can someone provide an ant build.xml or makefle that they use to build a release .swf file from a similar Flex project?
2009/09/17
[ "https://Stackoverflow.com/questions/1439713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23309/" ]
One quick way to know the compiler options is to add this tag into your compiler options: -dump-config your/drive/to/store/the/xmlfile.xml This will output the entire ant compiler options and you can copy off the parts you want to keep.
40,358,562
I wish to use connection pooling using NodeJS with MySQL database. According to docs, there are two ways to do that: either I explicitly get connection from the pool, use it and release it: ``` var pool = require('mysql').createPool(opts); pool.getConnection(function(err, conn) { conn.query('select 1+1', function(err, res) { conn.release(); }); }); ``` Or I can use it like this: ``` var mysql = require('mysql'); var pool = mysql.createPool({opts}); pool.query('select 1+1', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution); }); ``` If I use the second options, does that mean, that connections are automatically pulled from the pool, used and released? And if so, is there reason to use the first approach?
2016/11/01
[ "https://Stackoverflow.com/questions/40358562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2882245/" ]
Yes, the second one means that the pool is responsible to get the next free connection do a query on that and then release it again. You use this for *"one shot"* queries that have no dependencies. You use the first one if you want to do multiple queries that depend on each other. A connection holds certain states, like locks, transaction, encoding, timezone, variables, ... . Here an example that changes the used timezone: ``` pool.getConnection(function(err, conn) { function setTimezone() { // set the timezone for the this connection conn.query("SET time_zone='+02:00'", queryData); } function queryData() { conn.query( /* some query */, queryData); } function restoreTimezoneToUTC() { // restore the timezone to UTC (or what ever you use as default) // otherwise this one connection would use +02 for future request // if it is reused in a future `getConnection` conn.query("SET time_zone='+00:00'", releseQuery); } function releaseQuery() { // return the query back to the pool conn.release() } setTimezone(); }); ```
57,832,193
The footer disappears when trying to get the "back to top" to the right-hand side just above the footer. I want to try to get the button just above the footer. Before I implemented the "back to top" button I was also having difficulty with it not being aligned correctly, as it not covering the left-side of the page on the bottom. Also I've tried to find solutions to this but the ones I've found use javascript/jquery and I've got to make this using only html and css. Edit: I've removed the unnecessary stuff, left the table in, as I think that's what's causing the problem as it doesn't scale well on the smaller screens. Also forgot to mention earlier it also results in the navbar having space left over to the top-right corner, which is why I've left that in as well. ``` <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="test.css" type="text/css" rel="stylesheet"> <a name="top"></a> <div class="nav"> <input type="checkbox" id="nav-check"> <div class="nav-header"> <div class="nav-title"> <a href="index.html" class="active">Link1</a> </div> </div> <div class="nav-btn"> <label for="nav-check"> <span></span> <span></span> <span></span> </label> </div> <div class="nav-links"> <a href="#">Link2</a> <a href="#">Link3</a> <a href="#">Link4</a> </div> </div> <h1>Comments</h1> <table id = "table"> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td>html</td> <td>Element</td> <td>fdsfdddddddddddd ddddddd dffdfds fdfds</td> </tr> <tr> <td>html</td> <td>Element</td> <td>fdsfdddddddddddd ddddddd dffdfds fdfds</td> </tr> <tr> <td>html</td> <td>Element</td> <td>fdsfdddddddddddd ddddddd dffdfds fdfds</td> </tr> </table> </td> </tr> <div class="btopbutton"> <a href="#top">Back to top</a> <div> <div class="footer"> <p><span> Website | Website | Copyright 2019</span></p> <a href="#"> Link 1 </a> | <a href="#">Link 2</a> | <a href="#">Link 3</a> | <a href="#">Link 4</a></div> </div> </body></html> @charset "UTF-8"; /*set background for whole page*/ html { background-color: #26734d; scroll-behavior: smooth; margin: 0; padding: 0; width: 100%; height: 100%;} /*--start of nav bar--*/ * { box-sizing: border-box; } .nav { /* height: 50px;*/ width: 100%; background-color: #4d4d4d; position: relative; } .nav > .nav-header { display: inline; } .nav > .nav-header > .nav-title { display: inline-block; font-size: 22px; color: #fff; padding: 10px 10px 10px 10px; } .nav > .nav-btn { display: none; } .nav > .nav-links { display: inline; float: center; font-size: 18px; } .nav > .nav-links > a { display: inline-block; padding: 13px 10px 13px 10px; text-decoration: none; color: #efefef; text-transform: uppercase; } .nav > .nav-links > a:hover { font-weight: bold; /* background-color: rgba(0, 0, 0, 0.3);*/ } :any-link { color: #efefef; text-decoration: none; text-transform: uppercase; font-size: 18px; } :any-link:hover { font-weight: bold; cursor: pointer; } .nav > #nav-check { display: none; } /*--end of nav bar--*/ .heading1{ color:#FFFFFF; } /* Style the validation */ #validation{ text-align:center; padding: 10px 10px; } .footer { text-align: center; padding-top:20px; padding-bottom: 20px; background-color: #1B1B1B; color: #FFFFFF; text-transform: uppercase; font-weight: lighter; letter-spacing: 2px; border-top-width: 2px; padding: 2px; color:#ffffff; width: 100%; position: absolute; font-weight: 200; } /*back to top button*/ .btopbutton { position: fixed; bottom: 0; right: 0; text-align:right; } /*--table in comments section --*/ #table{ border: solid 1px black; border-collapse: collapse; width:100%; text-align: center; } #table th{ border: solid 1px black; border-collapse: collapse; background-color: inherit; } #table td{ border: solid 1px black; background-color: inherit; border-collapse: collapse; } /*--end of table in the comments --*/ div.desc { padding: 15px; text-align: center; } * { box-sizing: border-box; } .responsive { padding: 0 6px; float: left; width: 24.99999%; } @media only screen and (max-width: 700px) { .responsive { width: 49.99999%; margin: 6px 0; } } @media only screen and (max-width: 500px) { .responsive { width: 100%; } .clearfix:after { content: ""; display: table; clear: both; } /* Moved Content Below Header */ .content { margin-top:50px; } } @media (max-width:600px) { .nav > .nav-btn { display: inline-block; position: absolute; right: 0px; top: 0px; } .nav > .nav-btn > label { display: inline-block; width: 50px; height: 50px; padding: 13px; } .nav > .nav-btn > label:hover,.nav #nav-check:checked ~ .nav-btn > label { background-color: rgba(0, 0, 0, 0.3); } .nav > .nav-btn > label > span { display: block; width: 25px; height: 10px; border-top: 2px solid #eee; } .nav > .nav-links { display: block; width: 100%; background-color: #333; height: 0px; transition: all 0.3s ease-in; overflow-y: hidden; } .nav > .nav-links > a { display: block; width: 100%; } .nav > #nav-check:not(:checked) ~ .nav-links { height: 0px; } .nav > #nav-check:checked ~ .nav-links { height: auto; overflow-y: auto; } } @media (max-width:300px){ #table p{ width:100%; text-align: justify; } #table ul{ width: 58% } #table tr{ display: inline-flex; width: 100%; } #table th{ width: 100%; } } ```
2019/09/07
[ "https://Stackoverflow.com/questions/57832193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12028650/" ]
Using strongly typed datasets would make parts of this easier (Actually, they nearly always make all work with datatable and dataset easier; I would use them by default) I would perform the following steps: * Add a DataSet to your project * Add a table to it (open it in the visual designer, right click the surface, add a datatable) * Add your columns to the table and choose their data types (string, decimal etc) - right click the datatable and choose "add column" * Right click the prodCode column and set it to be the primary key * Set the Expression property of the Total column to be `[Qty] * [Price]` - it will now auto-calculate itself, so you don't need to do the calc in your code In your code: ``` string prodCode = txtProductCode.Text; decimal qty = Convert.ToInt32(txtQty.Text); decimal price = Convert.ToInt32(txtPrice.Text); //does the row exist? var ro = dt.FindByProdCode(prodCode); //the typed datatable will have a FindByXX method generated on whatever column(s) are the primary key if(ro != null){ ro.Price = price; //update the existing row ro.Qty += qty; } else { dt.AddXXRow(prodCode, qty, price); //AddXXRow is generated for typed datatables depending on the table name } ``` If you have a back end database related to these datatables, you life will get a lot easier if you connect your dataset to the database and have visual studio generate mappings between the dataset and the tables in the database. The TableAdapters it generates take the place of generic DataAdapters, and manage all the db connections, store the SQLs that retrieve and update the db etc.
185,728
I wrote a function in python to count the number of 1-bits in a sorted bit array. I'm basically using binary search but the code seems unnecessarily long and awkward. I did test it for several different cases and got the correct output but am looking to write a cleaner code if possible. Note: I want to use a binary-search inspired solution that theoretically takes O(lg n ) time. ``` def countOnes(arr): l, r = 0, len(arr)-1 while l <= r: mid = l + (r-l)/2 if mid == 0 and arr[mid] == 1: return len(arr) if mid == len(arr)-1 and arr[mid] == 0: return 0 if arr[mid] == 1 and arr[mid-1] == 0: return len(arr) - mid elif arr[mid] == 1 and arr[mid-1] == 1: r = mid - 1 elif arr[mid] == 0 and arr[mid+1] == 1: return len(arr) - (mid+1) else: l = mid + 1 print countOnes([0, 0, 0]) # got 0 print countOnes([0, 0, 1, 1]) # got 2 print countOnes([1, 1, 1, 1]) # got 4 print countOnes([0, 1, 1, 1]) # got 3 print countONes([1, 1, 1, 1, 1]) # got 5 ```
2018/01/22
[ "https://codereview.stackexchange.com/questions/185728", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/78739/" ]
I agree with your assessment of the code being *unnecessarily long and awkward*. It looks like the root cause is an opportunistic optimization. The bad news is that most of the secondary tests (like `arr[mid - 1] == 0` and `arr[mid - 1] == 1`) are bound to fail, so not only they contribute to awkwardness of the code - they also hurt the performance (by about a factor of 2, if I am not mistaken). I recommend to keep it simple, and test only what is necessary: ``` l, r = 0, len(arr) while l < r: mid = l + (r - l) // 2 if arr[mid] == 1: r = mid else: l = mid + 1 return len(arr) - l ``` Notice that working on a semi-open range (that is, `mid` is *beyond* the range) also makes it cleaner.
46,339
I'm running F17 and inside of `yum.repos.d`. I see multiple repos listed like `adobe-linux-1386.repo`, `fedora.repo`, `google-chrome.repo`, etc. When I `yum install` are some files being downloaded from multiple different repos or all from one?
2012/08/26
[ "https://unix.stackexchange.com/questions/46339", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/22122/" ]
Most of the repositories specify a `mirrorlist` in their configuration file. When present, `yum` will select one or more of the mirrors provided by the list. Repos that don't have mirrors will have `baseurl` instead of `mirrorlist`. When downloading multiple packages, yum can download from multiple sites in parallel, though this isn't always obvious in the terminal unless you watch very carefully.
35,045,808
The problem I am facing is that, given a list and a guard condition, I must verify if every element in the list passes the guard condition. If even one of the elements fails the guard check, then the function should return `false`. If all of them pass the guard check, then the function should return `true`. The restriction on this problem is that **I can only use a single return statement**. My code: ``` def todos_lista(lista, guarda): for x in lista: return(False if guarda(x)==False else True) ```
2016/01/27
[ "https://Stackoverflow.com/questions/35045808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5588032/" ]
You should use [all](https://docs.python.org/2/library/functions.html#all): ``` def todos_lista(lista, guarda): return all(guarda(x) for x in lista) ``` Or in a more functional way: ``` def todos_lista(lista, guarda): return all(map(guarda, lista)) ``` For example for range 0 to 9 (`range(10)`): ``` >>> all(x < 10 for x in range(10)) True >>> all(x < 9 for x in range(10)) False >>> all(map(lambda x: x < 9, range(10))) False >>> all(map(lambda x: x < 10, range(10))) True ```
10,972,246
I've built a site <http://ucemeche.weebly.com> , Now I want to transfer it on other server. <http://Weebly.com> provides a function to download whole site in zip format that I've done. But problem is when I am browsing that downloaded site the slide shows, photo gallery etc are not working in as working in live site. Perhaps it is related to java script. Why is it happening ? What is the solution ?
2012/06/10
[ "https://Stackoverflow.com/questions/10972246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1447820/" ]
Check the paths of the javascripts. You might be missing some scripts or you do not include them properly. Check the error console in your browser. Most likely it will show you what's wrong.
38,448,193
I tried doing this in python, but I get an error: ``` import numpy as np array_to_filter = np.array([1,2,3,4,5]) equal_array = np.array([1,2,5,5,5]) array_to_filter[equal_array] ``` and this results in: ``` IndexError: index 5 is out of bounds for axis 0 with size 5 ``` What gives? I thought I was doing the right operation here. I am expecting that if I do ``` array_to_filter[equal_array] ``` That it would return ``` np.array([1,2,5]) ``` If I am not on the right track, how would I get it to do that?
2016/07/19
[ "https://Stackoverflow.com/questions/38448193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4054573/" ]
The regex: <http://regexr.com/3dr56> Will match any nodes that consist of say the following: `<div>hello world</div>` Provided that the parameters passed to the function: ```js function removeNode(str, nodeName) { var pattern = '<'+nodeName+'>[\\s\\w]+<\/'+nodeName+'>'; var regex = new RegExp(pattern, 'gi'); return str.replace(regex, '').replace(/^\s*[\r\n]/gm, ''); } console.log("Node: <div>hello world</div>"); var str = removeNode("hello world", "div"); console.log("String returned: " + str); ``` are: Node match: `<div>hello world</div>` `removeNode("hello world", "div");` will return: `hello world` The function itself will return the `string` within the node. More info can be found here about [Regular Expressions](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions).
21,344,684
I've been wrestling with this for several days and have extensively dug through StackOverflow and various other sites. I'm literally drawing a blank. I'm trying to get a single result back from my stored procedure. Here's my stored procedure: ``` ALTER PROC [dbo].[myHelper_Simulate] @CCOID nvarchar(100), @RVal nvarchar OUTPUT AS DECLARE @UserID int DECLARE @GUID uniqueidentifier SELECT @UserID = UserID FROM [User] WHERE CCOID = @CCOID AND deleted = 0 SELECT @GUID = newid() IF @UserID > 0 BEGIN INSERT [Audit] ([GUID], Created, UserID, ActionType, Action, Level) VALUES (@GUID, getdate(), @UserID, 'Authentication', 'Test Authentication', 'Success') SELECT @RVal = 'http://www.ttfakedomain.com/Logon.aspx?id=' + CAST(@GUID AS nvarchar(50)) RETURN END ELSE SELECT @RVal = 'Couldn''t find a user record for the CCOID ' + @CCOID RETURN GO ``` Originally the procedure was written to print out the result. I've added the `@RVal` and the `RETURN` in an attempt to get the value to pass back to my C# code. Here's my C# routine (`svrConn` has already been connected to the database): ``` private void btnSimulate_MouseClick(object sender, MouseEventArgs e) { SqlCommand cmd = new SqlCommand(); cmd.Connection = svrConn; object result = new object(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + tDatabase + "].[dbo].myHelper_Simulate"; cmd.Parameters.Add(new SqlParameter("@CCOID", txtDUserCCOID.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@RVal", "")); cmd.Parameters.Add(new SqlParameter("RETURN_VALUE", SqlDbType.NVarChar)).Direction = ParameterDirection.ReturnValue; try { result = cmd.ExecuteScalar(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } if (result != null) { tString = result.ToString(); MessageBox.Show(tString); } } ``` The problem is that `result` is coming back null. I'm not sure if it's due to the stored procedure or how I'm setting my parameters and calling `ExecuteScalar`.
2014/01/25
[ "https://Stackoverflow.com/questions/21344684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/693895/" ]
[SP return values](http://technet.microsoft.com/en-us/library/ms174998.aspx) are integers and are meant for error code. The correct way is to use `OUTPUT` parameter. You are assigning it correctly in the SP, you don't need the return statements. In your C# code check the value after execution. Use `ExecuteNonQuery` as there is no result set from the SP. ``` var rval = new SqlParameter("@RVal", SqlDbType.NVarChar); rval.Direction = ParameterDirection.Output; cmd.Parameters.Add(rval); cmd.ExecuteNonQuery(); result = rval.Value; ```
61,015,445
I'm using [custom-elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) aka web-components within [Preact](https://preactjs.com/). The problem is that Typescript complains about elements not being defined in `JSX.IntrinsicElements` - in this case a `check-box` element: ```html <div className={styles.option}> <check-box checked={this.prefersDarkTheme} ref={this.svgOptions.darkTheme}/> <p>Dark theme</p> </div> ``` Error message (path omitted): ``` ERROR in MyComponent.tsx [tsl] ERROR in MyComponent.tsx(50,29) TS2339: Property 'check-box' does not exist on type 'JSX.IntrinsicElements'. ``` I came across the following, unfortunately not working, possible solutions: 1. <https://stackoverflow.com/a/57449556/7664765> *- It's an answer not really realted to the question but it covered my problem* I've tried adding the following to my `typings.d.ts` file: ```js import * as Preact from 'preact'; declare global { namespace JSX { interface IntrinsicElements { 'check-box': any; // The 'any' just for testing purposes } } } ``` My IDE grayed out the import part and `IntrinsicElements` which means it's not used (?!) and it didn't worked anyway. I'm still getting the same error message. 2. <https://stackoverflow.com/a/55424778/7664765> *- Also for react, I've tried to "convert" it to preact and I got the same results as for 1.* I've even found a [file](https://github.com/GoogleChromeLabs/squoosh/blob/master/src/custom-els/RangeInput/missing-types.d.ts) maintained by google in the [squoosh](https://github.com/GoogleChromeLabs/squoosh) project where they did the following to "polyfill" the support: > > In the same folder as the component a `missing-types.d.ts` file with the following content, basically the same setup I have but with a `index.ts` file instead of `check-bock.ts` and they're using an older TS version `v3.5.3`: > > > ```js declare namespace JSX { interface IntrinsicElements { 'range-input': HTMLAttributes; } } ``` I'm assuming their build didn't fail so how does it work and how do I properly define custom-elements to use them within preact / react components? I'm currently using `[email protected]` and `[email protected]`.
2020/04/03
[ "https://Stackoverflow.com/questions/61015445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7664765/" ]
Okay I managed to solve it using [module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation): ``` declare module 'preact/src/jsx' { namespace JSXInternal { // We're extending the IntrinsicElements interface which holds a kv-list of // available html-tags. interface IntrinsicElements { 'check-box': unknown; } } } ``` Using the `HTMLAttributes` interface we can tell JSX which attributes are available for our custom-element: ``` // Your .ts file, e.g. index.ts declare module 'preact/src/jsx' { namespace JSXInternal { import HTMLAttributes = JSXInternal.HTMLAttributes; interface IntrinsicElements { 'check-box': HTMLAttributes<CheckBoxElement>; } } } // This interface describes our custom element, holding all its // available attributes. This should be placed within a .d.ts file. declare interface CheckBoxElement extends HTMLElement { checked: boolean; } ```
1,668,531
What are some key bindings that aren't included?
2009/11/03
[ "https://Stackoverflow.com/questions/1668531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/178019/" ]
You can find the complete list of limitations in MonoTouch at [Xamarin](http://docs.xamarin.com/ios/about/limitations). A short list of .NET features not available in MonoTouch: * The Dynamic Language Runtime (DLR) * Generic Virtual Methods * P/Invokes in Generic Types * Value types as Dictionary Keys * System.Reflection.Emit * System.Runtime.Remoting
67,344,024
```py @app.route('/') def index(): return render_template("home.html") ``` My folder structure looks like this ``` tree-/ -static/ -styles.css -templates/ -home.html -app.py ``` I get **Not Found** The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. On the browser and ``` 127.0.0.1 - - [01/May/2021 09:41:47] "GET / HTTP/1.1" 404 - ``` In the debugger Have looked at other related posts saying stuff about trailing slashes and it doesn't look like its making a difference, either I access <http://127.0.0.1:5000> or <http://127.0.0.1:5000/> I run my application using ```py app = Flask(__name__) if __name__ == '__main__': app.run() ``` I get ```py * Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) ``` ```py from flask import Flask, redirect, url_for, render_template app = Flask(__name__) if __name__ == '__main__': app.run() @app.route('/') def index(): return "Hello World" ```
2021/05/01
[ "https://Stackoverflow.com/questions/67344024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15778393/" ]
Use conditional aggregation with a `having` clause: ``` select customer_id from t where location in ('Santa Clara', 'Milpitas') group by customer_id having max(store_entry) filter (where location = 'Santa Clara') > min(store_entry) filter (where location = 'Milpitas'); ``` Your statement is that the customer when to *after* Santa Clara *after* Milpitas. This leaves open the possibility that the customer visited both locations multiple times. To meet the condition as stated, you need to know that some visit to Santa Clara was later than some visit to Milpitas (at least that is how I interpret the question). Well, that is true if the *lastest* visit to Santa Clara was after the *earliest* visit to Milpitas.
32,250,035
I have a multi-dimensional list as like below ``` multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]] ``` How can I get below results fast: ``` [1,2]: count 1 times [3,4,5]: count 2 times [5,6]: count 3 times ``` and also get the unique multi-dimensional list (remove duplicates) : ``` multi_list = [[1,2],[3,4,5],[5,6]] ``` Thanks a lot.
2015/08/27
[ "https://Stackoverflow.com/questions/32250035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4737273/" ]
You can use tuples which are hashable and [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter): ``` >>> multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]] >>> multituples = [tuple(l) for l in multilist] >>> from collections import Counter >>> tc = Counter(multituples) >>> tc Counter({(5, 6): 3, (3, 4, 5): 2, (1, 2): 1}) ``` To get the set of elements you just need the keys: ``` >>> tc.keys() dict_keys([(1, 2), (3, 4, 5), (5, 6)]) ```
34,493,008
I need to use all the classes in one project in another. I tried adding the references, clicked on the project tab but I can't see the `.cs` or `.sln` files or any other files, just the exe in the debug folder and the `.vshost` file and the manifest file. What file do I need to reference in the project?
2015/12/28
[ "https://Stackoverflow.com/questions/34493008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5717987/" ]
File > Open > Project/Solution > Add to Solution (A little checkbox in the file dialog) then click the .sln you want
24,377,354
I'm struggling to understand what this code does ``` ldi r20, 80 loop: asr r20 brsh loop nop ``` What is this code doing and how many clock cycles does this code take to execute?
2014/06/24
[ "https://Stackoverflow.com/questions/24377354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3603183/" ]
using static yournamespace.yourclassname; then call the static class method without class name; Example: Class1.cs ``` namespace WindowsFormsApplication1 { class Utils { public static void Hello() { System.Diagnostics.Debug.WriteLine("Hello world!"); } } } ``` Form1.cs ``` using System.Windows.Forms; using static WindowsFormsApplication1.Utils; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); Hello(); // <====== LOOK HERE } } } ```
58,106,488
Say I have a `Dockerfile` that will run a Ruby on Rails app: ``` FROM ruby:2.5.1 # - apt-get update, install nodejs, yarn, bundler, etc... # - run yarn install, bundle install, etc... # - create working directory and copy files # .... CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"] ``` From my understanding, a container is an immutable running instance of an image and a set of runtime options (e.g. port mappings, volume mappings, networks, etc...). So if I build and start a container from the above file, I'll get something that executes the default `CMD` above (`rails server`) ``` docker build -t myapp_web:latest docker create --name myapp_web -p 3000:3000 -v $PWD:/app -e RAILS_ENV='production' myapp_web:latest docker start myapp_web ``` Great, so now it's running `rails server` in a container that has a `CONTAINER_ID`. But lets say tomorrow I want to run `rake db:migrate` because I updated something. How do I do that? 1. I can't use `docker exec` to run it in that container because `db:migrate` will fail while `rails server` is running 2. If I stop the `rails server` (and therefore the container) I have to create a *new container* with the same runtime options but a different command (`rake db:migrate`), which creates a new `CONTAINER_ID`. And then after runs that I have to restart my original container that runs `rails server`. Is #2 just something we have to live with? Each new rake task I run that requires `rails server` to be shut down will have to create a new CONTAINER and these pile up over time. Is there a more "proper" way to run this? Thanks! *EDIT*: If #2 is the way to go, is there an easy way to create a new container from an existing container so I can copy over all the runtime configs and just change the command?
2019/09/25
[ "https://Stackoverflow.com/questions/58106488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2490003/" ]
You have to capture the event in your callback and get the value from it ``` sendData = e => { this.props.parentCallback(e.target.value) } ``` And change `onClick` to `onChange`
2,864,016
I have some troubles with ssl using httpclient on android i am trying to access self signed certificate in details i want my app to trust all certificates ( i will use ssl only for data encryption). First i tried using this guide <http://hc.apache.org/httpclient-3.x/sslguide.html> on Desktop is working fine but on android i still got javax.net.ssl.SSLException: Not trusted server certificate. After searching in google i found some other examples how to enable ssl. <http://groups.google.com/group/android-developers/browse_thread/thread/62d856cdcfa9f16e> - Working when i use URLConnection but with HttpClient still got the exception. <http://www.discursive.com/books/cjcook/reference/http-webdav-sect-self-signed.html> - on Desktop using jars from apache is working but in android using included in SDK classes can't make it work. <http://mail-archives.apache.org/mod_mbox/hc-httpclient-users/200808.mbox/%3C1218824624.6561.14.camel@ubuntu%3E> - also get the same exception So any ideas how can i trust all certificates on android using HttpClient
2010/05/19
[ "https://Stackoverflow.com/questions/2864016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184601/" ]
If you happen to look at the code of DefaultHttpClient, it looks something like this: ``` @Override protected ClientConnectionManager createClientConnectionManager() { SchemeRegistry registry = new SchemeRegistry(); registry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register( new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager connManager = null; HttpParams params = getParams(); ... } ``` Notice the mapping of https scheme to org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory(). You can create a custom implementation for `org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory` interface (<http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.html>) wherein, you can create `java.net.SSLSocket` with a custom `TrustManager` that accepts all certificate. You may want to look into JSSE for more details at <http://java.sun.com/j2se/1.4.2/docs/guide/security/jsse/JSSERefGuide.html>
4,987,429
I'm trying to make an array of hashes. This is my code. The $1, $2, etc are matched from a regular expression and I've checked they exist. **Update:** Fixed my initial issue, but now I'm having the problem that my array is not growing beyond a size of 1 when I push items onto it... **Update 2:** It is a scope issue, as the @ACLs needs to be declared outside the loop. Thanks everyone! ``` while (<>) { chomp; my @ACLs = (); #Accept ACLs if($_ =~ /access-list\s+\d+\s+(deny|permit)\s+(ip|udp|tcp|icmp)\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(\s+eq (\d+))?/i){ my %rule = ( action => $1, protocol => $2, srcip => $3, srcmask => $4, destip => $5, destmask => $6, ); if($8){ $rule{"port"} = $8; } push @ACLs, \%rule; print "Got an ACL rule. Current number of rules:" . @ACLs . "\n"; ``` The array of hashes doesn't seem to be getting any bigger.
2011/02/13
[ "https://Stackoverflow.com/questions/4987429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/113705/" ]
You are pushing `$rule`, which does not exist. You meant to push a reference to `%rule`: ``` push @ACLs, \%rule; ``` Always start your programs with `use strict; use warnings;`. That would have stopped you from trying to push `$rule`. **Update:** In Perl, an array can only contain scalars. The way complex data structures are constructed is by having an array of hash references. Example: ``` my %hash0 = ( key0 => 1, key1 => 2 ); my %hash1 = ( key0 => 3, key1 => 4 ); my @array_of_hashes = ( \%hash0, \%hash1 ); # or: = ( { key0 => 1, key1 => 2 }, { key0 => 3, key1 => 4 ] ); print $array_of_hashes[0]{key1}; # prints 2 print $array_of_hashes[1]{key0}; # prints 3 ``` Please read the [Perl Data Structures Cookbook](http://perldoc.perl.org/perldsc.html).
507,894
Is it safe if my server will create a SSH key pair for my client? Scenario: I(server admin) will create a ssh key pair and put public key into authorized\_keys and give the private key to client so he can access my sftp server.
2019/03/22
[ "https://unix.stackexchange.com/questions/507894", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/343037/" ]
Quick $0.02 because I've got to get ready for work: Assuming this server isn't protecting actual banks or national security-level secrecy, you're fine. About the only potential risk I can imagine from this is if a hostile third party intercepted enough of those private keys and the exact time they were generated, they could use that to make predictions about the state and algorhithm of the server's random number generator, which might be useful in some very sophisticated attacks. ... Of course, if they can intercept that many of your private keys you have *much bigger problems already*. The safest thing to do would be to let the client generate the keypair and use a *trusted channel* to send you the public key for inclusion into the `authorized_keys` file, but if that isn't an option for whatever reason, your main worry is going to be how to securely get the private key to the recipient and *only* the intended recipient.
55,093,954
I am new to Spring and Spring Boot and am working through a book that is full of missing information. I have a taco class: ``` public class Taco { ... @Size(min=1, message="You must choose at least 1 ingredient") private List<Ingredient> ingredients; ... } ``` As you can see `ingredients` is of type `List<Ingredient>` and that is the problem, it used to be of type `List<String>` but that was before I started saving data in the database, now it must be `List<Ingredient>` which breaks the whole thing. In the contoller I have the following (among other things, I think this is the only required code for the problem at hand but if you need more let me know): ``` @ModelAttribute public void addIngredientsToModel(Model model) { List<Ingredient> ingredients = new ArrayList<>(); ingredientRepo.findAll().forEach(i -> ingredients.add(i)); Type[] types = Ingredient.Type.values(); for (Type type : types) { model.addAttribute(type.toString().toLowerCase(), filterByType(ingredients, type)); } } private List<Ingredient> filterByType(List<Ingredient> ingredients, Type type) { return ingredients .stream() .filter(x -> x.getType() .equals(type)) .collect(Collectors.toList()); } ``` And finally in my thymeleaf file I have: ``` <span class="text-danger" th:if="${#fields.hasErrors('ingredients')}" th:errors="*{ingredients}"> </span> ``` Which causes the error: ``` thymeleaf Failed to convert property value of type java.lang.String to required type java.util.List ``` Once again, when `private List<Ingredient> ingredients;` was `private List<String> ingredients;` it worked, but now it must be `private List<Ingredient> ingredients;` because of the way it is saved in the database but it breaks at this point, how to fix it?
2019/03/11
[ "https://Stackoverflow.com/questions/55093954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9949924/" ]
I met the same problem, what we need here is a converter. ``` package tacos.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import tacos.Ingredient; import tacos.data.IngredientRepository; @Component public class IngredientByIdConverter implements Converter<String, Ingredient> { private IngredientRepository ingredientRepo; @Autowired public IngredientByIdConverter(IngredientRepository ingredientRepo) { this.ingredientRepo = ingredientRepo; } @Override public Ingredient convert(String id) { return ingredientRepo.findOne(id); } } ```
7,921,457
hi have a template with a form and many inputs that pass some data trough a POST request to a view, that process them and send the result to another template. in the final template, if i use the browser back button to jump to the first view, i can see again old data. i refresh the page and i insert new data, i submit again but some old data remain when i see the final view. the problem remain even if i restart the debug server. how can i prevent it? it seems that there's some data-caching that i can solve only flushing browser cache. this is the view code: <http://dpaste.com/640956/> and the first template code: <http://dpaste.com/640960/> any idea? tnx - luke
2011/10/27
[ "https://Stackoverflow.com/questions/7921457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/998967/" ]
You're allocating a huge array in stack: ``` int prime[2000000]={}; ``` Four bytes times two million equals eight megabytes, which is often the maximum stack size. Allocating more than that results in segmentation fault. You should allocate the array in heap, instead: ``` int *prime; prime = malloc(2000000 * sizeof(int)); if(!prime) { /* not enough memory */ } /* ... use prime ... */ free(prime); ```
58,889,280
How to run Ruta scripts from command line? I tried this but not sure if this is right command. `javac DataExtraction.ruta` Error : `error: Class names, 'DataExtraction.ruta', are only accepted if annotation processing is explicitly requested`
2019/11/16
[ "https://Stackoverflow.com/questions/58889280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5894701/" ]
You are taking the wrong argument from the function parameter and should remove the `return` from `else` statement: Correct code will be: ```py import os def files(): files = os.listdir() file_found_flag = False for file in files: if file.lower().endswith('.jpg'): name= Dict['jpg'] name(file) file_found_flag = True elif file.lower().endswith('.pdf'): e= Dict['pdf'] e(file) file_found_flag = True elif file.lower().endswith('.xlsx'): f= Dict['xlsx'] f(file) file_found_flag = True if not file_found_flag: print('no file found') def jpg(file): print('image file found {}'.format(file)) def pdf(file): print('pdf file found {}'.format(file)) def xlsx(file): print('excel file found {}'.format(file)) Dict={"jpg":jpg, "pdf":pdf,"xlsx":xlsx } files() ```
81,929
I have acquired a lot of nice blue and green equipments ~lvl 20. I have no use for these since my class can't equip them. Should I just npc these or salvage them? What is the most profitable way?
2012/08/28
[ "https://gaming.stackexchange.com/questions/81929", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/27998/" ]
The most profitable way to get rid of rare equipment is often the Black Lion Trading Post. For common equipment, the trade price is not even high enough to account for the cost to post the item. In those cases, it is more profitable to just sell them to a merchant. I would just sell them to a merchant unless you really need the materials that they are composed of, the essences of luck, or are working on the monthly salvages achievement. Salvaging armor pieces usually nets less value than simply selling them.
34,479,693
*I am new to StackOverflow so please correct me if there is a better way to post a question which is a specific case of an existing question.* Alberto Barrera answered [How does one seed the random number generator in Swift?](https://stackoverflow.com/questions/25895081/how-does-one-seed-the-random-number-generator-in-swift) with ``` let time = UInt32(NSDate().timeIntervalSinceReferenceDate) srand(time) print("Random number: \(rand()%10)") ``` which is perfect generally, but when I try it in [The IBM Swift Sandbox](http://swiftlang.ng.bluemix.net/#/repl) it gives the same number sequence every run, at least in the space of a half hour. ``` import Foundation import CoreFoundation let time = UInt32(NSDate().timeIntervalSinceReferenceDate) srand(time) print("Random number: \(rand()%10)") ``` At the moment, every Run prints 5. Has anyone found a way to do this in the IBM Sandbox? I have found that random() and srandom() produce a different number sequence but similarly are the same each Run. I haven't found arc4random() in Foundation, CoreFoundation, Darwin, or Glibc. *As an aside, I humbly suggest someone with reputation above 1500 creates a tag IBM-Swift-Sandbox.*
2015/12/27
[ "https://Stackoverflow.com/questions/34479693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5646134/" ]
This was an issue with the way we implemented server-side caching in the Sandbox; non-deterministic code would continually return the same answer even though it should not have. We've disabled it for now, and you should be getting different results with each run. We're currently working on better mechanisms to ensure the scalability of the Sandbox. I'll see about that tag, as well!
56,955,320
I have a JSON file which contains text like this ``` .....wax, and voila!\u00c2\u00a0At the moment you can't use our ... ``` My simple question is how CONVERT (not remove) these \u codes to spaces, apostrophes and e.t.c...? **Input:** a text file with `.....wax, and voila!\u00c2\u00a0At the moment you can't use our ...` **Output:** `.....wax, and voila!(converted to the line break)At the moment you can't use our ...` Python code ``` def TEST(): export= requests.get('https://sample.uk/', auth=('user', 'pass')).text with open("TEST.json",'w') as file: file.write(export.decode('utf8')) ``` What I have tried: * Using .json() * any different ways of combining .encode().decode() and e.t.c. **Edit 1** When I upload this file to BigQuery I have - `Â` symbol **Bigger Sample:** ``` { "xxxx1": "...You don\u2019t nee...", "xxxx2": "...Gu\u00e9rer...", "xxxx3": "...boost.\u00a0Sit back an....", "xxxx4": "\" \u306f\u3058\u3081\u307e\u3057\u3066\"", "xxxx5": "\u00a0\n\u00a0", "xxxx6": "It was Christmas Eve babe\u2026", "xxxx7": "It\u2019s xxx xxx\u2026" } ``` Python code: ``` import json import re import codecs def load(): epos_export = r'{"xxxx1": "...You don\u2019t nee...","xxxx2": "...Gu\u00e9rer...","xxxx3": "...boost.\u00a0Sit back an....","xxxx4": "\" \u306f\u3058\u3081\u307e\u3057\u3066\"","xxxx5": "\u00a0\n\u00a0","xxxx6": "It was Christmas Eve babe\u2026","xxxx7": "It\u2019s xxx xxx\u2026"}' x = json.loads(re.sub(r"(?i)(?:\\u00[0-9a-f]{2})+", unmangle_utf8, epos_export)) with open("TEST.json", "w") as file: json.dump(x,file) def unmangle_utf8(match): escaped = match.group(0) # '\\u00e2\\u0082\\u00ac' hexstr = escaped.replace(r'\u00', '') # 'e282ac' buffer = codecs.decode(hexstr, "hex") # b'\xe2\x82\xac' try: return buffer.decode('utf8') # '€' except UnicodeDecodeError: print("Could not decode buffer: %s" % buffer) if __name__ == '__main__': load() ```
2019/07/09
[ "https://Stackoverflow.com/questions/56955320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11506172/" ]
I have made this crude UTF-8 unmangler, which appears to solve your messed-up encoding situation: ``` import codecs import re import json def unmangle_utf8(match): escaped = match.group(0) # '\\u00e2\\u0082\\u00ac' hexstr = escaped.replace(r'\u00', '') # 'e282ac' buffer = codecs.decode(hexstr, "hex") # b'\xe2\x82\xac' try: return buffer.decode('utf8') # '€' except UnicodeDecodeError: print("Could not decode buffer: %s" % buffer) ``` Usage: ``` broken_json = '{"some_key": "... \\u00e2\\u0080\\u0099 w\\u0061x, and voila!\\u00c2\\u00a0\\u00c2\\u00a0At the moment you can\'t use our \\u00e2\\u0082\\u00ac ..."}' print("Broken JSON\n", broken_json) converted = re.sub(r"(?i)(?:\\u00[0-9a-f]{2})+", unmangle_utf8, broken_json) print("Fixed JSON\n", converted) data = json.loads(converted) print("Parsed data\n", data) print("Single value\n", data['some_key']) ``` It uses regex to pick up the hex sequences from your string, converts them to individual bytes and decodes them as UTF-8. For the sample string above (I've included the 3-byte character `€` as a test) this prints: ``` Broken JSON {"some_key": "... \u00e2\u0080\u0099 w\u0061x, and voila!\u00c2\u00a0\u00c2\u00a0At the moment you can't use our \u00e2\u0082\u00ac ..."} Fixed JSON {"some_key": "... ’ wax, and voila!  At the moment you can't use our € ..."} Parsed data {'some_key': "... ’ wax, and voila!\xa0\xa0At the moment you can't use our € ..."} Single value ... ’ wax, and voila!  At the moment you can't use our € ... ``` The `\xa0` in the "Parsed data" is caused by the way Python outputs dicts to the console, it still is the actual non-breaking space.
2,209,575
I have a puzzling problem -- it seems like it should be so easy to do but somehow it is not working. I have an object called Player. The Manager class has four instances of Player: ``` @interface Manager { Player *p1, *p2, *mCurrentPlayer, *mCurrentOpponent; } // @property... ``` The Manager object has initPlayers and swapPlayers methods. ``` -(void) initPlayers { // this works fine self.p1 = [[Player alloc] init]; self.p2 = [[Player alloc] init]; self.mCurrentPlayer = self.p1; self.mCurrentOpponent = self.p2; } -(void) swapPlayers { // this swapping of pointer doesn't work self.mCurrentPlayer = self.p2; self.mCurrentOpponent = self.p1; // When I look at the pointer in debugger, self.mCurrentPlayer is still self.p1. :-( // I even tried first setting them to nil, // or first releasing them (with an extra retain on assignment) to no avail } ``` What am I missing? Thanks in advance!
2010/02/05
[ "https://Stackoverflow.com/questions/2209575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/237668/" ]
Without knowing how your accessors are set up, it will be difficult to troubleshoot the code as-is. That being said, here is how your accessors and code *should* be set up: > > **Manager.h** > > > ``` @interface Manager { Player *p1, *p2, *mCurrentPlayer, *mCurrentOpponent; } @property (nonatomic, retain) Player *p1; @property (nonatomic, retain) Player *p2; @property (nonatomic, assign) Player *mCurrentPlayer; @property (nonatomic, assign) Player *mCurrentOpponent; @end ``` > > **Manager.m** > > > ``` -(void) initPlayers { self.p1 = [[[Player alloc] init] autorelease]; self.p2 = [[[Player alloc] init] autorelease]; self.mCurrentPlayer = self.p1; self.mCurrentOpponent = self.p2; } -(void) swapPlayers { Player * temp = self.mCurrentPlayer; self.mCurrentPlayer = self.mCurrentOpponent; self.mCurrentOpponent = temp; } ```
800,831
How do I take inverse Laplace transform of $\frac{-2s+3}{s^2-2s+2}$? I have checked my transform table and there is not a suitable case for this expression.
2014/05/18
[ "https://math.stackexchange.com/questions/800831", "https://math.stackexchange.com", "https://math.stackexchange.com/users/141312/" ]
To perform the inverse Laplace transform you need to complete the square at the denominator, $$ s^2-2s+2=(s-1)^2+1$$ so you rewrite your expression as $$\frac{-2s+3}{(s-1)^2+1}= -2 \frac{(s-1)}{(s-1)^2+1}+\frac{(3-2)}{(s-1)^2+1}$$ now these expressions are standard on tables "exponentially decaying sine/cosine wave. The inverse transform is then $$e^t(-2\cos t+\sin t).$$
13,695
I have been working for this couple of investors for around 18 months. The set up is, these two people will buy small online businesses and I will run these businesses from a single office. Currently I have 5 businesses to manage on my own. Around a year ago, my boss decided to come up with a forfeit scheme, every time I made a mistake he wanted me to do a forfeit. These were small mistakes, such as sending somebody the wrong invoice, or missing an item off of an order. These have only happened once. Initially the forfeits were along the line of doing some press-ups or sit-ups, etc, I wasn't bothered about this. However, my boss has been pressuring me to do worse forfeits, it gets to the point he just sits there and waits for me to agree, if I say I don't want to do a forfeit he'll say "you don't have to" so I say ok, then he says "but how are you going to make up for making a mistake", and eventually gets round to me doing a forfeit. More recently he has started to say he wants me to feel humiliated for making mistakes, and tries to get me to do humiliating forfeits. When he first started I felt ok with it, almost as if it was a good idea. The mistakes were/are not big enough for any serious action, but they are still mistakes so a small forfeit as punishment was incentive for me to double check and take more consideration with the work. But now, its got to the point where I feel uncomfortable, pressured into situations I really don't want to be in and its almost like my boss is making me do forfeits for his personal interest rather than to help the business. It's distracting when I am at work, it deters my concentration, I almost feel like I'm being bullied. Is it OK what my boss is doing? --- The following has been added since posting this question -------------------------------------------------------- To clarify I live in the UK. I'm the only permanent employee here, I work here alone for about 2-3 days a week the other days one of the investors may come in for a few hours. There have been 2 or 3 temporary employees and a few contractors who I would only speak to via email/telephone calls. It is only 1 of the 2 investors who is putting me in this situation. At one point the investor said just remember what happens at work stays at work, almost as if he didn't want me to tell the other investor or my friends. For those of you who say the examples aren't small mistakes, I work as a sole employee for 5 businesses - I do almost everything to manage these businesses including processing sales/orders which is in the 1000s some months, dealing with all customers/clients briefing contractors/meeting up with suppliers, producing website content and promotional material, reporting on sales/marketing, purchasing, forecasting, etc, the only areas I do not really have an input in is the legal and corporate finance. So in over 18 months, if the most serious error I made was amended by me apologizing to a customer and saying there will be a 1 day delay with half of their order, costing the company less than £7 in extra shipping fees, I do not think I have done anything majorly wrong. The investor has also made me do forfeits when I didn't respond to emails with in a set time frame, when stock levels had been in accurate, and on one occasion the company who installed our e-commerce site had to add an update - after, one link was broken which I didn't notice so I was made to do a forfeit for each day the link was broken on the site which my boss decided was 7 days.
2013/08/07
[ "https://workplace.stackexchange.com/questions/13695", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/10218/" ]
> > Is it OK what my boss is doing? > > > It's not appropriate for a boss to humiliate a worker - in private or in public. And if it's at the point where you feel concerned about being at work, then it's clearly NOT OK. Tell your boss "No" next time, and mean it. Don't let your boss guilt you into doing something that clearly bothers you. If it continues, quit.
41,829
The answer to this is likely "It is not possible.", and from what I know about filesystems and storage, I would say the same thing. But, I thought I would try the great wisdom of SuperUser: I'm looking for a NAS device that will serve the same content over USB and via SMB. I have a device (let's call it the reader) which will read files from an external USB drive. I would like to attach a drive, but also make that drive writable across the network. The reader does not have a network port. I get that the reader considers the USB directly attached storage, so it partitions and formats it, while anything that served up the drive's content over the network (via SMB or something) is serving up file content and not a lower level storage device like the USB interface, and you'll end up with two different things having the filesystem mounted, which going to cause trouble.
2009/09/15
[ "https://superuser.com/questions/41829", "https://superuser.com", "https://superuser.com/users/9588/" ]
Basically, if I read you correctly, you want a Network Attached Storage device that allows you to access the data stored on it via USB and via an SMB network share simultaneously. To muse a bit more with you, I think it is possible. It may not actually exist out in the world (yet), but it is possible to build something that behaves this way I think. There is [this device on newegg](http://www.newegg.com/Product/Product.aspx?Item=N82E16817180005) that seems to do what you are talking about, but judging by reviews it may not do what you want. If you tried looking around, you might be able to find a way to repurpose a full-blown PC to both provide access to data on an internal hard-drive via both a USB connection and via SMB sharing. However, you might have to be creative with the USB side of things, as I doubt you could have the HDD available as mass storage coming from the PC, due to host/guest issues in USB. You could maybe have the HDD available over USB by using USB as a direct PC-to-PC connection system (kinda like PC-to-PC over parallel port, back in the day).
1,959,140
If I am given two 3-D points of a cube,how do I find the volume of that Cube?where $(x\_1, y\_1, z\_1)$ is the co-ordinate of one corner and $(x\_2, y\_2, z\_2)$ is the co-ordinate of the opposite corner.
2016/10/08
[ "https://math.stackexchange.com/questions/1959140", "https://math.stackexchange.com", "https://math.stackexchange.com/users/374055/" ]
We can solve the system in the following way (though I'm not sure if it is "reasonable") : We have $$\sqrt y+\sqrt z-\sqrt x=\frac{a}{\sqrt x}\tag1$$ $$\sqrt z+\sqrt x-\sqrt y=\frac{b}{\sqrt y}\tag2$$ $$\sqrt x+\sqrt y-\sqrt z=\frac{c}{\sqrt z}\tag3$$ From $(1)$, $$\sqrt z=\sqrt x-\sqrt y+\frac{a}{\sqrt x}\tag4$$ From $(2)(4)$, $$\sqrt x-\sqrt y+\frac{a}{\sqrt x}+\sqrt x-\sqrt y=\frac{b}{\sqrt y},$$ i.e. $$2\sqrt x-2\sqrt y+\frac{a}{\sqrt x}-\frac{b}{\sqrt y}=0$$ Multiplying the both sides by $\sqrt{xy}$ gives $$2x\sqrt y-2y\sqrt x+a\sqrt y-b\sqrt x=0,$$ i.e. $$y=\frac{2x\sqrt y+a\sqrt y-b\sqrt x}{2\sqrt x}\tag5$$ From $(3)(4)$, $$\sqrt x+\sqrt y-\left(\sqrt x-\sqrt y+\frac{a}{\sqrt x}\right)=\frac{c}{\sqrt x-\sqrt y+\frac{a}{\sqrt x}},$$ i.e. $$\frac{2\sqrt{xy}-a}{\sqrt x}=\frac{c\sqrt x}{x-\sqrt{xy}+a}$$ Multiplying the both sides by $\sqrt x\ (x-\sqrt{xy}+a)$ gives $$2x\sqrt{xy}-2xy+3a\sqrt{xy}-ax-a^2=cx,$$ i.e. $$y=\frac{2x\sqrt{xy}+3a\sqrt{xy}-ax-a^2-cx}{2x}\tag6$$ From $(5)(6)$, $$\frac{2x\sqrt y+a\sqrt y-b\sqrt x}{2\sqrt x}=\frac{2x\sqrt{xy}+3a\sqrt{xy}-ax-a^2-cx}{2x},$$ i.e. $$\sqrt y=\frac{a^2+(a-b+c)x}{2a\sqrt x}\tag7$$ From $(5)(7)$, $$\left(\frac{a^2+(a-b+c)x}{2a\sqrt x}\right)^2=\frac{(2x+a)\frac{a^2+(a-b+c)x}{2a\sqrt x}-b\sqrt x}{2\sqrt x},$$ i.e. $$\frac{(a^2+(a-b+c)x)^2}{4a^2x}=\frac{(2x+a)(a^2+(a-b+c)x)-2abx}{4ax}$$ Multiplying the both sides by $4a^2x$ gives $$(a^2+(a-b+c)x)^2=a((2x+a)(a^2+(a-b+c)x)-2abx),$$ i.e. $$x((a^2-b^2+2bc-c^2)x+a^3-a^2b-a^2c)=0$$ Finally, from $(7)(4)$, $$\color{red}{x=\frac{a^2(b+c-a)}{(a+b-c)(c+a-b)},\quad y=\frac{b^2(c+a-b)}{(b+c-a)(a+b-c)},\quad z=\frac{c^2(a+b-c)}{(b+c-a)(c+a-b)}}$$
878,520
I'm working on a small website for a local church. The site needs to allow administrators to edit content and post new events/updates. The only "secure" information managed by the site will be the admins' login info and a church directory with phone numbers and addresses. How at risk would I be if I were to go without SSL and just have the users login using straight HTTP? Normally I wouldn't even consider this, but it's a small church and they need to save money wherever possible.
2009/05/18
[ "https://Stackoverflow.com/questions/878520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/108893/" ]
Well, if you don't use SSL, you will always be at a higher risk for someone trying to sniff your passwords. You probably just need to evaluate the risk factor of your site. Also remember that even having SSL does not guarentee that your data is safe. It is really all in how you code it to make sure you provide the extra protection to your site. I would suggest using a one way password encryption algorythm and validate that way. Also, you can get SSL certificates really cheap, I have used Geotrust before and got a certification for 250.00. I am sure there are those out there that are cheaper.
226,735
I am looking at establish a circuit allowing to detect when one or two wire are cut such as a tamper system. When the wire are cut it should signal this a GPIO. I suppose I need to use a transistor connected to GPIO but I have a bit some difficulty to see how.
2016/04/06
[ "https://electronics.stackexchange.com/questions/226735", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/104309/" ]
![schematic](https://i.stack.imgur.com/A8UqT.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fA8UqT.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) *Figure 1. GPIO normally pulled low by tamper loop. Cutting loop causes GPIO to be pulled high by R1.* C1 will help eliminate any noise on a long tamper loop.
15,216,048
My Box Shadow is not showing in IE7 and IE8. ``` #bodyContainer{ background: url(../images/site_bg.png) repeat ; margin: 0px auto; width:1000px; float:left; position:relative; border: 1px solid #EEEEEE; /*background:#FFFFFF;*/ box-shadow: 0 0 5px 0 #000000; } ```
2013/03/05
[ "https://Stackoverflow.com/questions/15216048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548927/" ]
Use [CSS3 PIE](http://css3pie.com/), which emulates [some CSS3 properties](http://css3pie.com/documentation/supported-css3-features/) in older versions of IE. It supports `box-shadow` ([except for](https://github.com/lojjic/PIE/issues/3) the `inset` keyword). and There are article about [CSS3 Box Shadow in Internet Explorer](http://placenamehere.com/article/384/css3boxshadowininternetexplorerblurshadow/) and [Box-shadow](http://www.css3.info/preview/box-shadow/). Hope this helps also you can use ``` style="FILTER: DropShadow(Color=#0066cc, OffX=5, OffY=-3, Positive=1);width:300px;font-size:20pt;" style="filter: progid:DXImageTransform.Microsoft.dropShadow (OffX='-2', OffY='-2', Color='#c0c0c0', Positive='true')" ```
16,134,120
Visual Studio / monodevelop have awesome feature that can let you specify xml comments above every function / variable which is then displayed as a description of that function when you roll over it, click it etc. ``` /// <summary> /// This is example for stack overflow /// </summary> public void Foo() { } ``` This is cool, but it works only in your local code (within 1 project) how can I make these comments that are in functions in external library, which is referenced in another project, available in THAT project as well? It should be possible, because it works for .Net assemblies (when you reference a .Net library, you will be able to see these descriptions for functions in that library)
2013/04/21
[ "https://Stackoverflow.com/questions/16134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514983/" ]
You can generate the xml for documentation of your library using visual studio, check it [here](http://msdn.microsoft.com/en-us/library/vstudio/x4sa0ak0%28v=vs.100%29.aspx). > > The Generate XML documentation file property determines whether an XML > file will be generated during compilation. You set this property on > the Compile page (for Visual Basic) or Build page (for Visual C#) of > the Project Designer. When this option is selected, XML documentation > is automatically emitted into an XML file, which will have the same > name as your project and the .xml extension, [Reference](http://msdn.microsoft.com/en-us/library/vstudio/x4sa0ak0%28v=vs.100%29.aspx). > > >
6,411
How can I make backup from iPhoto without time machine?
2009/05/08
[ "https://serverfault.com/questions/6411", "https://serverfault.com", "https://serverfault.com/users/1968/" ]
iPhoto puts all of your photos into a library similar to the way iTunes puts all of your music into a music in a library folder structure. That being said you could easily just copy the library from your hard drive to another. I know you want to back it up, but here is some information on how to move the library and much of the info should be useful in your soluition: <http://basics4mac.com/article.php/move_iphoto_lib> and <http://www.hinkty.com/blogger/2006/02/how-to-move-your-iphoto-library-to.html> Also if you want to share a library between users/systems see here: <http://forums.macrumors.com/showthread.php?t=158248> And lastly there is a application manager which can handle much of this in a more simplier manner called [iPhoto Library Manager](http://www.fatcatsoftware.com/iplm/)
415,701
I am working on my chess engine in C++ and I went for bitboards to represent the board. It is basically a 64-bit number for which I use the `bitset` library. I feel the most crucial part in performance comes through the move generation. Earlier I encoded moves as `std::string`'s in a `std::vector` which would perform moves on a 2-D array. A move has to include at the most basic, A start location, and an end location. That means for my purpose, two numbers would be enough. However, it shall also include two more attributes which are, castling rights(if any) en-passant squares. One choice is to use a `struct` to represent two coordinates and the additional two attributes. And then create an array of those moves. Another choice is to use a 16-bit number to represent a move. For example: 6-bits for the first number, 6-bits for the second. And the remaining for the additional values. And then store them in an array/vector/any container. Even a `std::vector<int>` can work. The main purpose is to be able to iterate through the container efficiently as it will happen **multiple** times. What is the best way to encode the move?
2020/09/09
[ "https://softwareengineering.stackexchange.com/questions/415701", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/-1/" ]
Questions like this usually boil down to a trade-off between memory usage and speed. A program which uses a highly packed representation for keeping boards in memory will always require some time to unpack the data into a form where it can evaluate and apply the game's semantics. This is especially true when this "unpacking" is done implicitly, by the accessor functions. Keeping boards and moves directly in an unpacked representation hence saves these CPU cycles. However, in reality, the situation becomes more complex: if your program has to manage lots of boards and moves, and it is going to process millions of them, small-size representations may increase speed, since more boards and moves can be kept in main memory or CPU cache. As a compromise for such scenarios, it is not uncommon to keep boards in a highly packed representation, unpack them explicitly when they are pulled from the queue or lookup-table (or whatever container your program uses for a tree search), process the unpacked representation to generate new boards and pack the results again to put them into the containers. As you see, this is going to depend on the gory details of the algorithms of your program, and it may sometimes depend on the hardware on which the program is executed. Hence, if you want maximum speed, there is no way around * implementing different approaches, and * benchmark them!
54,754,090
I am trying to see if two times, both with start and end times, overlap in any way. for instance, if A has a start time of 0800 and an end time of 0900 and I want to see if B, which has a start time of 0845 and an end time of 0945, interests/ overlaps it in any way. I don't care about the actual date just the times.
2019/02/18
[ "https://Stackoverflow.com/questions/54754090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9761440/" ]
If you want to do this specifically using moment.js then you can try this plugin `moment-range` which allows you to have two date ranges and a function `overlaps` that can check this for you. <https://github.com/rotaready/moment-range#overlaps> Alternatively, you can manually do this check with if statements as well if you don't want to use moment.js.
126,532
So I have generic fantasy Human Empire, relatively Good folks, but mostly Orderly. Racially mostly homogeneous, some elves and dwarves are present, but 99% humans. And there is the Monster Empire, which is ruled by dragons, but has all kinds of naturally Evil monsters (and by Evil I mean DnD like alignments, so tangible Evil), from goblinoids to ogres and whatnot. Pre-Threat the two sides were in equilibrium: the monsters were never united enough to pose a significant threat to the otherwise also quite powerful Human Empire (lots of magic users and a strong army + various paramilitaristic organizations), and the Monster Empire is located in a hard to pass terrain, so a formal army's movements are extremely hindered. The monsters range from threat to only unskilled or old/wounded/ill/children to the mentioned dragons, which pose a significant threat to whole groups, though not unbeatable by any means. Border skirmishes were regular before the alliance. They both got undeniable proof that there is some Generic Threat that threatens the very existence of the world, and the lead dragon bands together with the Human King to stand togetherish against the threat. The world is a band of land from west to east, bound by mountains and waters. Monster Empire is to the west, Human Empire is in the middle, and the Threat comes from the east. The thing is, the threat is yet to materialize. What are some key points I would have to keep in mind when thinking about this? I would imagine the dragon would keep a sizable force in Human Empire, because of logistics, if the threat arrives (and they have no clear idea of how long it will take from the first actual sign to the invasion), they have to be there. So right now, there is a whole family of dragons (Evil, macho, aggressive), a good number of giant sized creatures (ogres, trolls, actual giants) and a sizable array of smaller goblionoids, orcs, kobolds and other cannon fodder. Is there any kind of historical reference for this? That might be a good basis for it, sans the Evil monsters part.
2018/10/02
[ "https://worldbuilding.stackexchange.com/questions/126532", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/55884/" ]
The US and Britain worked with the USSR in WW2. ----------------------------------------------- It's not exactly like your scenario, though, since the US+Britain and USSR made Germany fight a three-front war whereas your scenario is a one-front war. More importantly, there were people in US+Britain who were deluded into thinking that the USSR was a Workers Paradise.
29,934,164
I have two fragments within one fragment using ViewPager. Sometimes my app crash with following error: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.MyAcitivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.fragments.MyFragment: make sure class name exists, is public, and has an empty constructor that is public at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invokeNative(Method.java) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633) at dalvik.system.NativeStart.main(NativeStart.java) Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.fragments.MyFragment: make sure class name exists, is public, and has an empty constructor that is public at android.support.v4.app.Fragment.instantiate(Fragment.java:413) at android.support.v4.app.FragmentState.instantiate(Fragment.java:97) at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1801) at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:213) at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:97) at com.buzzreel.MyActivity.onCreate(MyActivity.java:55) at android.app.Activity.performCreate(Activity.java:5411) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invokeNative(Method.java) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633) at dalvik.system.NativeStart.main(NativeStart.java) Caused by: java.lang.InstantiationException: can't instantiate class com.fragments.MyFragment; no empty constructor at java.lang.Class.newInstanceImpl(Class.java) at java.lang.Class.newInstance(Class.java:1208) at android.support.v4.app.Fragment.instantiate(Fragment.java:402) at android.support.v4.app.FragmentState.instantiate(Fragment.java:97) at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1801) at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:213) at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:97) at com.buzzreel.MyActivity.onCreate(MyActivity.java:55) at android.app.Activity.performCreate(Activity.java:5411) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invokeNative(Method.java) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633) at dalvik.system.NativeStart.main(NativeStart.java) ``` But i have two constructors in my fragment class as follows: ``` public MyFragment(CustomObject custom) { this.custom = custom; } public MyFragment() { } ``` My pager adapter call: ``` import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.fragments.MyFragment public class MyPagerAdapter extends FragmentPagerAdapter { private String tabtitles[] = new String[] { "Info" }; private CustomOjbect object; public MyPagerAdapter(FragmentManager fm, CustomOjbect object) { super(fm); this.object = object; } @Override public Fragment getItem(int index) { switch (index) { case 0: return new MyFragment(object); } return null; } @Override public int getCount() { return 1; } @Override public CharSequence getPageTitle(int position) { return tabtitles[position]; } } ``` Fragment Code [Code was big as other was relevant just keeping core code] ``` public class MyFragment extends Fragment implements OnClickListener { /** Variable declaration for widgets and views comes here **/ public MyFragment(CustomObject object) { this.object = object; } public MyFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_layout, container, false); initializeUIComponents(); /** ... .. rest of code **/ return view; } private void initializeUIComponents() { // ui views initialization } } ``` In View pager i call constructor with arguements. Why is it failing?
2015/04/29
[ "https://Stackoverflow.com/questions/29934164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3176004/" ]
The deadlock is at `Line 3`. At this line both the `Threads` are waiting continuously to acquire lock on resource `t`. The initial value of `t` is 0, which means it is already in a locked state, so for example if `Thread1` reaches first to `line 3` it waits till the value of `t` becomes 1 and similarly after some time `Thread2` will wait at the same line for `t` to become 1. In this way both the process will wait continuously for the resource creating a `deadlock.
63,077,450
I've spent the last few hours trying to figure how to do something relatively simple- i'd like to write a python script that returns a number of strings from a predefined alphabet using certain weights. So for example ``` strings = 3 length= 4 alphabet = list('QWER') weights=[0.0, 0.0, 0.0, 1.0] ``` this would return ``` RRRR RRRR RRRR ``` or another example ``` strings = 2 length= 3 alphabet = list('ABC') weights=[0.3,0.3,0.3] ``` This would return ``` CBA ABC CAA ``` I've tried playing around with a number of example codes and this is the closest i've come- ``` import random import numpy as np LENGTH = 3 NO_CODES = 100 alphabet = list('ABCD') weights=[0.0, 0.0, 0.0, 1.0] np_alphabet = np.array(alphabet, dtype="|U1") np_codes = np.random.choice(np_alphabet, [NO_CODES, LENGTH]) codes = ["".join(np_codes[i]) for i in range(len(np_codes))] print(codes) ``` However, i know i'm not using the weight function correctly. If anyone can tell me what i'm doing wrong or suggest a better way to do it, that would be appreciated. As i'm sure you can tell i don't really know what i'm doing, so any advice would be useful.
2020/07/24
[ "https://Stackoverflow.com/questions/63077450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989644/" ]
SO thank you for the suggestions, i manged to puzzle through it- ``` import random for i in range(100): #number of strings a = random.choices(["A", "B", "C"], [0.5, 0.5, 0.0], k=100) #weights of strings random_sequence='' for i in range(0,5): #length of string random_sequence+=random.choice(a) print(random_sequence) ```
64,366,902
My code: Added data in array adapter but last data only comming how to add all the data in spinner using arrayadapter ``` while (rs.next()) { int_EMP_ID = rs.getInt("EmpID"); str_EMP_Name = rs.getString("EmployeeName"); int User_ID_List[] = {int_EMP_ID}; String User_name_List[] = {str_EMP_Name}; for (int i=0;i<=10;i++) { // Step 2: Create and fill an ArrayAdapter with a bunch of "State" objects ArrayAdapter<Employee> spinnerArrayAdapter = new ArrayAdapter<Employee>(this, android.R.layout.simple_spinner_item, new Employee[]{ new Employee(User_ID_List[i], User_name_List[i]), new Employee(User_ID_List[i], User_name_List[i]) }); } ``` > > Blockquote > > >
2020/10/15
[ "https://Stackoverflow.com/questions/64366902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14454144/" ]
You *could* try doing a regex replacement here: ``` String input = "\"email_settings\": {\n \"email.starttls.enable\":\"true\",\n \"email.port\":\"111\",\n \"email.host\":\"xxxx\",\n \"email.auth\":\"true\",\n}"; String output = input.replaceAll("([ ]*\"email.host\":\".*?\")", " \"email.name\":\"myTest\",\n$1"); System.out.println(output); ``` This prints: ``` "email_settings": { "email.starttls.enable":"true", "email.port":"111", "email.name":"myTest", "email.host":"xxxx", "email.auth":"true", } ``` However, if you are dealing with proper JSON content, then you should consider using a JSON parser instead. Parse the JSON text into a Java POJO and then write out with the new field.