qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
47,024,099
I get this error with a little arrow pointing at decimal integers. Are decimals allowed? What do I have to write to make decimals acceptable? This is my code: ``` public class BinarySearch { public static final int NOT_FOUND = -1; public static int search(int[] arr, int searchValue) { int left = 0; int right = arr.length - 1; return binarySearch(arr, searchValue, left, right); } private static int binarySearch(int[] arr, int searchValue, int left, int right) { if (right < left) { return NOT_FOUND; } int mid = (left + right) >>> 1; if (searchValue > arr[mid]) { return binarySearch(arr, searchValue, mid + 1, right); } else if (searchValue < arr[mid]) { return binarySearch(arr, searchValue, left, mid - 1); } else { return mid; } } } import java.util.Arrays; public class BinarySearchTest { public static void main(String[] args) { int[] arr = {-3, 10, 5, 24, 45.3, 10.5}; Arrays.sort(arr); System.out.println(BinarySearch.search(arr, 2)); } } ``` The error is this: 9: error: incompatible types: possible lossy conversion from double to int int[] arr = {-3, 10, 5, 24, 45.3, 10.5}; ^ 9: error: incompatible types: possible lossy conversion from double to int int[] arr = {-3, 10, 5, 24, 45.3, 10.5}; ^ 2 errors
2017/10/30
[ "https://Stackoverflow.com/questions/47024099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8858781/" ]
This isn't an Angular issue, it's just how CSS and Javascript interact. You need to use `getComputedStyle` to read style properties that were defined in a CSS file. ```js // This will work (because it's an inline style) console.log(document.getElementById('a').style.width) // This won't work (because the style was defined in css): console.log(document.getElementById('b').style.width) // getComputedStyle will work regardless of the source: console.log(window.getComputedStyle(document.getElementById('b')).width) ``` ```css #b {width: 100px} ``` ```html <div id="a" style="width: 100px">A</div> <div id="b">B</div> ```
You cannot get css template rule values of elements calling style properties unless they were set \*1. using inline style on html element level; or \*2. the style property has been set using JavaScript which does the same: writes to inline html style property of the target element. the solution is to use the computed style instead: as in : `getComputedStyle(box,0).width`
274
According to [Wikipedia](https://en.wikipedia.org/wiki/Chaos_Monkey), ChoasMonkey is used to test resilience of IT infrastructure. What about creating a [resilience](https://devops.stackexchange.com/questions/tagged/resilience "show questions tagged 'resilience'") or [resilience-testing](https://devops.stackexchange.com/questions/tagged/resilience-testing "show questions tagged 'resilience-testing'") tag? Note: in the mean time this tag has been created and assigned to [this Q&A](https://devops.stackexchange.com/q/3976/210). If this tag should not have been created then it could be removed. **Why this question?** It turned out that a couple of tags were removed, while I was not notified. In order to prevent that Q&As that will be untagged again in the future I would like to discuss some tags first before creating them.
2018/04/27
[ "https://devops.meta.stackexchange.com/questions/274", "https://devops.meta.stackexchange.com", "https://devops.meta.stackexchange.com/users/210/" ]
The generalized term being used in the industry is "chaos engineering", see <https://principlesofchaos.org/>, writing from Netflix, writing from Gremlin. Tag should be chaos-engineering.
I would like a chaos-monkey tag or "failure as a service". I work with that occasionally. Validating stuff and failing it.
19,506,988
Using some simple JavaScript, I'm getting what seems to be an incorrect value returned for one of my two pieces of similar code. For `browserName` I am getting Netscape as the value returned regardless of what browser I test the code on. `browserVer`, however, seems to return the correct value, shown below using Google Chrome. `browserVer` results: 5.0 (Macintosh; Intel Mac OS X 10\_8\_5) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1 Why is this? ``` var browserName = navigator.appName; var browserVer = navigator.appVersion; ```
2013/10/22
[ "https://Stackoverflow.com/questions/19506988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2262393/" ]
A quick Google of what `navigator.appName` actually means returns [this MDN page](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID.appName) which includes the fact that: > > The HTML5 specification also allows any browser to return "Netscape" here, for compatibility reasons. > > > Instead, you should probably use a browser sniffing library like [Modernizr](http://modernizr.com/)
A better search revealed the answer ([Why does JavaScript navigator.appName return Netscape for Safari, Firefox and Chrome?](https://stackoverflow.com/questions/14573881/why-the-javascript-navigator-appname-returns-netscape-for-safari-firefox-and-ch)) *"MDN says: "This was originally part of DOM Level 0, but has been since included in the HTML5 spec." See Mozilla documentation here. BTW; that's why this cannot be used for browser detection (maybe only for IE). Browser detection is a BAD practice and you should always avoid it where possible. Do feature detection instead. But if anybody insists on this; they should use the userAgent property instead."*
51,242
**Introduction** This challenge is about three (bad) sorting algorithms: [`Bogosort`](http://en.wikipedia.org/wiki/Bogosort), and two others variants that I came up with (but have probably been thought of by others at some point in time): `Bogoswap` (AKA Bozosort) and `Bogosmart`. `Bogosort` works by completely shuffling the array randomly and checking if it becomes sorted (ascending). If not, repeat. `Bogoswap` works by selecting two elements, randomly, and swapping them. Repeat until sorted (ascending). `Bogosmart` works by selecting two elements, randomly, and only swapping them if it makes the array closer to being sorted (ascending), ie. if the element with the lower index was originally larger than the one with the higher. Repeat until sorted. **The Challenge** This challenge explores the efficiency (or lack of) of each of these three sorting algorithms. The golfed code will 1. generate a shuffled 8 element array of the integers 1-8 inclusive (keep reading to see how you should do this); 2. apply each algorithm to this array; and 3. display the original array, followed by the number of computations required for each algorithm, separated by one space (trailing space ok), in the format `<ARRAY> <BOGOSORT> <BOGOSWAP> <BOGOSMART>`. The program will produce 10 test cases; you can generate all ten at the beginning or generate one at a time, whatever. Sample output below. **Details:** For `Bogosort`, it should record the number of times the array was shuffled. For `Bogoswap`, it should record the number of swaps made. For `Bogosmart`, it should record the number of swaps made. **Example output:** ``` 87654321 1000000 100 1 37485612 9050000 9000 10 12345678 0 0 0 28746351 4344 5009 5 18437256 10000 523 25 15438762 10000 223 34 18763524 58924 23524 5 34652817 9283 21 445 78634512 5748 234 13 24567351 577 24 34 ``` I made up these numbers; of course, your program will print different output but in the same format. **Rules** * All randomness used in your program must come from pseudorandom number generators available to you, and otherwise not computed extensively by you. You don't have to worry about seeds. * There is no time limit on the programs. * The arrays are to be sorted ascendingly. * Trailing spaces or an extra newline is no big deal. * For `Bogosort`, the array is to be shuffled using any unbiased shuffling algorithm such as Fisher-Yates or [Knuth Shuffling](http://en.wikipedia.org/wiki/Random_permutation#Knuth_shuffles), explicitly specified in your explanation. Built-in shuffling methods are not allowed. Generate your test arrays in the same manner. * If after shuffling or swapping the array remains the same, it still counts and should be included in the program's count. For example, shuffling the array to itself by coincidence counts as a shuffle, and swapping an element with itself counts as a swap, even though none of these operations change the array. * If my memory serves me correctly, an 8 element array shouldn't take too long for any of the three algorithms. In fact, I think a few times for a 10 element array, when I tried it, `Bogoswap` only required a few thousand (or less) actual shuffles and well under 10 seconds. * Your code must actually sort the arrays, don't just give expected values or mathematical calculations for an expected answer. * This is a code-golf challenge, so shortest program in bytes wins. Here are some sample steps for each sorting algorithm: ``` BOGOSORT 56781234 37485612 28471653 46758123 46758123 12685734 27836451 12345678 BOGOSWAP 56781234 16785234 17685234 12685734 12685743 12685734 12485763 12385764 12385764 12345768 12345678 BOGOSMART 56781234 16785234 12785634 12785364 12785364 12385764 12385674 12345678 ``` In this case, the program would output `56781234 7 10 7`, and then do the same thing 10 times. You do not have to print the arrays while sorting is going on, but I gave the above sample steps so you can understand how each algorithm works and how to count computations.
2015/06/04
[ "https://codegolf.stackexchange.com/questions/51242", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/40857/" ]
Pyth, ~~62~~ 60 bytes ===================== ``` VTjd[jkKJ=boO0=ZS8fqZ=KoO0K0fqZ=XJO.CJ2)0fqZ=Xb*>F=NO.Cb2N)0 ``` This was quite fun. Not sure if this is valid, I'm probably using some unwritten loopholes. A sample output would be: ``` 23187456 22604 23251 110 42561378 125642 115505 105 62715843 10448 35799 69 72645183 7554 53439 30 61357428 66265 6568 77 62348571 1997 105762 171 78345162 96931 88866 241 17385246 51703 7880 80 74136582 36925 19875 100 26381475 83126 2432 25 ``` ### Explanation: My shuffle function uses the built-function `order-by`. Basically I assign each element of the list a random number of the interval `[0-1)` and sort the list by them. This gives me an unbiased random shuffle. **Outer loop** The `VT` at the start repeats the following code 10 times. **Preparation** ``` jkKJ=boO0=ZS8 S8 create the list [1, 2, 3, 4, 5, 6, 7, 8] =Z and store in Z oO0 shuffle =b and store in b J and store in J K and store in K (3 copies of the same shuffled array) jkK join K with "" ``` **Bogosort** ``` fqZ=KoO0K0 oO0K shuffle K =K and store the result in K f 0 repeat ^ until: qZ K Z == K and give the number of repeats ``` **Bogoswap** ``` fqZ=XJO.CJ2)0 .CJ2 give all possible pairs of elements of J O take a random one XJ ) swap these two elements in J = and store the result in J f 0 repeat ^ until: qZ K Z == K and give the number of repeats ``` **Bogosmart** ``` fqZ=Xb*>F=NO.Cb2N)0 .Cb2 give all possible pairs of elements of b O take a random one =N assign it to N >F N check if N[0] > N[1] * N multiply the boolean with N Xb ) swap the two (or zero) values in b = and assign to b f 0 repeat ^ until: qZ Z == b and give the number of repeats ``` **Printing** ``` jd[ [ put all 4 values in a list jd join by spaces and print ```
JavaScript (*ES6*), 319 ~~345~~ =============================== Unsurprisingly this is quite long. For Random shuffle, credits to [@core1024](https://codegolf.stackexchange.com/a/45453/21348) (better than mine for the same chellenge) Test running the snippet (Firefox only as usual) ```js // FOR TEST : redefine console var console = { log: (...p)=>O.innerHTML += p.join(' ')+'\n' } // END // Solution R=n=>Math.random()*n|0, S=a=>(a.map((c,i)=>(a[i]=a[j=R(++i)],a[j]=c)),a), // shuffle T=f=>{for(a=[...z];a.join('')!=s;)f(a)}, // apply sort 'f' algorithm until sorted s='12345678'; for(i=0;i<10;i++) z=S([...s]), n=l=m=0, T(a=>S(a,++n)), T(a=>(t=a[k=R(8)],a[k]=a[j=R(8)],a[j]=t,++m)), T(a=>(t=a[k=R(8)],u=a[j=R(8)],(t<u?j<k:k<j)&&(a[k]=u,a[j]=t,++l))), console.log(z.join(''),n,m,l) ``` ```html <pre id=O></pre> ```
27,202,860
Why we use json and xml for web api rather then othen platform like jquery and array. Its interview based question and I was enable to response .
2014/11/29
[ "https://Stackoverflow.com/questions/27202860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3790663/" ]
JSON and XML are ways to format and data-interchange. JQuery is a library was built on top of javascript. so it has nothing to do in data-interchange. Array by its definition: its a method for storing information. in other words you can use arrays in any format you want to store data. In Conclusion, Web API is a service that provides or gathers data. and in general you can exchange data between client and server by JSON, XML, or you can use whatever data format you want such as HTML. JQuery can be use to call the Web API that can return an array of data in any data format.
This is not compulsory that you have to return the result in JSON or XML, but most of the time we are returning values in these format because there are media type formatter for JSON and XML, the capability of media type formatter is to read the CLR object from HTTP message and to write the CLR object into HTTP message. This is the main reason that we return values in JSON and XML format.
27,787,842
I have a code that will connect to several routers, using the telentlib, run some code within those, and finally write the output to a file. It runs smoothly. However, when I had to access lots of routers (+50) the task consumes a lot of time (the code runs serially, one router at a time). I thought then on implementing threads in order to accelerate the process. This is pretty much the code (just a snippet of it): ``` # We import the expect library for python import telnetlib import sys import csv import time import threading # --- Timers TimeLogin = 10 TelnetWriteTimeout = 1 TelnetReadTimeout = 2 # --- CSV FileCsv = "/home/lucas/Documents/script/file.csv" # --- Extras cr="\n" # variables IP = "A.B.C.D" User = ["user","password"] CliLogin = "telnet " + IP Prompt = ["root@host.*]#"] PromptLogin = ["login:"] PromptLogout = ["logout"] PromptPass = ["Password:"] CliLine = "ls -l" class MiThread(threading.Thread): def __init__(self,num,datos): threading.Thread.__init__(self) self.num = num self.datos = datos self.systemIP = self.datos[0] self.tn = telnetlib.Telnet(IP) self.tn.timeout = TimeLogin # File declaration self.FileOutGen = self.systemIP + "_commands" self.FileOutSend = self.systemIP + "_output" self.FileOutRx = self.systemIP + "_rx" self.fg = open(self.FileOutGen,"w") self.fr = open(self.FileOutRx,"a") self.fs = open(self.FileOutSend,"w") def run(self): print "Soy el hilo", self.num self.telnetLogin() self.runLs() self.telnetLogout() def telnetLogin(self): i=self.tn.expect(PromptLogin) print i if i: writeTelnet(User[0],TelnetWriteTimeout) j=self.tn.expect(PromptPass) print j if j: writeTelnet(User[1],TelnetWriteTimeout) def telnetLogout(self): i=self.tn.expect(Prompt) if i: writeTelnet("exit",TelnetWriteTimeout) j=self.tn.expect(PromptLogout) if j: print "Logged out OK from SAM" def runLs(self): writeLog("Prueba de Ls " + self.systemIP) self.writeCsv(self.systemIP,1) i=self.tn.expect(Prompt,TimeLogin) print i if i: # Prompt CliLine = "ls -l " writeTelnet(CliLine,TelnetWriteTimeout) def writeCsv(self,inText,lastIn): lock.acquire(1) if lastIn==0: fc.write(inText + ",") elif lastIn==1: fc.write(inText + "\n") lock.release() def writeTelnet(inText, timer): tn.write(inText + cr) time.sleep(timer) def writeLog(inText): print (inText) t.fs.write("\n" + inText) def printConsole(inText): print (inText) oFile = csv.reader(open(FileCsv,"r"), delimiter=",", quotechar="|") lock = threading.Lock() routers = list(oFile) threads_list = [] for i in range(len(routers)): FileOutCsv = "00_log.csv" # creating output file fc = open(FileOutCsv,"a") # running routine t = MiThread(i,routers[i]) threads_list.append(t) t.start() ``` ... everything runs nicely, but there is no gain in time since the t.join() will force a thread to complete before running the next one! The fact of serializing the threads (meaning, using the t.join()) makes me think that some memory spaces are being shared because the problem arises when I do want to parallelize them (commenting out the t.join()). Is there anything wrong that I'm doing? I can provide more information if needed but I really do not know what is it that I'm doing wrong so far ...
2015/01/05
[ "https://Stackoverflow.com/questions/27787842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4421575/" ]
So after some digging, the error was found. Before, the function writeTelnet() was declared outside the class. Once moved inside of it and properly being referenced by the rest (ie: self.writeTelnet()) everything worked so far as expected. Here's the snippet of the new code: ``` class MiThread(threading.Thread): def __init__(self,num,datos): threading.Thread.__init__(self) self.num = num self.datos = datos self.systemIP = self.datos[0] self.tn = telnetlib.Telnet(IP) self.tn.timeout = TimeLogin # File declaration self.FileOutGen = self.systemIP + "_commands" self.FileOutSend = self.systemIP + "_output" self.FileOutRx = self.systemIP + "_rx" self.fg = open(self.FileOutGen,"w") self.fr = open(self.FileOutRx,"a") self.fs = open(self.FileOutSend,"w") [ . . . ] def writeTelnet(self,inText, timer): self.tn.write(inText + ch_cr) time.sleep(timer) oFile = csv.reader(open(FileCsv,"r"), delimiter=",", quotechar="|") routers = list(oFile) for i in range(len(routers)): # creating output file fc = open(FileOutCsv,"a") # running routine t = MiThread(i,routers[i]) t.start() ``` And it's now clear (at least to me): Since the different threads need at some point to write into their telnet's connection, they need unambiguously to identify it. The only way that I've found to do it is to include the function inside the class. Thank you all, Lucas
From past experience, you need to start all of the threads and have them join after they have all started. ``` thread_list = [] for i in range(routers): t = MiThread(i, routers[i]) threadlist.append(t) t.start() for i in thread_list: i.join() ``` This will start every thread and then wait for all threads to complete before moving on.
27,787,842
I have a code that will connect to several routers, using the telentlib, run some code within those, and finally write the output to a file. It runs smoothly. However, when I had to access lots of routers (+50) the task consumes a lot of time (the code runs serially, one router at a time). I thought then on implementing threads in order to accelerate the process. This is pretty much the code (just a snippet of it): ``` # We import the expect library for python import telnetlib import sys import csv import time import threading # --- Timers TimeLogin = 10 TelnetWriteTimeout = 1 TelnetReadTimeout = 2 # --- CSV FileCsv = "/home/lucas/Documents/script/file.csv" # --- Extras cr="\n" # variables IP = "A.B.C.D" User = ["user","password"] CliLogin = "telnet " + IP Prompt = ["root@host.*]#"] PromptLogin = ["login:"] PromptLogout = ["logout"] PromptPass = ["Password:"] CliLine = "ls -l" class MiThread(threading.Thread): def __init__(self,num,datos): threading.Thread.__init__(self) self.num = num self.datos = datos self.systemIP = self.datos[0] self.tn = telnetlib.Telnet(IP) self.tn.timeout = TimeLogin # File declaration self.FileOutGen = self.systemIP + "_commands" self.FileOutSend = self.systemIP + "_output" self.FileOutRx = self.systemIP + "_rx" self.fg = open(self.FileOutGen,"w") self.fr = open(self.FileOutRx,"a") self.fs = open(self.FileOutSend,"w") def run(self): print "Soy el hilo", self.num self.telnetLogin() self.runLs() self.telnetLogout() def telnetLogin(self): i=self.tn.expect(PromptLogin) print i if i: writeTelnet(User[0],TelnetWriteTimeout) j=self.tn.expect(PromptPass) print j if j: writeTelnet(User[1],TelnetWriteTimeout) def telnetLogout(self): i=self.tn.expect(Prompt) if i: writeTelnet("exit",TelnetWriteTimeout) j=self.tn.expect(PromptLogout) if j: print "Logged out OK from SAM" def runLs(self): writeLog("Prueba de Ls " + self.systemIP) self.writeCsv(self.systemIP,1) i=self.tn.expect(Prompt,TimeLogin) print i if i: # Prompt CliLine = "ls -l " writeTelnet(CliLine,TelnetWriteTimeout) def writeCsv(self,inText,lastIn): lock.acquire(1) if lastIn==0: fc.write(inText + ",") elif lastIn==1: fc.write(inText + "\n") lock.release() def writeTelnet(inText, timer): tn.write(inText + cr) time.sleep(timer) def writeLog(inText): print (inText) t.fs.write("\n" + inText) def printConsole(inText): print (inText) oFile = csv.reader(open(FileCsv,"r"), delimiter=",", quotechar="|") lock = threading.Lock() routers = list(oFile) threads_list = [] for i in range(len(routers)): FileOutCsv = "00_log.csv" # creating output file fc = open(FileOutCsv,"a") # running routine t = MiThread(i,routers[i]) threads_list.append(t) t.start() ``` ... everything runs nicely, but there is no gain in time since the t.join() will force a thread to complete before running the next one! The fact of serializing the threads (meaning, using the t.join()) makes me think that some memory spaces are being shared because the problem arises when I do want to parallelize them (commenting out the t.join()). Is there anything wrong that I'm doing? I can provide more information if needed but I really do not know what is it that I'm doing wrong so far ...
2015/01/05
[ "https://Stackoverflow.com/questions/27787842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4421575/" ]
From past experience, you need to start all of the threads and have them join after they have all started. ``` thread_list = [] for i in range(routers): t = MiThread(i, routers[i]) threadlist.append(t) t.start() for i in thread_list: i.join() ``` This will start every thread and then wait for all threads to complete before moving on.
I think you can bunch them up. something like below. (not tried) ``` count=20 start=1 for i in range(len(routers)): if start == count : for _myth in range(1,i+1): thread_list[_myth].join() start+=1 FileOutCsv = "00_log.csv" # creating output file fc = open(FileOutCsv,"a") # running routine t = MiThread(i,routers[i]) threads_list.append(t) t.start() start+=1 ```
27,787,842
I have a code that will connect to several routers, using the telentlib, run some code within those, and finally write the output to a file. It runs smoothly. However, when I had to access lots of routers (+50) the task consumes a lot of time (the code runs serially, one router at a time). I thought then on implementing threads in order to accelerate the process. This is pretty much the code (just a snippet of it): ``` # We import the expect library for python import telnetlib import sys import csv import time import threading # --- Timers TimeLogin = 10 TelnetWriteTimeout = 1 TelnetReadTimeout = 2 # --- CSV FileCsv = "/home/lucas/Documents/script/file.csv" # --- Extras cr="\n" # variables IP = "A.B.C.D" User = ["user","password"] CliLogin = "telnet " + IP Prompt = ["root@host.*]#"] PromptLogin = ["login:"] PromptLogout = ["logout"] PromptPass = ["Password:"] CliLine = "ls -l" class MiThread(threading.Thread): def __init__(self,num,datos): threading.Thread.__init__(self) self.num = num self.datos = datos self.systemIP = self.datos[0] self.tn = telnetlib.Telnet(IP) self.tn.timeout = TimeLogin # File declaration self.FileOutGen = self.systemIP + "_commands" self.FileOutSend = self.systemIP + "_output" self.FileOutRx = self.systemIP + "_rx" self.fg = open(self.FileOutGen,"w") self.fr = open(self.FileOutRx,"a") self.fs = open(self.FileOutSend,"w") def run(self): print "Soy el hilo", self.num self.telnetLogin() self.runLs() self.telnetLogout() def telnetLogin(self): i=self.tn.expect(PromptLogin) print i if i: writeTelnet(User[0],TelnetWriteTimeout) j=self.tn.expect(PromptPass) print j if j: writeTelnet(User[1],TelnetWriteTimeout) def telnetLogout(self): i=self.tn.expect(Prompt) if i: writeTelnet("exit",TelnetWriteTimeout) j=self.tn.expect(PromptLogout) if j: print "Logged out OK from SAM" def runLs(self): writeLog("Prueba de Ls " + self.systemIP) self.writeCsv(self.systemIP,1) i=self.tn.expect(Prompt,TimeLogin) print i if i: # Prompt CliLine = "ls -l " writeTelnet(CliLine,TelnetWriteTimeout) def writeCsv(self,inText,lastIn): lock.acquire(1) if lastIn==0: fc.write(inText + ",") elif lastIn==1: fc.write(inText + "\n") lock.release() def writeTelnet(inText, timer): tn.write(inText + cr) time.sleep(timer) def writeLog(inText): print (inText) t.fs.write("\n" + inText) def printConsole(inText): print (inText) oFile = csv.reader(open(FileCsv,"r"), delimiter=",", quotechar="|") lock = threading.Lock() routers = list(oFile) threads_list = [] for i in range(len(routers)): FileOutCsv = "00_log.csv" # creating output file fc = open(FileOutCsv,"a") # running routine t = MiThread(i,routers[i]) threads_list.append(t) t.start() ``` ... everything runs nicely, but there is no gain in time since the t.join() will force a thread to complete before running the next one! The fact of serializing the threads (meaning, using the t.join()) makes me think that some memory spaces are being shared because the problem arises when I do want to parallelize them (commenting out the t.join()). Is there anything wrong that I'm doing? I can provide more information if needed but I really do not know what is it that I'm doing wrong so far ...
2015/01/05
[ "https://Stackoverflow.com/questions/27787842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4421575/" ]
So after some digging, the error was found. Before, the function writeTelnet() was declared outside the class. Once moved inside of it and properly being referenced by the rest (ie: self.writeTelnet()) everything worked so far as expected. Here's the snippet of the new code: ``` class MiThread(threading.Thread): def __init__(self,num,datos): threading.Thread.__init__(self) self.num = num self.datos = datos self.systemIP = self.datos[0] self.tn = telnetlib.Telnet(IP) self.tn.timeout = TimeLogin # File declaration self.FileOutGen = self.systemIP + "_commands" self.FileOutSend = self.systemIP + "_output" self.FileOutRx = self.systemIP + "_rx" self.fg = open(self.FileOutGen,"w") self.fr = open(self.FileOutRx,"a") self.fs = open(self.FileOutSend,"w") [ . . . ] def writeTelnet(self,inText, timer): self.tn.write(inText + ch_cr) time.sleep(timer) oFile = csv.reader(open(FileCsv,"r"), delimiter=",", quotechar="|") routers = list(oFile) for i in range(len(routers)): # creating output file fc = open(FileOutCsv,"a") # running routine t = MiThread(i,routers[i]) t.start() ``` And it's now clear (at least to me): Since the different threads need at some point to write into their telnet's connection, they need unambiguously to identify it. The only way that I've found to do it is to include the function inside the class. Thank you all, Lucas
I think you can bunch them up. something like below. (not tried) ``` count=20 start=1 for i in range(len(routers)): if start == count : for _myth in range(1,i+1): thread_list[_myth].join() start+=1 FileOutCsv = "00_log.csv" # creating output file fc = open(FileOutCsv,"a") # running routine t = MiThread(i,routers[i]) threads_list.append(t) t.start() start+=1 ```
3,545,259
I am currently using the following code but its very slow for large numbers ``` static int divisor(int number) { int i; for (i = number / 2; i >= 1; i--) { if (number % i == 0) { break; } } return i; } ```
2010/08/23
[ "https://Stackoverflow.com/questions/3545259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301012/" ]
First thought you can find the smallest divisor d (not equal to 1 of course), then N/d will be the largest divisor you're looking for. For example if N is divisible by 3 then you'll need 2 iterations to find the answer - in your case it would be about N/6 iterations. **Edit:** To further improve your algorithm you can iterate through odd numbers only (after checking if you number is even) or, even better, if you have the list of primes pre-calculated then you can iterate through them only because smallest divisor is obviously is a prime number.
Java implementation of the solution: ``` static int highestDivisor(int n) { if ((n & 1) == 0) return n / 2; int i = 3; while (i * i <= n) { if (n % i == 0) { return n / i; } i = i + 2; } return 1; } ```
3,545,259
I am currently using the following code but its very slow for large numbers ``` static int divisor(int number) { int i; for (i = number / 2; i >= 1; i--) { if (number % i == 0) { break; } } return i; } ```
2010/08/23
[ "https://Stackoverflow.com/questions/3545259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301012/" ]
First thought you can find the smallest divisor d (not equal to 1 of course), then N/d will be the largest divisor you're looking for. For example if N is divisible by 3 then you'll need 2 iterations to find the answer - in your case it would be about N/6 iterations. **Edit:** To further improve your algorithm you can iterate through odd numbers only (after checking if you number is even) or, even better, if you have the list of primes pre-calculated then you can iterate through them only because smallest divisor is obviously is a prime number.
You've basically hit the "factorization of large numbers" problem, which is the basis of today's Public Key encryption and is known (or hoped) to be a computationally hard problem. I indeed hope that you will not find a much better solution, otherwise the whole security infrastructure of the world will collapse... :)
3,545,259
I am currently using the following code but its very slow for large numbers ``` static int divisor(int number) { int i; for (i = number / 2; i >= 1; i--) { if (number % i == 0) { break; } } return i; } ```
2010/08/23
[ "https://Stackoverflow.com/questions/3545259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301012/" ]
Don't know if it's the optimal solution but you'd probably be better starting at 2 then going upwards such as: ``` static int divisor(int number) { int i; for (i = 2; i <sqrt(number); i++) { if (number % i == 0) { break; } } return number/i; } ``` EDIT ==== to get it to work with primes as well: ``` static int divisor(int number) { int i; for (i = 2; i <=sqrt(number); i++) { if (number % i == 0) { return number/i; } } return 1; } ```
A huge optimization (not sure if it's completely optimal - you'd have to ask a mathematician for that) is to search upwards using only prime numbers. As Vladimir and Bunnit said, it is better to search upwards, because you'll find it to be much faster. Then, return the inverse (`number / i`). However, if you've already tried 2 and come up dry, there is no point in trying 4 or 6. Similarly, if you've tried 3, there's no point in trying 6 or 9. So, if time of running is a big concern, you could have a list of the first 100 primes hard coded in your program. Test each of them. If you don't find an answer by then, then you could just increment by 2 (skipping even numbers).
3,545,259
I am currently using the following code but its very slow for large numbers ``` static int divisor(int number) { int i; for (i = number / 2; i >= 1; i--) { if (number % i == 0) { break; } } return i; } ```
2010/08/23
[ "https://Stackoverflow.com/questions/3545259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301012/" ]
In order to limit your search space, you should start at 2 and work up to the square root of the number. There are far more numbers (in a finite search space) divisible by 2 than by 27 so you're more likely to get a low divisor than a high one, statistically speaking. You'll find a big difference when using the square root, rather than half the value, when you processing (for example) 1,000,000. The difference is between a search space of 500,000 for your method and 1,000 for the square root method is considerable. Another advantage is to halve the search space right at the front by discounting multiples of two. Then, when you have your lowest divisor, the highest one is simply the number divided by that. Pseudocode: ``` if n % 2 == 0: # Halve search space straight up. print n / 2 else: i = 3 # Start at 3. while i * i <= n: # Or use i <= sqrt(n), provided sqrt is calc'ed once if n % i == 0: print n / i # If multiple, get opposite number, print and stop break i = i + 2 # Only need to process odd numbers ```
The best algorithm will depend on how huge your numbers will really be. This problem is basically as hard as factoring integers - if have some factoring algorithm, it will be rather easy to use it to construct the greatest non-trivial divisor. Again, which of all the known factoring algorithms you employ for a number should depend on its 'hugeness', as for different scales these fancy algorithms will likely have different performances. You will probably find several (maybe different) answers to your question in good books on cryptography, algorithmics and computational number theory. Again, depending on your scale, it might even be an option to simple precompute a large list a prime numbers, save it, and then given an input number search within this list for the smallest divisor - which will immediately have the greatest divisor pop up, too.
3,545,259
I am currently using the following code but its very slow for large numbers ``` static int divisor(int number) { int i; for (i = number / 2; i >= 1; i--) { if (number % i == 0) { break; } } return i; } ```
2010/08/23
[ "https://Stackoverflow.com/questions/3545259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301012/" ]
Optimization: An odd number can't have even number as largest divisor. Use this filter on number early. So if odd number is given. * First do division with 2. * Then decrement i by 2 everytime in loop This is will improve speed for odd numbers.
The best algorithm will depend on how huge your numbers will really be. This problem is basically as hard as factoring integers - if have some factoring algorithm, it will be rather easy to use it to construct the greatest non-trivial divisor. Again, which of all the known factoring algorithms you employ for a number should depend on its 'hugeness', as for different scales these fancy algorithms will likely have different performances. You will probably find several (maybe different) answers to your question in good books on cryptography, algorithmics and computational number theory. Again, depending on your scale, it might even be an option to simple precompute a large list a prime numbers, save it, and then given an input number search within this list for the smallest divisor - which will immediately have the greatest divisor pop up, too.
3,545,259
I am currently using the following code but its very slow for large numbers ``` static int divisor(int number) { int i; for (i = number / 2; i >= 1; i--) { if (number % i == 0) { break; } } return i; } ```
2010/08/23
[ "https://Stackoverflow.com/questions/3545259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301012/" ]
Don't know if it's the optimal solution but you'd probably be better starting at 2 then going upwards such as: ``` static int divisor(int number) { int i; for (i = 2; i <sqrt(number); i++) { if (number % i == 0) { break; } } return number/i; } ``` EDIT ==== to get it to work with primes as well: ``` static int divisor(int number) { int i; for (i = 2; i <=sqrt(number); i++) { if (number % i == 0) { return number/i; } } return 1; } ```
* Find the *first prime* which divides the number *N*. * Let's say that prime is *d*. * Divide *N* by *d*. * This is the required result that you want.
3,545,259
I am currently using the following code but its very slow for large numbers ``` static int divisor(int number) { int i; for (i = number / 2; i >= 1; i--) { if (number % i == 0) { break; } } return i; } ```
2010/08/23
[ "https://Stackoverflow.com/questions/3545259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301012/" ]
One of the industry standard methods for finding factors of large numbers is the Quadratic Sieve algorithm. Have a read of this: <http://en.wikipedia.org/wiki/Quadratic_sieve> P.S. you should also consider how big your numbers are. Different factorisation algorithms tend to perform well for a certain size, and not for others. As noted in the QS wiki article, this method is generally the fastest for numbers less than about 100 decimal digits.
The best algorithm will depend on how huge your numbers will really be. This problem is basically as hard as factoring integers - if have some factoring algorithm, it will be rather easy to use it to construct the greatest non-trivial divisor. Again, which of all the known factoring algorithms you employ for a number should depend on its 'hugeness', as for different scales these fancy algorithms will likely have different performances. You will probably find several (maybe different) answers to your question in good books on cryptography, algorithmics and computational number theory. Again, depending on your scale, it might even be an option to simple precompute a large list a prime numbers, save it, and then given an input number search within this list for the smallest divisor - which will immediately have the greatest divisor pop up, too.
3,545,259
I am currently using the following code but its very slow for large numbers ``` static int divisor(int number) { int i; for (i = number / 2; i >= 1; i--) { if (number % i == 0) { break; } } return i; } ```
2010/08/23
[ "https://Stackoverflow.com/questions/3545259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301012/" ]
In order to limit your search space, you should start at 2 and work up to the square root of the number. There are far more numbers (in a finite search space) divisible by 2 than by 27 so you're more likely to get a low divisor than a high one, statistically speaking. You'll find a big difference when using the square root, rather than half the value, when you processing (for example) 1,000,000. The difference is between a search space of 500,000 for your method and 1,000 for the square root method is considerable. Another advantage is to halve the search space right at the front by discounting multiples of two. Then, when you have your lowest divisor, the highest one is simply the number divided by that. Pseudocode: ``` if n % 2 == 0: # Halve search space straight up. print n / 2 else: i = 3 # Start at 3. while i * i <= n: # Or use i <= sqrt(n), provided sqrt is calc'ed once if n % i == 0: print n / i # If multiple, get opposite number, print and stop break i = i + 2 # Only need to process odd numbers ```
Optimization: An odd number can't have even number as largest divisor. Use this filter on number early. So if odd number is given. * First do division with 2. * Then decrement i by 2 everytime in loop This is will improve speed for odd numbers.
3,545,259
I am currently using the following code but its very slow for large numbers ``` static int divisor(int number) { int i; for (i = number / 2; i >= 1; i--) { if (number % i == 0) { break; } } return i; } ```
2010/08/23
[ "https://Stackoverflow.com/questions/3545259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301012/" ]
In order to limit your search space, you should start at 2 and work up to the square root of the number. There are far more numbers (in a finite search space) divisible by 2 than by 27 so you're more likely to get a low divisor than a high one, statistically speaking. You'll find a big difference when using the square root, rather than half the value, when you processing (for example) 1,000,000. The difference is between a search space of 500,000 for your method and 1,000 for the square root method is considerable. Another advantage is to halve the search space right at the front by discounting multiples of two. Then, when you have your lowest divisor, the highest one is simply the number divided by that. Pseudocode: ``` if n % 2 == 0: # Halve search space straight up. print n / 2 else: i = 3 # Start at 3. while i * i <= n: # Or use i <= sqrt(n), provided sqrt is calc'ed once if n % i == 0: print n / i # If multiple, get opposite number, print and stop break i = i + 2 # Only need to process odd numbers ```
Java implementation of the solution: ``` static int highestDivisor(int n) { if ((n & 1) == 0) return n / 2; int i = 3; while (i * i <= n) { if (n % i == 0) { return n / i; } i = i + 2; } return 1; } ```
3,545,259
I am currently using the following code but its very slow for large numbers ``` static int divisor(int number) { int i; for (i = number / 2; i >= 1; i--) { if (number % i == 0) { break; } } return i; } ```
2010/08/23
[ "https://Stackoverflow.com/questions/3545259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301012/" ]
First thought you can find the smallest divisor d (not equal to 1 of course), then N/d will be the largest divisor you're looking for. For example if N is divisible by 3 then you'll need 2 iterations to find the answer - in your case it would be about N/6 iterations. **Edit:** To further improve your algorithm you can iterate through odd numbers only (after checking if you number is even) or, even better, if you have the list of primes pre-calculated then you can iterate through them only because smallest divisor is obviously is a prime number.
A huge optimization (not sure if it's completely optimal - you'd have to ask a mathematician for that) is to search upwards using only prime numbers. As Vladimir and Bunnit said, it is better to search upwards, because you'll find it to be much faster. Then, return the inverse (`number / i`). However, if you've already tried 2 and come up dry, there is no point in trying 4 or 6. Similarly, if you've tried 3, there's no point in trying 6 or 9. So, if time of running is a big concern, you could have a list of the first 100 primes hard coded in your program. Test each of them. If you don't find an answer by then, then you could just increment by 2 (skipping even numbers).
51,549,554
I want to completely disconnect my app from Firebase. This question has been asked several times (e.g [here](https://stackoverflow.com/questions/37486516/how-do-i-delete-remove-an-app-from-a-firebase-project/37487344)). Most of the answers focus on disconnecting an app from Firebase **within the Firebase console** and not **within Android studio**. After disconnecting my app from the Firebase console. Everytime I try to reconnect the app to another Firebase project, an error balloon pops up stating that the app is already part of a Firebase project. I know this behaviour occurs because some files from the old Firebase project are still present. How do I get rid of them?
2018/07/27
[ "https://Stackoverflow.com/questions/51549554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670752/" ]
Try these steps to remove Fire-base from Android Studio project. > > Delete `google-services.json` file from the Project (Find the file by Project view) > > > Remove dependencies from Project-level `build.gradle` (/build.gradle) > > > ``` buildscript { dependencies { // Remove this line classpath 'com.google.gms:google-services:4.2.0' } } ``` > > Remove all the Fire-base related dependencies from the project App-level `build.gradle` (//build.gradle) file > > > ``` dependencies { // Remove this line implementation 'com.google.firebase:firebase-core:17.0.0' } ``` > > Remove the line below from the bottom of the App-level `build.gradle` (//build.gradle) file > > > ``` apply plugin: 'com.google.gms.google-services' ``` > > Restart Android Studio > > >
Try shutting down the Firebase project created with the package name of the connected application; although it doesn't delete at the same time and is scheduled for later. Don't link your android app with any other firebase app till the previous connected app has been deleted completely.
51,549,554
I want to completely disconnect my app from Firebase. This question has been asked several times (e.g [here](https://stackoverflow.com/questions/37486516/how-do-i-delete-remove-an-app-from-a-firebase-project/37487344)). Most of the answers focus on disconnecting an app from Firebase **within the Firebase console** and not **within Android studio**. After disconnecting my app from the Firebase console. Everytime I try to reconnect the app to another Firebase project, an error balloon pops up stating that the app is already part of a Firebase project. I know this behaviour occurs because some files from the old Firebase project are still present. How do I get rid of them?
2018/07/27
[ "https://Stackoverflow.com/questions/51549554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670752/" ]
Try this, On the project level, delete the google-services.json file [![enter image description here](https://i.stack.imgur.com/Aytkm.png)](https://i.stack.imgur.com/Aytkm.png) and then sync the project [![enter image description here](https://i.stack.imgur.com/ZfEdS.png)](https://i.stack.imgur.com/ZfEdS.png)
Try shutting down the Firebase project created with the package name of the connected application; although it doesn't delete at the same time and is scheduled for later. Don't link your android app with any other firebase app till the previous connected app has been deleted completely.
51,549,554
I want to completely disconnect my app from Firebase. This question has been asked several times (e.g [here](https://stackoverflow.com/questions/37486516/how-do-i-delete-remove-an-app-from-a-firebase-project/37487344)). Most of the answers focus on disconnecting an app from Firebase **within the Firebase console** and not **within Android studio**. After disconnecting my app from the Firebase console. Everytime I try to reconnect the app to another Firebase project, an error balloon pops up stating that the app is already part of a Firebase project. I know this behaviour occurs because some files from the old Firebase project are still present. How do I get rid of them?
2018/07/27
[ "https://Stackoverflow.com/questions/51549554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670752/" ]
Try these steps to remove Fire-base from Android Studio project. > > Delete `google-services.json` file from the Project (Find the file by Project view) > > > Remove dependencies from Project-level `build.gradle` (/build.gradle) > > > ``` buildscript { dependencies { // Remove this line classpath 'com.google.gms:google-services:4.2.0' } } ``` > > Remove all the Fire-base related dependencies from the project App-level `build.gradle` (//build.gradle) file > > > ``` dependencies { // Remove this line implementation 'com.google.firebase:firebase-core:17.0.0' } ``` > > Remove the line below from the bottom of the App-level `build.gradle` (//build.gradle) file > > > ``` apply plugin: 'com.google.gms.google-services' ``` > > Restart Android Studio > > >
Do the following (If you want to Switch Firebase Data Sources): In Android Studio, Go to Tools>Firebase, Choose any of the options such as Real time-database Click Connect to Firebase. You will get a warning that the App is already connected to Firebase. Click okay. Android Studio will open a Firebase console on a browser. Choose the Firebase App you want to you want to connect to. Done.
51,549,554
I want to completely disconnect my app from Firebase. This question has been asked several times (e.g [here](https://stackoverflow.com/questions/37486516/how-do-i-delete-remove-an-app-from-a-firebase-project/37487344)). Most of the answers focus on disconnecting an app from Firebase **within the Firebase console** and not **within Android studio**. After disconnecting my app from the Firebase console. Everytime I try to reconnect the app to another Firebase project, an error balloon pops up stating that the app is already part of a Firebase project. I know this behaviour occurs because some files from the old Firebase project are still present. How do I get rid of them?
2018/07/27
[ "https://Stackoverflow.com/questions/51549554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670752/" ]
Try these steps to remove Fire-base from Android Studio project. > > Delete `google-services.json` file from the Project (Find the file by Project view) > > > Remove dependencies from Project-level `build.gradle` (/build.gradle) > > > ``` buildscript { dependencies { // Remove this line classpath 'com.google.gms:google-services:4.2.0' } } ``` > > Remove all the Fire-base related dependencies from the project App-level `build.gradle` (//build.gradle) file > > > ``` dependencies { // Remove this line implementation 'com.google.firebase:firebase-core:17.0.0' } ``` > > Remove the line below from the bottom of the App-level `build.gradle` (//build.gradle) file > > > ``` apply plugin: 'com.google.gms.google-services' ``` > > Restart Android Studio > > >
You should undo all the steps that you are instructed to perform in the [manual integration](https://firebase.google.com/docs/android/setup). So, remove all Firebase dependencies from build.gradle, remove the Google Services plugin from the bottom of build.gradle, and remove the google-services.json file.
51,549,554
I want to completely disconnect my app from Firebase. This question has been asked several times (e.g [here](https://stackoverflow.com/questions/37486516/how-do-i-delete-remove-an-app-from-a-firebase-project/37487344)). Most of the answers focus on disconnecting an app from Firebase **within the Firebase console** and not **within Android studio**. After disconnecting my app from the Firebase console. Everytime I try to reconnect the app to another Firebase project, an error balloon pops up stating that the app is already part of a Firebase project. I know this behaviour occurs because some files from the old Firebase project are still present. How do I get rid of them?
2018/07/27
[ "https://Stackoverflow.com/questions/51549554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670752/" ]
You should undo all the steps that you are instructed to perform in the [manual integration](https://firebase.google.com/docs/android/setup). So, remove all Firebase dependencies from build.gradle, remove the Google Services plugin from the bottom of build.gradle, and remove the google-services.json file.
Do the following (If you want to Switch Firebase Data Sources): In Android Studio, Go to Tools>Firebase, Choose any of the options such as Real time-database Click Connect to Firebase. You will get a warning that the App is already connected to Firebase. Click okay. Android Studio will open a Firebase console on a browser. Choose the Firebase App you want to you want to connect to. Done.
51,549,554
I want to completely disconnect my app from Firebase. This question has been asked several times (e.g [here](https://stackoverflow.com/questions/37486516/how-do-i-delete-remove-an-app-from-a-firebase-project/37487344)). Most of the answers focus on disconnecting an app from Firebase **within the Firebase console** and not **within Android studio**. After disconnecting my app from the Firebase console. Everytime I try to reconnect the app to another Firebase project, an error balloon pops up stating that the app is already part of a Firebase project. I know this behaviour occurs because some files from the old Firebase project are still present. How do I get rid of them?
2018/07/27
[ "https://Stackoverflow.com/questions/51549554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670752/" ]
Try this, On the project level, delete the google-services.json file [![enter image description here](https://i.stack.imgur.com/Aytkm.png)](https://i.stack.imgur.com/Aytkm.png) and then sync the project [![enter image description here](https://i.stack.imgur.com/ZfEdS.png)](https://i.stack.imgur.com/ZfEdS.png)
On the main menu, select app ,select ,google-services.json' and then right click then delete
51,549,554
I want to completely disconnect my app from Firebase. This question has been asked several times (e.g [here](https://stackoverflow.com/questions/37486516/how-do-i-delete-remove-an-app-from-a-firebase-project/37487344)). Most of the answers focus on disconnecting an app from Firebase **within the Firebase console** and not **within Android studio**. After disconnecting my app from the Firebase console. Everytime I try to reconnect the app to another Firebase project, an error balloon pops up stating that the app is already part of a Firebase project. I know this behaviour occurs because some files from the old Firebase project are still present. How do I get rid of them?
2018/07/27
[ "https://Stackoverflow.com/questions/51549554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670752/" ]
You should undo all the steps that you are instructed to perform in the [manual integration](https://firebase.google.com/docs/android/setup). So, remove all Firebase dependencies from build.gradle, remove the Google Services plugin from the bottom of build.gradle, and remove the google-services.json file.
On the main menu, select app ,select ,google-services.json' and then right click then delete
51,549,554
I want to completely disconnect my app from Firebase. This question has been asked several times (e.g [here](https://stackoverflow.com/questions/37486516/how-do-i-delete-remove-an-app-from-a-firebase-project/37487344)). Most of the answers focus on disconnecting an app from Firebase **within the Firebase console** and not **within Android studio**. After disconnecting my app from the Firebase console. Everytime I try to reconnect the app to another Firebase project, an error balloon pops up stating that the app is already part of a Firebase project. I know this behaviour occurs because some files from the old Firebase project are still present. How do I get rid of them?
2018/07/27
[ "https://Stackoverflow.com/questions/51549554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670752/" ]
You should undo all the steps that you are instructed to perform in the [manual integration](https://firebase.google.com/docs/android/setup). So, remove all Firebase dependencies from build.gradle, remove the Google Services plugin from the bottom of build.gradle, and remove the google-services.json file.
Try shutting down the Firebase project created with the package name of the connected application; although it doesn't delete at the same time and is scheduled for later. Don't link your android app with any other firebase app till the previous connected app has been deleted completely.
51,549,554
I want to completely disconnect my app from Firebase. This question has been asked several times (e.g [here](https://stackoverflow.com/questions/37486516/how-do-i-delete-remove-an-app-from-a-firebase-project/37487344)). Most of the answers focus on disconnecting an app from Firebase **within the Firebase console** and not **within Android studio**. After disconnecting my app from the Firebase console. Everytime I try to reconnect the app to another Firebase project, an error balloon pops up stating that the app is already part of a Firebase project. I know this behaviour occurs because some files from the old Firebase project are still present. How do I get rid of them?
2018/07/27
[ "https://Stackoverflow.com/questions/51549554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670752/" ]
Try these steps to remove Fire-base from Android Studio project. > > Delete `google-services.json` file from the Project (Find the file by Project view) > > > Remove dependencies from Project-level `build.gradle` (/build.gradle) > > > ``` buildscript { dependencies { // Remove this line classpath 'com.google.gms:google-services:4.2.0' } } ``` > > Remove all the Fire-base related dependencies from the project App-level `build.gradle` (//build.gradle) file > > > ``` dependencies { // Remove this line implementation 'com.google.firebase:firebase-core:17.0.0' } ``` > > Remove the line below from the bottom of the App-level `build.gradle` (//build.gradle) file > > > ``` apply plugin: 'com.google.gms.google-services' ``` > > Restart Android Studio > > >
Try this, On the project level, delete the google-services.json file [![enter image description here](https://i.stack.imgur.com/Aytkm.png)](https://i.stack.imgur.com/Aytkm.png) and then sync the project [![enter image description here](https://i.stack.imgur.com/ZfEdS.png)](https://i.stack.imgur.com/ZfEdS.png)
51,549,554
I want to completely disconnect my app from Firebase. This question has been asked several times (e.g [here](https://stackoverflow.com/questions/37486516/how-do-i-delete-remove-an-app-from-a-firebase-project/37487344)). Most of the answers focus on disconnecting an app from Firebase **within the Firebase console** and not **within Android studio**. After disconnecting my app from the Firebase console. Everytime I try to reconnect the app to another Firebase project, an error balloon pops up stating that the app is already part of a Firebase project. I know this behaviour occurs because some files from the old Firebase project are still present. How do I get rid of them?
2018/07/27
[ "https://Stackoverflow.com/questions/51549554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670752/" ]
Try this, On the project level, delete the google-services.json file [![enter image description here](https://i.stack.imgur.com/Aytkm.png)](https://i.stack.imgur.com/Aytkm.png) and then sync the project [![enter image description here](https://i.stack.imgur.com/ZfEdS.png)](https://i.stack.imgur.com/ZfEdS.png)
Do the following (If you want to Switch Firebase Data Sources): In Android Studio, Go to Tools>Firebase, Choose any of the options such as Real time-database Click Connect to Firebase. You will get a warning that the App is already connected to Firebase. Click okay. Android Studio will open a Firebase console on a browser. Choose the Firebase App you want to you want to connect to. Done.
48,442,661
Using [`deal`](https://mathworks.com/help/matlab/ref/deal.html) we can write anonymous functions that have multiple output arguments, like for example ``` minmax = @(x)deal(min(x),max(x)); [u,v] = minmax([1,2,3,4]); % outputs u = 1, v = 4 ``` But if you want to provide a function with its gradient to the optimization function [`fminunc`](https://mathworks.com/help/optim/ug/fminunc.html) this does not work. ~~The function `fminunc` calls the input function sometimes with one and sometimes with two output arguments.~~ *(EDIT: This is not true, you just have to specify whether you actually want to use the gradient or not, using e.g. `optimset('SpecifyObjectiveGradient',true)`. Then within one call it always asks for the same number of arguments.)* We have to provide something like ``` function [f,g] = myFun(x) f = x^2; % function g = 2*x; % gradient ``` which can be called with one *or* two output arguments. So is there a way to do the same inline without using the `function` keyword?
2018/01/25
[ "https://Stackoverflow.com/questions/48442661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2913106/" ]
The [OP's solution](https://stackoverflow.com/a/48442667/3372061) is good in that it's concise and useful in many cases. However, it has one main shortcoming, in that it's less scalable than otherwise possible. This claim is made because all functions (`{x^2,2*x,2}`) are evaluated, regardless of whether they're needed as outputs or not - which results in "wasted" computation time and memory consumption when less than 3 outputs are requested. In the example of this question this is not an issue because the function and its derivatives are very easy to compute and the input `x` is a **scalar**, but under different circumstances, this can be a very real issue. I'm providing a modified version, which although uglier, avoids the aforementioned problem and is somewhat more general: ``` funcs_to_apply = {@(x)x.^2, @(x)2*x, @(x)2}; unpacker = @(x)deal(x{:}); myFun = @(x)unpacker(cellfun(@(c)feval(c,x),... funcs_to_apply(1:evalin('caller','nargout')),... 'UniformOutput',false)... ); ``` Notes: 1. The additional functions I use are [`cellfun`](https://www.mathworks.com/help/matlab/ref/cellfun.html), [`evalin`](https://www.mathworks.com/help/matlab/ref/evalin.html) and [`feval`](https://www.mathworks.com/help/matlab/ref/feval.html). 2. The `'UniformOutput'` argument was only added so that the output of `cellfun` is a cell (and can be "unpacked" to a [comma-separated list](https://www.mathworks.com/help/matlab/matlab_prog/comma-separated-lists.html); we could've wrapped it in `num2cell` instead). 3. The `evalin` trick is required since in the `myFun` scope we don't know how many outputs were requested from `unpacker`. 4. While `eval` in its various forms (here: `evalin`) is usually discouraged, in this case we know exactly who the caller is and that this is a safe operation.
Yes there is, it involves a technique used in [this question](https://stackoverflow.com/questions/32237198/recursive-anonymous-function-matlab) about recursive anonymous functions. First we define a helper function ``` helper = @(c,n)deal(c{1:n}); ``` which accepts a cell array `c` of the possible outputs as well as an integer `n` that says how many outputs we need. To write our actual function we just need to define the cell array and pass `nargout` (the number of expected output arguments) to `helper`: ``` myFun = @(x)helper({x^2,2*x,2},nargout); ``` This now works perfectly when calling `fminunc`: ``` x = fminunc(myFun,1); ```
3,474
I understand that you should use an amp that was meant to be used with your instrument, but sometimes maybe you just don't have the money, or your amp is not around when you need it, or for whatever reason you would like to make use of what you do have at the moment.. So, how safe is it to plug an electric bass guitar into a guitar amp? I remember some people saying to me that it would eventualy break the amp. Is it true? If it is, why? The same question goes to plugging it into your home hi-fi system.. I gues it also probably isn't a very smart ide to plug your electric guitar into your hi-fi neither?
2011/07/19
[ "https://music.stackexchange.com/questions/3474", "https://music.stackexchange.com", "https://music.stackexchange.com/users/935/" ]
With regard to hi-fis, one option that's not yet been discussed here is to use an amp-modelling pedal, such as the ones made by Line 6 and Zoom. These take instrument-level inputs, and have line-level outputs. So you can safely connect them to the phono inputs of a hi-fi, or PC speakers, etc, while getting the sound of a "proper" bass amp. Hi-fi speakers and amps are designed to play back recordings of bass parts, so they should be able to handle actual bass parts. Just don't crank it up louder than it's designed for.
Keep the volume low if your using a guitar amp for a bass. Last thing you want to do is crack the speakers in your amp if your playing the bass with high volume. Try to lower the bass on the amp as well.
3,474
I understand that you should use an amp that was meant to be used with your instrument, but sometimes maybe you just don't have the money, or your amp is not around when you need it, or for whatever reason you would like to make use of what you do have at the moment.. So, how safe is it to plug an electric bass guitar into a guitar amp? I remember some people saying to me that it would eventualy break the amp. Is it true? If it is, why? The same question goes to plugging it into your home hi-fi system.. I gues it also probably isn't a very smart ide to plug your electric guitar into your hi-fi neither?
2011/07/19
[ "https://music.stackexchange.com/questions/3474", "https://music.stackexchange.com", "https://music.stackexchange.com/users/935/" ]
It is actually nowhere near as dangerous as you might think, as long as you keep the volume relatively low. You won't get an ideal frequency response, as a guitar amp is designed for the frequencies a guitar produces, but it will do as a stop-gap until you get a suitable amp. The reason for keeping the volume lower than you might want to is that the large transients produced by a bass guitar could damage the electronics or the cone. My experience has been that most amps cope with a lot more than they are officially specced for:-) -oh, and depending on where you hook in, you can use a hifi as an amplifier. I have previously modified a 1956 radiogram and an original Sony Walkman to be guitar amps - both worked fine. In fact the radiogram had a wonderful sound!
I used a Line 6 Pod and a Midi-Man 6 channel mixer to get `Line Out` and piped it into my stereo system for over 10 years when I didn't have room for an amp for my Bass. It sounded awesome with the sub that I have, it would shake the walls of the house. And a bonus I was able to run my drum machine and a few other things through the mini-mixer and get a clean balanced mix just like it was recorded. Way better than an amp in my opinion. Now that I have more room, I still don't have any amps, I have a Bose L1 Model II instead, personally I don't have any use for bass or guitar amps. I use a Roland V-Bass now and only use my Bass Pod Pro for when friends come over with their bass, but the idea is the same, as long as it is a `Line Level` output it is safe to run into a home stereo amplifier.
3,474
I understand that you should use an amp that was meant to be used with your instrument, but sometimes maybe you just don't have the money, or your amp is not around when you need it, or for whatever reason you would like to make use of what you do have at the moment.. So, how safe is it to plug an electric bass guitar into a guitar amp? I remember some people saying to me that it would eventualy break the amp. Is it true? If it is, why? The same question goes to plugging it into your home hi-fi system.. I gues it also probably isn't a very smart ide to plug your electric guitar into your hi-fi neither?
2011/07/19
[ "https://music.stackexchange.com/questions/3474", "https://music.stackexchange.com", "https://music.stackexchange.com/users/935/" ]
It is actually nowhere near as dangerous as you might think, as long as you keep the volume relatively low. You won't get an ideal frequency response, as a guitar amp is designed for the frequencies a guitar produces, but it will do as a stop-gap until you get a suitable amp. The reason for keeping the volume lower than you might want to is that the large transients produced by a bass guitar could damage the electronics or the cone. My experience has been that most amps cope with a lot more than they are officially specced for:-) -oh, and depending on where you hook in, you can use a hifi as an amplifier. I have previously modified a 1956 radiogram and an original Sony Walkman to be guitar amps - both worked fine. In fact the radiogram had a wonderful sound!
With regard to hi-fis, one option that's not yet been discussed here is to use an amp-modelling pedal, such as the ones made by Line 6 and Zoom. These take instrument-level inputs, and have line-level outputs. So you can safely connect them to the phono inputs of a hi-fi, or PC speakers, etc, while getting the sound of a "proper" bass amp. Hi-fi speakers and amps are designed to play back recordings of bass parts, so they should be able to handle actual bass parts. Just don't crank it up louder than it's designed for.
3,474
I understand that you should use an amp that was meant to be used with your instrument, but sometimes maybe you just don't have the money, or your amp is not around when you need it, or for whatever reason you would like to make use of what you do have at the moment.. So, how safe is it to plug an electric bass guitar into a guitar amp? I remember some people saying to me that it would eventualy break the amp. Is it true? If it is, why? The same question goes to plugging it into your home hi-fi system.. I gues it also probably isn't a very smart ide to plug your electric guitar into your hi-fi neither?
2011/07/19
[ "https://music.stackexchange.com/questions/3474", "https://music.stackexchange.com", "https://music.stackexchange.com/users/935/" ]
With regard to hi-fis, one option that's not yet been discussed here is to use an amp-modelling pedal, such as the ones made by Line 6 and Zoom. These take instrument-level inputs, and have line-level outputs. So you can safely connect them to the phono inputs of a hi-fi, or PC speakers, etc, while getting the sound of a "proper" bass amp. Hi-fi speakers and amps are designed to play back recordings of bass parts, so they should be able to handle actual bass parts. Just don't crank it up louder than it's designed for.
I used a Line 6 Pod and a Midi-Man 6 channel mixer to get `Line Out` and piped it into my stereo system for over 10 years when I didn't have room for an amp for my Bass. It sounded awesome with the sub that I have, it would shake the walls of the house. And a bonus I was able to run my drum machine and a few other things through the mini-mixer and get a clean balanced mix just like it was recorded. Way better than an amp in my opinion. Now that I have more room, I still don't have any amps, I have a Bose L1 Model II instead, personally I don't have any use for bass or guitar amps. I use a Roland V-Bass now and only use my Bass Pod Pro for when friends come over with their bass, but the idea is the same, as long as it is a `Line Level` output it is safe to run into a home stereo amplifier.
3,474
I understand that you should use an amp that was meant to be used with your instrument, but sometimes maybe you just don't have the money, or your amp is not around when you need it, or for whatever reason you would like to make use of what you do have at the moment.. So, how safe is it to plug an electric bass guitar into a guitar amp? I remember some people saying to me that it would eventualy break the amp. Is it true? If it is, why? The same question goes to plugging it into your home hi-fi system.. I gues it also probably isn't a very smart ide to plug your electric guitar into your hi-fi neither?
2011/07/19
[ "https://music.stackexchange.com/questions/3474", "https://music.stackexchange.com", "https://music.stackexchange.com/users/935/" ]
It is actually nowhere near as dangerous as you might think, as long as you keep the volume relatively low. You won't get an ideal frequency response, as a guitar amp is designed for the frequencies a guitar produces, but it will do as a stop-gap until you get a suitable amp. The reason for keeping the volume lower than you might want to is that the large transients produced by a bass guitar could damage the electronics or the cone. My experience has been that most amps cope with a lot more than they are officially specced for:-) -oh, and depending on where you hook in, you can use a hifi as an amplifier. I have previously modified a 1956 radiogram and an original Sony Walkman to be guitar amps - both worked fine. In fact the radiogram had a wonderful sound!
Keep the volume low if your using a guitar amp for a bass. Last thing you want to do is crack the speakers in your amp if your playing the bass with high volume. Try to lower the bass on the amp as well.
3,474
I understand that you should use an amp that was meant to be used with your instrument, but sometimes maybe you just don't have the money, or your amp is not around when you need it, or for whatever reason you would like to make use of what you do have at the moment.. So, how safe is it to plug an electric bass guitar into a guitar amp? I remember some people saying to me that it would eventualy break the amp. Is it true? If it is, why? The same question goes to plugging it into your home hi-fi system.. I gues it also probably isn't a very smart ide to plug your electric guitar into your hi-fi neither?
2011/07/19
[ "https://music.stackexchange.com/questions/3474", "https://music.stackexchange.com", "https://music.stackexchange.com/users/935/" ]
With regard to hi-fis, one option that's not yet been discussed here is to use an amp-modelling pedal, such as the ones made by Line 6 and Zoom. These take instrument-level inputs, and have line-level outputs. So you can safely connect them to the phono inputs of a hi-fi, or PC speakers, etc, while getting the sound of a "proper" bass amp. Hi-fi speakers and amps are designed to play back recordings of bass parts, so they should be able to handle actual bass parts. Just don't crank it up louder than it's designed for.
I was rehearsing at either guitar amp or home hi-fi. First of all, you should low down all your switches, and only after that slowly add all of them. You should decide for yourself then to stop, generally you should simply avoid extraneous sounds from your hi-fi or amp. I've switched into small Fender amp, something like that: ![enter image description here](https://i.stack.imgur.com/U2Soz.jpg) and standard hi-fi system, switched into the microphone hole, and there were no problems at all, just in somewhat strange sound (not very `bass`). This level is good for rehearsing, but if you are going to make some show, do not use this way - it's not worth.
3,474
I understand that you should use an amp that was meant to be used with your instrument, but sometimes maybe you just don't have the money, or your amp is not around when you need it, or for whatever reason you would like to make use of what you do have at the moment.. So, how safe is it to plug an electric bass guitar into a guitar amp? I remember some people saying to me that it would eventualy break the amp. Is it true? If it is, why? The same question goes to plugging it into your home hi-fi system.. I gues it also probably isn't a very smart ide to plug your electric guitar into your hi-fi neither?
2011/07/19
[ "https://music.stackexchange.com/questions/3474", "https://music.stackexchange.com", "https://music.stackexchange.com/users/935/" ]
Keyboard amps and Electronic Drum Amps will work fine for bass. They both produce frequencies in the same range that a bass does. I'll leave the discussion of guitar amps and hifi's to what has already been contributed.
I was rehearsing at either guitar amp or home hi-fi. First of all, you should low down all your switches, and only after that slowly add all of them. You should decide for yourself then to stop, generally you should simply avoid extraneous sounds from your hi-fi or amp. I've switched into small Fender amp, something like that: ![enter image description here](https://i.stack.imgur.com/U2Soz.jpg) and standard hi-fi system, switched into the microphone hole, and there were no problems at all, just in somewhat strange sound (not very `bass`). This level is good for rehearsing, but if you are going to make some show, do not use this way - it's not worth.
3,474
I understand that you should use an amp that was meant to be used with your instrument, but sometimes maybe you just don't have the money, or your amp is not around when you need it, or for whatever reason you would like to make use of what you do have at the moment.. So, how safe is it to plug an electric bass guitar into a guitar amp? I remember some people saying to me that it would eventualy break the amp. Is it true? If it is, why? The same question goes to plugging it into your home hi-fi system.. I gues it also probably isn't a very smart ide to plug your electric guitar into your hi-fi neither?
2011/07/19
[ "https://music.stackexchange.com/questions/3474", "https://music.stackexchange.com", "https://music.stackexchange.com/users/935/" ]
It is actually nowhere near as dangerous as you might think, as long as you keep the volume relatively low. You won't get an ideal frequency response, as a guitar amp is designed for the frequencies a guitar produces, but it will do as a stop-gap until you get a suitable amp. The reason for keeping the volume lower than you might want to is that the large transients produced by a bass guitar could damage the electronics or the cone. My experience has been that most amps cope with a lot more than they are officially specced for:-) -oh, and depending on where you hook in, you can use a hifi as an amplifier. I have previously modified a 1956 radiogram and an original Sony Walkman to be guitar amps - both worked fine. In fact the radiogram had a wonderful sound!
I was rehearsing at either guitar amp or home hi-fi. First of all, you should low down all your switches, and only after that slowly add all of them. You should decide for yourself then to stop, generally you should simply avoid extraneous sounds from your hi-fi or amp. I've switched into small Fender amp, something like that: ![enter image description here](https://i.stack.imgur.com/U2Soz.jpg) and standard hi-fi system, switched into the microphone hole, and there were no problems at all, just in somewhat strange sound (not very `bass`). This level is good for rehearsing, but if you are going to make some show, do not use this way - it's not worth.
3,474
I understand that you should use an amp that was meant to be used with your instrument, but sometimes maybe you just don't have the money, or your amp is not around when you need it, or for whatever reason you would like to make use of what you do have at the moment.. So, how safe is it to plug an electric bass guitar into a guitar amp? I remember some people saying to me that it would eventualy break the amp. Is it true? If it is, why? The same question goes to plugging it into your home hi-fi system.. I gues it also probably isn't a very smart ide to plug your electric guitar into your hi-fi neither?
2011/07/19
[ "https://music.stackexchange.com/questions/3474", "https://music.stackexchange.com", "https://music.stackexchange.com/users/935/" ]
With regard to hi-fis, one option that's not yet been discussed here is to use an amp-modelling pedal, such as the ones made by Line 6 and Zoom. These take instrument-level inputs, and have line-level outputs. So you can safely connect them to the phono inputs of a hi-fi, or PC speakers, etc, while getting the sound of a "proper" bass amp. Hi-fi speakers and amps are designed to play back recordings of bass parts, so they should be able to handle actual bass parts. Just don't crank it up louder than it's designed for.
Keyboard amps and Electronic Drum Amps will work fine for bass. They both produce frequencies in the same range that a bass does. I'll leave the discussion of guitar amps and hifi's to what has already been contributed.
3,474
I understand that you should use an amp that was meant to be used with your instrument, but sometimes maybe you just don't have the money, or your amp is not around when you need it, or for whatever reason you would like to make use of what you do have at the moment.. So, how safe is it to plug an electric bass guitar into a guitar amp? I remember some people saying to me that it would eventualy break the amp. Is it true? If it is, why? The same question goes to plugging it into your home hi-fi system.. I gues it also probably isn't a very smart ide to plug your electric guitar into your hi-fi neither?
2011/07/19
[ "https://music.stackexchange.com/questions/3474", "https://music.stackexchange.com", "https://music.stackexchange.com/users/935/" ]
It is actually nowhere near as dangerous as you might think, as long as you keep the volume relatively low. You won't get an ideal frequency response, as a guitar amp is designed for the frequencies a guitar produces, but it will do as a stop-gap until you get a suitable amp. The reason for keeping the volume lower than you might want to is that the large transients produced by a bass guitar could damage the electronics or the cone. My experience has been that most amps cope with a lot more than they are officially specced for:-) -oh, and depending on where you hook in, you can use a hifi as an amplifier. I have previously modified a 1956 radiogram and an original Sony Walkman to be guitar amps - both worked fine. In fact the radiogram had a wonderful sound!
Keyboard amps and Electronic Drum Amps will work fine for bass. They both produce frequencies in the same range that a bass does. I'll leave the discussion of guitar amps and hifi's to what has already been contributed.
1,667,269
I have 5 views in my ASP.NET MVC application. Some data were captured from these views and I am navigating through these views using 2 buttons: the Previous and Next buttons. So I fill the data in View 1 and I go to view 2 and enter the data there and so on.. till View 5. Now the question is: If I come back again to previous views, how to retain the data entered there in that particular view. In addition, I want to submit the data from all the 5 views at a time, once I finish entering data to all 5 views. What is the best way to do it?
2009/11/03
[ "https://Stackoverflow.com/questions/1667269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200507/" ]
I can think of a number of approaches to your issue. You could create a single view with a number of 'panels' which are hidden or revealed depending on which step you are on in the process, like a wizard control. You could try and use a cookie but that's not very clean. Ideally, you embrace the statelessness of the MVC pattern and the fact the View is a view of the Model and update your Model as each page posts back to your Controller and you persist the Model (however you choose) between pages. Simplicity might lead me to suggest the 'wizard' approach if you don't want to persist anything until the process is complete. I'm certain jQuery could help you out with this solution.
If you only want to submit the content once all pages are filled, you will probably need to store entered data into a cookie on the client machine. You can do this with javascript: <http://www.quirksmode.org/js/cookies.html>
2,624,575
I have found a proof: Let $x=ab$ with $|x|=n$. If we can show that $n=pq$ then we will have a generator for G. Since G is abelian, $x^{pq} = (ab)^{pq} = (a^p)^q (b^q)^p=e$. This only tells us that $n|pq$. Now, $a^n = a^n b^n b^{-n}=(ab)^n(b^{-1})^n=(b^{-1})^n$. We also know that $|b^{-1}| = |b|$. Now, $|a^n| = \frac{p}{gcd(p,n)}$ (why is this always true? I understand that this is valid when $a$ is a generator of G, but $a$ is not a generator in this case). Also, $|b^{-n}|=|b^n|=\frac{q}{gcd(q,n)}=|a^n|$ and therefore $p\cdot gcd(q,n) = q \cdot gcd(p,n) $ and so $p | gcd(p,n)$ because $gcd(p,q)=1$. Thus $p|n$ (again, why is this true? We haven't assumed $p$ is prime, so if $p|gcd(p,n)=\alpha p + \beta n$ and therefore $p|\beta n$ then it is not necessary that $p|n$). Similarly, if $q|gcd(q,n)\Rightarrow q|n$ and because $gcd(p,q)=1$ then $pq|n$ and so $n=pq$. Thus $x$ is a generator of G.
2018/01/28
[ "https://math.stackexchange.com/questions/2624575", "https://math.stackexchange.com", "https://math.stackexchange.com/users/365321/" ]
First we prove that $\langle a\rangle\cap\langle b\rangle={e}.$ If $x=a^{m}=b^{n}$, then $\mathrm{ord}(x)|gcd(p,q)=1,$ thus $x=e.$ Then we show that $G$ is a cyclic group generated by $ab$. Let $\mathrm{ord}(ab)=t.$ We have $e=(ab)^{t}=a^{t}b^{t},$ hence $a^{t}=b^{-t}.$ However $\langle a\rangle\cap\langle b\rangle={e},$ $a^{t}=b^{-t}=e.$ $p|t,q|t\Rightarrow pq=t.$ Clearly,$(ab)^{pq}=e,$ so $G$ is cyclic whose generator is $ab$.
$|a^n| = \frac{p}{gcd(p,n)}$ is true by the proposition (Dummit and Foote page 57): > > **Proposition.** Let $G$ be a group, let $x\in G$ and let $a\in \mathbb{Z}-\{0\}$. > If $|x|=n<\infty$, then $|x^{a}|=\frac{n}{(n,a)}$. > > > $p|n$ is true because $p|(p,n)$ and $(p,n)|n$.
36,763,842
I am trying to come up with a build system for a large project that has a structure like this: ``` ├── deploy ├── docs ├── libs │   ├── lib1 │   └── lib2 ├── scripts └── tools ├── prog1 └── prog2 ``` My problem is that libs and programs may depend on each other in an order that may change very often. I have looked up info on the internet and I get mixed messages. Some people say that I should just use makefiles and some other say that recursive makefiles are evil. Besides that, I don't know how to manage dependencies with makefiles (if `lib2` needs `lib1` to build, how to tell make to build `lib1` first). Someone told me that it is easily achievable using the variable `VPATH` but I have read the documentation and I think it has nothing to do with this. So my questions are: * Should I really avoid makefiles in this case? If so, what are the alternatives? * If I should use makefiles, how can I manage dependencies automatically and efficiently?
2016/04/21
[ "https://Stackoverflow.com/questions/36763842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2235928/" ]
I am in the *don't lie to make* camp. Here, fine-grained dependencies are your friend. Get away from thinking that you need to express that *prog1* depends on *lib2*. What you really want to say to *make* is something like: "To link *prog1* you need all the `.o` files, and all the appropriate `.a` files." If you can express this, it will improve a number of very important parameters for your build: 1. Parallel build works properly * The `.o` file for `prog1` can compile at the same time as those for `lib2.a` * This is more important if you run tests as a part of the build (you do do that, don't you?) 2. Time-to-do-nothing is very close to zero * Nothing worse than issuing a build, and several minutes later you get a *build was already up-to-date* (WinCE, I'm looking at you) 3. Work is properly culled * In other words you can rely on your dependencies, and never have to do a *make clean* because you don't trust them After all, these goals are really the whole point of using *make*. Get them wrong and you might as well use a batch file. (It's pretty tricky getting them right in a recursive make system BTW.) Of course, expressing this cleanly in *make* does take a bit of effort, but you did say you had a *large* project.
I'm not in the recursive makefiles are evil camp -- while it's true that recursive makefiles are not as efficient (they don't maximize concurrency, etc), it's usually negligible. On the flip side, using recursive makefiles makes your project more scalable -- it's simpler to move modules in and out, share with other groups, etc. In your case, if lib2 depends on lib1, you can just do: ``` lib2: lib1 make -C libs/lib2 ``` Now make will build lib1 before lib2 (even if you have -j specified). Now if you have cross-dependencies (something in lib1 depends on something in lib2, which in turn depends on something else in lib1), then you might want to consider either restructuring your directories to avoid the cross-dependencies, or using a single makefile (there's lots of sharp sticks exposed if you try to use recursive makefiles in this case).
157,464
I would like to fit a `LogNormalDistribution[μ,σ]` based on some data that I have. Roughly speaking, would I need to take the `Log` of these data's *y*-values before calculating the mean and standard deviation in order to determine $\mu$ and $\sigma$ above, or can I calculate $\mu$ and $\sigma$ directly from the data and supply these values to Mathematica's `LogNormalDistribution`-function? Thanks.
2017/10/10
[ "https://mathematica.stackexchange.com/questions/157464", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/38354/" ]
**Update:** Added in @gwr 's suggestion about using `SeedRandom` so the one can obtain exactly the same answers as below. It's not clear that your question has anything to do with *Mathematica* but rather should you use maximum likelihood or method of moments (which would be best asked at CrossValidated). Consider a random sample from a log normal distribution: ``` SeedRandom[12345] n = 100; data = RandomVariate[LogNormalDistribution[1, 0.3], n]; ``` One can use the `FindDistributionParameters` function or brute force it: ``` (* Maximum likelihood *) FindDistributionParameters[data, LogNormalDistribution[μ, σ]] {μ -> 0.940761, σ -> 0.291374} (* Maximum likelihood the direct way *) Mean[Log[data]] (* 0.940761 *) StandardDeviation[Log[data]] ((n - 1)/n)^0.5 (* 0.291374 *) ``` If you don't want to take the logs of the data, then consider the method of moments where you equate the sample moments to the population moments: $$E(X)=e^{\mu+\sigma^2/2}$$ $$V(X)=e^{2\mu} e^{\sigma^2}(e^{\sigma^2}-1)$$ ``` (* Method of moments *) FindDistributionParameters[data, LogNormalDistribution[μ, σ], ParameterEstimator -> "MethodOfMoments"] (* {μ -> 0.939427, σ -> 0.298547} *) (* Method of moments the direct way *) FindRoot[{Mean[data] == Exp[μ + σ^2/2], Variance[data] (n - 1)/n == Exp[2 μ] Exp[σ^2] (Exp[σ^2] - 1)}, {{μ, Mean[Log[data]]}, {σ, StandardDeviation[data]}}] (* {μ -> 0.939427, σ -> 0.298547} *) ``` As to which method (or some other method) is best, that would be a question for CrossValidated.
There are slight variations in the distribution obtained depending on the specific approach taken Generating data ``` SeedRandom[0] data = RandomVariate[LogNormalDistribution[3, 1.5], 1000]; ``` [`FindDistribution`](http://reference.wolfram.com/language/ref/FindDistribution.html) will conclude that this data has a [`LogNormalDistribution`](http://reference.wolfram.com/language/ref/LogNormalDistribution.html) ``` (dist1 = FindDistribution[data]) // InputForm (* LogNormalDistribution[ 2.875997585829534, 1.5560895409245938] *) ``` However, if you specify that it is a `LogNormalDistribution` ``` (dist2 = FindDistribution[data, TargetFunctions -> {LogNormalDistribution}]) // InputForm (* LogNormalDistribution[ 2.904567956011853, 1.5056882462684804] *) ``` To force a fit to a `LogNormalDistribution` using [`FindDistributionParameters`](http://reference.wolfram.com/language/ref/FindDistributionParameters.html) ``` (dist4 = LogNormalDistribution[m, s] /. FindDistributionParameters[data, LogNormalDistribution[m, s]]) // InputForm (* LogNormalDistribution[ 2.904567990925176, 1.505688384471444] *) ``` This is equivalent to ``` (dist5 = LogNormalDistribution[m, s] /. FindDistributionParameters[Log[data], NormalDistribution[m, s]]) // InputForm (* LogNormalDistribution[ 2.904567990925176, 1.505688384471444] *) dist4 === dist5 (* True *) ``` Using the [`Mean`](http://reference.wolfram.com/language/ref/Mean.html) and [`StandardDeviation`](http://reference.wolfram.com/language/ref/StandardDeviation.html) of the [`Log`](http://reference.wolfram.com/language/ref/Log.html) of the data ``` (dist6 = LogNormalDistribution @@ (#[Log[data]] & /@ {Mean, StandardDeviation})) // InputForm (* LogNormalDistribution[ 2.904567990925176, 1.5064417937677634] *) ``` Using [`TransformedDistribution`](http://reference.wolfram.com/language/ref/TransformedDistribution.html) on the `Log` of the data ``` (dist7 = TransformedDistribution[E^x, x \[Distributed] FindDistribution[Log[data]]]) // InputForm (* LogNormalDistribution[ 2.904567990925176, 1.5056883844714437] *) (dist8 = TransformedDistribution[E^x, x \[Distributed] FindDistribution[Log[data], TargetFunctions -> {NormalDistribution}]]) // InputForm (* LogNormalDistribution[ 2.904567941143856, 1.505688383284438] *) ```
19,985,306
How can I get text from a node so that it returns it with whitespace formatting like "innerText" does, but excludes descendant nodes that are hidden (style display:none)?
2013/11/14
[ "https://Stackoverflow.com/questions/19985306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/97786/" ]
**UPDATE**: As the OP points out in comments below, even though [MDN clearly states that IE introduced `innerText` to exclude hidden content](https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent), testing in IE indicates that is not the case. To summarize: * Chrome: `innerText` returns text only from *visible* elements. * IE: `innerText` returns all text, regardless of the element's visibility. * Firefox: `innerText` is undefined ([as indicated by the W3C](http://www.quirksmode.org/dom/w3c_html.html), and in my testing). Add all of this up, and you have a property to avoid like the plague. Read on for the solution.... If you want cross-browser compatibility, you'll have to roll your own function. Here's one that works well: ``` function getVisibleText( node ) { if( node.nodeType === Node.TEXT_NODE ) return node.textContent; var style = getComputedStyle( node ); if( style && style.display === 'none' ) return ''; var text = ''; for( var i=0; i<node.childNodes.length; i++ ) text += getVisibleText( node.childNodes[i] ); return text; } ``` If you want to get *painfully* clever, you can create a property on the `Node` object so that this feels more "natural". At first I thought this would be a clever way to polyfill the `innerText` property on Firefox, but that property is not created as a property on the `Node` object prototype, so you would really be playing with fire there. However, you can create a new property, say `textContentVisible`: ``` Object.defineProperty( Node.prototype, 'textContentVisible', { get: function() { return getVisibleText( this ); }, enumerable: true }); ``` Here's a JsFiddle demonstrating these techniques: <http://jsfiddle.net/8S82d/>
This is interesting, I came here because I was looking for why the text of `display:none` elements was omitted in Chrome. So, this was ultimately my solution. Basically, I clone the node and remove the classes/styling that set `display:none`. How to add hidden element's `innerText` ======================================= ``` function getInnerText(selector) { let d = document.createElement('div') d.innerHTML = document.querySelector(selector).innerHTML.replaceAll(' class="hidden"', '') return d.innerText } ```
24,431
Da gibt es (laut Google) nur eine Frage (auf Gutefrage.de) mit unbefriedigenden Antworten. Ich bin im englischen StackExchange darauf gestoßen und ich weiß nicht einmal, wie man es auf Deutsch beschreibt. Am liebsten wäre mir ein zutreffendes Wort (ein Adjektiv wäre gut, wenn es das gibt). Ich unterscheide hier zwischen Zweierlei. * Jemand, der das gerne tut (weil er es mag, aber es ist kein Zwang). * Und jemand, der ein zwanghaftes Verhalten aufweist (*er muss planen, er kann einfach nicht anders*). Ich suche Bezeichnungen für beide.
2015/07/15
[ "https://german.stackexchange.com/questions/24431", "https://german.stackexchange.com", "https://german.stackexchange.com/users/15848/" ]
Eventuell "sein ganzes [eigenes] Leben verplanen" > > Er hat sein ganzes Leben verplant. > > > (im Gegensatz zu jemandem , der jemand anderes Leben verplant) > > Sein Vater hat sein ganzes Leben verplant. > > > Beispiel aus [der FAZ](http://www.faz.net/aktuell/wirtschaft/kommentar-wo-ist-nur-die-ganze-zeit-geblieben-13333534.html) > > Vielleicht sollte man sich öfter dafür entscheiden, nicht das ganze Leben zu verplanen, sondern einfach einmal nichts zu tun. > > > Wenn es ein Wort sein soll: Vielleicht *Planungsmensch*, oder sogar *Planungstier* ( letzteres auch in Bezug auf Menschen, vgl. Gewohnheitstier). Das ist dann aber eher umgangssprachlich und eher in keinem Wörterbuch zu finden. Grundsätzlich kann man fast beliebig solche Wörter bilden: Planungsfetischist, Planungsfanatiker, Planungsneurotiker...
So wie du den Personentypus beschreibst, würde ich > > Sicherheitsfanatiker > > > dazu sagen. Das Wort verwendet man zwar auch (und an erster Stelle) für Leute, die ihr Haus, ihr Wohnung, ihr Land oder was auch immer gegen jegliche mögliche Unbill schützen wollen; doch in zweiter Linie meint man damit auch Leute, die bei allem, was sie tun, auf Nummer sicher gehen wollen, und von hier ist der Schritt zum peniblen Vorausplanen nur klein. Darum, denke ich, passt der Begriff auf einen Menschentyp. Wenn ich die Schilderung recht verstanden habe. Einen Menschen mit gegenteiligem Verhalten, der also auffällig wenig plant und vieles sehr spontan tut, nennt man manchmal (mit verächtlichem Unterton) einen > > Sponti > > > wobei mir die Wortbildung unklar ist, da es im Deutschen nur wenige Personentypenbezeichnungen mit -i gibt. Vielleicht ist es eine Parallelbildung zu Sozi und Nazi. Dementsprechend läge es nahe, man spräche beim > > \*Planungsfanatiker / \*Planfanatiker > > > von einem > > \*Plani > > > Doch denke ich nicht, dass jemand dieses Wort je schon benutzt hat. (Die Wörter mit Sternchen habe ich hier neu gebildet; sie sind mir bisher ansonsten nicht begegnet.)
24,065,268
I want to show the image aligned to the top in the relative layout and the shadow should be around the image and not around the layout. What is going wrong I can't understand. ``` <RelativeLayout android:layout_width="117dp" android:layout_height="162dp"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:src="@drawable/rectangle" android:background="@drawable/drop_shadow"/> </RelativeLayout> ``` This is how the image looks when preview in design mode. notice the white background that is coming because of drop shadow and it looks like eventhough the actual image is smaller but the imageview is taking relative layout parameters to drop shadow. Any help is appreciated. ![enter image description here](https://i.stack.imgur.com/yDONx.png)
2014/06/05
[ "https://Stackoverflow.com/questions/24065268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1147094/" ]
``` <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/selector"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:src="@drawable/ic_launcher" /> </RelativeLayout> ``` * Here selector file: ``` <shape xmlns:android="http://schemas.android.com/apk/res/android"> <stroke android:width="1dp" android:color="#000000" /> </shape> ``` Hope this might help.
Looks like you just need add the adjustViewBounds property. That property defaults to false... ``` <RelativeLayout android:layout_width="117dp" android:layout_height="162dp"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:adjustViewBounds="true" <-- ADD THIS android:src="@drawable/rectangle" android:background="@drawable/drop_shadow"/> </RelativeLayout> ```
14,214,830
I am using Liferay 6.1.1 CE. How can i disable add,manage and edit control (Dockbar) of a user's "My Public Pages" and "My Private Pages"? Please find me some ideas?
2013/01/08
[ "https://Stackoverflow.com/questions/14214830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1651564/" ]
<http://vir-liferay.blogspot.in/2012/05/how-to-configure-dockbar-based-on-roles.html> this works for me....I fix it
try this thing. write this code in your **portal-ext.properties** ``` layout.user.public.layouts.enabled=false layout.user.public.layouts.modifiable=false layout.user.public.layouts.auto.create=false ``` similarly you found other options also.
14,214,830
I am using Liferay 6.1.1 CE. How can i disable add,manage and edit control (Dockbar) of a user's "My Public Pages" and "My Private Pages"? Please find me some ideas?
2013/01/08
[ "https://Stackoverflow.com/questions/14214830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1651564/" ]
<http://vir-liferay.blogspot.in/2012/05/how-to-configure-dockbar-based-on-roles.html> this works for me....I fix it
I have the same problem and I looked for disable access to public and private pages. The solution is to add these lines in your portal-ext.properties : To disable access to private pages : ``` layout.user.private.layouts.enabled=false layout.user.private.layouts.modifiable=false layout.user.private.layouts.auto.create=false ``` to disable public pages : ``` layout.user.public.layouts.enabled=false layout.user.public.layouts.modifiable=false layout.user.public.layouts.auto.create=false ``` P.S : That's disable also the access to default portlets (Directory user list) <http://yoursite/web/yourusername/home> <http://yoursite/user/yourusername/home>
35,069,691
Hey I have started using Cloudfront. In my application I have images in s3 bucket. User can update these images .When user update the image ,image get created in the s3bucket and replaces the older image with the new image .After the image get still the older image get dispalyed to user as for GET operations I am using Cloudfront so the older image is retrieved from the cloudfront cache. So is there any technique to resolve this ...
2016/01/28
[ "https://Stackoverflow.com/questions/35069691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5644924/" ]
It seems to be an issue with using a fragment context instead of an activity context. The way I fixed the problem was to do the following in my fragment. ``` getActivity().startActivity(intent); ``` I get no recorded intents if I leave off the getActivty() part and use the fragment's context to start the new activity.
It's an issue that Google is working on fixing, see this [issue](https://code.google.com/p/android/issues/detail?id=202217&q=espresso&sort=-opened&colspec=ID%20Status%20Priority%20Owner%20Summary%20Stars%20Reporter%20Opened).
79,918
I have a wireless garage door remote and looking to turn it into a wifi opener. I am looking for something to act as a switch. I was hoping i could connect a wire to 0v side of the switch and feed it 3.3v from the PI but manually doing it to the opener doesn't seem to give the desired result. bridging a wire across the switch terminals does though. so im needing a relay of some sort. i have read about relay boards, not sure how many "relays" i can operate from the board? i need a minimum of 4 preferably 5 I was hoping to run it on a model A or Zero but neither have an ethernet port. i did also read about being able to add an ethernet port using the SPI pins but am i still able to add the relay board provided i have enough pins? and not have an issue with lack of power?
2018/03/04
[ "https://raspberrypi.stackexchange.com/questions/79918", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/81803/" ]
Connecting unknown electronic devices to the Pi (or anything else) is fraught with difficulty. There is **NO WAY** the Pi can "short out the pin". You **may** be able to drive a transistor or MOSFET to simulate a button press. This requires at the minimum a common ground connection. The only SAFE way is with an opto-isolator or relay.
I have done this with a remote power point controller. If activating the button on the controller grounds the controller IC input pins you could remove the buttons and connect GPIO to the controller input pins. Relays avoid the need to remove the buttons.
79,918
I have a wireless garage door remote and looking to turn it into a wifi opener. I am looking for something to act as a switch. I was hoping i could connect a wire to 0v side of the switch and feed it 3.3v from the PI but manually doing it to the opener doesn't seem to give the desired result. bridging a wire across the switch terminals does though. so im needing a relay of some sort. i have read about relay boards, not sure how many "relays" i can operate from the board? i need a minimum of 4 preferably 5 I was hoping to run it on a model A or Zero but neither have an ethernet port. i did also read about being able to add an ethernet port using the SPI pins but am i still able to add the relay board provided i have enough pins? and not have an issue with lack of power?
2018/03/04
[ "https://raspberrypi.stackexchange.com/questions/79918", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/81803/" ]
I ended up soldering NPN transistors to the roller door remote either side of the manual switches. the base of the transistor had a 1k resistor that was attached to my PI GPIO pins. i made a common ground from the remote to the ground GPIO pin then created a script to turn the gpio pins on for 1 second then back off. works a treat!
Connecting unknown electronic devices to the Pi (or anything else) is fraught with difficulty. There is **NO WAY** the Pi can "short out the pin". You **may** be able to drive a transistor or MOSFET to simulate a button press. This requires at the minimum a common ground connection. The only SAFE way is with an opto-isolator or relay.
79,918
I have a wireless garage door remote and looking to turn it into a wifi opener. I am looking for something to act as a switch. I was hoping i could connect a wire to 0v side of the switch and feed it 3.3v from the PI but manually doing it to the opener doesn't seem to give the desired result. bridging a wire across the switch terminals does though. so im needing a relay of some sort. i have read about relay boards, not sure how many "relays" i can operate from the board? i need a minimum of 4 preferably 5 I was hoping to run it on a model A or Zero but neither have an ethernet port. i did also read about being able to add an ethernet port using the SPI pins but am i still able to add the relay board provided i have enough pins? and not have an issue with lack of power?
2018/03/04
[ "https://raspberrypi.stackexchange.com/questions/79918", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/81803/" ]
I ended up soldering NPN transistors to the roller door remote either side of the manual switches. the base of the transistor had a 1k resistor that was attached to my PI GPIO pins. i made a common ground from the remote to the ground GPIO pin then created a script to turn the gpio pins on for 1 second then back off. works a treat!
I have done this with a remote power point controller. If activating the button on the controller grounds the controller IC input pins you could remove the buttons and connect GPIO to the controller input pins. Relays avoid the need to remove the buttons.
68,378,889
I've just started with [mcpi](https://pypi.org/project/mcpi/) and I want to have custom commands to capture chat posts starting with `/`. How can I use custom commands to accomplish this?
2021/07/14
[ "https://Stackoverflow.com/questions/68378889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16447728/" ]
So the original code I used was wrong. With the help of [this post](https://stackoverflow.com/questions/64693789/system-invalidcastexception-unable-to-cast-object-was-received-when-retriev) I got to the following code which is correct: ``` ILocalStorage webStorage = ((IHasWebStorage)webDriver).WebStorage.LocalStorage; webStorage.SetItem("useTestData", "true"); ``` However, as with the poster in the link this gave me an exception: ``` System.InvalidOperationException: 'Driver does not support manipulating HTML5 web storage ``` So it seems the web driver doesn't support that feature. With the help of [this post](https://stackoverflow.com/questions/64693789/system-invalidcastexception-unable-to-cast-object-was-received-when-retriev) I got the following code: ``` IJavaScriptExecutor js = (IJavaScriptExecutor)webDriver; js.ExecuteScript("localStorage.setItem('useTestData','true');"); ``` This successfully adds the key to local storage. Just be careful when you add the key as it seems to be associated with the URL, so if you load it too early before loading the URL it will fail.
In Visual Studio, when I drill down through the ChromeDriver base classes, I eventually get to OpenQA.Selenium.Webdriver. Many of the properties there are deprecated with a helpful message. For example: ``` [Obsolete("Use JavaScript instead for managing localStorage and sessionStorage. This property will be removed in a future release.")] public bool HasWebStorage { get; } [Obsolete("Use JavaScript instead for managing localStorage and sessionStorage. This property will be removed in a future release.")] public IWebStorage WebStorage { get; } [Obsolete("Use JavaScript instead for managing applicationCache. This property will be removed in a future release.")] public bool HasApplicationCache { get; } [Obsolete("Use JavaScript instead for managing applicationCache. This property will be removed in a future release.")] public IApplicationCache ApplicationCache { get; } [Obsolete("Getting and setting geolocation information is not supported by the W3C WebDriver Specification. This property will be removed in a future release.")] public bool HasLocationContext { get; } public ICommandExecutor CommandExecutor { get; } [Obsolete("Getting and setting geolocation information is not supported by the W3C WebDriver Specification. This property will be removed in a future release.")] public ILocationContext LocationContext { get; } ```
15,599,160
The question asked to write a function split() that copies the contents of a linked list into two other linked lists. The function copies nodes with even indices (0,2,etc)to EvenList and nodes with odd indices to oddList. The original linked list should not be modified. Assume that evenlist and oddlist will be passed into the function as empty lists (\*ptrEvenList = \*ptrOddList = NULL). In my program it can show the initial list. While there is something wrong with the other two list. And it causes the terminating of the program. ``` #include<stdio.h> #include<stdlib.h> #define SIZE 9 ``` // define the structure of of the list of nodes ``` typedef struct node{ int item; struct node *next; }ListNode; ``` //call functions ``` int search(ListNode *head,int value); void printNode(ListNode *head); void split(ListNode *head,ListNode **OddList,ListNode **EvenList); ``` //main function ``` int main(){ ListNode *head=NULL; ListNode *temp; ListNode *OddList=NULL; ListNode *EvenList=NULL; ``` //in the question, it asked me to pass two empty lists to the function 'slipt' ``` int ar[SIZE]={1,3,5,2,4,6,19,16,7}; int value=0; int i; head=(struct node*)malloc(sizeof(ListNode)); temp=head; for(i=0;i<SIZE;i++){ temp->item=ar[i]; if(i==(SIZE-1)) //last item break; temp->next=(struct node*)malloc(sizeof(ListNode)); temp=temp->next; } temp->next=NULL; printf("Current list:"); printNode(head); split(head,&OddList,&EvenList); return 0; } ``` \*\*\*\*!!!!!!!!! the problem I think is in this part. ``` void split(ListNode *head,ListNode **ptrOddList,ListNode **ptrEvenList){ int remainder; ListNode *tempO,*tempE,*temp; if (head==NULL) return; else{ temp=head; *ptrOddList=(struct node*)malloc(sizeof(ListNode)); *ptrEvenList=(struct node*)malloc(sizeof(ListNode)); tempO=*ptrOddList; tempE=*ptrEvenList; while(temp!=NULL){ remainder=temp->item%2; if(remainder==0){ tempE->next=(struct node*)malloc(sizeof(ListNode)); tempE->item=temp->item; tempE=tempE->next; } else{ tempO->next=(struct node*)malloc(sizeof(ListNode)); tempO->item=temp->item; tempO=tempO->next; } temp=temp->next; } tempE=NULL; tempO=NULL; ``` // I also tried `tempE->next=NULL;` and `tempO->next=NULL` //the program can run if I modify it like above, but the last two numbers shown will be two random numbers. ``` printf("Even List:"); printNode((*ptrEvenList)); printf("Odd List:"); printNode((*ptrOddList)); } } ``` --- //function used to print out the results ``` void printNode(ListNode *head){ if (head==NULL) return; while(head!=NULL){ printf("%d ",head->item); head=head->next; } printf("\n"); } ```
2013/03/24
[ "https://Stackoverflow.com/questions/15599160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201968/" ]
``` void split(ListNode *head, ListNode **ptrOddList, ListNode **ptrEvenList){ for( ; head ; head= head->next) { ListNode *temp; temp = malloc(sizeof *temp ); memcpy (temp, head, sizeof *temp); if (temp->item %2) { *ptrOddList = temp; ptrOddList = &temp->next;} else { *ptrEvenList = temp; ptrEvenList = &temp->next;} } *ptrOddList = NULL; *ptrEvenList = NULL; } ```
You're always allocating your nodes one step too early. Notice that at the beginning you're always allocating one node for both lists -- but what if there are no odd numbers in the list? Then your list is already too long at this point. You keep doing this every time you allocate a new node. What you need to do is to keep a pointer to a *pointer* to a node for each list. This would be a pointer to the "next" pointer of the last node in the list, or the pointer to the head of the list if the list is empty. The next pointers, and the list pointers, should all start off as NULL. When you allocate a new node, set the last "next" pointer to point to your new node, using your pointer-to-pointer-to-node.
15,599,160
The question asked to write a function split() that copies the contents of a linked list into two other linked lists. The function copies nodes with even indices (0,2,etc)to EvenList and nodes with odd indices to oddList. The original linked list should not be modified. Assume that evenlist and oddlist will be passed into the function as empty lists (\*ptrEvenList = \*ptrOddList = NULL). In my program it can show the initial list. While there is something wrong with the other two list. And it causes the terminating of the program. ``` #include<stdio.h> #include<stdlib.h> #define SIZE 9 ``` // define the structure of of the list of nodes ``` typedef struct node{ int item; struct node *next; }ListNode; ``` //call functions ``` int search(ListNode *head,int value); void printNode(ListNode *head); void split(ListNode *head,ListNode **OddList,ListNode **EvenList); ``` //main function ``` int main(){ ListNode *head=NULL; ListNode *temp; ListNode *OddList=NULL; ListNode *EvenList=NULL; ``` //in the question, it asked me to pass two empty lists to the function 'slipt' ``` int ar[SIZE]={1,3,5,2,4,6,19,16,7}; int value=0; int i; head=(struct node*)malloc(sizeof(ListNode)); temp=head; for(i=0;i<SIZE;i++){ temp->item=ar[i]; if(i==(SIZE-1)) //last item break; temp->next=(struct node*)malloc(sizeof(ListNode)); temp=temp->next; } temp->next=NULL; printf("Current list:"); printNode(head); split(head,&OddList,&EvenList); return 0; } ``` \*\*\*\*!!!!!!!!! the problem I think is in this part. ``` void split(ListNode *head,ListNode **ptrOddList,ListNode **ptrEvenList){ int remainder; ListNode *tempO,*tempE,*temp; if (head==NULL) return; else{ temp=head; *ptrOddList=(struct node*)malloc(sizeof(ListNode)); *ptrEvenList=(struct node*)malloc(sizeof(ListNode)); tempO=*ptrOddList; tempE=*ptrEvenList; while(temp!=NULL){ remainder=temp->item%2; if(remainder==0){ tempE->next=(struct node*)malloc(sizeof(ListNode)); tempE->item=temp->item; tempE=tempE->next; } else{ tempO->next=(struct node*)malloc(sizeof(ListNode)); tempO->item=temp->item; tempO=tempO->next; } temp=temp->next; } tempE=NULL; tempO=NULL; ``` // I also tried `tempE->next=NULL;` and `tempO->next=NULL` //the program can run if I modify it like above, but the last two numbers shown will be two random numbers. ``` printf("Even List:"); printNode((*ptrEvenList)); printf("Odd List:"); printNode((*ptrOddList)); } } ``` --- //function used to print out the results ``` void printNode(ListNode *head){ if (head==NULL) return; while(head!=NULL){ printf("%d ",head->item); head=head->next; } printf("\n"); } ```
2013/03/24
[ "https://Stackoverflow.com/questions/15599160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201968/" ]
``` void split(ListNode *head, ListNode **ptrOddList, ListNode **ptrEvenList){ for( ; head ; head= head->next) { ListNode *temp; temp = malloc(sizeof *temp ); memcpy (temp, head, sizeof *temp); if (temp->item %2) { *ptrOddList = temp; ptrOddList = &temp->next;} else { *ptrEvenList = temp; ptrEvenList = &temp->next;} } *ptrOddList = NULL; *ptrEvenList = NULL; } ```
``` void split(ListNode *head,ListNode **ptrOddList,ListNode **ptrEvenList){ int remainder; int countO=0; int countE=0; ListNode *tempO,*tempE; if (head==NULL) return; else{ (*ptrOddList)=(struct node*)malloc(sizeof(ListNode)); (*ptrEvenList)=(struct node*)malloc(sizeof(ListNode)); while(head!=NULL){ remainder=head->item%2; if(remainder==0){ if(countE>0){ tempE->next=head; tempE=tempE->next; } else tempE=*ptrOddList; tempE->item=head->item; countE++; } else{ if(countO>0){ tempO->next=head; tempO=tempO->next; } else tempO=*ptrOddList; tempO->item=head->item; countO++; } head=head->next; } tempE->next=NULL; tempO->next=NULL; printf("Even List:"); printNode((*ptrEvenList)); printf("Odd List:"); printNode((*ptrOddList)); } } ```
15,599,160
The question asked to write a function split() that copies the contents of a linked list into two other linked lists. The function copies nodes with even indices (0,2,etc)to EvenList and nodes with odd indices to oddList. The original linked list should not be modified. Assume that evenlist and oddlist will be passed into the function as empty lists (\*ptrEvenList = \*ptrOddList = NULL). In my program it can show the initial list. While there is something wrong with the other two list. And it causes the terminating of the program. ``` #include<stdio.h> #include<stdlib.h> #define SIZE 9 ``` // define the structure of of the list of nodes ``` typedef struct node{ int item; struct node *next; }ListNode; ``` //call functions ``` int search(ListNode *head,int value); void printNode(ListNode *head); void split(ListNode *head,ListNode **OddList,ListNode **EvenList); ``` //main function ``` int main(){ ListNode *head=NULL; ListNode *temp; ListNode *OddList=NULL; ListNode *EvenList=NULL; ``` //in the question, it asked me to pass two empty lists to the function 'slipt' ``` int ar[SIZE]={1,3,5,2,4,6,19,16,7}; int value=0; int i; head=(struct node*)malloc(sizeof(ListNode)); temp=head; for(i=0;i<SIZE;i++){ temp->item=ar[i]; if(i==(SIZE-1)) //last item break; temp->next=(struct node*)malloc(sizeof(ListNode)); temp=temp->next; } temp->next=NULL; printf("Current list:"); printNode(head); split(head,&OddList,&EvenList); return 0; } ``` \*\*\*\*!!!!!!!!! the problem I think is in this part. ``` void split(ListNode *head,ListNode **ptrOddList,ListNode **ptrEvenList){ int remainder; ListNode *tempO,*tempE,*temp; if (head==NULL) return; else{ temp=head; *ptrOddList=(struct node*)malloc(sizeof(ListNode)); *ptrEvenList=(struct node*)malloc(sizeof(ListNode)); tempO=*ptrOddList; tempE=*ptrEvenList; while(temp!=NULL){ remainder=temp->item%2; if(remainder==0){ tempE->next=(struct node*)malloc(sizeof(ListNode)); tempE->item=temp->item; tempE=tempE->next; } else{ tempO->next=(struct node*)malloc(sizeof(ListNode)); tempO->item=temp->item; tempO=tempO->next; } temp=temp->next; } tempE=NULL; tempO=NULL; ``` // I also tried `tempE->next=NULL;` and `tempO->next=NULL` //the program can run if I modify it like above, but the last two numbers shown will be two random numbers. ``` printf("Even List:"); printNode((*ptrEvenList)); printf("Odd List:"); printNode((*ptrOddList)); } } ``` --- //function used to print out the results ``` void printNode(ListNode *head){ if (head==NULL) return; while(head!=NULL){ printf("%d ",head->item); head=head->next; } printf("\n"); } ```
2013/03/24
[ "https://Stackoverflow.com/questions/15599160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201968/" ]
``` void split(ListNode *head, ListNode **ptrOddList, ListNode **ptrEvenList){ for( ; head ; head= head->next) { ListNode *temp; temp = malloc(sizeof *temp ); memcpy (temp, head, sizeof *temp); if (temp->item %2) { *ptrOddList = temp; ptrOddList = &temp->next;} else { *ptrEvenList = temp; ptrEvenList = &temp->next;} } *ptrOddList = NULL; *ptrEvenList = NULL; } ```
I think here the question is to split the list into 2 halves based on the indices. But I can see the implementations on the `values(item%2)`. So in the list the first node should have index of 1 and second node is of 2 and so on. Use a count variable, which sets to 0 initially. ``` int node_count = 0; while(head != NULL) { node_count ++; if(node_count%2) { //prepare odd_list; } else { //prepare even_list; } head = head->next; } ```
15,599,160
The question asked to write a function split() that copies the contents of a linked list into two other linked lists. The function copies nodes with even indices (0,2,etc)to EvenList and nodes with odd indices to oddList. The original linked list should not be modified. Assume that evenlist and oddlist will be passed into the function as empty lists (\*ptrEvenList = \*ptrOddList = NULL). In my program it can show the initial list. While there is something wrong with the other two list. And it causes the terminating of the program. ``` #include<stdio.h> #include<stdlib.h> #define SIZE 9 ``` // define the structure of of the list of nodes ``` typedef struct node{ int item; struct node *next; }ListNode; ``` //call functions ``` int search(ListNode *head,int value); void printNode(ListNode *head); void split(ListNode *head,ListNode **OddList,ListNode **EvenList); ``` //main function ``` int main(){ ListNode *head=NULL; ListNode *temp; ListNode *OddList=NULL; ListNode *EvenList=NULL; ``` //in the question, it asked me to pass two empty lists to the function 'slipt' ``` int ar[SIZE]={1,3,5,2,4,6,19,16,7}; int value=0; int i; head=(struct node*)malloc(sizeof(ListNode)); temp=head; for(i=0;i<SIZE;i++){ temp->item=ar[i]; if(i==(SIZE-1)) //last item break; temp->next=(struct node*)malloc(sizeof(ListNode)); temp=temp->next; } temp->next=NULL; printf("Current list:"); printNode(head); split(head,&OddList,&EvenList); return 0; } ``` \*\*\*\*!!!!!!!!! the problem I think is in this part. ``` void split(ListNode *head,ListNode **ptrOddList,ListNode **ptrEvenList){ int remainder; ListNode *tempO,*tempE,*temp; if (head==NULL) return; else{ temp=head; *ptrOddList=(struct node*)malloc(sizeof(ListNode)); *ptrEvenList=(struct node*)malloc(sizeof(ListNode)); tempO=*ptrOddList; tempE=*ptrEvenList; while(temp!=NULL){ remainder=temp->item%2; if(remainder==0){ tempE->next=(struct node*)malloc(sizeof(ListNode)); tempE->item=temp->item; tempE=tempE->next; } else{ tempO->next=(struct node*)malloc(sizeof(ListNode)); tempO->item=temp->item; tempO=tempO->next; } temp=temp->next; } tempE=NULL; tempO=NULL; ``` // I also tried `tempE->next=NULL;` and `tempO->next=NULL` //the program can run if I modify it like above, but the last two numbers shown will be two random numbers. ``` printf("Even List:"); printNode((*ptrEvenList)); printf("Odd List:"); printNode((*ptrOddList)); } } ``` --- //function used to print out the results ``` void printNode(ListNode *head){ if (head==NULL) return; while(head!=NULL){ printf("%d ",head->item); head=head->next; } printf("\n"); } ```
2013/03/24
[ "https://Stackoverflow.com/questions/15599160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201968/" ]
``` void split(ListNode *head, ListNode **ptrOddList, ListNode **ptrEvenList){ for( ; head ; head= head->next) { ListNode *temp; temp = malloc(sizeof *temp ); memcpy (temp, head, sizeof *temp); if (temp->item %2) { *ptrOddList = temp; ptrOddList = &temp->next;} else { *ptrEvenList = temp; ptrEvenList = &temp->next;} } *ptrOddList = NULL; *ptrEvenList = NULL; } ```
``` void split(ListNode *head, ListNode **pOddList, ListNode **pEvenList) { int remainder; ListNode *tmpO = NULL, *tmpE= NULL, *tmp; if (head == NULL) { *pEvenList = NULL; *pOddList = NULL; } else { tmp = head; while (tmp != NULL) { remainder = tmp->item % 2; if (remainder == 0) { if (tmpE == NULL) { tmpE = tmp; tmp = tmp->next; *pEvenList = tmpE; tmpE->next = NULL; } else { tmpE->next = tmp; tmp = tmp->next; tmpE = tmpE->next; tmpE->next = NULL; } } else { if (tmpO == NULL) { tmpO = tmp; tmp = tmp->next; *pOddList = tmpO; tmpO->next = NULL; } else { tmpO->next = tmp; tmp = tmp->next; tmpO = tmpO->next; tmpO->next = NULL; } } } } } ```
44,051,035
From q for mortals, i'm struggling to understand how to read this, and understand it logically. ``` 1 2 3,/:\:10 20 ``` I understand the result is a cross product when in full form: `raze 1 2 3,/:\:10 20`. But reading from left to right, I'm currently lost at understanding what this yields (in my head) ``` \:10 20 ``` combined with `1 2 3,/:` ?? Help in understanding how to read this clearly (in words or clear logic) would be appreciated.
2017/05/18
[ "https://Stackoverflow.com/questions/44051035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I found myself saying the following in my head whilst I program the syntax in q. q works from right to left. ``` Internal Monologue -> Join the string on the right onto each of the strings on the left code -> "ABC",\:"-D" result -> "A-D" "B-D" "C-D" ``` I think that's an easy way to understand it. 'join' can be replaced with whatever... ``` Internal Monologue -> Does the string on the right match any of the strings on the left code -> ("Cat";"Dog";"CAT";"dog")~\:"CAT" result -> 0010b ``` Each-right is the same concept and combining them is straightforward also; ``` Internal Monologue -> Does each of the strings on the right match each of the strings on the left code -> ("Cat";"Dog";"CAT";"dog")~\:/:("CAT";"Dog") result -> 0010b 0100b ``` So in your example `1 2 3,/:\:10 20` - you're saying 'Join each of the elements on the right to each of the elements on the left' Hope this helps!! *EDIT* To add a real world example.... - consider the following table ``` q)show tab:([] upper syms:10?`2; names:10?("Robert";"John";"Peter";"Jenny"); amount:10?til 10) syms names amount -------------------- CF "Peter" 8 BP "Robert" 1 IC "John" 9 IN "John" 5 NM "Peter" 4 OJ "Jenny" 6 BJ "Robert" 6 KH "John" 1 HJ "Peter" 8 LH "John" 5 q) ``` I you want to get all records where the name is Robert, you can do; `select from tab where names like "Robert"` But if you want to get the results where the name is either Robert or John, then it is a perfect scenario to use our each-left and each-right. Consider the names column - it's a list of strings (a list where each element is a list of chars). What we want to ask is 'does any of the strings in the names column match any of the strings we want to find'... that translates to `(namesList)~\:/:(list;of;names;to;find)`. Here's the steps; ``` q)(tab`names)~\:/:("Robert";"John") 0100001000b 0011000101b ``` From that result we want a compiled list of booleans where each element is true of it is true for Robert OR John - for example, if you look at index 1 of both lists, it's 1b for Robert and 0b for John - in our result, the value at index 1 should be 1b. Index 2 should be 1b, index3 should be 1b, index4 should be 0b etc... To do this, we can apply the `any` function (or max or sum!). The result is then; ``` q)any(tab`names)~\:/:("Robert";"John") 0111001101b ``` Putting it all together, we get; ``` q)select from tab where any names~\:/:("Robert";"John") syms names amount -------------------- BP "Robert" 1 IC "John" 9 IN "John" 5 BJ "Robert" 6 KH "John" 1 LH "John" 5 q) ```
Firstly, q is executed (and hence generally read) right to left. This means that it's interpreting the `\:` as a modifier to be applied to the previous function, which itself is a simple join modified by the `/:` adverb. So the way to read this is "Apply join each-right to each of the left-hand arguments." In this case, you're applying the two adverbs to the join - `\:10 20` on its own has no real meaning here. I find it helpful to also look at the converse case `1 2 3,\:/:10 20`, running that code produces a 2x6 matrix, which I'd describe more like "apply join each-left to each of the right hand arguments" ... I hope that makes sense. An alternative syntax which also might help is `,/:\:[1 2 3;10 20]` - this might be useful as it makes it very clear what the function you're applying is, and is equivalent to your in-place notation.
56,969,572
So I basically have a huge dataset to work with, its almost made up of 1,200,000 rows, and my target class count is about 20,000 labels. I am performing text classifiaction on my data, so I first cleaned it, and then performed tfidf vectorzation on it. The problem lies whenever I try to pick a model and fit the data, it gives me a Memory Error My current PC is Core i7 with 16GB of RAM ``` vectorizer = feature_extraction.text.TfidfVectorizer(ngram_range=(1, 1), analyzer='word', stop_words= fr_stopwords) datavec = vectorizer.fit_transform(data.values.astype('U')) X_train, X_test, y_train, y_test = train_test_split(datavec,target,test_size=0.2,random_state=0) print(type(X_train)) print(X_train.shape) ``` Output: class 'scipy.sparse.csr.csr\_matrix' (963993, 125441) ``` clf.fit(X_train, y_train) ``` This is where the Memory Error is happening I have tried: 1 - to take a sample of the data, but the error is persisting. 2 - to fit many different models, but only the KNN model was working (but with a low accuracy score) 3- to convert datavec to an array, but this process is also causing a Memory Error 4- to use multi processing on different models 5 - I have been through every similar question on SO, but either an answer was unclear, or did not relate to my problem exactly This is a part of my code: ``` vectorizer = feature_extraction.text.TfidfVectorizer(ngram_range=(1, 1), analyzer='word', stop_words= fr_stopwords) df = pd.read_csv("C:\\Users\\user\\Desktop\\CLEAN_ALL_DATA.csv", encoding='latin-1') classes = np.unique(df['BENEFITITEMCODEID'].str[1:]) vec = vectorizer.fit(df['NEWSERVICEITEMNAME'].values.astype('U')) del df clf = [KNeighborsClassifier(n_neighbors=5), MultinomialNB(), LogisticRegression(solver='lbfgs', multi_class='multinomial'), SGDClassifier(loss="log", n_jobs=-1), DecisionTreeClassifier(max_depth=5), RandomForestClassifier(n_jobs=-1), LinearDiscriminantAnalysis(), LinearSVC(multi_class='crammer_singer'), NearestCentroid(), ] data = pd.Series([]) for chunk in pd.read_csv(datafile, chunksize=100000): data = chunk['NEWSERVICEITEMNAME'] target = chunk['BENEFITITEMCODEID'].str[1:] datavec = vectorizer.transform(data.values.astype('U')) clf[3].partial_fit(datavec, target,classes = classes) print("**CHUNK DONE**") s = "this is a testing sentence" svec = vectorizer.transform([s]) clf[3].predict(svec) --> memory error clf[3].predict(svec).todense() --> taking a lot of time to finish clf[3].predict(svec).toarrray() --> taking a lot of time to finish as well ``` Anything else I could try?
2019/07/10
[ "https://Stackoverflow.com/questions/56969572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11154881/" ]
Go to Android Studio Preferences. [![enter image description here](https://i.stack.imgur.com/3Xiek.png)](https://i.stack.imgur.com/3Xiek.png) Go to Editor -> Inspections -> Lint [![enter image description here](https://i.stack.imgur.com/5AVYw.png)](https://i.stack.imgur.com/5AVYw.png) Then search for Timber and uncheck "Logging call to Log instead of Timber" [![enter image description here](https://i.stack.imgur.com/w2zEz.png)](https://i.stack.imgur.com/w2zEz.png) Be aware that this will turn off this lint check for all of your projects
add `exclude group: "com.jakewharton.timber", module: 'timber'` to the dependency that uses Timber For example: ``` implementation("com.raygun:raygun4android:4.0.1") { exclude group: "com.jakewharton.timber", module: 'timber' } ```
106,543
We are planning to convert some of our VF pages to Lightning apps. Some our VF pages, particularly surveys are URL parameter-driven, since we send survey links directly to users, i.e. `https://[vf_instance].force.com/apex/CaseSurvey?caseid=xxxxx` Say we convert the VF page to an Lightning app, we would probably be sending the Lightning survey like this `https://[vf_instance].lightning.force.com/c/CaseSurvey.app?caseid=xxxxx` **Problem:** In VF page controller, PageReference.getParameters() contains the much needed **`caseid`** However, in Lightning component controller, PageReference.getParameters() does not contain any URL parameters. How can I get the URL parameter in Lightning app/component apex controller? THANKS!
2016/01/25
[ "https://salesforce.stackexchange.com/questions/106543", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/24838/" ]
In lightning whatever attribute you define can be passed as a query parameter . Lets take a look with sample example ``` <aura:application> <aura:attribute name="whom" type="String" default="world"/> Hello {!v.whom}! </aura:application> ``` Here is how the result will look like [![enter image description here](https://i.stack.imgur.com/ZXNpD.png)](https://i.stack.imgur.com/ZXNpD.png) Now I will add a query parameter with value as per my attribute defined **whom** in the URL and now the result will be as below [![enter image description here](https://i.stack.imgur.com/h2emK.png)](https://i.stack.imgur.com/h2emK.png) > > In very simple terms you just need to define an aura:attribute and you are good > > > ``` <aura:attribute name="caseid" type="String"/> ```
Just adding this answer for completion of the thread with the latest release. After Summer 18 release (API version 43 and up) we can utilise `lightning:isUrlAddressable` interface. Implement `lightning:isUrlAddressable` interface and use `pageReference` attribute. Example. - Component Assume url is *<https://<instance>.lightning.force.com/lightning/cmp/<namespace>__componentName?testAttribute=XYZ>* ``` <aura:component implements="lightning:isUrlAddressable"> <aura:handler name="init" value="{!this}" action="{!c.doInit}" description="Handler for valueInit event fired when the component has been initialised"/> {!v.pageReference.state.testAttribute} </aura:component> ``` Component Controller ``` ({ doInit : function(component, event, helper) { console.log(component.get("v.pageReference").state.testAttribute); } }) ``` Console output will look like: "XYZ"
106,543
We are planning to convert some of our VF pages to Lightning apps. Some our VF pages, particularly surveys are URL parameter-driven, since we send survey links directly to users, i.e. `https://[vf_instance].force.com/apex/CaseSurvey?caseid=xxxxx` Say we convert the VF page to an Lightning app, we would probably be sending the Lightning survey like this `https://[vf_instance].lightning.force.com/c/CaseSurvey.app?caseid=xxxxx` **Problem:** In VF page controller, PageReference.getParameters() contains the much needed **`caseid`** However, in Lightning component controller, PageReference.getParameters() does not contain any URL parameters. How can I get the URL parameter in Lightning app/component apex controller? THANKS!
2016/01/25
[ "https://salesforce.stackexchange.com/questions/106543", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/24838/" ]
In lightning whatever attribute you define can be passed as a query parameter . Lets take a look with sample example ``` <aura:application> <aura:attribute name="whom" type="String" default="world"/> Hello {!v.whom}! </aura:application> ``` Here is how the result will look like [![enter image description here](https://i.stack.imgur.com/ZXNpD.png)](https://i.stack.imgur.com/ZXNpD.png) Now I will add a query parameter with value as per my attribute defined **whom** in the URL and now the result will be as below [![enter image description here](https://i.stack.imgur.com/h2emK.png)](https://i.stack.imgur.com/h2emK.png) > > In very simple terms you just need to define an aura:attribute and you are good > > > ``` <aura:attribute name="caseid" type="String"/> ```
There isn't any documented way of doing that, but I was able to do so using a hack. The Salesforce Lightning URL is something like "/one/one.app#\_\_\_\_\_\_\_" . The blank contains some encoded value in the URL. The encoded value is nothing but the details of the Component/Page in Base64 encoded form. Use the below code in Javascript in Visualforce to navigate to Lightning Components- ``` <script> var compDefinition = { "componentDef" : "c:NewContact", "attributes" :{ "recordTypeId" : "012xxxxxxxxxxxx", "testAttribute" : "attribute value" } }; // Base64 encode the compDefinition JS object var encodedCompDef = btoa(JSON.stringify(compDefinition)); window.parent.location = "/one/one.app#"+encodedCompDef; </script> ```
106,543
We are planning to convert some of our VF pages to Lightning apps. Some our VF pages, particularly surveys are URL parameter-driven, since we send survey links directly to users, i.e. `https://[vf_instance].force.com/apex/CaseSurvey?caseid=xxxxx` Say we convert the VF page to an Lightning app, we would probably be sending the Lightning survey like this `https://[vf_instance].lightning.force.com/c/CaseSurvey.app?caseid=xxxxx` **Problem:** In VF page controller, PageReference.getParameters() contains the much needed **`caseid`** However, in Lightning component controller, PageReference.getParameters() does not contain any URL parameters. How can I get the URL parameter in Lightning app/component apex controller? THANKS!
2016/01/25
[ "https://salesforce.stackexchange.com/questions/106543", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/24838/" ]
Just adding this answer for completion of the thread with the latest release. After Summer 18 release (API version 43 and up) we can utilise `lightning:isUrlAddressable` interface. Implement `lightning:isUrlAddressable` interface and use `pageReference` attribute. Example. - Component Assume url is *<https://<instance>.lightning.force.com/lightning/cmp/<namespace>__componentName?testAttribute=XYZ>* ``` <aura:component implements="lightning:isUrlAddressable"> <aura:handler name="init" value="{!this}" action="{!c.doInit}" description="Handler for valueInit event fired when the component has been initialised"/> {!v.pageReference.state.testAttribute} </aura:component> ``` Component Controller ``` ({ doInit : function(component, event, helper) { console.log(component.get("v.pageReference").state.testAttribute); } }) ``` Console output will look like: "XYZ"
There isn't any documented way of doing that, but I was able to do so using a hack. The Salesforce Lightning URL is something like "/one/one.app#\_\_\_\_\_\_\_" . The blank contains some encoded value in the URL. The encoded value is nothing but the details of the Component/Page in Base64 encoded form. Use the below code in Javascript in Visualforce to navigate to Lightning Components- ``` <script> var compDefinition = { "componentDef" : "c:NewContact", "attributes" :{ "recordTypeId" : "012xxxxxxxxxxxx", "testAttribute" : "attribute value" } }; // Base64 encode the compDefinition JS object var encodedCompDef = btoa(JSON.stringify(compDefinition)); window.parent.location = "/one/one.app#"+encodedCompDef; </script> ```
11,141,312
I recently bought the SuperBible 5th edition book. I use Ubuntu 12.04 LTS. I use Code::Blocks. I'm not very proficient with C++ libraries and setting up. I wanted a book that will guide me from scratch. I was disappointed when I saw that the book doesn't help us set up projects in Linux. They use 2 libraries ,freeglut and GLTools. I read [this](http://www.codeproject.com/Articles/182109/Setting-up-an-OpenGL-development-environment-in-Ub) wonderful tutorial that explained the freeglut part for linux. Now I am clueless about GLTools. I searched in debian.org for a package containing GLTools.h and there were none. So, I can't find the package at all. [Here](http://www.starstonesoftware.com/OpenGL/), they do give the libraries , but it is only for Windows and Mac. Inclusion of a library in Ubuntu was a piece of cake(just a command in the terminal) , but I do not how I can use a Windows library for this. Is there any other book that would help with Linux? edit: after doing the 1st 2 steps of what HaloWebMaster said, I did a cd and went inside the gltools folder (and there was a makefile there). There I did `make all`. But this is what hapenned: ``` Package OpenEXR was not found in the pkg-config search path. Perhaps you should add the directory containing `OpenEXR.pc' to the PKG_CONFIG_PATH environment variable No package 'OpenEXR' found make[1]: sdl-config: Command not found make[1]: Entering directory `/home/user/gltools/framework' make[1]: freetype-config: Command not found Package OpenEXR was not found in the pkg-config search path. Perhaps you should add the directory containing `OpenEXR.pc' to the PKG_CONFIG_PATH environment variable No package 'OpenEXR' found make[1]: sdl-config: Command not found make[1]: freetype-config: Command not found Compiling camera.cpp Package OpenEXR was not found in the pkg-config search path. Perhaps you should add the directory containing `OpenEXR.pc' to the PKG_CONFIG_PATH environment variable No package 'OpenEXR' found make[1]: sdl-config: Command not found make[1]: freetype-config: Command not found Package OpenEXR was not found in the pkg-config search path. Perhaps you should add the directory containing `OpenEXR.pc' to the PKG_CONFIG_PATH environment variable No package 'OpenEXR' found make[1]: sdl-config: Command not found make[1]: freetype-config: Command not found Compiling fs.cpp Package OpenEXR was not found in the pkg-config search path. Perhaps you should add the directory containing `OpenEXR.pc' to the PKG_CONFIG_PATH environment variable No package 'OpenEXR' found make[1]: sdl-config: Command not found make[1]: freetype-config: Command not found Package OpenEXR was not found in the pkg-config search path. Perhaps you should add the directory containing `OpenEXR.pc' to the PKG_CONFIG_PATH environment variable No package 'OpenEXR' found make[1]: sdl-config: Command not found make[1]: freetype-config: Command not found Compiling image/image-convert.cpp image/image-convert.cpp:7:18: fatal error: half.h: No such file or directory compilation terminated. Compilation failed for libgltools_a_image-convert.o: make[1]: *** [libgltools_a_image-convert.o] Error 1 make[1]: Leaving directory `/home/user/gltools/framework' make: *** [framework] Error 2 ```
2012/06/21
[ "https://Stackoverflow.com/questions/11141312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1418853/" ]
Right now you are telling all the elements with a class of 'inline' that you want with the selector '#inline\_content-1'. Try this instead: ``` $(document).ready(function(){ $(".inline").colorbox({inline:true, width:"440px"}); $.colorbox({inline:true, href:"#inline_content_1", open:true, width:"330px", height:"640px"}); }); ```
Change your selector to use the id of the div you want to come up at `onload`? ``` $(document).ready(function(){ $(".inline #inline_content-1").colorbox({inline:true, width:"440px"}); $(".inline #inline_content-1").colorbox({href:"#inline_content_1", open:true, width:"330px", height:"640px"}); }); ``` Thank you for taking time to think about this! I am currently using: ``` <link rel="stylesheet" href="/colorbox/colorbox.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="/colorbox/jquery.colorbox.js"></script> <script> $(document).ready(function(){ $(".inline").colorbox({inline:true, width:"440px"}); $(".inline #inline_content_onload").colorbox({href:"#inline_content_onload", open:true, width:"330px", height:"640px"}); }); </script> <div style='display:none'> <div id='inline_content-1'> HTML here</div> </div> <div style='display:none'> <div id='inline_content-2'> HTML here</div> </div> <div style='display:none'> <div id='inline_content-3'> HTML here</div> </div> <div style='display:none'> <div id='inline_content-4'> HTML here</div> </div> <div style='display:none'> <div id='inline_content_onload'> HTML onload here</div> </div> ```
69,258,753
I have an html page with a search field that can have a name typed in which returns a table of Names and IDs (from Steam, specifically). The leftmost column, the names, are hyperlinks that I want to, when clicked, take the user to said player's profile (profile.php) and I want to send the "name" and "steamid" to that profile.php when the name link is clicked, so essentially sending two JS variables from one page to the PHP backend of another page. I'm new to ajax and it seems that that is the only way to use it, so after researching for a while this is what I've come to: ``` $(document).ready(function() { $('#playerList td').click(function(e) { if ($(this).text() == $(this).closest('tr').children('td:first').text()) { console.log($(this).text()); var name = $(this).text(); var steamid = $(this).closest('tr').children('td:nth-child(2)').text(); $.ajax({ url: 'profile.php', method: 'POST', data: { playersSteamID : steamid, playersName : name }, success: function() { console.log('success'); }, error: function(XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest); console.log(textStatus); console.log(errorThrown); } }) } }); }); ``` Everything up to the ajax definition works as I want, and I want to send the "name" and "steamid" vars to profile.php, but I don't think I'm understanding how ajax works. My understanding is that ajax can "post" information (usually a json object from what I've seen) to a url, but can also return information from a page? That's where I'm a bit confused and am wondering if I'm just using it wrong. As a quick note: `playerList` is my table's id. When I click the hyperlink, it takes me to profile.php, which is what I want, but php's $\_POST[] array seems to be empty/null as I get the "undefined array key" error when trying to access both 'playersSteamID' and 'playersName'. var\_dump() returns NULL as well, so I'm wondering if there's a problem with the way the data{} field is being sent in the ajax. I'm still very new to this so any help would be much appreciated. Update: How I'm accessing the variables in profile.php ``` <?php echo var_dump($_POST['playersName']); echo var_dump($_POST['playersSteamID']); if (isset($_POST['playersName'])) { console_log("PLAYER_NAME => ".$_POST['playersName']); } if (isset($_POST['playersSteamID'])) { console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']); } ?> ``` The rest of profile.php is taking those variables and running several sql queries and building a table which work given proper variables, but since the $\_POST[] is empty I can't continue past the above point as the first two lines return null and the conditionals are never true since `isset()` is false.
2021/09/20
[ "https://Stackoverflow.com/questions/69258753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16959530/" ]
The ajax is used to, `post` or `get` parameters/info from/to URL without redirecting/refreshing/navigating to a particular page. Please note down **without redirecting/refreshing/navigating** In your case you want to send 2 parameters to `profile.php` and you also want to navigate to it, yes..? but for that you are using Ajax, which is not a right choice. **Solutions:-** **->** Use normal form submission kinda thing, and post the parameters to `profile.php`, in this case you will get redirect to profile.php and can expect proper functionality. You can use a normal form with a submit button {pretty normal}, or use a custom function to submit form with some further work if need to be done {form validation}. you function would look like this... ``` $(document).ready(function() { $('#playerList td').click(function(e) { e.preventDefault(); if ($(this).text() == $(this).closest('tr').children('td:first').text()) { console.log($(this).text()); var name = $(this).text(); var steamid = $(this).closest('tr').children('td:nth-child(2)').text(); //Do some other stuffs document.forms['someform'].submit();//submitting the form here } }); }); ``` The rest in `profile.php` remains same. **->** If you really wanna use `ajax` do following. Ajax are meant for dynamic web designing, pretty useful to grab data from server without refreshing the page. You should change the way your response is in `profile.php` file. for eg:- ``` <?php if(isset($_POST['playersSteamID'])){ $name = $_POST['playersName']; $id = $_POST['playersSteamID']; //Do your stuff here db query whatever //Here echo out the needed html/json response. echo "<h3>".$name."</h3>"; echo "<h4>".$playersSteamID."</h4>"; } ?> ``` The response {from: `echo`} will be available in `data` of `function(data)` in ajax success, you can use this `data` in whatever you want and however you want. for eg:- ``` success: function(data){ console.log(data);//for debugging $('#mydiv').html(data);//appending the response. } ``` **->** Use php sessions and store steamID in sesssion variable, very useful if you have some login functionality in your website. ``` $_SESSION['steamID'] = //the steamID here; ``` This variable can be used anywhere in site use by calling `session_start()` in the page, you want to use sessions. for eg:- ``` <a href="profile.php" target="_self"> click here to view your profile </a> ``` profile.php ``` <?php session_start(); $id = $_SESSION['steamID']; //echo var_dump($_POST['playersName']); //echo var_dump($_POST['playersSteamID']); /*if (isset($_POST['playersName'])) { console_log("PLAYER_NAME => ".$_POST['playersName']); } if (isset($_POST['playersSteamID'])) { console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']); }*/ echo $id; //Do your work here...... ?> ``` For any queries comment down.
A hyperlink may be causing the page navigation, which you dont want. Page navigation will make a get request but your endpoint is expecting a post request. You can stop the navigation by setting the href to # or by removing the `<a>` altogether. You could also try calling the `preventDefault` on the event object. ``` $(document).ready(function() { $('#playerList td').click(function(e) { e.preventDefault(); if ($(this).text() == $(this).closest('tr').children('td:first').text()) { console.log($(this).text()); var name = $(this).text(); var steamid = $(this).closest('tr').children('td:nth-child(2)').text(); $.ajax({ url: 'profile.php', method: 'POST', data: { playersSteamID : steamid, playersName : name }, success: function(data) { console.log('success', data); }, error: function(XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest); console.log(textStatus); console.log(errorThrown); } }) } }); }); ```
41,586,474
I am trying to use file\_get\_contents to "post" to a url and get auth token. The problem I am having is that it returns a error. `Message: file_get_contents(something): failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required.` I am not sure what is causing this but need help. Here is the function. ``` public function ForToken(){ $username = 'gettoken'; $password = 'something'; $url = 'https://something.com'; $context = stream_context_create(array ( 'http' => array ( 'header' => 'Authorization: Basic ' . base64_encode("$username:$password"), 'method' => 'POST' ) )); $token = file_get_contents($url, false, $context); if(token){ var_dump($token); }else{ return $resultArray['result'] = 'getting token failed'; } } ``` I tried it with POSTMAN, and it works, so only problem I am having is that why isnt it working with file\_get\_contents.
2017/01/11
[ "https://Stackoverflow.com/questions/41586474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3495940/" ]
Cannot command so i will do it this way. If you use Postman why don't you let Postman generate the code for you. In postman you can click code at a request and you can even select in what coding language you wanne have it. Like PHP with cURL: ``` $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "http://somthing.com/", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTPHEADER => array( "password: somthing", "username: gettoken" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } ``` Hope this will help!
I can not comment because of my reputation; In some servers file\_get\_content is not available... You may try with CURL like [this](https://stackoverflow.com/questions/2138527/php-curl-http-post-sample-code)
41,586,474
I am trying to use file\_get\_contents to "post" to a url and get auth token. The problem I am having is that it returns a error. `Message: file_get_contents(something): failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required.` I am not sure what is causing this but need help. Here is the function. ``` public function ForToken(){ $username = 'gettoken'; $password = 'something'; $url = 'https://something.com'; $context = stream_context_create(array ( 'http' => array ( 'header' => 'Authorization: Basic ' . base64_encode("$username:$password"), 'method' => 'POST' ) )); $token = file_get_contents($url, false, $context); if(token){ var_dump($token); }else{ return $resultArray['result'] = 'getting token failed'; } } ``` I tried it with POSTMAN, and it works, so only problem I am having is that why isnt it working with file\_get\_contents.
2017/01/11
[ "https://Stackoverflow.com/questions/41586474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3495940/" ]
Cannot command so i will do it this way. If you use Postman why don't you let Postman generate the code for you. In postman you can click code at a request and you can even select in what coding language you wanne have it. Like PHP with cURL: ``` $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "http://somthing.com/", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTPHEADER => array( "password: somthing", "username: gettoken" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } ``` Hope this will help!
Your request havent any data and content length is missing. You can try this: ``` public function ForToken(){ $username = 'gettoken'; $password = 'something'; $url = 'https://something.com'; $data = array('foo' => 'some data'); $data = http_build_query($data); $context_options = array ( 'http' => array ( 'method' => 'POST', 'header'=> "Content-type: application/x-www-form-urlencoded\r\n" . "Authorization: Basic " . base64_encode("$username:$password") . "\r\n" . "Content-Length: " . strlen($data) . "\r\n", 'content' => $data ) ); $context = context_create_stream($context_options); $token = file_get_contents($url, false, $context); if(token){ var_dump($token); }else{ return $resultArray['result'] = 'getting token failed'; } } ``` Here is similar problem: [How to fix 411 Length Required error with file\_get\_contents and the expedia XML API?](https://stackoverflow.com/questions/9412650/how-to-fix-411-length-required-error-with-file-get-contents-and-the-expedia-xml)
41,586,474
I am trying to use file\_get\_contents to "post" to a url and get auth token. The problem I am having is that it returns a error. `Message: file_get_contents(something): failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required.` I am not sure what is causing this but need help. Here is the function. ``` public function ForToken(){ $username = 'gettoken'; $password = 'something'; $url = 'https://something.com'; $context = stream_context_create(array ( 'http' => array ( 'header' => 'Authorization: Basic ' . base64_encode("$username:$password"), 'method' => 'POST' ) )); $token = file_get_contents($url, false, $context); if(token){ var_dump($token); }else{ return $resultArray['result'] = 'getting token failed'; } } ``` I tried it with POSTMAN, and it works, so only problem I am having is that why isnt it working with file\_get\_contents.
2017/01/11
[ "https://Stackoverflow.com/questions/41586474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3495940/" ]
Cannot command so i will do it this way. If you use Postman why don't you let Postman generate the code for you. In postman you can click code at a request and you can even select in what coding language you wanne have it. Like PHP with cURL: ``` $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "http://somthing.com/", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTPHEADER => array( "password: somthing", "username: gettoken" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } ``` Hope this will help!
RFC2616 10.4.12 <https://www.rfc-editor.org/rfc/rfc2616#section-10.4.12> Code: (Doesn't work, see below) ``` public function ForToken(){ $username = 'gettoken'; $password = 'something'; $url = 'https://something.com'; $context = stream_context_create(array ( 'http' => array ( 'header' => 'Authorization: Basic ' . base64_encode("$username:$password") . 'Content-Length: ' . strlen($url) . '\r\n', 'method' => 'POST' ) )); $token = file_get_contents($url, false, $context); if(token){ var_dump($token); }else{ return $resultArray['result'] = 'getting token failed'; } } ``` 2nd Try: ``` public function ForToken(){ $username = 'gettoken'; $password = 'something'; $url = 'https://something.com'; $context_options = array ( 'http' => array ( 'method' => 'POST', 'header'=> "Content-type: application/x-www-form-urlencoded\r\n" . "Authorization: Basic " . base64_encode("$username:$password") . "Content-Length: " . strlen($url) . "\r\n", 'content' => $url ) ); $context = stream_context_create($context_options); $token = file_get_contents($url, false, $context); if(token){ var_dump($token); }else{ return $resultArray['result'] = 'getting token failed'; } } ``` This is from patryk-uszynski's answer formatted with the OP's code.
749,247
Given a polynomial $p(x) = x^3-bx^2+cx-d = 0 $ such that all three roots are **real positive integers**. How does one figure out if the three roots are distinct? The coefficient of $x^3$ is 1. In the case of a quadratic equation, we can determine that the roots are distinct if $b^2-4ac != 0$ for the equation $ax^2+bx+c=0$. Are there similar methods that can be applied to a third-order polynomial?
2014/04/11
[ "https://math.stackexchange.com/questions/749247", "https://math.stackexchange.com", "https://math.stackexchange.com/users/142369/" ]
One way to do it is to check if the discriminant of the cubic is positive. The roots are distinct $\iff$ the discriminant is nonzero. For a cubic, our discriminant is $\Delta = b^2c^2-4ac^3-4b^3d-27a^2d^2+18abcd$. Yuck! <http://en.wikipedia.org/wiki/Discriminant>
In this special case one may be able to avoid computing the discriminant. If you know all roots are natural numbers, the roots must be divisors of $d$. In fact, from $d=x\_1x\_2x\_3$ and $c=x\_1x\_2+x\_1x\_3+x\_2x\_3$ we see that a multiple root must divide $\gcd(c,d)$. In simple cases one may simply try all these divisors. Another approach is that multiple roots of $f$ are also roots of $f'$. So determine the polynomial $\gcd(f(x),f'(x))=\gcd(x^3-bx^2+cx-d,3x^2-2bx+c)=\ldots$.
65,314,732
Declaring classes ``` class A { public string a; public static implicit operator A(B b) => new A() { a = b.b }; } class B { public string b; } ``` comparison `?:` and `if-else` ``` static public A Method1(B b) { return (b is null) ? null : b; //equally return b; } static public A Method2(B b) { if (b is null) return null; else return b; } ``` Method1 will throw an exception Method2 will work fine ``` Method1(null); Method2(null); ``` Why do they behave differently?
2020/12/15
[ "https://Stackoverflow.com/questions/65314732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14832315/" ]
When using a ternary operator in `Method1`, the type of the return value must be the same in both branches (`B`, in your case). That value has to be cast to `A` later to match the return type of the method. So, a `NullReferenceException` is thrown in your implicit operator (because `b` is null). In `Method2`, on the other hand, you're returning `null` *directly*; so, no cast is needed. You get the same result (i.e., exception) in `Method2` if you change it into something like this: ``` static public A Method2(B b) { B temp; if (b is null) temp = null; else temp = b; return temp; // Throws a NullReferenceException. } ``` What you ought to be doing is adding a null-check in the implicit operator: ``` public static implicit operator A(B b) => (b is null ? null : new A { a = b.b }); ```
`Method1` For the ternary operator type of return values should be equal. So `null` is actually returned as `(B)null`, which then uses implicit operator to get converted to type `A` `Method2` The return value is directly converted to `(A)null`, and implicit operator is not used. `Bonus` Try changing return type of `Method1` to `B` and it should work. ``` public static B Method1(B b) { return (b is null) ? null : b; } ```
56,773,826
I'm wondering if it's possible to concatenate PLyResults somehow inside a function. For example, let's say that firstly I have a function \_get\_data that, given a tuple (id, index) returns a table of values: ``` CREATE OR REPLACE FUNCTION _get_data(id bigint, index bigint): RETURNS TABLE(oid bigint, id bigint, val double precision) AS $BODY$ #...process for fetching the data, irrelevant for the question. return recs $BODY$ LANGUAGE plpython3u; ``` Now I would like to be able to create a generic function defined as such, that fetches data between two boundaries for a given ID, and uses the previous function to fetch data individually and then aggregate the results somehow: ``` CREATE OR REPLACE FUNCTION get_data(id bigint, lbound bigint, ubound bigint) RETURNS TABLE(oid bigint, id bigint, val double precision) AS $BODY$ concatenated_recs = [] #<-- For the sake of argument. plan = plpy.prepare("SELECT oid, id, val FROM _get_data($1, $2);", ['bigint', 'bigint']) for i in range(lbound, ubound+1): recs = plpy.execute(plan, [id, i]) # <-- Records fetched individually concatenated_recs += [recs] #<-- Not sure how to concatenate them... return concatenated_recs $BODY$ LANGUAGE plpython3u; ```
2019/06/26
[ "https://Stackoverflow.com/questions/56773826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6400144/" ]
Perhaps I am missing something, but the answer you gave looks like a slower, more complicated version of this query: ``` SELECT oid, id, val FROM generate_series(your_lower_bound, your_upper_bound) AS g(i), _get_data(your_id, i); ``` You could put that in a simple SQL function with no loops or temporary tables: ``` CREATE OR REPLACE FUNCTION get_data(id bigint, lbound bigint, ubound bigint) RETURNS TABLE(oid bigint, id bigint, val double precision) AS $BODY$ SELECT oid, id, val FROM generate_series(lbound, ubound) AS g(i), _get_data(id, i); $BODY$ LANGUAGE SQL; ```
Although I wasn't able to find a way to concatenate the results from the PL/Python documentation, and as of 06-2019, I'm not sure if the language supports this resource, I could solve it by creating a temp table, inserting the records in it for each iteration and then returning the full table: ``` CREATE OR REPLACE FUNCTION get_data(id bigint, lbound bigint, ubound bigint) RETURNS TABLE(oid bigint, id bigint, val double precision) AS $BODY$ #Creates the temp table plpy.execute("""CREATE TEMP TABLE temp_results(oid bigint, id bigint, val double precision) ON COMMIT DROP""") plan = plpy.prepare("INSERT INTO temp_results SELECT oid, id, val FROM _get_data($1, $2);", ['bigint', 'bigint']) #Inserts the results in the temp table for i in range(lbound, ubound+1): plpy.execute(plan, [id, i]) #Returns the whole table recs = plpy.execute("SELECT * FROM temp_results") return recs $BODY$ LANGUAGE plpython3u; ```
69,151,455
I am trying to generate a list of urls by looping two word lists. I can do it one through f-string but I am not so sure how to do two at the same time. Any suggestion? ```py tag_names = ['business', 'science', 'technology'] domain_names = ['bbc', 'cnn', 'nytimes'] for domain in domain_names: print(f'www.{domain}.com/{tag}') ``` Expected result ``` www.bbc.com/business www.bbc.com/science www.bbc.com/technology www.cnn.com/business www.cnn.com/science www.cnn.com/technology www.nytimes.com/business www.nytimes.com/science www.nytimes.com/technology ```
2021/09/12
[ "https://Stackoverflow.com/questions/69151455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13236293/" ]
You can use `itertools.product` and a list comprehension: ```py import itertools tag_names = ['business', 'science', 'technology'] domain_names = ['bbc', 'cnn', 'nytimes'] [f'www.{domain}.com/{tag}' for domain, tag in itertools.product(domain_names, tag_names)] ``` output: ``` ['www.bbc.com/business', 'www.bbc.com/science', 'www.bbc.com/technology', 'www.cnn.com/business', 'www.cnn.com/science', 'www.cnn.com/technology', 'www.nytimes.com/business', 'www.nytimes.com/science', 'www.nytimes.com/technology'] ```
Or use a nested loop: ``` tag_names = ['business', 'science', 'technology'] domain_names = ['bbc', 'cnn', 'nytimes'] print([f'www.{domain}.com/{tag}' for domain in domain_names for tag in tag_names]) ``` Output: ``` ['www.bbc.com/business', 'www.bbc.com/science', 'www.bbc.com/technology', 'www.cnn.com/business', 'www.cnn.com/science', 'www.cnn.com/technology', 'www.nytimes.com/business', 'www.nytimes.com/science', 'www.nytimes.com/technology'] ```
69,151,455
I am trying to generate a list of urls by looping two word lists. I can do it one through f-string but I am not so sure how to do two at the same time. Any suggestion? ```py tag_names = ['business', 'science', 'technology'] domain_names = ['bbc', 'cnn', 'nytimes'] for domain in domain_names: print(f'www.{domain}.com/{tag}') ``` Expected result ``` www.bbc.com/business www.bbc.com/science www.bbc.com/technology www.cnn.com/business www.cnn.com/science www.cnn.com/technology www.nytimes.com/business www.nytimes.com/science www.nytimes.com/technology ```
2021/09/12
[ "https://Stackoverflow.com/questions/69151455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13236293/" ]
You can use `itertools.product` and a list comprehension: ```py import itertools tag_names = ['business', 'science', 'technology'] domain_names = ['bbc', 'cnn', 'nytimes'] [f'www.{domain}.com/{tag}' for domain, tag in itertools.product(domain_names, tag_names)] ``` output: ``` ['www.bbc.com/business', 'www.bbc.com/science', 'www.bbc.com/technology', 'www.cnn.com/business', 'www.cnn.com/science', 'www.cnn.com/technology', 'www.nytimes.com/business', 'www.nytimes.com/science', 'www.nytimes.com/technology'] ```
```py res=zip(tag_names,domain_names) for i in res: print(f'www.{i[1]}.com/{i[0]}') ```
69,151,455
I am trying to generate a list of urls by looping two word lists. I can do it one through f-string but I am not so sure how to do two at the same time. Any suggestion? ```py tag_names = ['business', 'science', 'technology'] domain_names = ['bbc', 'cnn', 'nytimes'] for domain in domain_names: print(f'www.{domain}.com/{tag}') ``` Expected result ``` www.bbc.com/business www.bbc.com/science www.bbc.com/technology www.cnn.com/business www.cnn.com/science www.cnn.com/technology www.nytimes.com/business www.nytimes.com/science www.nytimes.com/technology ```
2021/09/12
[ "https://Stackoverflow.com/questions/69151455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13236293/" ]
Or use a nested loop: ``` tag_names = ['business', 'science', 'technology'] domain_names = ['bbc', 'cnn', 'nytimes'] print([f'www.{domain}.com/{tag}' for domain in domain_names for tag in tag_names]) ``` Output: ``` ['www.bbc.com/business', 'www.bbc.com/science', 'www.bbc.com/technology', 'www.cnn.com/business', 'www.cnn.com/science', 'www.cnn.com/technology', 'www.nytimes.com/business', 'www.nytimes.com/science', 'www.nytimes.com/technology'] ```
```py res=zip(tag_names,domain_names) for i in res: print(f'www.{i[1]}.com/{i[0]}') ```
17,172,510
ok so I have a graph that has a steady increasing slope, much like an exponential graph. It then hits a point where the slope changes to a steep line, much steeper than a y=x graph. My question is, how do I find the point where the slope changes, whether it's VBA or just a function graph, I don't care, I just have no idea how to do this.
2013/06/18
[ "https://Stackoverflow.com/questions/17172510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2460293/" ]
I am the developer working on the other side of this web service. There was indeed a circular reference in the WSDL. I have since fixed that issue and Mike is no longer seeing the recursion error. On my side, the service is being built on the .NET framework using WCF. The issue was due to my attempt to get rid of the <http://tempuri.org> namespace in the WSDL. I had added the correct Namespace to the ServiceContract, DataContract, and ServiceBehavior attributes on the appropriate service classes, but did not know about the bindingNamespace configuration value on the server endpoint element. This caused Visual Studio to generate two WSDL files which referenced eachother, one for the elements belonging in the correct namespace and one for the binding information which was in the tempuri.org namespace. I found the following blog post to be extremely helpful: <http://www.ilovesharepoint.com/2008/07/kill-tempuri-in-wcf-services.html>
Alternatively if you know you are working with a .NET WCF service you can just change your .svc?wsdl to .svc?singleWsdl and the WCF server will take care of the recursion for you.
12,874,153
I created an MVC 4 application in .net 4.5 and installed the Identity and Access tool so that I could create a claims aware application. I configured the application so that it uses the new LocalSTS that comes with 2012, so it doesn't create an STS website like it used to in 2010. How do I support a log off scenario in my application? Is there a method I can call like `FormsAuthentication.SignOut`?
2012/10/13
[ "https://Stackoverflow.com/questions/12874153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143919/" ]
The `s.c_str()` returns a pointer to the const char to prevent you from modifying the backing up memory. You need to make a writable copy of this constant string say with `strdup()` function as `strtok()` really modifies the string that you are scanning for tokens.
`strtok` modifies its argument. This is not allowed with `string.c_str()` since it is a *const* char\* Also, even if it worked your `if( tok == "&" )` will not work since tok is a char\*, not a string, and you will thus be doing pointer and not content comparisons. You would need to use `strcmp()` Since you are using string, why not go for broke and use other c++ constructs? ``` stringstream ss(s); string tmp; while (ss >> buf) { if( buf == "&" ) background = buf; // one wonders why cout << buf << '\n'; } ```
12,874,153
I created an MVC 4 application in .net 4.5 and installed the Identity and Access tool so that I could create a claims aware application. I configured the application so that it uses the new LocalSTS that comes with 2012, so it doesn't create an STS website like it used to in 2010. How do I support a log off scenario in my application? Is there a method I can call like `FormsAuthentication.SignOut`?
2012/10/13
[ "https://Stackoverflow.com/questions/12874153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143919/" ]
The `s.c_str()` returns a pointer to the const char to prevent you from modifying the backing up memory. You need to make a writable copy of this constant string say with `strdup()` function as `strtok()` really modifies the string that you are scanning for tokens.
Your code is mixing C++ `string`s and `cout`s with the C `strtok_r` function. It's not a good combination. The immediate cause of your error is that `c_str()` returns a `const char *` while `strtok()` asks for a non-const `char *`. It wants to modify the string you pass as an argument, and you're not allowed to modify the string that `c_str()` returns. If you want to do this C-style, then switch `s` to a `char[]`. ``` char s[] = "hello hi here whola"; int background = 0; char *strval; char* tok = strtok_r(s, " ", &strval); while (tok != NULL) { printf("%s\n", tok); if (strcmp(tok, "&") == 0) background = 1; else { statement1; statement2; ... } tok = strtok_r(NULL, " ", &strval); } ```
12,874,153
I created an MVC 4 application in .net 4.5 and installed the Identity and Access tool so that I could create a claims aware application. I configured the application so that it uses the new LocalSTS that comes with 2012, so it doesn't create an STS website like it used to in 2010. How do I support a log off scenario in my application? Is there a method I can call like `FormsAuthentication.SignOut`?
2012/10/13
[ "https://Stackoverflow.com/questions/12874153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143919/" ]
`strtok` modifies its argument. This is not allowed with `string.c_str()` since it is a *const* char\* Also, even if it worked your `if( tok == "&" )` will not work since tok is a char\*, not a string, and you will thus be doing pointer and not content comparisons. You would need to use `strcmp()` Since you are using string, why not go for broke and use other c++ constructs? ``` stringstream ss(s); string tmp; while (ss >> buf) { if( buf == "&" ) background = buf; // one wonders why cout << buf << '\n'; } ```
Your code is mixing C++ `string`s and `cout`s with the C `strtok_r` function. It's not a good combination. The immediate cause of your error is that `c_str()` returns a `const char *` while `strtok()` asks for a non-const `char *`. It wants to modify the string you pass as an argument, and you're not allowed to modify the string that `c_str()` returns. If you want to do this C-style, then switch `s` to a `char[]`. ``` char s[] = "hello hi here whola"; int background = 0; char *strval; char* tok = strtok_r(s, " ", &strval); while (tok != NULL) { printf("%s\n", tok); if (strcmp(tok, "&") == 0) background = 1; else { statement1; statement2; ... } tok = strtok_r(NULL, " ", &strval); } ```
42,655
The Lamport signature scheme is faster, less complex and considerably safer than ECDSA. It's only downside - being only usable once - isn't really a downside when signing transactions, since you could just include your next public key whenever signing it. Why isn't, thus, the Lamport signature scheme used in crypto currencies such as Bitcoin?
2016/12/30
[ "https://crypto.stackexchange.com/questions/42655", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/38444/" ]
The major issue will be size difference. The size of ECDSA in bitcoin is much less than the Lamport Signature. For [ECDSA in bitcoin](https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm) * The public key is only 33 Bytes (1 byte for prefix, and 32 bytes for 256-bit integer x) * Signature is at maximum 73 bytes Whereas in [Lamport Signature](https://en.wikipedia.org/wiki/Lamport_signature) * The public key is 512 numbers of 256-bit (total of 16KB) * The Signature is 256 number of 256-bit (total of 8KB) The size of Lamport public key and signature together is 231 times (106 bytes vs 24KB) more than the ECDSA public key and signature. The public key and signature form part of each bitcoin transaction and are stored in block chain. So use of Lamport Signature will need 231 times more storage than ECDSA. As of 1 Oct 2017, the Blockchain size is approximately 135GB. Had it been the Lamport Signature, this would have been in TeraBytes. This would have resulted in higher storage and bandwidth requirement, less number of transactions in one block(which may create backlog, as one block is committed in 10 minutes) and more time in blockchain propagation to other nodes. Moreover, In bitcoin each transaction is charged a network fee based upon transaction size(in terms of bytes, not in terms of amount). At the moment, the [network fee rate](https://bitaps.com/) is 178, 149, 120 [satoshi](https://en.bitcoin.it/wiki/Satoshi_(unit)) / byte for high, medium and low priority respectively.
I know this question is really old, but you should look into IOTA (iota.org), they use Winternitz one time signature instead of ECDSA. There's also a paper about Winternitz OTS here: <http://eprint.iacr.org/2011/191.pdf>
42,655
The Lamport signature scheme is faster, less complex and considerably safer than ECDSA. It's only downside - being only usable once - isn't really a downside when signing transactions, since you could just include your next public key whenever signing it. Why isn't, thus, the Lamport signature scheme used in crypto currencies such as Bitcoin?
2016/12/30
[ "https://crypto.stackexchange.com/questions/42655", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/38444/" ]
The major issue will be size difference. The size of ECDSA in bitcoin is much less than the Lamport Signature. For [ECDSA in bitcoin](https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm) * The public key is only 33 Bytes (1 byte for prefix, and 32 bytes for 256-bit integer x) * Signature is at maximum 73 bytes Whereas in [Lamport Signature](https://en.wikipedia.org/wiki/Lamport_signature) * The public key is 512 numbers of 256-bit (total of 16KB) * The Signature is 256 number of 256-bit (total of 8KB) The size of Lamport public key and signature together is 231 times (106 bytes vs 24KB) more than the ECDSA public key and signature. The public key and signature form part of each bitcoin transaction and are stored in block chain. So use of Lamport Signature will need 231 times more storage than ECDSA. As of 1 Oct 2017, the Blockchain size is approximately 135GB. Had it been the Lamport Signature, this would have been in TeraBytes. This would have resulted in higher storage and bandwidth requirement, less number of transactions in one block(which may create backlog, as one block is committed in 10 minutes) and more time in blockchain propagation to other nodes. Moreover, In bitcoin each transaction is charged a network fee based upon transaction size(in terms of bytes, not in terms of amount). At the moment, the [network fee rate](https://bitaps.com/) is 178, 149, 120 [satoshi](https://en.bitcoin.it/wiki/Satoshi_(unit)) / byte for high, medium and low priority respectively.
The Capitalisk (<https://capitalisk.com/>) blockchain uses the Lamport OTS Scheme in conjunction with the Merkle Signature Scheme (MSS) to produce signatures. MSS provides some degree of key reuse which is useful for signing multiple transactions concurrently. Here are some pros and cons of using Lamport OTS with MSS in this way: Pros: * Simple and easy to understand scheme. * Fast signature creation. * Fast signature verification. * Quantum resistant. * Changing public keys allows the user to change their account passphrase; this provides additional security and peace of mind. Cons: * Large signature sizes (which are typically 30KB with classic Lamport OTS and 15KB with simplified Lamport OTS). * It's a stateful signature scheme; this means that the public key needs to be changed every N signatures to prevent key reuse beyond the number which is allowed by the MSS hash tree (depends on the tree size). Having to handle a changing key state tends to add complexity to the code. * Because a public key leaf in the MSS tree cannot be reused, it makes it cumbersome (and risky) for a user to sign off-chain messages to prove ownership of an account (I.e. it's relatively easy to keep track of which private key index was last used on-chain, but it's harder to keep track of it off-chain). Note also that with Lamport OTS, the blockchain cannot be forked as effectively (e.g. to make a new clone blockchain with the same account balances) because keys cannot be reused. If someone tried to move their funds on the forked chain, they would end up revealing additional hash preimages from one of their OTS private keys on the main chain; this would make their tokens on the main chain less secure. Note that this could also be seen as a positive since it would act as a deterrent from forking the main blockchain. For the blockchain use case, there are trade-offs which can be made to reduce the usage of storage space.
10,082,949
Hi all it's been sometime since I've touched C so I'm really rusty on it. I wrote a small program to create a matrix using two dynamic arrays. However, I'm getting this warning and I don't understand why? I guess I'm not quite sure about pointers to pointers. Can someone help me point out where my problem is? Thanks. ``` sm.c: In function ‘main’: sm.c:11:13: warning: initialisation from incompatible pointer type [enabled by default] sm.c: In function ‘makeMatrix’: sm.c:27:3: warning: return from incompatible pointer type [enabled by default] #include <stdio.h> #include <stdlib.h> typedef int (**intptr) (); intptr makeMatrix(int n); int main(int argc, char *argv[]) { int n = 2; int **A = makeMatrix(n); if(A) { printf("A\n"); } else printf("ERROR"); } intptr makeMatrix(int size) { int **a = malloc(sizeof *a * size); if (a) { for (int i = 0; i < size; i++) { a[i] = malloc(sizeof *a[i] * size); } } return a; } ```
2012/04/10
[ "https://Stackoverflow.com/questions/10082949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119141/" ]
You've got some problems here: ``` typedef int (**intptr) (); intptr makeMatrix(int n); ... int **A = makeMatrix(n); ``` The `intptr` typedef declares a pointer to a pointer to a function that takes an indeterminate number of arguments and returns an `int`. `A` is not an `int`. You need to write: ``` int **makeMatrix(int n); int **A = makeMatrix(n); ``` Using a `typedef` won't help much here. ``` typedef int **(*intptr)(); ``` That declares a pointer to a function that returns a pointer to a pointer to an `int`. But writing ``` intptr makeMatrix(int n); ``` would declare that `makeMatrix()` returns a pointer to a function, not an `int **`.
Your typedef has an extra `()`, making it a zero argument function type. Remove that and you should be good.
29,821,792
I use an HTML `button` to run a function called `start_KEMT` in my `recorder.js` script. ```js var recording = false; var button = document.getElementById('button'); function start_KEMT() { if(!recording) { init(); toggleRecording(button); } toggleRecording(button); recording = !recording; } function toggleRecording(button) { var run = parseInt(button.getAttribute('data-run')); if(run === 1) { recorder && recorder.stop(); recorder && recorder.exportWAV(function(blob) { uploadAudioFromBlob(blob); }); __log('Recording is stopped'); button.setAttribute('data-run', 0); } recorder && recorder.clear(); recorder && recorder.record(); __log('Speak'); button.setAttribute('data-run', 1); } } ...... ``` ```html <button type="submit" class="btn btn-info" id="button" onclick="start_KEMT(this)" data-run="0"><i class="fa fa-dot-circle-o fa-fw"></i>&nbsp;</button> ``` After clicking on the button the `init()` function runs. There is problem with `toggleRecording(button)`. I think that problem is because of the `button` element. After clicking on the button there is also an error in the console: > > Uncaught TypeError: Cannot read property 'getAttribute' of null > > > Can you please give me an whole example how to modify it? I am really new to JS. I am just trying to modify this script. It wasn't created by me.
2015/04/23
[ "https://Stackoverflow.com/questions/29821792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4465075/" ]
You are passing the `button` in the HTML - `onclick="start_KEMT(this)"`. `this` is button element. But you are not defining it in the function. Change your function `start_KEMT` to ``` function start_KEMT(button) { if(!recording) { init(); toggleRecording(button); } toggleRecording(button); recording = !recording; } ```
In your `recorder.js` ,change your function signature from `start_KEMT()` to `start_KEMT(**button**)` .That will solve your problem , as it (i.e. button variable) is undefined right now.
11,782,961
I've got the following structure (in reality, it is much bigger): ``` $param_hash = { 'param1' => [0, 1], 'param2' => [0, 1, 2], 'param3' => 0, }; ``` And I'd like to print all the possible combinations of different parameters in the line, like this: ``` param1='0' param2='0' param3='0' param1='0' param2='1' param3='0' param1='0' param2='2' param3='0' ... ``` I understand that an iteration is needed (like [this one](https://stackoverflow.com/questions/2363142/how-to-iterate-through-hash-of-hashes-in-perl)), but I just cannot get it to work. How should I do this? Or maybe I just should use another structure for storing parameters values scope?
2012/08/02
[ "https://Stackoverflow.com/questions/11782961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016937/" ]
It means there is an open connection to that database somewhere. It could be in a different tab than the one that's calling deleteDatabase. That connection received a versionchange event notifying it that a call to deleteDatabase had been made and that it needs to close. You can add such a handler when the database is opened: ``` request = indexeddb.open("dbname"); request.onsuccess = function(event) { db = event.target.result; db.onversionchange = function(event) { event.target.close(); } } ```
The problem was in the accessing the database from the web workers. In this line of code: ``` database.close();//closing the database self.close();//closing the web worker ``` There is probably some bug in Google chrome if database closing needs more time than usual and you close the web worker, then the database is locked when you try to delete it afterwards. I've fixed the problem by not closing the web worker and let it stay in idle mode.
36,731,378
I am working on a project that will have any number of HTML cards, and the format and positioning of the cards is the same, but the content of them will differ. My plan was to implement the content of each card as an angular directive, and then using ngRepeat, loop through my array of directives which can be in any order, displaying each directive in a card. It would be something like this: inside my controller: ``` $scope.cards = [ 'directice-one', 'directive-two', //etc.. ] ``` my directive: ``` .directive('directiveOne', function () { return { restrict: "C", template: '<h1>One!!</h1>' }; }) .directive('directiveTwo', function () { return { restrict: "C", template: '<h1>Two!!</h1>' }; }) //etc.. ``` my html: ``` <div class="card" ng-repeat="item in cards"> <div class="{{item}}"></div> </div> ``` But.. the directives don't render. So I just get a div with `class="directive-one"`. This might be a design flaw on my part, some sort of syntax error, or just a limitation of angular. I'm not sure. I've also considered making a directive `<card>`, and then passing the `templateUrl:` into it, but that would cause me to lose my access to `$scope` and the javsacript capabilities that I would have if each card was it's own directive. So, advise, code help, anything would be very helpful!
2016/04/19
[ "https://Stackoverflow.com/questions/36731378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5136485/" ]
The posted code works just fine under ksh. ``` $ contract=c $ fld1=c $ if [[ $contract = "$fld1" ]];then > read position?"Enter the position of Contract number in m-n format,m should be less than n " < > fi Enter the position of Contract number in m-n format,m should be less than n 1-2 $ echo $position 1-2 ``` In answer to hedgehog's comment, you might use a less confusing prompt like that one: ``` read position?"Enter the position of Contract number in m-n format, (m should be less than n) : " ``` Note that the `read variable?prompt` syntax is `ksh` specific. Under `bash` you'll use `read -p prompt variable`. A portable method usable on most Bourne syntax based shells would be `printf "%s" "$prompt" ; read variable`
this is the working version of your code: ``` if [[ $contract = "$fld1" ]];then echo "Enter the position of Contract number in m-n format,m should be less than n" read position fi ``` if you want the terminal to wait the user for a reply you have to add the echo and the read seperately. This works fine for you. This is the output: ``` Enter the position of Contract number in m-n format,m should be less than n ##cursor waiting here for an input## ```
48,863,030
With this code I enable a button if any form value is not `nil`: ``` myButton.isEnabled = !myForm.values.contains(where: { $0 == nil }) ``` Is there any way to add multiple checks? I want to enable my button: * if the value of any field is nil (done, as you can see above); * if the value of any field is > 0; * if the value of any field is < 2; (that is, the value should NOT be nil and should NOT be outside the range 0.0 - 2.0) Can I still use [contains(where:)](https://developer.apple.com/documentation/swift/array/2297359-contains) to do it? MyForm is a dictionary like this one: ``` ["oct": nil, "jan": Optional(3666.0), "nov": nil, "apr": nil, "sep": nil, "feb": nil, "jul": nil, "mar": nil, "dec": nil, "may": nil, "jun": nil, "aug": nil] ``` (strange enough, due to the behavior of a 3rd party library, it accepts `nil` values)
2018/02/19
[ "https://Stackoverflow.com/questions/48863030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As wrote in the comment - I can see two solutions 1) add a space after the variable ``` ($email_body =~ s/\{REGISTRATION URL\}/$registration_url.' '/ieg;) ``` 2) replace with space everything that is not a whitespace ``` ($email_body =~ s/\{REGISTRATION URL\}\S+/$registration_url/ieg) ```
Perhaps the best approach would be to check your file before starting the process of replacing those variables. If you expect that line to be `finish your registration here: {REGISTRATION URL}`, then you can check if that line is what you were expecting like this: `$checkEmailTag =~ /\s\{REGISTRATION URL\}$/`. In this case, a preceding space, then your tag and then the end of the line. If it's not, then you can throw an error stating your file is corrupted and abort the process, or add a space so that user characters won´t hurt your URL allowing you to continue, or any other course of action you see fit. You don't need to do this for every variable in your file, just for critical variables like this one.
48,863,030
With this code I enable a button if any form value is not `nil`: ``` myButton.isEnabled = !myForm.values.contains(where: { $0 == nil }) ``` Is there any way to add multiple checks? I want to enable my button: * if the value of any field is nil (done, as you can see above); * if the value of any field is > 0; * if the value of any field is < 2; (that is, the value should NOT be nil and should NOT be outside the range 0.0 - 2.0) Can I still use [contains(where:)](https://developer.apple.com/documentation/swift/array/2297359-contains) to do it? MyForm is a dictionary like this one: ``` ["oct": nil, "jan": Optional(3666.0), "nov": nil, "apr": nil, "sep": nil, "feb": nil, "jul": nil, "mar": nil, "dec": nil, "may": nil, "jun": nil, "aug": nil] ``` (strange enough, due to the behavior of a 3rd party library, it accepts `nil` values)
2018/02/19
[ "https://Stackoverflow.com/questions/48863030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As wrote in the comment - I can see two solutions 1) add a space after the variable ``` ($email_body =~ s/\{REGISTRATION URL\}/$registration_url.' '/ieg;) ``` 2) replace with space everything that is not a whitespace ``` ($email_body =~ s/\{REGISTRATION URL\}\S+/$registration_url/ieg) ```
A common convention is to embed URLs in `<brokets>` in plain text to show exactly where the URL begins and ends. ``` No misunderstanding: <http://stackoverflow.com/>! ```
48,863,030
With this code I enable a button if any form value is not `nil`: ``` myButton.isEnabled = !myForm.values.contains(where: { $0 == nil }) ``` Is there any way to add multiple checks? I want to enable my button: * if the value of any field is nil (done, as you can see above); * if the value of any field is > 0; * if the value of any field is < 2; (that is, the value should NOT be nil and should NOT be outside the range 0.0 - 2.0) Can I still use [contains(where:)](https://developer.apple.com/documentation/swift/array/2297359-contains) to do it? MyForm is a dictionary like this one: ``` ["oct": nil, "jan": Optional(3666.0), "nov": nil, "apr": nil, "sep": nil, "feb": nil, "jul": nil, "mar": nil, "dec": nil, "may": nil, "jun": nil, "aug": nil] ``` (strange enough, due to the behavior of a 3rd party library, it accepts `nil` values)
2018/02/19
[ "https://Stackoverflow.com/questions/48863030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A common convention is to embed URLs in `<brokets>` in plain text to show exactly where the URL begins and ends. ``` No misunderstanding: <http://stackoverflow.com/>! ```
Perhaps the best approach would be to check your file before starting the process of replacing those variables. If you expect that line to be `finish your registration here: {REGISTRATION URL}`, then you can check if that line is what you were expecting like this: `$checkEmailTag =~ /\s\{REGISTRATION URL\}$/`. In this case, a preceding space, then your tag and then the end of the line. If it's not, then you can throw an error stating your file is corrupted and abort the process, or add a space so that user characters won´t hurt your URL allowing you to continue, or any other course of action you see fit. You don't need to do this for every variable in your file, just for critical variables like this one.
3,746
I don't know if Gus Van Sant has admitted it but it seems clear that this movie has been inspired by the shooting in Columbine High School. Is there a link between this event and an elephant? Why is the movie [*Elephant*](https://www.imdb.com/title/tt0363589/) (2003) called that?
2012/08/11
[ "https://movies.stackexchange.com/questions/3746", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/1872/" ]
From the [IMDb link](http://www.imdb.com/title/tt0363589/) in the question: > > Gus Van Sant borrowed the title from Alan Clarke's film of the same name, and thought that it referred to the Chinese proverb about five blind men who were each led to a different part of an elephant. Each man thinks that it is a different thing. What Clarke's title actually referred to was the idea of the "elephant in the room", where something is so obvious that to miss it would be the equivalent of not seeing a huge elephant in an ordinary room, yet is still not recognized out of either stupidity or willful ignorance. In this film, the "elephant in the room" is the homicidal rage of Alex and Eric, which leaves them free to precipitate the last-scene massacre at their school. > > >
I always thought it was because of the treatment of elephants in the circus. Time and time again these elephants are abused, beaten, and whipped, which creates an inevitable breaking point and they end up stampeding over everyone. Much in the same way, these pariahs who have been bullied far too long finally explode...
3,746
I don't know if Gus Van Sant has admitted it but it seems clear that this movie has been inspired by the shooting in Columbine High School. Is there a link between this event and an elephant? Why is the movie [*Elephant*](https://www.imdb.com/title/tt0363589/) (2003) called that?
2012/08/11
[ "https://movies.stackexchange.com/questions/3746", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/1872/" ]
From the [IMDb link](http://www.imdb.com/title/tt0363589/) in the question: > > Gus Van Sant borrowed the title from Alan Clarke's film of the same name, and thought that it referred to the Chinese proverb about five blind men who were each led to a different part of an elephant. Each man thinks that it is a different thing. What Clarke's title actually referred to was the idea of the "elephant in the room", where something is so obvious that to miss it would be the equivalent of not seeing a huge elephant in an ordinary room, yet is still not recognized out of either stupidity or willful ignorance. In this film, the "elephant in the room" is the homicidal rage of Alex and Eric, which leaves them free to precipitate the last-scene massacre at their school. > > >
It's an homage to this film: <http://www.screenonline.org.uk/tv/id/439410/> Elephant is without question Alan Clarke's bleakest film. Essentially a compilation of eighteen murders on the streets of Belfast, without explanatory narrative or characterisation and shot in a cold, dispassionate documentary style, the film succinctly captures the horror of sectarian killing. The lack of narrative removes any scope for justification of the killings on religious, political or any other grounds and the matter-of-factness of Clarke's approach debases the often-heroic portrayal - by all sides - of the individuals involved in sectarian murder. Moreover, Clarke's use of a Steadicam to follow the killers before and during the murders casts the viewer as at best a willing voyeur, at worst an accomplice. After each killing, the camera dwells on the bodies slumped on floors or draped over desks for longer than is comfortable, forcing the viewer to confront the brutality of their deaths.
3,746
I don't know if Gus Van Sant has admitted it but it seems clear that this movie has been inspired by the shooting in Columbine High School. Is there a link between this event and an elephant? Why is the movie [*Elephant*](https://www.imdb.com/title/tt0363589/) (2003) called that?
2012/08/11
[ "https://movies.stackexchange.com/questions/3746", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/1872/" ]
I always thought it was because of the treatment of elephants in the circus. Time and time again these elephants are abused, beaten, and whipped, which creates an inevitable breaking point and they end up stampeding over everyone. Much in the same way, these pariahs who have been bullied far too long finally explode...
It's an homage to this film: <http://www.screenonline.org.uk/tv/id/439410/> Elephant is without question Alan Clarke's bleakest film. Essentially a compilation of eighteen murders on the streets of Belfast, without explanatory narrative or characterisation and shot in a cold, dispassionate documentary style, the film succinctly captures the horror of sectarian killing. The lack of narrative removes any scope for justification of the killings on religious, political or any other grounds and the matter-of-factness of Clarke's approach debases the often-heroic portrayal - by all sides - of the individuals involved in sectarian murder. Moreover, Clarke's use of a Steadicam to follow the killers before and during the murders casts the viewer as at best a willing voyeur, at worst an accomplice. After each killing, the camera dwells on the bodies slumped on floors or draped over desks for longer than is comfortable, forcing the viewer to confront the brutality of their deaths.
9,613,676
I am using hazelcast 1.9.4 version... I started run.bat from the bin directory, but it doesn't seem to be started.. Mar 8, 2012 11:46:38 AM com.hazelcast.impl.LifecycleServiceImpl INFO: /10.50.26.189:5704 [dev] Address[10.50.26.189:5704] is STARTING---> It stuck here.. Any idea what would have gone wrong.!
2012/03/08
[ "https://Stackoverflow.com/questions/9613676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/854190/" ]
I see that your member started with port 5704? It may be that some of the members that you previously started were not properly shutdown. Make sure that you don't have any hanging java(running hazelcast) process.
Exit already running Hazelcast nodes . (this seems to be the fourth node :5704)The other nodes might have crashed. Restarting Hazelcast should fix your problem.!
2,777,843
I have to show that $\operatorname{SO}(2)$ defined as: $$\operatorname{SO}(2)=\{ \left(\begin{array}{cc} \cos\phi& -\sin\phi\\ \sin\phi&\cos\phi \end{array}\right)\in M\_2(\mathbb R)\,|\, \phi \in [0,2\pi]\}$$ is an abelian group by proving these points: 1. $A^{-1}$ exists $\forall A \in \operatorname{SO}(2),$ 2. if $A,B \in \operatorname{SO}(2)$, then $AB\in \operatorname{SO}(2),$ 3. $\forall A,B \in \operatorname{SO}(2),\ AB=BA.$ The first point is easy: $$\forall A \in \operatorname{SO}(2): \det(A)=(\sin\phi)^2+(\cos\phi)^2=1 \implies \det(A)\neq 0 \to \exists A^{-1}.$$ The third one is also true, you just have to multiply $AB$ and $BA$ and you will get: $$\forall A,B \in \operatorname{SO}(2): AB=BA.$$ I'm having trouble with the second point, I tried just multiplying but I don't think it's enough to show that $(AB)\_{11}=(AB)\_{22}$ and $(AB)\_{12}=-(AB)\_{21}$. One has to show that this applies to the same $\phi$ for both equations. But I don't know how. Thanks for your tips and help in advance :)
2018/05/12
[ "https://math.stackexchange.com/questions/2777843", "https://math.stackexchange.com", "https://math.stackexchange.com/users/561203/" ]
You haven't really proved 1., you've shown that $A$ is invertible matrix, you didn't show that the inverse is contained in $\operatorname{SO}(2)$. For all three points, the same **hint** applies, write $$A = \begin{pmatrix} \cos \alpha & -\sin\alpha\\ \sin \alpha & \cos\alpha \end{pmatrix},\ B = \begin{pmatrix} \cos \beta & -\sin\beta\\ \sin \beta & \cos\beta \end{pmatrix}$$ and after you multiply them, use **trigonometric addition formulas**.
I think the easiest way is realising $\mathbb{C} \cong \mathbb{R}^2$ and identifying $z=a+bi$ as $$ Z=\begin{pmatrix}a & -b \\ b & a \end{pmatrix}. $$ Also note that $\det{Z}=a^2+b^2=|z|^2$. Next, one can identify $SO(2)$ as the unit circle $S^1=\{z=\exp{ix}:0 \leq x <2\pi\}$, which is clearly abelian.
2,777,843
I have to show that $\operatorname{SO}(2)$ defined as: $$\operatorname{SO}(2)=\{ \left(\begin{array}{cc} \cos\phi& -\sin\phi\\ \sin\phi&\cos\phi \end{array}\right)\in M\_2(\mathbb R)\,|\, \phi \in [0,2\pi]\}$$ is an abelian group by proving these points: 1. $A^{-1}$ exists $\forall A \in \operatorname{SO}(2),$ 2. if $A,B \in \operatorname{SO}(2)$, then $AB\in \operatorname{SO}(2),$ 3. $\forall A,B \in \operatorname{SO}(2),\ AB=BA.$ The first point is easy: $$\forall A \in \operatorname{SO}(2): \det(A)=(\sin\phi)^2+(\cos\phi)^2=1 \implies \det(A)\neq 0 \to \exists A^{-1}.$$ The third one is also true, you just have to multiply $AB$ and $BA$ and you will get: $$\forall A,B \in \operatorname{SO}(2): AB=BA.$$ I'm having trouble with the second point, I tried just multiplying but I don't think it's enough to show that $(AB)\_{11}=(AB)\_{22}$ and $(AB)\_{12}=-(AB)\_{21}$. One has to show that this applies to the same $\phi$ for both equations. But I don't know how. Thanks for your tips and help in advance :)
2018/05/12
[ "https://math.stackexchange.com/questions/2777843", "https://math.stackexchange.com", "https://math.stackexchange.com/users/561203/" ]
Convince yourself that the rotation around the origin by an angle $\alpha$ in the counterclockwise sense is given by multiplying a vector in the plane by $$R\_{\alpha}=\begin{pmatrix} \cos \alpha & -\sin \alpha \\\sin\alpha & \cos \alpha\end{pmatrix}. $$ Rotation by $-\alpha$ is the inverse of rotation by $\alpha$, so $R\_{\alpha}^{-1} = R\_{\alpha}$. Rotation by $\alpha$ followed by rotation by $\beta$, $R\_{\beta}R\_{\alpha}$, is the same as rotation by $\beta$ followed by rotation by $\alpha$, $R\_{\alpha}R\_{\beta}$, because both compositions yield rotation by $\alpha + \beta$, $R\_{\alpha + \beta}$. Since $R\_{0}= I$, this suffices to show that these matrices constitute an abelian group.
I think the easiest way is realising $\mathbb{C} \cong \mathbb{R}^2$ and identifying $z=a+bi$ as $$ Z=\begin{pmatrix}a & -b \\ b & a \end{pmatrix}. $$ Also note that $\det{Z}=a^2+b^2=|z|^2$. Next, one can identify $SO(2)$ as the unit circle $S^1=\{z=\exp{ix}:0 \leq x <2\pi\}$, which is clearly abelian.
1,952,225
I have no formal education in computer science but I have been programming in Java, Ruby, jQuery for a long time. I was checking out macruby project. I keep running into statements which are similar to "In MacRuby objective-c runtime is same as ruby runtime". I understand what MRI is. I understand what ruby 1.9 is bringing to the table. However I fail to understand how the VM for one language can support another language. I know I am asking a question answer to which relies on years of formal education. Still any pointers and any discussion will help. Also I like what I see in macruby.
2009/12/23
[ "https://Stackoverflow.com/questions/1952225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175838/" ]
Well, The simplest explanation is that MacRuby is a ruby 1.9 VM. During earlier versions it was a modified version of the YARV (ruby 1.9's official VM) which instead of using custom types for things like ruby strings, hashes etc. made use of equivalents found within apples foundation classes such as NString. With the advent of version 0.5 a whole new VM has been developed based on the LLVM framework, again ruby 1.9 compatible, which is ground up based on apples foundation classes. Therefore you can think of Macruby simply as a ruby 1.9 VM. However, due to the use of aforementioned foundation classes it has been possible to interface natively with much of apples own api's providing additional features only available to those running MacRuby (such as HotCocoa for example.)
Just a note on the > > However I fail to understand how the VM for one language can support another language. > > > part. A VM represents a middle layer between the machine and your programming language. E.g. the Java Virtual Machine (JVM) execute so called java bytecode. The `javac` compiler takes the source code and compiles it into an intermediate language - that bytecode. When you run your application, you actually run bytecode inside the virtual machine: > > The JVM runtime executes .class or .jar files, emulating the JVM instruction set by interpreting it, or using a just-in-time compiler (JIT) such as Sun's HotSpot. JIT compiling, not interpreting, is used in most JVMs today to achieve greater speed. Ahead-of-time compilers that enable the developer to precompile class files into native code for a particular platforms also exist. > > > It is therefore possible to code in any language (e.g. Clojure, Scala, Rhino, [...](http://en.wikipedia.org/wiki/List_of_JVM_languages)) for which a compiler to a certain VM has been written. The same princle applies to the architecture around Microsoft .NET's Common Intermediate Language (CIL). As for macruby internals, there is a [short overview](http://www.macruby.org/documentation/overview.html) on their site.
15,623,996
I need help, I'm just learning C, have no idea what is wrong: Here I call `set_opts` function : ``` char * tmploc ; tmploc=set_opts("windir","\\temp.rte"); printf(tmploc); ``` ( I know , that printf is not formated, just used it for testing purposes) function looks like this : ``` char * set_opts(char * env,char * path){ char * opt; opt=malloc(strlen(env)+strlen(path)+1); strcpy(opt,getenv(env)); strcat(opt,path); return opt; } ``` Everything is ok, but when I try to call it again : ``` char * tmploc2 ; tmploc2=set_opts("windir","\\temp.rte"); printf(tmploc2); ``` ...program just terminates Please tell me what I'm doing wrong
2013/03/25
[ "https://Stackoverflow.com/questions/15623996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2209077/" ]
Be careful what you are doing with [`getenv()`](http://linux.die.net/man/3/getenv), because: > > The getenv() function returns a pointer to the value in the environment, or NULL if there is no match. > > > So if you pass a name that does not correspond to an existing environment variable then you get NULL returned and that is going to kill your `strcpy(opt,getenv(env));` I recomend: 1. Check what `malloc()` returns and make sure that it is non-null. 2. Check what `getenv()` returns and make sure that it is non-null. 3. As you pointed out, use a format string in your printf's and compile with `-Wall`. 4. Step through your code with a debugger to make sure it not terminating before you see the output.
One possible reason: malloc returns `NULL` and you never check for it. Same for getenv(). And it must be ``` malloc(strlen(getenv(env))+strlen(path)+1); ``` If the actual contents of getenv("windir") is longer than 6 characters, you write past the malloced buffer, which invokes *undefined behavior*.
15,623,996
I need help, I'm just learning C, have no idea what is wrong: Here I call `set_opts` function : ``` char * tmploc ; tmploc=set_opts("windir","\\temp.rte"); printf(tmploc); ``` ( I know , that printf is not formated, just used it for testing purposes) function looks like this : ``` char * set_opts(char * env,char * path){ char * opt; opt=malloc(strlen(env)+strlen(path)+1); strcpy(opt,getenv(env)); strcat(opt,path); return opt; } ``` Everything is ok, but when I try to call it again : ``` char * tmploc2 ; tmploc2=set_opts("windir","\\temp.rte"); printf(tmploc2); ``` ...program just terminates Please tell me what I'm doing wrong
2013/03/25
[ "https://Stackoverflow.com/questions/15623996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2209077/" ]
You allocate the length of the string using `env`, but then populate it with `getenv(env)`. If `getenv(env)` is longer than `env` then you have a good chance of a segfault. Did you mean to use `strlen(getenv(env))`? You really ought to add some error checking to your code: ``` char *set_opts(char *env, char *path) { char *opt; char *value; value = getenv(env); if (value == NULL) ... handle error opt = malloc(strlen(value)+strlen(path)+1); if (opt == NULL) ... handle error strcpy(opt,value); strcat(opt,path); return opt; } ```
One possible reason: malloc returns `NULL` and you never check for it. Same for getenv(). And it must be ``` malloc(strlen(getenv(env))+strlen(path)+1); ``` If the actual contents of getenv("windir") is longer than 6 characters, you write past the malloced buffer, which invokes *undefined behavior*.
15,623,996
I need help, I'm just learning C, have no idea what is wrong: Here I call `set_opts` function : ``` char * tmploc ; tmploc=set_opts("windir","\\temp.rte"); printf(tmploc); ``` ( I know , that printf is not formated, just used it for testing purposes) function looks like this : ``` char * set_opts(char * env,char * path){ char * opt; opt=malloc(strlen(env)+strlen(path)+1); strcpy(opt,getenv(env)); strcat(opt,path); return opt; } ``` Everything is ok, but when I try to call it again : ``` char * tmploc2 ; tmploc2=set_opts("windir","\\temp.rte"); printf(tmploc2); ``` ...program just terminates Please tell me what I'm doing wrong
2013/03/25
[ "https://Stackoverflow.com/questions/15623996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2209077/" ]
You allocate the length of the string using `env`, but then populate it with `getenv(env)`. If `getenv(env)` is longer than `env` then you have a good chance of a segfault. Did you mean to use `strlen(getenv(env))`? You really ought to add some error checking to your code: ``` char *set_opts(char *env, char *path) { char *opt; char *value; value = getenv(env); if (value == NULL) ... handle error opt = malloc(strlen(value)+strlen(path)+1); if (opt == NULL) ... handle error strcpy(opt,value); strcat(opt,path); return opt; } ```
Be careful what you are doing with [`getenv()`](http://linux.die.net/man/3/getenv), because: > > The getenv() function returns a pointer to the value in the environment, or NULL if there is no match. > > > So if you pass a name that does not correspond to an existing environment variable then you get NULL returned and that is going to kill your `strcpy(opt,getenv(env));` I recomend: 1. Check what `malloc()` returns and make sure that it is non-null. 2. Check what `getenv()` returns and make sure that it is non-null. 3. As you pointed out, use a format string in your printf's and compile with `-Wall`. 4. Step through your code with a debugger to make sure it not terminating before you see the output.
15,623,996
I need help, I'm just learning C, have no idea what is wrong: Here I call `set_opts` function : ``` char * tmploc ; tmploc=set_opts("windir","\\temp.rte"); printf(tmploc); ``` ( I know , that printf is not formated, just used it for testing purposes) function looks like this : ``` char * set_opts(char * env,char * path){ char * opt; opt=malloc(strlen(env)+strlen(path)+1); strcpy(opt,getenv(env)); strcat(opt,path); return opt; } ``` Everything is ok, but when I try to call it again : ``` char * tmploc2 ; tmploc2=set_opts("windir","\\temp.rte"); printf(tmploc2); ``` ...program just terminates Please tell me what I'm doing wrong
2013/03/25
[ "https://Stackoverflow.com/questions/15623996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2209077/" ]
Be careful what you are doing with [`getenv()`](http://linux.die.net/man/3/getenv), because: > > The getenv() function returns a pointer to the value in the environment, or NULL if there is no match. > > > So if you pass a name that does not correspond to an existing environment variable then you get NULL returned and that is going to kill your `strcpy(opt,getenv(env));` I recomend: 1. Check what `malloc()` returns and make sure that it is non-null. 2. Check what `getenv()` returns and make sure that it is non-null. 3. As you pointed out, use a format string in your printf's and compile with `-Wall`. 4. Step through your code with a debugger to make sure it not terminating before you see the output.
Try getting rid of `getenv(env)`. Just put `strcpy(opt,env);`. `getenv()` is probably returning `NULL`.
15,623,996
I need help, I'm just learning C, have no idea what is wrong: Here I call `set_opts` function : ``` char * tmploc ; tmploc=set_opts("windir","\\temp.rte"); printf(tmploc); ``` ( I know , that printf is not formated, just used it for testing purposes) function looks like this : ``` char * set_opts(char * env,char * path){ char * opt; opt=malloc(strlen(env)+strlen(path)+1); strcpy(opt,getenv(env)); strcat(opt,path); return opt; } ``` Everything is ok, but when I try to call it again : ``` char * tmploc2 ; tmploc2=set_opts("windir","\\temp.rte"); printf(tmploc2); ``` ...program just terminates Please tell me what I'm doing wrong
2013/03/25
[ "https://Stackoverflow.com/questions/15623996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2209077/" ]
Be careful what you are doing with [`getenv()`](http://linux.die.net/man/3/getenv), because: > > The getenv() function returns a pointer to the value in the environment, or NULL if there is no match. > > > So if you pass a name that does not correspond to an existing environment variable then you get NULL returned and that is going to kill your `strcpy(opt,getenv(env));` I recomend: 1. Check what `malloc()` returns and make sure that it is non-null. 2. Check what `getenv()` returns and make sure that it is non-null. 3. As you pointed out, use a format string in your printf's and compile with `-Wall`. 4. Step through your code with a debugger to make sure it not terminating before you see the output.
Are you sure: getenv(env) will fit into "opt" ? I don't think so. And if it doesn't fit, then the strcpy could kill your program. A correction: char \* set\_opts(char \* env,char \* path){ char \* opt; char \* value = getenv(env); opt=malloc(strlen(value)+strlen(path)+1); strcpy(opt,value); strcat(opt,path); return opt; } This way, you're sure you have enough space.
15,623,996
I need help, I'm just learning C, have no idea what is wrong: Here I call `set_opts` function : ``` char * tmploc ; tmploc=set_opts("windir","\\temp.rte"); printf(tmploc); ``` ( I know , that printf is not formated, just used it for testing purposes) function looks like this : ``` char * set_opts(char * env,char * path){ char * opt; opt=malloc(strlen(env)+strlen(path)+1); strcpy(opt,getenv(env)); strcat(opt,path); return opt; } ``` Everything is ok, but when I try to call it again : ``` char * tmploc2 ; tmploc2=set_opts("windir","\\temp.rte"); printf(tmploc2); ``` ...program just terminates Please tell me what I'm doing wrong
2013/03/25
[ "https://Stackoverflow.com/questions/15623996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2209077/" ]
You allocate the length of the string using `env`, but then populate it with `getenv(env)`. If `getenv(env)` is longer than `env` then you have a good chance of a segfault. Did you mean to use `strlen(getenv(env))`? You really ought to add some error checking to your code: ``` char *set_opts(char *env, char *path) { char *opt; char *value; value = getenv(env); if (value == NULL) ... handle error opt = malloc(strlen(value)+strlen(path)+1); if (opt == NULL) ... handle error strcpy(opt,value); strcat(opt,path); return opt; } ```
Try getting rid of `getenv(env)`. Just put `strcpy(opt,env);`. `getenv()` is probably returning `NULL`.
15,623,996
I need help, I'm just learning C, have no idea what is wrong: Here I call `set_opts` function : ``` char * tmploc ; tmploc=set_opts("windir","\\temp.rte"); printf(tmploc); ``` ( I know , that printf is not formated, just used it for testing purposes) function looks like this : ``` char * set_opts(char * env,char * path){ char * opt; opt=malloc(strlen(env)+strlen(path)+1); strcpy(opt,getenv(env)); strcat(opt,path); return opt; } ``` Everything is ok, but when I try to call it again : ``` char * tmploc2 ; tmploc2=set_opts("windir","\\temp.rte"); printf(tmploc2); ``` ...program just terminates Please tell me what I'm doing wrong
2013/03/25
[ "https://Stackoverflow.com/questions/15623996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2209077/" ]
You allocate the length of the string using `env`, but then populate it with `getenv(env)`. If `getenv(env)` is longer than `env` then you have a good chance of a segfault. Did you mean to use `strlen(getenv(env))`? You really ought to add some error checking to your code: ``` char *set_opts(char *env, char *path) { char *opt; char *value; value = getenv(env); if (value == NULL) ... handle error opt = malloc(strlen(value)+strlen(path)+1); if (opt == NULL) ... handle error strcpy(opt,value); strcat(opt,path); return opt; } ```
Are you sure: getenv(env) will fit into "opt" ? I don't think so. And if it doesn't fit, then the strcpy could kill your program. A correction: char \* set\_opts(char \* env,char \* path){ char \* opt; char \* value = getenv(env); opt=malloc(strlen(value)+strlen(path)+1); strcpy(opt,value); strcat(opt,path); return opt; } This way, you're sure you have enough space.