qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
48,367,970
I have .sql file with 100s of Oracle queries, so while spooling the results of all 100s queries are getting written into one file, but I want a single file should be created for every single query, for 100 queries there should be 100 files having result for their particular query.
2018/01/21
[ "https://Stackoverflow.com/questions/48367970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could do a SELECT before UPDATE in same transaction at the moment user try to buy something. So that your second user would get an info that there is no item he's looking for, because first user take it, and UPDATE wouldn't be runned.
19,474,796
My `grunt build` task creates a `/dist/` which my project depends on. I don't want to include built file in my repository. I would rather use Jenkins to allow for continuous integration builds on my project. This is what I have in my `.openshift/action_hooks/build`, and I'm not sure why it's not running: ``` echo " >>>>>>>>> Building with grunt..." grunt build echo " >>>>>>>>> Finished building with grunt..." ``` I know it's not running because I don't see those echo lines in the Jenkins build log or the application log (`rhc tail <app-name>`). Also, when I ssh into the server and attempt to run `grunt build` manually, it is unable to find the grunt command, so that makes me wonder whether this is possible... Am I supposed to just include the built files in my repo? If so, when will OpenShift fix this? :) Let me know if I'm doing something wrong. Thanks!
2013/10/20
[ "https://Stackoverflow.com/questions/19474796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971592/" ]
The fundamental issue here is the [openshift-origin-cartridge-nodejs](https://github.com/wshearn/openshift-origin-cartridge-nodejs) and furthermore [npm\_global\_module\_list](https://github.com/openshift/origin-server/blob/master/cartridges/openshift-origin-cartridge-nodejs/versions/shared/configuration/npm_global_module_list) doesn't include grunt/grunt-cli in the global npm modules. I opened [openshift/origin-server/issues/4069](https://github.com/openshift/origin-server/issues/4069) as an RFE to get this in the default cartridge. In the meantime, I've been working on [engineersamuel/openshift-origin-cartridge-nodejs](https://github.com/engineersamuel/openshift-origin-cartridge-nodejs) which includes bower and Grunt support. My cartridge runs `grunt prod` if a Gruntfile.js is found. By default grunt is not on the path, this is easily fixed by prefixing the command with the node\_modules. ```sh # If there is a grunt file, run $ grunt prod if [ -f "${OPENSHIFT_REPO_DIR}"/Gruntfile.js ]; then (cd "${OPENSHIFT_REPO_DIR}"; node_modules/grunt-cli/bin/grunt prod) fi ``` The `./bin/control` also checks for a bower.json file and installs the corresponding packages. You can quickly and easily test out this custom cartridge with the cartridge reflector with the following command: `rhc create-app nodejstest "http://cartreflect-claytondev.rhcloud.com/reflect?github=engineersamuel/openshift-origin-cartridge-nodejs"`
250,482
I have a table `OriginTable` with the following structure ``` EventID | Date | Value1 | Value2 | Value3 ----------------------------------------------------------- 5 | 2019-10-07 | MyValue1_1 | MyValue2_1 | MyValue3_1 5 | 2019-10-07 | MyValue1_2 | MyValue2_2 | MyValue3_2 5 | 2019-10-07 | MyValue1_3 | MyValue2_3 | MyValue3_3 6 | 2019-10-07 | MyValue1_4 | MyValue2_4 | MyValue3_4 6 | 2019-10-07 | MyValue1_5 | MyValue2_5 | MyValue3_5 6 | 2019-10-07 | MyValue1_6 | MyValue2_6 | MyValue3_6 ``` where `EventID` is reinitiated every day, but the combination of EventID and Date values provides a suitable unique identifier. I want to split this table into two tables `FirstDestinationTable` and `SecondDestinationTable` like ``` ID | EventID | Date ------------------------- 1 | 5 | 2019-10-07 2 | 6 | 2019-10-07 ``` and ``` FirstDstTblID | Value1 | Value2 | Value3 ---------------------------------------------------- 1 | MyValue1_1 | MyValue2_1 | MyValue3_1 1 | MyValue1_2 | MyValue2_2 | MyValue3_2 1 | MyValue1_3 | MyValue2_3 | MyValue3_3 2 | MyValue1_4 | MyValue2_4 | MyValue3_4 2 | MyValue1_5 | MyValue2_5 | MyValue3_5 2 | MyValue1_6 | MyValue2_6 | MyValue3_6 ``` where `FirstDstTblID` references `FirstDestinationTable(ID)`. The purpose of this task is to save storage space since `OriginTable` is 120MB each day and I want to execute this on a daily basis. Thanks.
2019/10/07
[ "https://dba.stackexchange.com/questions/250482", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/192559/" ]
I do not believe you will save any storage space by splitting the attributes into two tables. INT uses 4 bytes of storage space. A date uses 3 bytes. Say you compress down a million rows to just one value. ( Ex There are 1 Million rows that have the combination of Event ID 5 and date 2019-10-07). You will save a total of 3 million bytes. That's only 3 megabytes. You could technically do the same thing you want on the other side of the table; split off every combination of MyValue, create a look up table of them, and then join each on a third table. But don't! Readability and maintenance are things to consider along side just storage cost. So is your time developing this solution. The current 10/7/2019 cost for Azure SQL database storage (past your 32gb of free data) is $0.138/GB/Month. After 3 years of every week gaining a full GB of data(Total storage is now 156gb), you will have only spent a TOTAL of $1,679.18.
33,590,109
Im able to create and install printers using powershell. Now i also need to automate the printer configuration and need to change multiple values in the Administration tab. [![Printer Settings](https://i.stack.imgur.com/d9A3J.png)](https://i.stack.imgur.com/d9A3J.png) How can i do that via powershell? I tried Set-PrinterProperty but i can't get it to work. Thanks
2015/11/08
[ "https://Stackoverflow.com/questions/33590109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/933976/" ]
One way I found easy to implement this was to start from current printer configuration, using Get-PrinterConiguration, then look at the xml and change whatever you need to, then use Set-PrinterProperty to push up the new xml. Below is a function I created a while ago to update Printer Tray. It should (hopefully) get you started. ``` Function Set-MyDefaultPrinterTray { #Requires -module PrintManagement <# .SYNOPSIS Update Default Tray assignment of printer .EXAMPLE > Set-MyDefaultPrinterTray -ComputerName (Get-Content C:\temp\epicprinter\servers.txt) -PrintQueue ZZZ_Adil_Test03 -Tray 4 -Verbose VERBOSE: Change tray to Tray4 on epswcdcqvm001 VERBOSE: Getting PrintConfiguration... VERBOSE: epswcdcqvm001 : CurrentTray is psk:AutoSelect VERBOSE: epswcdcqvm001 : New Tray ns0000:Tray4 VERBOSE: Performing the operation "Update Tray" on target "epswcdcqvm001". VERBOSE: epswcdcqvm001 : Setting new tray assignment VERBOSE: epswcdcqvm001 : Adding to success table VERBOSE: Change tray to Tray4 on epswcdcqvm002 VERBOSE: Getting PrintConfiguration... VERBOSE: epswcdcqvm002 : CurrentTray is psk:AutoSelect VERBOSE: epswcdcqvm002 : New Tray ns0000:Tray4 VERBOSE: Performing the operation "Update Tray" on target "epswcdcqvm002". VERBOSE: epswcdcqvm002 : Setting new tray assignment VERBOSE: epswcdcqvm002 : Adding to success table VERBOSE: Change tray to Tray4 on epswcdcqvm001 VERBOSE: Getting PrintConfiguration... VERBOSE: epswcdcqvm001 : CurrentTray is ns0000:Tray4 VERBOSE: epswcdcqvm001 : New Tray ns0000:Tray4 VERBOSE: Performing the operation "Update Tray" on target "epswcdcqvm001". VERBOSE: epswcdcqvm001 : Setting new tray assignment Name Value ---- ----- epswcdcqvm002 Succeed epswcdcqvm001 Succeed .EXAMPLE D:\> Set-MyDefaultPrinterTray -PrintServer 'epswcdcqvm001','epswcdcqvm002' -PrintQueue ZZZ_Adil_Test03 -Tray Tray2 -Verbose VERBOSE: Change tray to Tray2 on epswcdcqvm001 VERBOSE: Getting PrintConfiguration... VERBOSE: epswcdcqvm001 : CurrentTray is psk:AutoSelect VERBOSE: epswcdcqvm001 : New Tray ns0000:Tray2 VERBOSE: Performing the operation "Set-EpicDefaultPrinterTray" on target "epswcdcqvm001". VERBOSE: epswcdcqvm001 : Setting new tray assignment VERBOSE: Change tray to Tray2 on epswcdcqvm002 VERBOSE: Getting PrintConfiguration... VERBOSE: epswcdcqvm002 : CurrentTray is psk:AutoSelect VERBOSE: epswcdcqvm002 : New Tray ns0000:Tray2 VERBOSE: Performing the operation "Set-EpicDefaultPrinterTray" on target "epswcdcqvm002". VERBOSE: epswcdcqvm002 : Setting new tray assignment #> [CMDLETBINDING(SupportsShouldProcess)] param( [Parameter(Mandatory,ValueFromPipeline,Position=0)] [Alias('PrintServer')] [string[]]$ComputerName, #[string[]]$PrintServer, [Parameter(Mandatory,Position=1)] [string]$PrintQueue, [ValidateSet('1','2','3','4','Tray1','Tray2','Tray3','Tray4','AutoSelect','ManualFeed')] $Tray='AutoSelect' ) BEGIN { switch ($tray) { 1 {$tray='Tray1';break} 2 {$tray='Tray2';break} 3 {$tray='Tray3';break} 4 {$tray='Tray4';break} } $result = @{} } PROCESS { Foreach ($ps in $ComputerName) { Write-Verbose "Change tray to $tray on $ps" try { if (! (Test-Connection -ComputerName $ps -Count 1 -Quiet)) { throw "Not Pingable" } Write-Verbose "Getting PrintConfiguration..." $PrintConfiguration = Get-PrintConfiguration -ComputerName $ps -PrinterName $PrintQueue $PrintTicketXML = [xml]$PrintConfiguration.PrintTicketXML $currentTray = ($PrintTicketXML.PrintTicket.Feature).where({$_.name -eq 'psk:JobInputBin'}).option.name Write-Verbose "$ps : CurrentTray is $currentTray " if ($Tray -eq 'AutoSelect') { $NewTray= "psk:$Tray" } else { $NewTray= "ns0000:$Tray" } Write-Verbose "$ps : New Tray $NewTray " $UpdatedPrintTicketXML = $PrintConfiguration.PrintTicketXML -replace "$currentTray","$NewTray" if ($PSCmdlet.ShouldProcess($ps,"Update Tray") ) { Write-Verbose "$ps : Setting new tray assignment" Set-PrintConfiguration -ComputerName $ps -printername $PrintQueue -PrintTicketXml $UpdatedPrintTicketXML if (!$result.ContainsKey($ps)) { Write-Verbose "$ps : Adding to success table" $result.Add($ps,'Succeed') } } } catch { if (!$result.ContainsKey($ps)) { Write-Verbose "$ps : Adding to fail table" $result.Add($ps,'Fail') } Write-Error $error[0].exception } } } END { $result } } ```
31,663,574
I have some problems with my Synology NAS Cloud Station (like Dropbox). Somehow my local version has come out of sync with the version on the server. It's a pain to inspect the differences and get an overview. I would like to print a tree structure including size, last-modified, and created date. It will serve as a snapshot before I begin cleaning up. I can't really program in Bash, but I hope it is OK to ask for such a script. By the way, I can't use `tree` since it is not available on the NAS, which uses some proprietary version of Linux.
2015/07/27
[ "https://Stackoverflow.com/questions/31663574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735070/" ]
Listing of all files under the "present working directory" (`PWD="."`) is easy: ``` find . -type f -print0 | xargs -0 -I '{}' ls -la -- '{}' ``` Edit: ===== One script as an example of what you need is: ``` #!/bin/sh -- if [ "$1" ] ; then SearchDir="$1" fi find ${SearchDir:=\./} \( ! -regex '.*/\..*' \) -type f | while IFS= read -r file; do a="$(stat -c "%X" "$file")" b="$(date --date='@'"$a" "+%D")" c="$(stat -c "%Y" "$file")" d="$(date --date='@'"$c" "+%D")" printf "%10s %10s -- %s\n" "$b" "$d" "$file|" done ```
21,045,284
What is best way to find given 3d Point is inside/outside in concave/convex model ? I tried vtkSelectEnclosedPoints but it seems it can only handle convex case. Alex
2014/01/10
[ "https://Stackoverflow.com/questions/21045284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2546731/" ]
This is the topic of Section 7.5 in [*Computational Geometry in C*](http://cs.smith.edu/~orourke/books/compgeom.html). The problem is generally called "Point in Polyhedron." It is not a straightforward issue, but it is by now well-explored. Code is available for the computation at the book link. At a high level, one shoots a ray from the point *p* and counts intersections: if odd, then *p* is inside; if even, outside. But there are delicate issues about how to "count" correctly.
30,526,971
I've tried adding a facebook plugin to my page but it doesn't appear correctly. What i've done so far was going to the Facebook Developpers for the new [Page Plugin](https://developers.facebook.com/docs/plugins/page-plugin), included correctly (i hope) the SDK, included the script and pasted the html code the generator gave me. But my Page Plugin is not working correctly, what i get is a simple orange block with a simple hyperlink redirecting to my fb page. I couldn't find any help since they changed the possibility to switch between html5 xfbml and iframe. I thought it would be a css issue so i tried editing my div containing the Page plugin to disable some css proprieties but it didn't change a thing. If i try adding an iframe code from another site on mine, it works fine, for example. I really don't know where my issue comes from, i hope someone could help me ! (:
2015/05/29
[ "https://Stackoverflow.com/questions/30526971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4909002/" ]
It is to check that the FILE exists. You can refer the [manual](http://linux.die.net/man/1/test) for details. ``` -e FILE FILE exists ``` On a side note here are some other useful options ``` -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file -h FILE FILE exists and is a symbolic link (same as -L) -r FILE FILE exists and is readable -s FILE FILE exists and has a size greater than zero -w FILE FILE exists and is writable -x FILE FILE exists and is executable -z STRING the length of STRING is zero ```
25,793,658
I wrote a naive Parallel.For() loop in C#, shown below. I also did the same work using a regular for() loop to compare single-thread vs. multi-thread. The single thread version took about five seconds every time I ran it. The parallel version took about three seconds at first, but if I ran it about four times, it would slow down dramatically. Most often it took about thirty seconds. One time it took eighty seconds. If I restarted the program, the parallel version would start out fast again, but slow down after three or four parallel runs. Sometimes the parallel runs would speed up again to the original three seconds then slow down. I wrote another Parallel.For() loop for computing Mandelbrot set members (discarding the results) because I figured that the problem might be related to memory issues allocating and manipulating a large array. The Parallel.For() implementation of this second problem does indeed execute faster than the single-thread version every time, and the times are consistent too. What data should I be looking at to understand to understand why my first naive program slows down after a number of runs? Is there something in Perfmon I should be looking at? I still suspect it is memory related, but I allocate the array outside the timer. I also tried a GC.Collect() at the end of each run, but that didn't seem help, not consistently anyway. Might it be an alignment issue with cache somewhere on the processor? How would I figure that out? Is there anything else that might be the cause? JR ``` const int _meg = 1024 * 1024; const int _len = 1024 * _meg; private void ParallelArray() { int[] stuff = new int[_meg]; System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch(); lblStart.Content = DateTime.Now.ToString(); s.Start(); Parallel.For(0, _len, i => { stuff[i % _meg] = i; } ); s.Stop(); lblResult.Content = DateTime.Now.ToString(); lblDiff.Content = s.ElapsedMilliseconds.ToString(); } ```
2014/09/11
[ "https://Stackoverflow.com/questions/25793658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4031976/" ]
I have profiled your code and it indeed looks strange. There should be no deviations. It is not an allocation issue (GC is fine and you are allocating only one array per run). The problem can be reproduced on my Haswell CPU where the parallel version suddenly takes much longer to execute. I have CLR version 4.0.30319.34209 FX452RTMGDR. On x64 it works fine and has no issues. Only x86 builds seem to suffer from it. I have profiled it with the Windows Performance Toolkit and have found that it looks like a CLR issue where the TPL tries to find the next workitem. Sometimes it happens that the call ``` System.Threading.Tasks.RangeWorker.FindNewWork(Int64 ByRef, Int64 ByRef) System.Threading.Tasks.Parallel+<>c__DisplayClassf`1[[System.__Canon, mscorlib]].<ForWorker>b__c() System.Threading.Tasks.Task.InnerInvoke() System.Threading.Tasks.Task.InnerInvokeWithArg(System.Threading.Tasks.Task) System.Threading.Tasks.Task+<>c__DisplayClass11.<ExecuteSelfReplicating>b__10(System.Object) System.Threading.Tasks.Task.InnerInvoke() ``` seems to "hang" in the clr itself. clr!COMInterlocked::ExchangeAdd64+0x4d When I compare the sampled stacks with a slow and fast run I find: ``` ntdll.dll!__RtlUserThreadStart -52% kernel32.dll!BaseThreadInitThunk -52% ntdll.dll!_RtlUserThreadStart -52% clr.dll!Thread::intermediateThreadProc -48% clr.dll!ThreadpoolMgr::ExecuteWorkRequest -48% clr.dll!ManagedPerAppDomainTPCount::DispatchWorkItem -48% clr.dll!ManagedThreadBase_FullTransitionWithAD -48% clr.dll!ManagedThreadBase_DispatchOuter -48% clr.dll!ManagedThreadBase_DispatchMiddle -48% clr.dll!ManagedThreadBase_DispatchInner -48% clr.dll!QueueUserWorkItemManagedCallback -48% clr.dll!MethodDescCallSite::CallTargetWorker -48% clr.dll!CallDescrWorkerWithHandler -48% mscorlib.ni.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() -48% mscorlib.ni.dll!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() -48% mscorlib.ni.dll!System.Threading.Tasks.Task.ExecuteEntry(Boolean) -48% mscorlib.ni.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.TaskByRef) -48% mscorlib.ni.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext System.Threading.ContextCallback System.Object Boolean) -48% mscorlib.ni.dll!System.Threading.Tasks.Task.ExecutionContextCallback(System.Object) -48% mscorlib.ni.dll!System.Threading.Tasks.Task.Execute() -48% mscorlib.ni.dll!System.Threading.Tasks.Task.InnerInvoke() -48% mscorlib.ni.dll!System.Threading.Tasks.Task+<>c__DisplayClass11.<ExecuteSelfReplicating>b__10(System.Object) -48% mscorlib.ni.dll!System.Threading.Tasks.Task.InnerInvokeWithArg(System.Threading.Tasks.Task) -48% mscorlib.ni.dll!System.Threading.Tasks.Task.InnerInvoke() -48% ParllelForSlowDown.exe!ParllelForSlowDown.Program+<>c__DisplayClass1::<ParallelArray>b__0 -24% ParllelForSlowDown.exe!ParllelForSlowDown.Program+<>c__DisplayClass1::<ParallelArray>b__0<itself> -24% ... clr.dll!COMInterlocked::ExchangeAdd64 +50% ``` In the dysfunctional case most of the time (50%) is spent in clr.dll!COMInterlocked::ExchangeAdd64. This method was compiled with FPO since the stacks were broken in the middle to get more performance. I have thought that such code is not allowed in the Windows Code base because it makes profiling harder. Looks like the optimizations have gone too far. When I single step with the debugger to the actual exachange operation ``` eax=01c761bf ebx=01c761cf ecx=00000000 edx=00000000 esi=00000000 edi=0274047c eip=747ca4bd esp=050bf6fc ebp=01c761bf iopl=0 nv up ei pl zr na pe nc cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00000246 clr!COMInterlocked::ExchangeAdd64+0x49: 747ca4bd f00fc70f lock cmpxchg8b qword ptr [edi] ds:002b:0274047c=0000000001c761bf ``` cmpxchg8b compares EDX:EAX=1c761bf with the memory location and if the values equal copy the new value of ECX:EBX=1c761cf to the memory location. When you look at the registers you find that at index 0x1c761bf = 29.843.903 all values are **not** equal. Looks like there is an race condition (or excessive contention) when incrementing the global loop counter which surfaces only when your method body does so little work that it pops out. Congrats you have found a real bug in the .NET Framework! You should report it at the connect website to make them aware of this issue. To be absolutely sure that it is not another issue you can try the parallel loop with an empty delegate: ``` System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch(); s.Start(); Parallel.For(0,_len, i => {}); s.Stop(); System.Console.WriteLine(s.ElapsedMilliseconds.ToString()); ``` This does also repro the issue. It is therefore definitely a CLR issue. Normally we at SO tell people to not try to write lock free code since it is very hard to get right. But even the smartest guys at MS seem to get it wrong sometimes .... **Update:** I have opened a bug report here: <https://connect.microsoft.com/VisualStudio/feedbackdetail/view/969699/parallel-for-causes-random-slowdowns-in-x86-processes>
47,491,867
I am just beginning working with Python and am a little confused. I understand the basic idea of a dictionary as (key, value). I am writing a program and want to read in a file, story it in a dictionary and then complete different functions by referrencing the values. I am not sure if I should use a dictionary or lists. The basic layout of the file is: Name followed by 12 different years for example : A 12 12 01 11 0 0 2 3 4 9 12 9 I am not sure what the best way to read in this information would be. I was thinking that a dictionary may be helpful if I had Name followed by Years, but I am not sure if I can map 12 years to one key name. I am really confused on how to do this. I can read in the file line by line, but not within the dictionary. ``` def readInFile(): fileDict ={"Name ": "Years"} with open("names.txt", "r") as f: _ = next(f) for line in f: if line[1] in fileDict: fileDict[line[0]].append(line[1]) else: fileDict[line[0]] = [line[1]] ``` My thinking with this code was to append each year to the value. Please let me know if you have any recommendations. Thank you!
2017/11/26
[ "https://Stackoverflow.com/questions/47491867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9008954/" ]
You can map 12 years to one key name. You seem to think that you need to choose between a dictionary and a list ("I am not sure if I should use a dictionary or lists.") But those are not alternatives. Your 12 years can usefully be represented as a list. Your names can be dictionary keys. So you need (as PM 2Ring suggests) a dictionary where the *key* is a name and the *value* is a list of years. ``` def readInFile(): fileDict = {} with open(r"names.txt", "r") as f: for line in f: name, years = line.split(" ",1) fileDict[name] = years.split() ``` There are two calls to the string method `split()`. The first splits the name from the years at the first space. (You can get the name using `line[0]`, but only if the name is one character long, and that is unlikely to be useful with real data.) The second call to `split()` picks the years apart and puts them in a list. The result from the one-line sample file will be the same as running this: ``` fileDict = {'A': ['12', '12', '01', '11', '0', '0', '2', '3', '4', '9', '12', '9']} ``` As you can see, these years are strings not integers: you may want to convert them. Rather than doing: ``` _ = next(f) ``` to throw away your record count, consider doing ``` for line in f: if line.strip().isdigit(): continue ``` instead. If you are using `file`'s built-in iteration (`for line in f`) then it's generally best not to call `next()` on `f` yourself. It's also not clear to me why your code is doing this: ``` fileDict ={"Name ": "Years"} ``` This is a description of what you plan to put in the dictionary, but that is not how dictionaries work. They are not database tables with named columns. If you use a dictionary with key:*name* and value:*list of years*, that structure is *implicit*. The best you can do is describe it in a comment or a type annotation. Performing the assignment will result in this: ``` fileDict = { 'A': ['12', '12', '01', '11', '0', '0', '2', '3', '4', '9', '12', '9'], 'Name ': 'Years' } ``` which mixes up description and data, and is probably not what you want, because your subsequent code is likely to expect a 12-list of years in the dictionary value, and if so it will choke on the string `"Years"`.
35,186,224
I just upgraded to AS 2.0 Preview 8 and I'm trying to build my old project. I updated it to be ``` classpath 'com.android.tools.build:gradle-experimental:0.6.0-alpha8' ``` and updated the `gradle-wrapper.properties` to use `gradle-2.10-all.zip`, but when I try to build my project I get a Java stactrace saying: ``` Unable to load class com.android.build.gradle.managed.NdkConfig$Impl ``` I'm using Java 8 to start AS as well as having that set as the JDK for the project. I was also having the same problem with Java7. What am I missing?
2016/02/03
[ "https://Stackoverflow.com/questions/35186224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1146334/" ]
Oddly enough, this was fixed by simply doing a Gradle `clean`. Hope this helps someone else as this was not intuitive
39,251
I have a SQL select statement which produces the following results, and I need to define it so that we can group the data based on 30 minute intervals of time and provide the sum of Revenue and Nbr of Trans. Table Date/Time field - ``` ActionDateTime REVENUE NBR of TRANS 2013-01-03 07:44:57.840 5.00 1 2013-01-03 07:45:10.093 5.00 1 2013-01-03 07:45:21.557 1.00 1 2013-01-03 09:07:21.253 50.00 1 2013-01-03 09:07:42.680 40.00 1 2013-01-03 09:07:49.007 104.30 1 ``` Current Results - ``` DATE TIME REVENUE NBR of TRANS 01/03/2013 07:44:57 5.00 1 01/03/2013 07:45:10 5.00 1 01/03/2013 07:45:21 1.00 1 01/03/2013 09:07:21 50.00 1 01/03/2013 09:07:42 40.00 1 01/03/2013 09:07:49 104.30 1 ``` Desired Results - ``` DATE TIME REVENUE NBR of TRANS 01/03/2013 08:00:00 11.00 3 01/03/2013 09:30:00 194.30 3 ``` Current SQL statement - ``` select 'DATE' = CONVERT(VARCHAR(12), x30.ActionDateTime, 101), 'TIME' = CONVERT(VARCHAR(12), x30.ActionDateTime, 108), 'REVENUE' = SUM(t01.Amount), 'NBR of TRANS' = COUNT(t01.DocumentNumber) from dbo.X30_AuditInformation x30 with (nolock), dbo.T01_TransactionMaster t01 with (nolock), dbo.T04_GiftDetails t04 with (nolock), dbo.B01_BatchMaster b01 with (nolock) where x30.TableRecordId = t01.RecordId and x30.TableId = 'T01_' and x30.Action = 'INSERT' and t01.DocumentNumber = t04.DocumentNumber and b01.BatchNumber = t01.BatchNumber and t01.Date between '01/01/2013' and '01/02/2013' and b01.BatchCategory in ('IMC') and t04.SourceCode like 'T%' GROUP BY x30.ActionDateTime, DATEPART(MINUTE, x30.ActionDateTime)/30 ORDER BY x30.ActionDateTime ``` Is my `GROUP BY` incorrect?
2013/04/04
[ "https://dba.stackexchange.com/questions/39251", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/22154/" ]
The documentation explains it very well: > > An Oracle database server consists of an Oracle database and an Oracle > instance. Every time a database is started, a system global area (SGA) > is allocated and Oracle background processes are started. The > combination of the background processes and memory buffers is called > an Oracle instance. > > > An oracle database is the physical files that make up the database itself (control files, data files etc) - [Documentation link](http://docs.oracle.com/cd/B19306_01/server.102/b14220/intro.htm#sthref35). A database is associated with one or more instances, with multiple instances making a RAC setup - [Documentation link](http://docs.oracle.com/cd/B19306_01/server.102/b14220/intro.htm#i60813). As far as your second question is concerned, multiple instances of a single database is a RAC setup.
365,180
> > **Note** > > > When answering please add references/links for any claims made. Answers based on guesses or assumptions will be deleted. > > > macOS 10.14.6 was just released. One of the lines is "Improves file-sharing reliability over SMB". What specifically has changed?
2019/07/23
[ "https://apple.stackexchange.com/questions/365180", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/339767/" ]
Apple does not normally provide the level of detail you seek. It doesn't even provide that level to developers and beta-testers in the pre-release seeds for testing purposes. It may eventually be deduced by sufficient people who used to have a particular problem in that area all reporting some improvement. It may also be uncovered by researchers delving into system files and uncovering relevant strings or other data.
54,293,485
In the original code one can see that I'm just extracting an expression into a binding which is one of the basic things that haskell claims should be always possible. **Minimal case (created with the help of @dminuoso on freenode)** I'd like `g` to remain polymorphic (so that I can feed it to other functions that expect it to be): ``` {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} main = do let a :: forall t. Functor t => t () = undefined let g :: forall u. Functor u => u () = a pure () ``` error: ``` source_file.hs:6:44: Couldn't match expected type ‘forall (u :: * -> *). Functor u => u ()’ with actual type ‘t0 ()’ When checking that: t0 () is more polymorphic than: forall (u :: * -> *). Functor u => u () In the expression: a ``` **Original question (motivation) posted on #haskell IRC:** ``` {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} class Monad m => Monad' m where instance Monad' IO where f1 :: (forall m . Monad' m => m Int) -> IO Int f1 g = do let a :: forall n . Monad' n => n Int = g a -- this works --f1 :: (forall m . Monad' m => m Int) -> IO Int --f1 g = do -- g main = print $ "Hello, world!" ``` but I get: ``` source_file.hs:12:45: Couldn't match expected type ‘forall (n :: * -> *). Monad' n => n Int’ with actual type ‘m0 Int’ When checking that: m0 Int is more polymorphic than: forall (n :: * -> *). Monad' n => n Int In the expression: g ``` Based on <https://ghc.haskell.org/trac/ghc/ticket/12587> I tried to explicitly apply the type to help the type-checker: ``` {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} class Monad m => Monad' m where instance Monad' IO where f1 :: (forall m . Monad' m => m Int) -> IO Int f1 g = do let a :: forall n . Monad' n => n Int = g @n a main = print $ "Hello, world!" ``` but then I get: ``` main.hs:13:48: error: Not in scope: type variable ‘n’ ```
2019/01/21
[ "https://Stackoverflow.com/questions/54293485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3343425/" ]
Part 1 ====== The Good -------- What happens when you write ``` a :: forall f. Functor f => f () a = _ ``` ? Specifically, what type of expression is GHC looking for to fill the hole (`_`)? You might think it's looking for a `forall f. Functor f => f ()`, but that's not quite right. Instead, `a` is actually a bit more like a function, and GHC implicitly inserts two arguments: one type argument named `f` with kind `* -> *`, and one instance of the constraint `Functor f` (which is unnamed, like all instances). ``` a :: forall f. Functor f => f () a @f {Functor f} = _ -- @-syntax is a currently proposed extension, {}-syntax is fake ``` GHC is looking for, *in the context of* `type f :: * -> *; instance Functor f`, a `f ()`. This is the same difference as between looking for a `(A -> B) -> C -> D` and looking for a `D` *in the context of* `f :: A -> B; c :: C`. If I directly have `solution :: (A -> B) -> C -> D`, in the first case I can just write `solution`, but, in the second case, I must write out `solution f c`. The Bad ------- This is not what happens when you write ``` a :: forall f. Functor f => f () = _ ``` Because you've used a pattern type signature, not a normal one, GHC no longer implicitly binds the type variable and the instance for you. GHC now, honestly and truly, wants you to fill that `_` with a `forall f. Functor f => f ()`. This is hard, as we'll see soon... (I really don't think the thing Daniel Wagner has quoted is relevant here. I believe it's just referring to the difference (when `ScopedTypeVariables` is on and `type a` is not in scope) between the way that `5 :: Num a => a` implicitly means `5 :: forall a. Num a => a` and the way `g :: a -> a = id` *doesn't* mean `g :: forall a. a -> a = id`.) Part 2 ====== What happens when you write ``` undefined ``` ? Specifically, what is its type? You might think it's `forall a. a`, but that's not quite right. Yes, it's true that, *all by itself*, `undefined` has the type `forall a. a`, but GHC doesn't let you write `undefined` all by itself. Instead, every occurrence of `undefined` in an expression is always applied to a type argument. The above is implicitly rewritten to ``` undefined @_a0 ``` and a new unification variable (which doesn't really have a name) `_a0` is created. This expression has type `_a0`. If I use this expression in a context that requires an `Int`, then `_a0` must be equal to `Int`, and GHC sets `_a0 := Int`, rewriting the expression to ``` undefined @Int ``` (Because `_a0` can be *set* to something, it's called a unification variable. It's under "our", internal control. Above, `f` *couldn't* be set to anything. It's a given, and its under "their" (the user's), external control, which makes it a skolem variable.) Part 3 ====== The Good -------- Usually, the automatic binding of type variables and the automatic application of unification variables works well. E.g., both of these work out fine: ``` undefined :: forall a. a ``` ``` bot :: forall a. a bot = undefined ``` Because they respectively expand as ``` (\@a -> undefined @a) :: forall a. a ``` ``` bot :: forall a. a bot @a = undefined @a ``` The Medium ---------- When you do ``` a :: forall f. Functor f => f () = undefined ``` , you make something very strange happen. As I said before, a pattern type signature with a `forall` doesn't introduce anything. The `undefined` on the RHS actually needs to be a `forall f. Functor f => f ()`. The implicit application of unification variables still occurs: ``` a :: forall f. Functor f => f () = undefined @_a0 ``` `undefined @_a0 :: _a0`, so `_a0 ~ (forall f. Functor f => f ())` must hold. GHC thus has to set `_a0 := (forall f. Functor f => f ())`. Usually, this is a no-no, because this is impredicative polymorphism: setting a type variable to a type containing `forall`s. However, in sufficiently outdated GHCs, this is allowed for certain functions. That is, `undefined` is not defined with the type `forall (a :: *). a`, but `forall (a :: OpenKind). a`, where `OpenKind` allows for this impredicativity. That means your code goes through as ``` a :: forall f. Functor f => f () = undefined @(forall f. Functor f => f ()) ``` If you write ``` a :: forall f. Functor f => f () = bot ``` , it won't work, as `bot` doesn't have the same magic sauce that `undefined` has. Additionally, this won't work in more recent GHCs, which have stamped out this weird kind of impredicative polymorphism. (Which I say is a very good thing). The Bad ------- Your definition of `a`, even with the pattern signature, does indeed come out with the desired type `forall f. Functor f => f ()`. The issue is now in `g`: ``` g :: forall f. Functor f => f () = a ``` `g`, again, doesn't bind `type f :: * -> *` or `instance Functor f`. Meanwhile, `a` gets applied to some implicit stuff: ``` g :: forall f. Functor f => f () = a @_f0 {_} ``` But... the RHS now has type `_f0 ()`, and the LHS wants it to have type `forall f. Functor f => f ()`. These don't look alike. Therefore, type error. As you can't stop the implicit application of `a` to a type variable and just write `g = a`, you must instead allow the implicit binding of type variables in `g`: ``` g :: forall f. Functor f => f () g = a ``` This works.
8,068
In 1912 was there a town or city called Osometz in russia? records show my grandmother came from Osometz russia in 1912. Example from the passenger list of the Campania, arriving in New York NY from Liverpool England on 3 Mar 1912 (indexed as Osometz at both EllisIsland and Ancestry): ![Details from 1912 Campania passenger list](https://i.stack.imgur.com/clpHM.jpg)
2015/04/08
[ "https://genealogy.stackexchange.com/questions/8068", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/3904/" ]
It could be Osowetz from North-Eastern Poland, Russian Empire in 1912 -<http://en.wikipedia.org/wiki/Osowiec-Twierdza>.
73,445,510
I have set up a lambda function using AWS Sam CLI that I am using for local development. After development, I have deployed this function to AWS console for production from my IDE (visual studio code). After deployment, when I see It has created several other resources such as cloudformation, Api Gateway, and a few others. What's problem? I am seeking a way through which I can deploy only my Lambda code that doesn't create other resources like Api gateway, etc. Is there any way that allow me to only create lambda function on local environment and then I want to push my code to AWS console. Moreover, when I use AWS Sam the size of my Lambda code also increased incredibly. When I created the same Lambda manually on AWS Console it consumes only a few kbs but when I created Lambda using AWS Sam it's size ramped up to 25MB. If someone know a better way to do this please elaborate. You can see my concerns the following: 1. Create Lambda function on local machine for development 2. I don't want to shift my Lambda function manually from local environment to AWS Console. 3. Also assign the Lambda function with specific permissions What are the best practices for this? If someone is still confuse please ask anything in the comment section.
2022/08/22
[ "https://Stackoverflow.com/questions/73445510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18268737/" ]
You can upload your application to aws lambda in 3 way : 1- Create a zip file and upload via console (project files can not exceed 250mb) 2- Upload your files to s3 and reference it (doable) 3- Create docker images and upload it (the easiest way) The best way is to upload as container images because you can upload files/dependencies up to 10gb inside the docker image. After you create your docker images, you can test it locally too. Please check : <https://docs.aws.amazon.com/lambda/latest/dg/images-test.html>
29,750,009
I'm a beginner in JAVA and programming in general, so please be patient as I may not use the correct terms to correctly describe my doubts. I'll do my best, nevertheless. So, I have this ArrayList that I'm going to use regular expressions on, to split it on the commas. I really needed some help solving this problem, even if I have to change the way that I do the process. It's not important that it stays this way, it's the final result that matters the most to me. Thank you. ``` String temp; String temp2; ArrayList <String> tempsplit = new ArrayList<String> (); ArrayList <String> dominios = new ArrayList<String> (); { for (int h = 0; h < 191; h++){ temp = features.get(h); **temp2.add(temp.split(",")); tempsplit.add(temp.split(","));** //in these last couple lines I get the error "The method add(String) in the type ArrayList<String> is not applicable for the arguments (String[])" for(int oi = 0; oi < tempsplit.size(); oi++){ for (int t = 0; t < dominios.size() ; t++){ int conf = 0; if (tempsplit.get(oi) == dominios.get(t)){ conf = 0; } else{ conf = 1; } if (conf == 1){ dominios.add (tempsplit.get(oi)); } } } ```
2015/04/20
[ "https://Stackoverflow.com/questions/29750009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3756933/" ]
``` Collections.addAll(temp2, temp.split(",")); ``` This uses the help class Collections to add a `String[]` by item.
68,070,891
I am working on a Spring MVC project where I am dealing with different types of services,Repositories i.e classes annotated with `@Service` and `@Repository`. I am confused with a couple of questions: * When to use `@AutoWired` annotation? I have seen various repositories using this: ``` CourseRepository crepo=new CourseRepository(); ``` and I have seen this also ``` @AutoWired private CourseRepository crepo; ``` Which one of the above options should be used to get an instance of repository in Service class? * Can I use `@AutoWired` for classes which are not annotated with `@Repository` or `@Service`? I am a beginner in this java world.Any help will be highly appreciated. Thanks
2021/06/21
[ "https://Stackoverflow.com/questions/68070891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16134191/" ]
You use `new` for *data objects*, which in most modern architectures are passive (they're not "active records"). Everything else is a *service object*, and you should inject those. (The one place that you do use `new` is with an `@Bean` method, which is a "factory" that creates the service object; in this case you normally pass the dependencies as method parameters.) Note that it is recommended to use constructor injection instead of field injection; it makes your code easier to test, and it eliminates the possibility of certain kinds of errors. In fact, if using constructor injection, it's not required to have any Spring annotations in your service classes at all; beans can be registered using `@Import` instructions or `@Bean` methods on a configuration class.
29,797,598
I have following table ``` AssignmentID UserFrom UserTo GroupFrom GroupTo CreatedOn 201410 NULL 4327 103 103 2014/11/11 09:24.7 201549 NULL 4327 103 103 2014/11/11 09:32.4 201549 NULL 4327 103 103 2014/11/11 09:38.4 201673 NULL 4328 103 103 2014/12/11 09:56.1 201673 NULL 4328 103 103 2014/12/11 10:55.1 201673 NULL 4328 103 103 2014/12/11 10:59.1 ``` I want to have datedifference in minutes vertically group by userto in following way.Please give me suggestion to produce following output. ``` userto minutes 4327 8 4327 6 4328 55 4328 4 ```
2015/04/22
[ "https://Stackoverflow.com/questions/29797598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2952939/" ]
If you are using sqlserver 2008, you could use [CROSS APPLY](https://technet.microsoft.com/en-us/library/ms175156%28v=sql.105%29.aspx) Note this will not work well with duplicated CreatedOn within the same UserTo: ``` SELECT t1.UserTo, DateDiff(minute, 0, t1.CreatedOn - t2.previousCreatedOn) minutes FROM yourtable t1 CROSS APPLY ( SELECT MAX(CreatedOn) previousCreatedOn FROM yourtable WHERE t1.UserTo = UserTo AND CreatedOn < t1.CreatedOn HAVING MAX(CreatedOn) is not null ) t2 ``` If you are using sqlserver 2012 it is easy using [LAG](https://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(LAG_TSQL);k(SQL11.SWB.TSQLRESULTS.F1);k(SQL11.SWB.TSQLQUERY.F1);k(MISCELLANEOUSFILESPROJECT);k(DevLang-TSQL)&rd=true): ``` ;WITH CTE AS ( SELECT userto, datediff(minute, 0, createdon -lag(createdon) over (partition by userto order by createdon)) minutes FROM yourtable ) SELECT userto, minutes FROM CTE WHERE minutes is not null ```
30,828,373
I have an X matrix that contains on every row some features extracted from images (one image for one row) and a Y matrix that has on every row a classification criteria for every feature vector/row in matrix X (Y is a matrix with just one column). Now I want to feed these two matrices to a Neural Networks and train it and then I want to test a new feature vector of an image (new\_ft) and be able to get one of the two classification criterias built in the Neural Network model. Basically I want to see what group does a new feature vector belong to. I tried training a network in the form: net = newpr(X,Y,numHiddenNeurons) and then use [net,tr] = train(net,Xx,Y); outputs = sim(net,Xx); but I get the an error "Dimensions of matrices being concatenated are not consistent." on the first line. My matrices have the sizes: X= 46 x 25750 double and Y = 46 x 1 cell. I tried giving Y the same size 46 x 25750, but I get the same problem. Could you let me know what could be the problem here? Thank you!
2015/06/14
[ "https://Stackoverflow.com/questions/30828373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4779970/" ]
You can use `row/col` indexing ``` popcombined <- D[3:5][cbind(1:nrow(D),findInterval(D$year, c(-Inf, 1990, 2000, Inf)))] cbind(D[1:2], popcombined) # countrycode year popcombined #1 2 1980 1 #2 2 1991 3 #3 2 2013 5 #4 3 1980 2 #5 3 1991 4 #6 3 2013 6 ```
28,290,872
I am calling a function that has a type declared against the method, ie. ``` public T Get<T>(). ``` I read in a string from a file and parse this through a switch to determine the type used, ie. ``` switch (type) { case "Text": item = Get<Text>(); break; case "Button": item = Get<Button>(); break; } ``` How would I then go about returning the item of Type from the function where it was called? Note that I don't want to return a common parent as I need access to the methods of the derived class. ``` public <????> newGet() { switch (type) { case "Text": item = Get<Text>(); break; case "Button": item = Get<Button>(); break; } return item; } ```
2015/02/03
[ "https://Stackoverflow.com/questions/28290872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/994685/" ]
Using `dynamic` sounds like a bad idea. You should reconsider what you're doing here. "Note that I don't want to return a common parent as I need access to the methods of the derived class." OK, so... you're going to do what to access these methods? Use another `switch` to switch between the types and then call the methods you want? Why are there two `switch` statements here doing the same thing? I don't know the exact architecture of what you're dealing with, but generally you'd be better off finding out what type you're going to be getting back (i.e. by returning "Text" or "Button" or whatever from a function) and then calling a strongly-typed function which goes and gets the thing and calls methods on it.
513,127
I want to have a multiline equation, and to annotate the lines, for the purposes of a key, to explain the various steps being taken. I currently use the `tag` command, which works fine for short explanations, but if they get too long, then the flow is broken. If I try to include a line break or similar, I get a bunch of errors thrown. ``` \begin{align*} \int\frac{\ln x}{x^{10}}\ dx&=-\frac{\ln x}{9x^{-9}}+\frac{1}{9}\int x^{-10}\ dx \tag{IBP: $u=\ln x$, $dv=x^{-10}dx$, $du=\frac{dx}{x}$, $v=-\frac{1}{9}x^{-9}$}\\ %This tag is too long, I want to split it. &=-\frac{\ln x}{9x^{-9}}+\frac{1}{81} x^{-9}+C \end{align*} ``` Is there a convienent way to make this?
2019/10/21
[ "https://tex.stackexchange.com/questions/513127", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/142439/" ]
The following solution demonstrates how to employ @DavidCarlisle's suggestion to use `\intertext` rather than `\tag`. Never shy away from using complete, human-language sentences to explain your thought process. It's neither shameful nor a sign of weakness to be clear. [![enter image description here](https://i.stack.imgur.com/8BXf1.png)](https://i.stack.imgur.com/8BXf1.png) ``` \documentclass{article} \usepackage{amsmath} \begin{document} \begin{align*} \int\frac{\ln x}{x^{10}}\,dx &=-\frac{\ln x}{9x^{-9}}+\frac{1}{9}\int x^{-10}\,dx\\ \intertext{The preceding equality employs integration by parts: Put $u=\ln x$ and $dv=x^{-10}dx$; thus, $du=\frac{dx}{x}$ and $v=-\frac{1}{9}x^{-9}$.} &=-\frac{\ln x}{9x^{-9}}+\frac{1}{81} x^{-9} + C \end{align*} \end{document} ```
503,517
[![Cans with compressed air and vacuum](https://i.stack.imgur.com/psrGD.jpg)](https://i.stack.imgur.com/psrGD.jpg) This picture is from L.C.Epstein's book *Thinking Physics*. The upper can is filled with compressed air, and, when an opening is made on the right, the air comes out and the can shoots left. The question is what happens to the lower can, filled with vacuum, when we similarly make an opening. Does it move left - right - not at all? Epstein says that the lower can doesn't move at all, "except for a momentarily slight oscillation about the center of mass". I'm not sure I understand this. The explanation is that the air incoming into the bottle provides force on the left inner wall to compensate for the lack of force on the opening, and this balances the force on the left outer wall from the outer air. Which seems convincing, but opens a path to more questions: 1. Shouldn't the can still start moving from the moment we make the opening and until the air pressure inside the can is equalized with the outside air? 2. If that in fact happens, why would it stop and return ("a momentary slight oscillation about the center of mass") and not simply continue moving right with the constant velocity it's acquired?
2019/09/18
[ "https://physics.stackexchange.com/questions/503517", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/55817/" ]
The easiest way to answer this problem is by thinking about *conservation of momentum*. Consider the still closed can with vacuum inside, and the air outside. [![before](https://i.stack.imgur.com/PhiCN.png)](https://i.stack.imgur.com/PhiCN.png) The can is at rest, hence it has momentum $\vec{p}\_\text{can} = \vec{0}$. The air is at rest too, hence it has momentum $\vec{p}\_\text{air} = \vec{0}$. Therefore total momentum is $$\vec{p}\_{\text{total}} = \vec{p}\_{\text{can}} + \vec{p}\_{\text{air}} = \vec{0}. \tag{1}$$ --- Now we open the hole in the can. [![after](https://i.stack.imgur.com/NGxyW.png)](https://i.stack.imgur.com/NGxyW.png) No matter what complicated things will happen now, no external forces are involved. Only internal forces are involved (air molecules colliding with each other, and air molecules colliding with the can). Therefore we know, the total momentum will remain zero as before in (1): $$\vec{p}\_{\text{total}} = \vec{p}\_{\text{can}} + \vec{p}\_{\text{air}} = \vec{0} \tag{2}$$ We know that air will shoot into the can from right to left, that means $\vec{p}\_\text{air}$ will point to the left. From (2) we conclude, the can must get a momentum in the opposite direction, i.e. to the right: $$\vec{p}\_\text{can} = - \vec{p}\_\text{air}$$ --- We can also further predict what will happen when the air settles down inside the can. So let's assume after a while the air has come to rest. This obviously means we have $\vec{p}\_\text{air} = \vec{0}$ again. With a similar reasoning like above (conservation of total momentum) we can conclude: $\vec{p}\_\text{can} = \vec{0}$, which means the can will come to rest, too. But because the can was moving to the right for a while, its final position will be displaced to the right by a certain distance. [![end](https://i.stack.imgur.com/HvR9C.png)](https://i.stack.imgur.com/HvR9C.png)
13,285,876
I'm trying to write a history trigger but can't get it to work. here is the code : ``` create or replace TRIGGER abc BEFORE UPDATE ON abc REFERENCING OLD AS oldValue NEW AS newValue FOR EACH ROW BEGIN INSERT INTO history ( id, record_id, col_name, old_val, new_val ) VALUES ( MF_SEQ_HISTORY.nextval, :oldvalue.id, :oldvalue.column_name, :oldvalue.object_value, :newvalue.object_value ); END; ``` as you can see , i'm trying to save the column name that has been updated ,the value and the new value. the errors i'm getting is : ``` Error(19,13): PLS-00049: bad bind variable 'OLDVALUE.COLUMN_NAME' Error(20,13): PLS-00049: bad bind variable 'OLDVALUE.OBJECT_VALUE' Error(21,13): PLS-00049: bad bind variable 'NEWVALUE.OBJECT_VALUE' ``` Any help will be appreciated. Thanks.
2012/11/08
[ "https://Stackoverflow.com/questions/13285876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1808709/" ]
According to the [Google Guide](http://www.googleguide.com) website, which *is not* affiliated with Google, you can use a mix of both, the `OR` operator (alternatively `|`) and the double quotes `"` as a group compound, to achieve what you wanted, it's all described in [this article](http://www.googleguide.com/or_operator.html). Further the whole [Crafting Your Query](http://www.googleguide.com/crafting_queries.html) article is also interesting to learn how to get the most of Google's possibilities when using their search.
216,359
I want to show/hide contents by using radio buttons on a WordPress page. When a user clicks on the radio button with label "red", the corresponding div with the class "red" needs to show up. Here's the (working) example I'm trying to integrate: <http://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-radio-button> In WordPress, I've placed this in the custom CSS of my theme: ``` .box { padding: 20px; display: none; margin-top: 20px; border: 1px solid #000; } .red { background: #ff0000; } .green { background: #00ff00; } .blue { background: #0000ff; } ``` I've placed this in an external script (script-pricing.js). That file was copied to the child-theme folder: ``` $(document).ready(function(){ $('input[type="radio"]').click(function(){ if($(this).attr("value")=="red"){ $(".box").not(".red").hide(); $(".red").show(); } if($(this).attr("value")=="green"){ $(".box").not(".green").hide(); $(".green").show(); } if($(this).attr("value")=="blue"){ $(".box").not(".blue").hide(); $(".blue").show(); } }); ``` I've enqueued that script with this code in functions.php: ``` //add a custom jQuery script to Wordpress function add_pricing() { wp_register_script('pricing', get_stylesheet_directory_uri() . '/script-pricing.js', array('jquery'), '1.0' ); wp_enqueue_script('pricing'); } add_action('wp_enqueue_scripts', 'add_pricing'); ``` I've placed this in a WordPress page: ``` <div><label><input name="colorRadio" type="radio" value="red" /> One- year</label> <label><input name="colorRadio" type="radio" value="green" /> Two-year</label> <label><input name="colorRadio" type="radio" value="blue" /> Three-year</label></div> <div class="red box">You have selected red</div> <div class="green box">You have selected green</div> <div class="blue box">You have selected blue</div> ``` The page displays the three radio buttons. The CSS hides the three 'You have selected" lines. But when a radio button is clicked the respective line isn't showing up. What have I missed and what needs to be improved? Thanks in advance for your response!
2016/02/01
[ "https://wordpress.stackexchange.com/questions/216359", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87912/" ]
We could rewrite: ``` wp_list_comments( array( 'callback' => 'bootstrap_comment_callback', )); ``` with the null `walker` parameter: ``` wp_list_comments( array( 'walker' => null, 'callback' => 'bootstrap_comment_callback', )); ``` which means we are using the default `Walker_Comment` class: ``` wp_list_comments( array( 'walker' => new Walker_Comment, 'callback' => 'bootstrap_comment_callback', )); ``` The `Walker_Comment::start_el()` method is just a wrapper for one of these *protected* methods: ``` Walker_Comment::comment() Walker_Comment::html5_comment() Walker_Comment::ping() ``` that, depending on the context, append each comment to the output string when walking along the comment tree. Using a *custom walker* class, that extends the `Walker_Comment` class, gives us the ability to override these *public* methods: ``` Walker_Comment::start_el() Walker_Comment::end_el() Walker_Comment::start_lvl() Walker_Comment::end_lvl() Walker_Comment::display_element() ``` in addition to the protected ones above. If we only need to modify the output of the `start_el()` method, we would only need to use the `callback` parameter in `wp_list_comments()`.
17,514,293
Assuming I have two tables: * Students : Id, Name, Age, Class, etc * Conditions : Id, Condition The Column Conditions.Condition contains a SQL Condition for example "std.Age >2" or "std.Class = 3" I want somthing that does the following: ``` SELECT std.Id as StudentId, con.Id as ConId FROM Students as std, Condition as con WHERE con.Condition ``` Maybe a function that takes Student Id? How do I achieve this? --- Students: ``` 1 , Yossi, 25, 3.. 2 , David, 22, 3.. 3 , Jhon, 5, 2.. 4 , Smith, 25, 4.. ``` Conditions: ``` 1 , Age > 3 2 , Class = 4 3 , Name LIKE '%i%' ``` result would be (Condition, Studnet): ``` (1,1) (1,2) (1,3) (1,4) // all are older than 3 (2,4) // only Smith is in class 4 (3,1) (3,2) (3,4) // all except jhon have an i in their name ```
2013/07/07
[ "https://Stackoverflow.com/questions/17514293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/182360/" ]
Try following Query : ``` DECLARE @CONDITIONS varchar(max) = REPLACE(REPLACE(( SELECT'UNION ALL SELECT ID AS STUDENTID , ' + CONVERT(VARCHAR , ID ) + ' AS CONDITIONID FROM STUDENTS WHERE ' + CONDITION + ' ' FROM CONDITION FOR XML PATH('') ) , '&LT;' , '<') , '&GT;' , '>') SET @CONDITIONS = (SELECT SUBSTRING(@CONDITIONS , 11 , LEN(@CONDITIONS))) EXEC(@CONDITIONS) ``` This is more generalize way to apply condition . if you want to apply only one condition then add where clause in query from where we fetch all the condition . you can run this query for one or more condition . currently i have written this query which apply all the conditions . [sqlfiddle](http://sqlfiddle.com/#!3/682b8/2)
57,679,391
Let's say I have the following generic combination generator static method: ``` public static IEnumerable<IEnumerable<T>> GetAllPossibleCombos<T>( IEnumerable<IEnumerable<T>> items) { IEnumerable<IEnumerable<T>> combos = new[] {new T[0]}; foreach (var inner in items) combos = combos.SelectMany(c => inner, (c, i) => c.Append(i)); return combos; } ``` Perhaps I am not understanding this correctly, but doesn't this build the entire combos list in RAM? If there are a large number of items the method might cause the computer to run out of RAM. Is there a way to re-write the method to use a `yield return` on each combo, instead of returning the entire combos set?
2019/08/27
[ "https://Stackoverflow.com/questions/57679391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/855203/" ]
There are some misconceptions in your question, which is awesome because now you have an opportunity to learn facts rather than myths. --- First off, the method you are implementing is usually called `CartesianProduct`, not `GetAllPossibleCombos`, so consider renaming it. --- > > Perhaps I am not understanding this correctly > > > You are not understanding it correctly. > > doesn't this build the entire combos list in RAM? > > > No. **A query builder builds a query, not the results of executing the query.** When you do a `SelectMany`, what you get is an object that *will do the selection in the future*. You don't get the results of that selection. > > If there are a large number of items the method might cause the computer to run out of RAM. > > > Today would be a good day to stop thinking of memory and RAM as the same thing. When a process runs out of memory, it does not run out of RAM. It runs out of *address space*, which is not RAM. The better way to think about memory is: memory is *on-disk page file*, and RAM is *special hardware that makes your page file faster*. When you run out of RAM, your machine might get unacceptably slow, but you don't run out of *memory* until you run out of *address space*. Remember, **process memory is virtualized**. Now, **there may be scenarios in which executing this code is inefficient because enumerating the query runs out of stack**. And there may be scenarios in which execution becomes inefficient because you're moving n items up a stack n deep. I suggest that you to do a deeper analysis of your code and see if that is the case, and report back. --- > > Is there a way to re-write the method to use a yield return on each combo, instead of returning the entire combos set? > > > `SelectMany` is implemented as a `yield return` in a `foreach` loop, so you've already implemented it as a `yield return` on each combo; you've just hidden the `yield return` inside a call to `SelectMany`. That is, `SelectMany<A, B, C>(IE<A> items, Func<A, IE<B>> f, Func<A, B, C> g)` is implemented as something like: ``` foreach(A a in items) foreach(B b in f(a)) yield return g(a, b); ``` So you've already done it in `yield return`. If you want to write a method that *directly* does a `yield return` that's a little harder; the easiest way to do that is to form an array of enumerators on each child sequence, then make a vector from each `Current` of the enumerators, `yield return` the vector, and then advance the correct iterator one step. Keep on doing that until there is no longer a correct iterator to advance. As you can probably tell from that description, the bookkeeping gets messy. It is doable, but it's not very pleasant code to write. Give it a try though! The nice thing about that solution is that you are guaranteed to have good performance because you're not consuming any stack. UPDATE: This related question has an answer posted that does an iterative algorithm, but I have not reviewed it to see if it is correct. <https://stackoverflow.com/a/57683769/88656> --- Finally, I encourage you to compare your implementation to mine: <https://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/> Is my implementation in any way *fundamentally* different than yours, or are we doing the same thing, just using slightly different syntax? Give that some thought. Also I encourage you to read Ian Griffiths' excellent six-part series on an analysis of various implementations of this function: <http://www.interact-sw.co.uk/iangblog/2010/07/28/linq-cartesian-1>
71,592,207
I have this table: | Site\_ID | Volume | RPT\_Date | RPT\_Hour | | --- | --- | --- | --- | | 1 | 10 | 01/01/2021 | 1 | | 1 | 7 | 01/01/2021 | 2 | | 1 | 13 | 01/01/2021 | 3 | | 1 | 11 | 01/16/2021 | 1 | | 1 | 3 | 01/16/2021 | 2 | | 1 | 5 | 01/16/2021 | 3 | | 2 | 9 | 01/01/2021 | 1 | | 2 | 24 | 01/01/2021 | 2 | | 2 | 16 | 01/01/2021 | 3 | | 2 | 18 | 01/16/2021 | 1 | | 2 | 7 | 01/16/2021 | 2 | | 2 | 1 | 01/16/2021 | 3 | I need to select the RPT\_Hour with the highest Volume for each set of dates Needed Output: | Site\_ID | Volume | RPT\_Date | RPT\_Hour | | --- | --- | --- | --- | | 1 | 13 | 01/01/2021 | 1 | | 1 | 11 | 01/16/2021 | 1 | | 2 | 24 | 01/01/2021 | 2 | | 2 | 18 | 01/16/2021 | 1 | ```sql SELECT site_id, volume, rpt_date, rpt_hour FROM (SELECT t.*, ROW_NUMBER() OVER (PARTITION BY site_id, rpt_date ORDER BY volume DESC) AS rn FROM MyTable) t WHERE rn = 1; ``` I cannot figure out how to group the table into like date groups. If I could do that, I think the rn = 1 will return the highest volume row for each date.
2022/03/23
[ "https://Stackoverflow.com/questions/71592207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11902246/" ]
You may use the following pattern: ``` ^(?:Remove - )?([^-]+)(?: - ([^-]+))?$ ``` And if you're dealing with a multiline text, simply add `\r\n` to the negated character class to avoid matches across multiple lines: ``` ^(?:Remove - )?([^-\r\n]+)(?: - ([^-\r\n]+))?$ ``` [**Demo**](https://regex101.com/r/W1nDIh/1).
31,409,515
I have a site that displays bar graphs of data. I am trying to implement pagination for the graphs so that the user can click 'next' or 'previous' to scroll through different subsets of the total data. Here is the HTML section in question: ``` <div class="graph_fields_wrap1 row backdrop col-lg-12"> <div class="col-lg-6"> <h3 class="titles">Top Ten Author Citations</h3> <h4 class="titles">All time (from 1970)</h4> <button class="pager" id="previous1" type="button"><span class="glyphicon glyphicon-chevron-left"></span> previous</button> <button class="pager" id="next1" type="button">next <span class="glyphicon glyphicon-chevron-right"></span></button> <div class="chart1 well bs-component"></div> </div> <div class="col-lg-6"> <h3 class="titles">Top Ten Author Citations</h3> <h4 class="titles userTitle"></h4> <button class="pager" id="previous2" type="button"><span class="glyphicon glyphicon-chevron-left"></span> previous</button> <button class="pager" id="next2" type="button">next <span class="glyphicon glyphicon-chevron-right"></span></button> <div class="chart2 well bs-component"></div> </div> </div> <!-- row --> ``` Here is the JavaScript: ``` $(document).ready(function() { // change graph according to author selection var wrapperG = $(".graph_fields_wrap1"); // wrapper for div containing citations graphs var next1 = $("#next1"); // pagination for all time cited graph var previous1 = $("#previous1"); var next2 = $("#next2"); // pagination for user defined cited graph var previous2 = $("#previous2"); // variables to log subset location in arrays (to use in slice) var from1 = 1; var to1 = 11; // PAGINATION // // all time cited, next author set $(wrapperG).on("click", next1, function (e) { // ignore default action for this event e.preventDefault(); // shift pointers up 10 for next subset of array from1 += 10; console.log(from1); to1 += 10; console.log(to1); // remove currently displayed graph, 1st child of div (1st graph is 0th) $($(wrapperG).children()[0]).remove(); // load new graph before other graph (1st child of div) $(wrapperG).prepend("<div class='col-lg-6'><h3 class='titles'>Top Ten Author Citations</h3><h4 class='titles'>All time (from 1970)</h4><button class='pager' id='previous1' type='button'><span class='glyphicon glyphicon-chevron-left'></span> previous</button><button class='pager' id='next1' type='button'>next <span class='glyphicon glyphicon-chevron-right'></span></button><div class='chart1 well bs-component'></div></div>").loadGraph((topCited.slice(from1,to1)), "chart1", palette1); }); // all time cited, previous author set $(wrapperG).on("click", previous1, function (e) { // ignore default action for this event e.preventDefault(); // shift pointers down 10 for previous subset of array from1 -= 10; console.log(from1); to1 -= 10; console.log(to1); // remove currently displayed graph, 1st child of div (1st graph is 0th) $($(wrapperG).children()[0]).remove(); // load new graph before other graph (1st child of div) $(wrapperG).prepend("<div class='col-lg-6'><h3 class='titles'>Top Ten Author Citations</h3><h4 class='titles'>All time (from 1970)</h4><button class='pager' id='previous1' type='button'><span class='glyphicon glyphicon-chevron-left'></span> previous</button><button class='pager' id='next1' type='button'>next <span class='glyphicon glyphicon-chevron-right'></span></button><div class='chart1 well bs-component'></div></div>").loadGraph((topCited.slice(from1,to1)), "chart1", palette1); }); }); ``` I initially used `$(next1).on("click", function` but the button only fired once then stopped working. Looking up similar queries on Stack Overflow I saw that, because the HTML is removed, the bound handlers are as well. So then I binded the handler to a part that is not removed (`wrapperG`). I put the `console.log` lines to help me see what's going on when I click the buttons. When I load the page and click 'next', the console logs the data 11, 21, 1, 11 and keeps repeating that data on repeat clicks of either the 'next' or 'previous' button click. Obviously on clicking 'next' I want the data to log 11, 21 then 21, 31 then 31, 41 and so on. Similarly for the 'previous' button but decreasing by 10 each time. The bar graph then shows 10 bars of data according to where in the array the `slice` is taken. If I comment out the 'previous' button jQuery section then the 'next' button works fine and the bar graph displays the data properly. This makes me think that the problem is in both buttons being contained within the same `div`. As I'm removing `child()[0]` of `.graph_fields_wrap1` within the function then this is the only `div` I can refer to. \*\* ADDITIONAL \*\* Listing the `console.log` data above I realised I'd copied it out incorrectly. It is actually returning 11, 21, 1, 11. This localizes the problem to being when clicking the 'next' button, it is firing both event handlers, so the first one increases the values by 10, but then the second one decreases them by 10, negating the effect. Therefore, I need to find out why clicking the 'next' button is firing off both events and how to stop this from happening.
2015/07/14
[ "https://Stackoverflow.com/questions/31409515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1895461/" ]
The problem is that you use the same element ID twice. To prevent double events add "return false" to your handler, or use differnt ID's Sidenode: never use an ID twice instead use a class
25,771,314
I want to query my Laravel model using eloquent for results that may need to match some where clauses, then `take` and `skip` predefined numbers. This isn't a problem in itself, but I also need to know the number of rows that were found in the query before reducing the result set with take and skip - so the original number of matches which could be every row in the table if no where clauses are used or a few if either is used. What I want to do could be accomplished by making the query twice, with the first omitting "`->take($iDisplayLength)->skip($iDisplayStart)`" at the end and counting that, but that just seems messy. Any thoughts? ``` $contacts = Contact::where(function($query) use ($request) { if (!empty($request['firstname'])) { $query->where(function($query) use ($request) { $query->where('firstname', 'LIKE', "%{$request['firstname']}%"); }); } if (!empty($request['lastname'])) { $query->where(function($query) use ($request) { $query->where('lastname', 'LIKE', "%{$request['lastname']}%"); }); } }) ->take($iDisplayLength)->skip($iDisplayStart)->get(); $iTotalRecords = count($contacts); ```
2014/09/10
[ "https://Stackoverflow.com/questions/25771314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/942944/" ]
You can use `count` then `get` on the same query. And by the way, your whole query is a bit over complicated. It results in something like this: ``` select * from `contacts` where ((`firstname` like ?) and (`lastname` like ?)) limit X, Y ``` Closure in `where` is used to make a query like this for example: ``` select * from table where (X or Y) and (A or B); ``` So to sum up you need this: ``` $query = Contact::query(); if (!empty($request['firstname'])) { $query->where('firstname', 'like', "%{$request['firstname']}%"); } if (!empty($request['lastname'])) { $query->where('lastname', 'like', "%{$request['lastname']}%"); } $count = $query->count(); $contacts = $query->take($iDisplayLength)->skip(iDisplayStart)->get(); ```
372,541
I have the following in a script: ``` yes >/dev/null & pid=$! echo $pid sleep 2 kill -INT $pid sleep 2 ps aux | grep yes ``` When I run it, the output shows that `yes` is still running by the end of the script. However, if I run the commands interactively then the process terminates successfully, as in the following: ``` > yes >/dev/null & [1] 9967 > kill -INT 9967 > ps aux | grep yes sean ... 0:00 grep yes ``` Why does SIGINT terminate the process in the interactive instance but not in the scripted instance? EDIT Here's some supplementary information that may help to diagnose the issue. I wrote the following Go program to simulate the above script. ``` package main import ( "fmt" "os" "os/exec" "time" ) func main() { yes := exec.Command("yes") if err := yes.Start(); err != nil { die("%v", err) } time.Sleep(time.Second*2) kill := exec.Command("kill", "-INT", fmt.Sprintf("%d", yes.Process.Pid)) if err := kill.Run(); err != nil { die("%v", err) } time.Sleep(time.Second*2) out, err := exec.Command("bash", "-c", "ps aux | grep yes").CombinedOutput() if err != nil { die("%v", err) } fmt.Println(string(out)) } func die(msg string, args ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", args...) os.Exit(1) } ``` I built it as `main` and running `./main` in a script, and running `./main` and `./main &` interactively give the same, following, output: ``` sean ... 0:01 [yes] <defunct> sean ... 0:00 bash -c ps aux | grep yes sean ... 0:00 grep yes ``` However, running `./main &` in a script gives the following: ``` sean ... 0:03 yes sean ... 0:00 bash -c ps aux | grep yes sean ... 0:00 grep yes ``` This makes me believe that the difference has less to do on Bash's own job control, though I'm running all of this in a Bash shell.
2017/06/21
[ "https://unix.stackexchange.com/questions/372541", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/14703/" ]
What shell is used is a concern as different shells handle job control differently (and job control is complicated; `job.c` in `bash` presently weighs in at 3,300 lines of C according to `cloc`). `pdksh` 5.2.14 versus `bash` 3.2 on Mac OS X 10.11 for instance show: ``` $ cat code pkill yes yes >/dev/null & pid=$! echo $pid sleep 2 kill -INT $pid sleep 2 pgrep yes $ bash code 38643 38643 $ ksh code 38650 $ ``` Also relevant here is that `yes` performs no signal handling so inherits whatever there is to be inherited from the parent shell process; if by contrast we do perform signal handling— ``` $ cat sighandlingcode perl -e '$SIG{INT} = sub { die "ouch\n" }; sleep 5' & pid=$! sleep 2 kill -INT $pid $ bash sighandlingcode ouch $ ksh sighandlingcode ouch $ ``` —the SIGINT is triggered regardless the parent shell, as `perl` here unlike `yes` has changed the signal handling. There are system calls relevant to signal handling which can be observed with things like DTrace or here `strace` on Linux: ``` -bash-4.2$ cat code pkill yes yes >/dev/null & pid=$! echo $pid sleep 2 kill -INT $pid sleep 2 pgrep yes pkill yes -bash-4.2$ rm foo*; strace -o foo -ff bash code 21899 21899 code: line 9: 21899 Terminated yes > /dev/null -bash-4.2$ ``` We find that the `yes` process ends up with `SIGINT` ignored: ``` -bash-4.2$ egrep 'exec.*yes' foo.21* foo.21898:execve("/usr/bin/pkill", ["pkill", "yes"], [/* 24 vars */]) = 0 foo.21899:execve("/usr/bin/yes", ["yes"], [/* 24 vars */]) = 0 foo.21903:execve("/usr/bin/pgrep", ["pgrep", "yes"], [/* 24 vars */]) = 0 foo.21904:execve("/usr/bin/pkill", ["pkill", "yes"], [/* 24 vars */]) = 0 -bash-4.2$ grep INT foo.21899 rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f18ebee0250}, {SIG_DFL, [], SA_RESTORER, 0x7f18ebee0250}, 8) = 0 rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f18ebee0250}, {SIG_DFL, [], SA_RESTORER, 0x7f18ebee0250}, 8) = 0 rt_sigaction(SIGINT, {SIG_IGN, [], SA_RESTORER, 0x7f18ebee0250}, {SIG_DFL, [], SA_RESTORER, 0x7f18ebee0250}, 8) = 0 --- SIGINT {si_signo=SIGINT, si_code=SI_USER, si_pid=21897, si_uid=1000} --- -bash-4.2$ ``` Repeat this test with the `perl` code and one should see that `SIGINT` is not ignored, or also that under `pdksh` there is no ignore being set as there is in `bash`. With "monitor mode" turned on like it is in interactive mode in `bash`, `yes` is killed. ``` -bash-4.2$ cat monitorcode #!/bin/bash set -m pkill yes yes >/dev/null & pid=$! echo $pid sleep 2 kill -INT $pid sleep 2 pgrep yes pkill yes -bash-4.2$ ./monitorcode 22117 [1]+ Interrupt yes > /dev/null -bash-4.2$ ```
21,558,242
[Moops](http://search.cpan.org/~tobyink/Moops-0.030/lib/Moops.pm) enhances the perl syntax by constructs such as: ```perl class MyPkg::MyClass { # ... } ``` and adds the possibility to declare signatures for member functions by introducing the new keywords `fun` and `method`: ```perl class MyPkg::MyClass { method run(ArrayRef $ar){ } } ``` I use vim and tag files to navigate my code base, but those new keywords are unknown to `ctags`, so classes, functions and methods are not indexed. How can I improve the situation?
2014/02/04
[ "https://Stackoverflow.com/questions/21558242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/321307/" ]
I can add regular expressions to ctags extending the built-in perl language like so: ``` $ ctags \ --regex-Perl="/^[ \t]*method\s+([a-zA-Z0-9]+)/\1/s/" \ --regex-Perl="/^\s*class\s+([a-zA-Z0-9:]+)/\1/p/" \ -R . ``` or I can put them in my `~/.ctags` file (omitting the quotes) Assuming we have a small project: ``` $ tree . ├── MyPkg │   ├── MyClass.pm │   └── MyOtherClass.pm └── myscript.pl ``` With `MyPkg/MyClass.pm`: ```perl use Moops; class MyPkg::MyClass { method run( ArrayRef $args ){ } } ``` and `MyPkg/MyOtherClass.pm`: ```perl use Moops; package MyPkg; class MyOtherClass { method run( ArrayRef $args ){ } } ``` Note the alternate syntax here. The package name gets prepended to the class name resulting in `MyPkg::MyOtherClass`. Finally, `myscript.pl`: ```perl #!/usr/bin/env perl use MyPkg::MyClass; use MyPkg::MyOtherClass; MyPkg::MyClass->new()->run(\@ARGV); MyPkg::MyOtherClass->new()->run(\@ARGV); ``` Calling `ctags` with the additional regex definitions mentioned above, the resulting tag file looks like this: ```none MyOtherClass MyPkg/MyOtherClass.pm /^class MyOtherClass {$/;" p MyPkg MyPkg/MyOtherClass.pm /^package MyPkg;$/;" p MyPkg::MyClass MyPkg/MyClass.pm /^class MyPkg::MyClass {$/;" p run MyPkg/MyClass.pm /^ method run( ArrayRef $args ){$/;" s run MyPkg/MyOtherClass.pm /^ method run( ArrayRef $args ){$/;" s ``` This almost works: 1. moving the cursor over `MyPkg::MyClass` and pressing `CTRL-]` vim can find the class definition 2. moving the cursor over the first call of `run()` vim finds a definition for the function But, there are two problems here: 1. in the case of the first call of `run()` vim cannot unambigously decide which function is called, as it lacks context; you have to decide for yourself (using `:ts`) 2. moving the cursor over `MyPkg::MyOtherClass` vim cannot find a tag at all So, in conclusion, my best practise for `Moops`, `vim` and `ctags` would be to always declare classes fully qualified.
55,523,508
I need to find the maximum test score from an input file of test scores. The test scores are listed as percentages, one per line in the text file. I'm just not sure how to go about doing so. Right now my program just reads in the numbers and assigns them a letter grade. I'm thinking I can assign the numbers to an array, but if there is a way to do this without using arrays I would prefer that. ``` string grade (double g) { string p; if (g >= 90) { p = "A"; } if (g >= 80 && g < 90) { p = "B"; } if (g >= 70 && g < 80) { p = "C"; } if (g >= 60 && g < 70) { p = "D"; } if (g < 60) { p = "F"; } return p; } int main() { ifstream inData; try { inData.open("Scores.txt"); } catch (int e) { return -1; } cout << "Percentage" << " " << "Grade" << endl; cout << "-------------------" << endl; while (!inData.eof()) { double g; inData >> g; string p; p = grade (g); cout << " " << g << "%" << " -- " << p << endl; } } ```
2019/04/04
[ "https://Stackoverflow.com/questions/55523508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11262147/" ]
Since you are streaming the data in, you can use a 'compare and replace' type of algorithm to keep track of the maximum score. First you would initialize a variable to be lower than all possible scores, `double max_score_so_far = 0.0;` Then every time you look at a new score you ask "is this bigger than the biggest I've seen so far?" If it is, then you replace your max so far with the current value. `if (g > max_score_so_far) { max_score_so_far = g; }` At the end of your file, `max_score_so_far` should contain the highest score.
38,819,458
I have my DataBase ms-access Contain Table 'Client' and this table contain : (ClientName, ClientPhone, ClientAddress, ClientCredit, ClientDes)\_\_ok! Im want to addition all values of ClientCredit in my software vb.net . Im use this code and its work but i its give me a wrong value !! ```vb Dim credit As Double = 0 Try Dim dt As DataTable = New DBConnect().selectdata( _ "SELECT ClientName, ClientPhone, ClientAddress, ClientCredit, ClientDes FROM Client;") For i As Integer = 0 To dt.Rows.Count - 1 credit = dt.Rows(0)(3).ToString + credit Next Catch ex As Exception MessageBox.Show(ex.Message) End Try FlatTextBox1.Text = credit ``` this code give me result : 400 but the real result is 415.2
2016/08/07
[ "https://Stackoverflow.com/questions/38819458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6588913/" ]
The problem is with your `TasksController#index` action. What is `project_id` there? For accessing a project's tasks, the project needs to exist in the first place. And not just that. To access any CRUD action on tasks, a project has to exist first. Modify your TasksController as ``` class TasksController < ApplicationController before_action :set_project before_action :set_task, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! def index @tasks = @project.tasks end def show #makes use of set_task end def new @task = @project.tasks.new end def edit end def references respond_to do |format| if @task.valid? format.html { redirect_to root_url } format.json { render :show, status: :created, location: @task } else format.html { render :home_url } format.json { render json: @task.errors, status: :unprocessable_entity } end end end def create @task = @project.tasks.create(task_params) respond_to do |format| if @task.valid? format.html { redirect_to root_url } format.json { render :show, status: :created, location: @task } else format.html { render :home_url } format.json { render json: @task.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @task.update(task_params) format.html { redirect_to root_url } format.json { render :home_url, status: :ok, location: @task } else format.html { render :root_url } format.json { render json: @task.errors, status: :unprocessable_entity } end end end def destroy @task.destroy respond_to do |format| format.html { redirect_to root_url } format.json { head :no_content } end end private def set_project @project = current_user.projects.find(params[:project_id] end def set_task @task = @project.tasks.find(params[:id]) end def task_params params.require(:task).permit(:deadline, :body, :project_id) end end ``` Since we have defined a `before_action` set\_project, `@project` will be available to all methods. Note that `set_project`finds the project from the projects created by the current user. In the ProjectsController#index, you won't actually get a value for `params[:project_id]`. Modify your index action to ``` def index @projects = current_user.projects unless current_user.nil? end ``` And I don't understand your `show` method. The `build` method is actually used to create a in-memory representation of an object. The `show` method of projects\_controller can be used to display the project along with its tasks. If this is what you need, change you `show` action in `ProjectsController` to ``` def show #@project is available from load_project @tasks = @project.tasks end ``` You could also modify your `load_project` project as ``` def load_project begin @project = Project.find(params[:id]) #raises an exception if project not found rescue ActiveRecord::RecordNotFound redirect_to projects_path end end ``` To know more about rescuing exceptions, see [Begin, Rescue and Ensure in Ruby?](https://stackoverflow.com/questions/2191632/begin-rescue-and-ensure-in-ruby) For more, see <http://blog.8thcolor.com/en/2011/08/nested-resources-with-independent-views-in-ruby-on-rails/>
6,331
I have already made a function of multiplication of long numbers, addition of long numbers, subtraction of long numbers and division of long numbers. But division takes a very long time, how it could be improved? Here is my code: ``` /// removes unnecessary zeros vector<int> zero(vector<int> a) { bool f=false; int size=0; for(int i=a.size()-1;i>=0;i--) { if(a[i]!=0) { f=true; size=i; break; } } if(f) { vector<int> b(size+1); for(int i=0;i<size+1;i++) b[i]=a[size-i]; return b; } else return a; } /// a+b vector<int> sum(vector<int> a,vector<int> b) { if(a.size()>b.size()) { vector<int> rez(3000); int a_end=a.size()-1; int remainder=0,k=0,ans; for(int i=b.size()-1;i>=0;i--) { ans=a[a_end]+b[i]+remainder; if(ans>9) { rez[k]=ans%10; remainder=ans/10; } else { rez[k]=ans; remainder=0; } k++; a_end--; } int kk=k; for(int i=a.size();i>kk;i--) { ans=a[a_end]+remainder; if(ans>9) { rez[k]=ans%10; remainder=ans/10; } else { rez[k]=ans; remainder=0; } k++; a_end--; } if(remainder!=0) { rez[k]=remainder; } return zero(rez); } else { vector<int> rez(3000); int b_end=b.size()-1; int remainder=0,k=0,ans; for(int i=a.size()-1;i>=0;i--) { ans=b[b_end]+a[i]+remainder; if(ans>9) { rez[k]=ans%10; remainder=ans/10; } else { rez[k]=ans; remainder=0; } k++; b_end--; } int kk=k; for(int i=b.size();i>kk;i--) { ans=b[b_end]+remainder; if(ans>9) { rez[k]=ans%10; remainder=ans/10; } else { rez[k]=ans; remainder=0; } k++; b_end--; } if(remainder!=0) { rez[k]=remainder; } return zero(rez); } } /// a & b comparison int compare(vector<int> a,vector<int> b) { if(a.size()>b.size()) return 1; if(b.size()>a.size()) return 2; int r=0; for(int i=0;i<a.size();i++) { if(a[i]>b[i]) { r=1; break; } if(b[i]>a[i]) { r=2; break; } } return r; } /// a-b vector<int> subtraction(vector<int> a,vector<int> b) { vector<int> rez(1000); int a_end=a.size()-1; int k=0,ans; for(int i=b.size()-1;i>=0;i--) { ans=a[a_end]-b[i]; if(ans<0) { rez[k]=10+ans; a[a_end-1]--; } else { rez[k]=ans; } k++; a_end--; } int kk=k; for(int i=a.size();i>kk;i--) { ans=a[a_end]; if(ans<0) { rez[k]=10+ans; a[a_end-1]--; } else { rez[k]=ans; } k++; a_end--; } return zero(rez); } /// a div b vector<int> div(vector<int> a,vector<int> b) { vector<int> rez(a.size()); rez=a; int comp=-1; vector<int> count(1000); vector<int> one(1); one[0]=1; while(comp!=0 || comp!=2) { comp=compare(rez,b); if(comp==0) break; rez=subtraction(rez,b); count=sum(count,one); } count=sum(count,one); return count; } ```
2011/11/27
[ "https://codereview.stackexchange.com/questions/6331", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/8647/" ]
You could try implementing long division. Example: 13587643180765 / 153483 1) Find first dividend: **1358764**3180765 / 153483 #1358764 > 153483 2) Divide it by divisor (e.g by repeated subtraction, like you are doing 1358764 / 153483 = 8 3) Find the remainder (could be the result of previous computation) 1358764 % 153483 = 130900 4) Bring down the next digit to the end of the remainder. 135876**4**3180765 130900**4** Repeat steps 2-4 until you have reached the last digit in the dividend. --- Since 13587643180765 / 153483 = 88528652, it would take that many subtractions your way. With long division, there's going to be at most 9 \* digits\_in\_quotient subtractions (in step 2), in this case at most 8 \* 9 = 72 subtractions (and in fact 8+8+5+2+8+6+5+2 = 44 subtractions)
11,001,368
I am trying to restrict MySQL 3306 port on a linux machine from making any connections to anything other than localhost to prevent outside attacks. i have the following code, i am not sure if it's correct: > > > ``` > iptables -A INPUT -p tcp -s localhost --dport 3306 -j ACCEPT > > iptables -A OUTPUT -p tcp -s localhost --dport 3306 -j ACCEPT > > iptables -A INPUT -p tcp --dport 3306 -j DROP > > iptables -A OUTPUT -p tcp --dport 3306 -j DROP > > ``` > > my other question is - is it correct to only give localhost access? this is a standard dedicated centos webserver with more than 30 domains on it.
2012/06/12
[ "https://Stackoverflow.com/questions/11001368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1352152/" ]
Why not just turn off networking with MySQL? Add to my.cnf: `skip-networking` It's supposed to also give a negligible performance improvement by forcing connection through pipes, which skips over lots of tests used for the networking section. Please note you will need to use localhost, *not* 127.0.0.1, after the change.
7,790,788
![enter image description here](https://i.stack.imgur.com/woRm6.png)So far I have missed a histogram function with a fraction on the y-axis. Like this: ``` require(ggplot2) data(diamonds) idealD <- diamonds[diamonds[,"cut"]=="Ideal",] fracHist <- function(x){ frac <- (hist(x,plot=F)$counts) / (sum(hist(x,plot=F)$counts)) barplot(frac) } ### call fracHist(idealD$carat) ``` It ain't pretty but basically should explain what I want: bar heights should add up to one. Plus the breaks should be labelling the x-axis. I'd love to create the same with `ggplot2` `but can't figure out how to get around plotting the frequencies of`frac`instead of plotting`frac`itself`. ``` all I get with `ggplot` is density... m <- ggplot(idealD, aes(x=carat)) m + geom_histogram(aes(y = ..density..)) + geom_density() ```
2011/10/17
[ "https://Stackoverflow.com/questions/7790788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366256/" ]
The solution is to use `stat_bin` and map the aesthetic `y=..count../sum(..count..)` ``` library(ggplot2) ggplot(idealD, aes(x=carat)) + stat_bin(aes(y=..count../sum(..count..))) ``` From a quick scan of `?hist` I couldn't find how the values are binned in `hist`. This means the graphs won't be identical unless you fiddle with the `binwidth` argument of `stat_bin`. ![enter image description here](https://i.stack.imgur.com/qk8Q1.png)
25,296,743
My website is hosting on the commun server free.fr and the default php is php4. So I configure the .htaccess file to set the version of php to php5. ``` AddHandler application/x-httpd-php5 .php ``` The .htaccess file cause the download of index.php when I access to the domain.
2014/08/13
[ "https://Stackoverflow.com/questions/25296743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2834039/" ]
Not all (in fact almost none) devices have an external temperature sensor. Its rare hardware and even was discouraged by Google for a while. The reason is that phones run hot- the battery can easily get hot enough to burn. That means any thermometer will be inaccurate. You're better off with either local weather date via web service, or using a usb or bluetooth device connected to your phone to take temperature. Even if you find a device with a temperature sensor you can't trust its accuracy, for the reasons stated above.
18,578,192
So I am trying to submit just an email address using ajax to get people to register and I have no idea why I am getting a 500 internal server error. I am new to ajax calls. I have tried to follow the following tutorial: <http://www.youtube.com/watch?v=TZv5cgua5f0> However I have done as they have said and still if I do a post with values I do not get to the desired controller method. If I do add data to the post then I get an internal server error. javascript: ``` $('#email_submit').click(function() { var form_data = { users_email: $('#users_email_address').val() }; $.ajax ({ url: 'http://localhost/myZone/NewsLetter/submit', type: 'POST', data: form_data, success: function(msg) { alert(msg); } }); return false; }); ``` HTML ``` <div id="email_newsletter_signup" class="ajax_email_block_signup" > <h3>Sign up to the newsletter:</h3> <?php echo form_error('signup_email','<div id="email_error" class="error">','</div>');?> <h3>email: <input id="users_email_address" type="email" name="signup_email" value="<?php echo set_value('signup_email'); ?>" placeholder="Your email"/> </h3> <input id="email_submit" type="submit" name="submit"/> </div> ``` contoller ``` public function index() { Assets::add_module_js('newsletter','email.js'); //If included will be added Template::set_block('email_block','email_block'); Template::render(); } public function submit($email) { $success = $this->newsletter_model->set_unverified_email($email); // if($success === FALSE) // { // Template::set_block('newsletter_error','newsletter_error'); // } // else // { // Template::set_block('newsletter_success','newsletter_success'); // } // Template::render(); return; } ``` I have a breakpoint inside the submit and it just wont be hit when I do a post Thanks
2013/09/02
[ "https://Stackoverflow.com/questions/18578192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/700786/" ]
Found my solution. Nothing to do with bonfire but with the codeigniter. It was the CSRF token. Here is an excellent post about sorting the issue: <http://aymsystems.com/ajax-csrf-protection-codeigniter-20>
72,365,539
I have googled and found some topics discussing similar topic but never got one thread having final and clear response. We are working on a Java application where we will need to support RAC connections. The question is what is the difference between the two URL styles: ``` jdbc:oracle:thin:@<host>:1521/<SERVICENAME> jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(HOST=myhost)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=myorcldbservicename))) ``` Is there any best practice to sue one format over the other? Does the first style supports RAC connection? Does the first style supports failover/load balancing testing? Does it make sense to use the second style and only providing one node? Do we need always to specify all nodes (for the two approches) or is only specifying one node up when the application starts is enough?
2022/05/24
[ "https://Stackoverflow.com/questions/72365539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6529706/" ]
Depending on the client version, the "short" syntax does not support all required attributes required for RAC. So you should use the long format, as it provides all capabilities also when requiring Data Guard. See: * <https://www.oracle.com/a/tech/docs/application-checklist-for-continuous-availability-for-maa.pdf> * <https://www.oracle.com/technetwork/database/options/clustering/applicationcontinuity/applicationcontinuityformaa-6348196.pdf> * <https://www.oracle.com/technetwork/database/availability/client-failover-2280805.pdf> Even though the first is for Autonomous, they are still applicable even for a standard On-Premises deployment. For more good whitepapers, see [www.oracle.com/goto/maa](http://www.oracle.com/goto/maa)
31,862,294
Here is what I have so far: ``` var constructor = typeof (ParentModel).GetConstructor(FieldInformationTypes); var model = (ParentModel)constructor.Invoke(Values.Values.ToArray()); return model; ``` and FieldInformationTypes (which is in the superclass of the class having the above code) ``` protected Type[] FieldInfoTypes; public Type[] FieldInformationTypes { get { if (FieldInfoTypes == null) return FieldInfoTypes; var memberTypes = ( from fieldInfo in FieldInformation select fieldInfo.MemberType).ToArray(); FieldInfoTypes = ( from memberType in memberTypes select memberType.GetType()).ToArray(); return FieldInfoTypes; } } protected FieldInfo[] FieldInfos; public FieldInfo[] FieldInformation { get { // don't GetFields all the time if (FieldInfos != null) return FieldInfos; FieldInfos = typeof(T).GetFields( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); return FieldInfos; } } ``` Where `T` is the class with the constructor I'm trying to dynamically create. `Values` is just a dictionary of `strings` to `objects`, where the strings are the parameter field names, and values can be whatever. I know that with named parameters, the `ParentModel` can be created like this: ``` new ParentModel( children: _children, isResponsible: _isResponsible); ``` Or via this technique: ``` new ParentModel() { Children = _children, IsResponsible = _isResponsible }; ``` Both of those techniques for invoking a method (in my case, the constructor) look an awful lot like a hash / dictionary. So, I feel like it should be possible to dynamically invoke methods via a dictionary. My question is: how? Ideally, I'd like to just be able to invoke a method by doing something like this: ``` new MyObject(myDictionaryOfParameters.ToNamedParameter()); ``` Or something like that.
2015/08/06
[ "https://Stackoverflow.com/questions/31862294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356849/" ]
What about such extension method for the ConstructorInfo returned by GetConstructor(): ``` public static object Invoke(this ConstructorInfo constructor, Dictionary<string, object> parameters) { List<object> parameterValues = new List<object>(); foreach(var parameterInfo in constructor.GetParameters()) { if (parameters.ContainsKey(parameterInfo.Name)) parameterValues.Add(parameters[parameterInfo.Name]); else parameterValues.Add(null); } return constructor.Invoke(parameterValues.ToArray()); } ``` then you could make such call: ``` var constructor = typeof (ParentModel).GetConstructor(FieldInformationTypes); var model = (ParentModel)constructor.Invoke(Values); return model; ```
5,468,739
Can anyone get me a detailed answer on this? What's the advantage of using Session-less Controllers in ASP.NET MVC?
2011/03/29
[ "https://Stackoverflow.com/questions/5468739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669225/" ]
The question doesn't really make sense - what would the result type be? Intersections have to be performed on two sequences of the same type. It sounds like you don't so much want an intersection between two sets, as a filter of the first sequence based on possible values of z2. For example: ``` HashSet<int> validZ2 = new HashSet<int>(listB.Select(x => x.j6)); var filtered = listA.Where(x => validZ2.Contains(x.z2)); ``` Or possibly as Gabe suggests, you want a join. For example: ``` var query = from a in listA join b in listB on a.z2 equals b.j6 select new { a, b }; ``` That will give you all pairings of values from the two lists which match on z2/j6.
4,128,165
I'm trying to figure out how to remove the iPhone 3G as a supported device for my application in the AppStore. I emailed Apple support asking for them to update it in the reqs section and they responded saying I need to update my UIRequiredDeviceCapabilities keys. Well, it was submitted with : ``` <key>UIBackgroundModes</key> <array> <string>location</string> </array> ``` and ``` <key>UIRequiredDeviceCapabilities</key> <array> <string>telephony</string> <string>location-services</string> <string>gps</string> </array> ``` in my plist. Does anyone know what the exact key/value I'd need to set in order for 3G support to not be listed in the AppStore?
2010/11/08
[ "https://Stackoverflow.com/questions/4128165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157110/" ]
Currently, you cannot explicitly prevent one device type from using your app. You would need to require features that the device doesn't have, but they may not be used by your application, possibly causing background and memory usage issues.
32,182,027
I have list of dates: ``` 23/08/2014 8:23:23 24/08/2014 5:23:23 24/08/2014 6:23:23 24/08/2014 7:23:23 24/08/2014 7:25:23 24/08/2014 8:23:23 ``` I want to compare all dates to current date time and find the closest date time. Is there any simple way to compare them instead of looping and comparing? I have tried below example Date1.after(date2) date1.compareTo(date2)>0 But I not able to accomplish the result. I have to compare entire date and time not only date or time by using below format i have to compare Date currentTimeDate = new Date(System.currentTimeMillis());
2015/08/24
[ "https://Stackoverflow.com/questions/32182027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1051762/" ]
* Make the list of your Date Objects in a sorted way. * Then create a Date object for current Date time. * Now use the logic of Binary search to find the closest Date Time in your list. * Use Joda Time for comparison. Consider the above points as hint.
45,879,028
I have a parameterized test which takes `str`, and `dict` as an argument and so the name look pretty weird if I allow pytest to generate ids. I want to generate custom ids using a function, however it seems it's not working as intended. ``` def id_func(param): if isinstance(param, str): return param @pytest.mark.parametrize(argnames=('date', 'category_value'), argvalues=[("2017.01", {"bills": "0,10", "shopping": "100,90", "Summe": "101,00"}), ("2017.02", {"bills": "20,00", "shopping": "10,00", "Summe": "30,00"})], ids=id_func) def test_demo(date, category_value): pass ``` I was thinking it would return something like this ``` test_file.py::test_demo[2017.01] PASSED test_file.py::test_demo[2017.02] PASSED ``` but it's returning this. ``` test_file.py::test_demo[2017.01-category_value0] PASSED test_file.py::test_demo[2017.02-category_value1] PASSED ``` Could someone tell me what's wrong with this, or is there any way to achieve this? **Update:** I realize what's the issue, if\_func will be called for each parameter and if I won't return `str` for any parameter default function will be called. I have fix but that's also ugly. ``` def id_func(param): if isinstance(param, str): return param return " " ``` Now it returns something like this, ``` test_file.py::test_demo[2017.01- ] PASSED test_file.py::test_demo[2017.02- ] PASSED ``` **The problem is even If I return empty string (i.e. `return ""` )it takes the default representation. Could someone let me know why?**
2017/08/25
[ "https://Stackoverflow.com/questions/45879028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2504762/" ]
One way is to move your `argvalues` to another variable and write your test like this: ``` import pytest my_args = [ ("2017.01", {"bills": "0,10", "shopping": "100,90", "Summe": "101,00"}), ("2017.02", {"bills": "20,00", "shopping": "10,00", "Summe": "30,00"}) ] @pytest.mark.parametrize( argnames=('date', 'category_value'), argvalues=my_args, ids=[i[0] for i in my_args] ) def test_demo(date, category_value): pass ``` **Test execution:** ``` $ pytest -v tests.py ================= test session starts ================= platform linux2 -- Python 2.7.12, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 -- /home/kris/.virtualenvs/2/bin/python2 cachedir: .cache rootdir: /home/kris/projects/tmp, inifile: collected 2 items tests.py::test_demo[2017.01] PASSED tests.py::test_demo[2017.02] PASSED ============== 2 passed in 0.00 seconds =============== ``` I think it's not possible with a function (`idfn` in your case), because if it's not generating label for an object the default pytest representation is used. Check [pytest site](https://docs.pytest.org/en/latest/example/parametrize.html) for details.
4,997,325
I have a file that has strings hand typed as \u00C3. I want to create a unicode character that is being represented by that unicode in java. I tried but could not find how. Help. Edit: When I read the text file String will contain "\u00C3" not as unicode but as ASCII chars '\' 'u' '0' '0' '3'. I would like to form unicode character from that ASCII string.
2011/02/14
[ "https://Stackoverflow.com/questions/4997325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616867/" ]
I picked this up somewhere on the web: ``` String unescape(String s) { int i=0, len=s.length(); char c; StringBuffer sb = new StringBuffer(len); while (i < len) { c = s.charAt(i++); if (c == '\\') { if (i < len) { c = s.charAt(i++); if (c == 'u') { // TODO: check that 4 more chars exist and are all hex digits c = (char) Integer.parseInt(s.substring(i, i+4), 16); i += 4; } // add other cases here as desired... } } // fall through: \ escapes itself, quotes any character but u sb.append(c); } return sb.toString(); } ```
58,667,832
A co-worker needs to search our network and her File Explorer search does not work well. I threw this app together quickly to allow her to search and it works well. The results are written to a datagridview, but the results are not shown until the search is complete. I would like the datagridview to show records as they are added and allow her to cancel the search if she wants. Using a backgroundworker, I tried to refresh the grid, but as soon as it finds a match, the code stops running. There are no errors, it just stops running. So how can I get the grid to update as it continues to search? ``` Public dtResults As DataTable Dim myDataSet As New DataSet Dim myDataRow As DataRow Dim colType As DataColumn Dim colResult As DataColumn Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load dtResults = New DataTable() colType = New DataColumn("Type", Type.GetType("System.String")) colResult = New DataColumn("Search Result", Type.GetType("System.String")) dtResults.Columns.Add(colType) dtResults.Columns.Add(colResult) DataGridView1.DataSource = dtResults DataGridView1.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill End Sub Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click btnSearch.Enabled = False sbStatusBar.Text = "Searching..." dtResults.Clear() BackgroundWorker1.RunWorkerAsync() End Sub Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork LoopSubFolders(txtSearchLocation.Text) End Sub Public Sub LoopSubFolders(sLocation As String) Dim di = New DirectoryInfo(sLocation) Dim mySearchterm As String = LCase(txtSearchTerm.Text) Dim fiArr As FileInfo() = di.GetFiles() Dim sSearchTarget As String sbStatusBar.Text = "Searching " & sLocation 'Search File names in If cbFileNames.Checked = True Then For Each myFile In fiArr sSearchTarget = LCase(myFile.Name) If sSearchTarget.Contains(mySearchterm) Then myDataRow = dtResults.NewRow() myDataRow(dtResults.Columns(0)) = "File" myDataRow(dtResults.Columns(1)) = Path.Combine(sLocation, myFile.Name) dtResults.Rows.Add(myDataRow) End If Next End If For Each d In Directory.GetDirectories(sLocation) If cbFolderNames.Checked = True Then sSearchTarget = LCase(d) If sSearchTarget.Contains(mySearchterm) Then myDataRow = dtResults.NewRow() myDataRow(dtResults.Columns(0)) = "Folder" myDataRow(dtResults.Columns(1)) = d dtResults.Rows.Add(myDataRow) End If End If LoopSubFolders(d) Next End Sub Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted btnSearch.Enabled = True sbStatusBar.Text = "Complete" DataGridView1.DataSource = Nothing DataGridView1.DataSource = dtResults DataGridView1.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill End Sub ```
2019/11/02
[ "https://Stackoverflow.com/questions/58667832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4114838/" ]
Here's an example of how you might do it using the suggested `ReportProgress` method and `ProgressChanged` event: ``` Private table As New DataTable Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'Configure table here. DataGridView1.DataSource = table End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'Setup UI here. 'Note that you MUST pass in the TextBox data as you MUST NOT touch the UI directly on the secondary thread. BackgroundWorker1.RunWorkerAsync({TextBox1.Text, TextBox2.Text}) End Sub Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork 'Get the data passed in and separate it. Dim arguments = DirectCast(e.Argument, String()) Dim folderPath = arguments(0) Dim searchTerm = arguments(1) SearchFileSystem(folderPath, searchTerm) End Sub Private Sub SearchFileSystem(folderPath As String, searchTerm As String) For Each filePath In Directory.GetFiles(folderPath) If filePath.IndexOf(searchTerm, StringComparison.InvariantCultureIgnoreCase) <> -1 Then 'Update the UI on the UI thread. BackgroundWorker1.ReportProgress(0, {"File", filePath}) End If Next For Each subfolderPath In Directory.GetDirectories(folderPath) If subfolderPath.IndexOf(searchTerm, StringComparison.InvariantCultureIgnoreCase) <> -1 Then 'Update the UI on the UI thread. BackgroundWorker1.ReportProgress(0, {"Folder", subfolderPath}) End If SearchFileSystem(subfolderPath, searchTerm) Next End Sub Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged 'Get the data passed out and separate it. Dim data = DirectCast(e.UserState, String()) 'Update the UI. table.Rows.Add(data) End Sub ``` Note that you should NEVER touch the UI directly in the `DoWork` event handler or a method called from it. ONLY touch the UI on the UI thread. That means that the text in your `TextBoxes` must be extracted BEFORE calling `RunWorkerAsync`. You can eithewr pass the `Strings` in as arguments or you can assign them to fields and access them from there on any thread. Don't EVER access a member of a control on other than the UI thread. Some times it will work, sometimes it will appear to work but not do as intended and sometimes it will crash your app. So that you don't have to remember which specific scenarios cause which result, avoid such scenario altogether. I haven't tested this code so I'm not sure but you may have to call `Refresh` on the grid or the form after adding the new row to the `DataTable`.
4,289,564
I wrote a login system for my website. When the user registers, the system emails an activation link to the email address the user provided. The link contains two parameters, email and key. The email parameter has the user's email address and the key parameter has the registration code so that the registration can be verified and changed from pending to confirmed. The activation page is supposed to fetch the Status column from the row that has the email parameter set in the Email column. For some reason, the script decides that any link is valid, and attempts to update the status of the account whether it exists or not. **Here is my code:** ``` <?php $email = $_GET['email']; if($email == "") { header("Location: http://www.zbrowntechnology.info/yard/register.php?message=Invalid Activation Link!"); exit; } $key = $_GET['key']; if($key == "") { header("Location: http://www.zbrowntechnology.info/yard/register.php?message=Invalid Activation Link!"); exit; } $con = mysql_connect("HOST", "USER", "PASS") or die(mysql_error()); mysql_select_db("zach_yardad", $con) or die(mysql_error()); $query1 = "SELECT `Status` FROM Accounts WHERE `Email`='".mysql_real_escape_string($email)."' AND `Status`='".mysql_real_escape_string($key)."'"; $result1 = mysql_query($query1) or die(mysql_error()); if(mysql_num_rows($result1) <= 0) { header("Location: http://www.zbrowntechnology.info/yard/register.php?message=Invalid Activation Link!"); exit; } else { $query = "UPDATE Accounts SET `Status`='Confirmed' WHERE `Email`='$email'"; mysql_query($query) or die(mysql_error()); header("Location: http://www.zbrowntechnology.info/yard/login.php?message=Registration Complete!"); exit; } ?> ``` Here is a valid activation link: ``` http://www.zbrowntechnology.info/yard/activate.php?email=zach@zbrowntechnology.com&key=2772190956485245 ``` It will activate that account by following the link, but it will redirect to the login page after activation if the link is not valid. --- **EDIT:** Here is the result of the query `DESCRIBE `Accounts``: ``` First Name varchar(65) NO NULL Last Name varchar(65) NO NULL Email varchar(100) NO NULL Username varchar(65) NO NULL Password varchar(65) NO NULL Status varchar(65) NO NULL ```
2010/11/27
[ "https://Stackoverflow.com/questions/4289564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326544/" ]
Can you try changing your code to this: ``` $query1 = mysql_query("SELECT `Status` FROM `Accounts` WHERE `Email`='".mysql_real_escape_string($email)."' AND `Status`='".mysql_real_escape_string($key)."'"); if(mysql_num_rows($query1) <= 0) { ``` This should work.. If that doesn't work, try this: ``` $query1 = mysql_query("SELECT `Status` FROM `Accounts` WHERE `Email`='".mysql_real_escape_string($email)."' AND `Status`='".mysql_real_escape_string($key)."'", $con); if(mysql_num_rows($query1) <= 0) { ``` ====Full Code==== ``` <?php if($_GET['email'] == "") { header("Location: http://www.zbrowntechnology.info/yard/register.php?message=Invalid Activation Link!"); exit; } if($_GET['key'] == "") { header("Location: http://www.zbrowntechnology.info/yard/register.php?message=Invalid Activation Link!"); exit; } $email = mysql_real_escape_string($_GET['email']); $key = mysql_real_escape_string($_GET['key']); $con = mysql_connect('HOST', 'USER', 'PASS'); mysql_select_db('zach_yardad', $con) or die(mysql_error()); $query1 = mysql_query("SELECT `Status` FROM `Accounts` WHERE `Email` = '" . $email . "' AND `Status` = '" . $key ."'", $con); if(mysql_num_rows($query1) <= 0) { header("Location: http://www.zbrowntechnology.info/yard/register.php?message=Invalid Activation Link!"); exit(); } else { mysql_query("UPDATE `Accounts` SET `Status`='Confirmed' WHERE `Email`='$email'", $con); header("Location: http://www.zbrowntechnology.info/yard/login.php?message=Registration Complete!"); exit(); } ?> ```
5,219,378
Resharper really complains about files such as reference.cs that is generated by things like WCF service reference. How do I get Resharper to skip such files entirely?
2011/03/07
[ "https://Stackoverflow.com/questions/5219378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81514/" ]
1. menu `ReSharper -> Options` 2. `Code inspection -> Settings` item 3. button `Edit items to skip`
50,801,418
I'm building an app with ES5 JS just for practice and "fun" where I store websites in `localStorage` then print them out on the page, i.e. a bookmarker application. I'm getting a > > TypeError: Cannot set property 'innerHTML' of null > > > error in the console when I run the following code: **index.html** ``` <body onload="fetchBookmarks()"> <div class="container"> ...some code </div> <div class="jumbotron"> <h2>Bookmark Your Favorite Sites</h2> <form id="myForm"> ...some code </form> </div> <div class="row marketing"> <div class="col-lg-12"> <div id="bookmarksResults"></div> /* problem code */ </div> </div> <footer class="footer"> <p>&copy; 2018 Bookmarker</p> </footer> </div> <link rel="stylesheet" href="main.css"> <script src="./index.js"></script> </body> ``` **index.js** ``` ...someJScode that stores the websites in localStorage function fetchBookmarks() { var bookmarks = JSON.parse(localStorage.getItem('bookmarks')); //Get output id var bookmarksResults = document.getElementById('#bookmarksResults'); bookmarksResults.innerHTML = ''; for(var i = 0; i < bookmarks.length; i++) { var name = bookmarks[i].name; var url = bookmarks[i].url; bookmarksResults.innerHTML += name; } } ``` now, the error is obviously because I am loading the `<body>` before the `<div id="bookmarksResults"></div>` so `innerHTML` responds with `null` But two things here: 1) When I assign `onload="fetchBookmarks()"` to the `<footer>` element, the function doesn't run. 2) The tututorial I am following has this code almost exactly and it runs there. I've also tried running the `fetchBookmarks()` function like this: ``` window.onload = function() { fetchBookmarks(); function fetchBookmarks(){ ...some JS code }; } ``` But that returned the same > > TypeError: Cannot set property 'innerHTML' of null > > > So I'm a bit lost here and am much more interested in figuring out **why** this isn't working and the theory behind it so I understand JS better (the whole point of building this app in the first place). Any help would be appreciated! Thanks SO team.
2018/06/11
[ "https://Stackoverflow.com/questions/50801418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8844309/" ]
So your basic question is, how do you invert and find `x_0` given a known `n` and: ``` x_n = x_0 * 1.1^n ``` Looks like we can simply divide through by `1.1^n` ``` x_n/(1.1^n) = x_0 ``` So you can either calculate `1.1^n` with `pow(1.1, n)` and divide `x_n` (your "increased" value) by that, or just loop and reduce like you increased: ``` //1. $original = $increased/pow(1.1, n); //2. $original = $increased; for ($i = 0; $i < n; $i++) { $original = $original / 1.1; } ``` So in your example, let's say our `$increased` is known to be 133, and `n=3`. Then using the first method: ``` $original = 133 / (1.1^3) = 133 / 1.33 = 100 ```
5,402
I have data in a java object as data1, data2. data1 and data2 together forms a composite key in myTable where I want to insert the object. The writing is happening as a batch. Like 10 insert statements are prepared using 10 objects and are executed as a batch. I want to insert the above data with the constraint: data1 + data2 should not already be present in myTable i.e. data1 + data2 should be unique --- if unique then write else just ignore. The query I am using is: ``` Insert into mySchema.myTable(column1, column2) select 'abc', '123' from SYSIBM.DUAL where not exists ( select 1 from mySchema.myTable A where 'abc' = A.column1 and '123' = A.column2 ) ``` Running above query independently for single set of data runs successfully. However, while running in batch scenario I am getting "com.ibm.db2.jcc.b.ie: Non-atomic batch failure." error. I think it has something to do with using SYSIBM.DUAL in batch scenario. Code which is failing: Insert Query: ``` Insert into mySchema.myTable(column1, column2) select ?, ? from SYSIBM.DUAL where not exists ( select 1 from mySchema.myTable A where ? = A.column1 and ? = A.column2 ) ``` Statement Setters: ``` ps.setString(1, item.getColumn1()); ps.setString(2, item.getColumn2()); ps.setString(3, item.getColumn1()); ps.setString(4, item.getColumn2()); ``` where item is the java object holding the two columns to write. Error is: ``` org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [Insert into mySchema.myTable(column1, column2) select ?,? from SYSIBM.DUAL where not exists (select 1 from mySchema.myTable A where ?=A.column1 and ?=A.column2)]; nested exception is com.ibm.db2.jcc.b.ie: Non-atomic batch failure. The batch was submitted, but at least one exception occurred on an individual member of the batch. Use getNextException() to retrieve the exceptions for specific batched elements. ``` Thanks, Nik
2011/09/05
[ "https://dba.stackexchange.com/questions/5402", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/3247/" ]
This question is somewhat old, so you may have already figured out your problem, but if I may offer an alternative... It may be better to use a [`MERGE`](http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/topic/com.ibm.db2z9.doc.sqlref/src/tpc/db2z_sql_merge.htm) statement in this situation (click the link for the publib entry): ``` MERGE INTO mySchema.myTable tab USING ( VALUES ('abc', '123') ) AS merge (C1, C2) ON tab.column1 = merge.C1 AND tab.column2 = merge.C2 WHEN MATCHED THEN IGNORE WHEN NOT MATCHED THEN INSERT (column1, column2) VALUES (merge.C1, merge.C2) ``` This will take the columns in the "fake" table `merge`, and compare them using the keys in the `ON` clause, and if there is not a match, then it will use the `INSERT` statement. If there is a match, that row will just be ignored. However, the availability of `MERGE` depends on your platform. I'm fairly certain `MERGE` has been in Linux/Unix/Windows DB2 since v8 (although, you can only use `PREPARE`'d merges since 9.7), and it was added in z/OS DB2 in v9.1. I don't know about the other platforms (AS/400, etc.).
51,325,051
[![App Hierarchy ](https://i.stack.imgur.com/57tL1.jpg)](https://i.stack.imgur.com/57tL1.jpg) I am developing an app where i am using only 1 Main Activity and Multiple fragment, Including `ViewPager` , Custom video/Image Gallery, Fullscreen Fragment(Without toolbar or bottom navigation button). I am not sure is it good practice or not but i am facing few issues cause of this. Image above is actual App hierarchy. Following the issue i am facing. 1. Toolbar doesn't change title of fragment, when press back button or going forward by clicking button or some link. 2. Navigation hamburger keep showing if i change into back arrow by `using: getSupportActionBar().setDisplayHomeAsUpEnabled(true);` then back arrow opens drawers but not going back to last fragment. 3. Fragment State Loss when pressed back button or jumping directly to some fragment. 4. Whether is it good practice to doing all task within `Fragment` with Single `Activity`. I am also using single Toolbar whole app. Toolbar.xml ``` <android.support.v7.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/primary" app:contentInsetLeft="0dp" app:contentInsetStart="0dp" app:contentInsetStartWithNavigation="0dp" android:fitsSystemWindows="true" app:layout_collapseMode="pin" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/toolbar_connections" android:visibility="visible" android:orientation="horizontal"> <ImageView android:layout_width="35dp" android:layout_height="match_parent" android:id="@+id/appLogo" android:layout_gravity="center_vertical" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|center_horizontal" android:textSize="22sp" android:id="@+id/activityTitle" android:textColor="@color/primary_text" /> </LinearLayout> <LinearLayout android:id="@+id/toolbar_chat" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone" android:orientation="horizontal"> <de.hdodenhof.circleimageview.CircleImageView android:layout_width="50dp" android:layout_height="50dp" android:layout_gravity="center_vertical" android:layout_marginRight="5dp" android:src="@drawable/baby" android:id="@+id/User_Image_Toolbar"/> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/User_Name_Toolbar" android:textSize="17sp" android:textStyle="bold" android:layout_marginBottom="5dp" android:text="My Name" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Online" android:textStyle="italic" android:id="@+id/User_Online_Status_Toolbar" android:layout_marginBottom="5dp" android:layout_below="@+id/User_Name_Toolbar" /> </LinearLayout> </LinearLayout> </android.support.v7.widget.Toolbar> ``` Navigation Drawer (Single Activity which parent of all Fragments) ``` public class Navigation_Drawer extends AppCompatActivity implements UserData { Toolbar toolbar; DrawerLayout drawerLayout; NavigationView navigationView; String navTitles[]; TypedArray navIcons; RecyclerView.Adapter recyclerViewAdapter; ActionBarDrawerToggle drawerToggle; public static final String TAG = "###Navigation Drawer###"; boolean nextScreen; //Header ImageView headerImage,headerUserImage; TextView userName,userViews; Context context = this; //Setting Tabs ViewPager viewPager; TabAdapter tabAdapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.navigation_drawer); //Initialise Views drawerLayout = findViewById(R.id.Navigation_Drawer_Main); navigationView = findViewById(R.id.nvView); setupToolbar(); navigationView.setItemIconTintList(null); setupDrawerContent(navigationView); settingHeaderItems(); drawerToggle = setupDrawerToggle(); getSupportActionBar().setHomeButtonEnabled(true); drawerLayout.addDrawerListener(drawerToggle); viewPager = findViewById(R.id.Navigation_Drawer_ViewPager); tabAdapter = new TabAdapter(getFragmentManager(), this, false); viewPager.setAdapter(tabAdapter); } public void setupToolbar() { toolbar = findViewById(R.id.Navigation_Drawer_toolbar); setSupportActionBar(toolbar); } private ActionBarDrawerToggle setupDrawerToggle() { // NOTE: Make sure you pass in a valid toolbar reference. ActionBarDrawToggle() does not require it // and will not render the hamburger icon without it. //return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close); return new ActionBarDrawerToggle(this, drawerLayout,toolbar, R.string.drawer_open, R.string.drawer_close); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); // inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { //Handle Item Selection return super.onOptionsItemSelected(item); } private void setupDrawerContent(NavigationView navigationView) { navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { selectDrawerItem(menuItem); return true; } }); } public void ChangeFragment_ViewPager(int position, boolean outside) { if (outside) { Log.d(TAG, "Change Fragment Calling From Outside"); tabAdapter = new TabAdapter(getFragmentManager(), this, false); viewPager.setAdapter(tabAdapter); } viewPager.setCurrentItem(position); } @Override public void onBackPressed() { super.onBackPressed(); showSystemUI(); Log.d(TAG, "On Back Pressed"); } public void showSystemUI() { if (getWindow() != null) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getSupportActionBar().show(); } else { return; } } public void selectDrawerItem(MenuItem menuItem) { // Create a new fragment and specify the fragment to show based on nav item clicked Fragment fragment = null; switch (menuItem.getItemId()) { case R.id.HeaderImageView: fragment = new EditProfile(); break; case R.id.home_Fragment: Log.d(TAG,"Home Fragment Pressed "); getFragmentManager().popBackStack(null, android.app.FragmentManager.POP_BACK_STACK_INCLUSIVE); ChangeFragment_ViewPager(0,false); // Highlight the selected item has been done by NavigationView menuItem.setChecked(true); // Set action bar title setTitle(menuItem.getTitle()); // Close the navigation drawer drawerLayout.closeDrawers(); return; case R.id.ppl_Fragment: Log.d(TAG,"PPL Fragment Pressed "); ChangeFragment_ViewPager(1,false); // Highlight the selected item has been done by NavigationView menuItem.setChecked(true); // Set action bar title setTitle(menuItem.getTitle()); // Close the navigation drawer drawerLayout.closeDrawers(); return; case R.id.message_Fragment: Log.d(TAG,"Message Fragment Pressed "); fragment = new Messages_Fragment(); break; case R.id.addMedia_Fragment: Log.d(TAG,"Add Media Fragment Pressed "); fragment = new UserProfile_Photos(); break; case R.id.invite_Fragment: Log.d(TAG,"Invite Fragment Pressed "); //fragmentClass = fragment_1.class; onInviteClicked(); // Highlight the selected item has been done by NavigationView menuItem.setChecked(true); // Set action bar title setTitle(menuItem.getTitle()); // Close the navigation drawer drawerLayout.closeDrawers(); return; case R.id.setting_Fragment: Log.d(TAG,"Setting Fragment Pressed "); fragment = new Setting_NavigationDrawer(); break; case R.id.help_Fragment: Log.d(TAG,"Help Fragment Pressed "); //fragmentClass = fragment_1.class; fragment=new FullScreen_WebView(); Bundle urlToSend=new Bundle(); urlToSend.putString("webViewURL","http://boysjoys.com/test/Android/Data/help.php"); //urlToSend.putString("webViewURL",chat_wrapper.getGoogleSearch().get(2)); fragment.setArguments(urlToSend); FragmentTransaction transaction=((Activity)context).getFragmentManager().beginTransaction(); //fragmentTrasaction.replace(R.id.Chat_Screen_Main_Layout,gallery); //transaction.replace(R.id.Chat_Screen_Main_Layout,fullScreen_webView); transaction.replace(R.id.Navigation_Main_Layout,fragment); transaction.addToBackStack(null); transaction.commit(); // Highlight the selected item has been done by NavigationView menuItem.setChecked(true); // Set action bar title setTitle(menuItem.getTitle()); // Close the navigation drawer drawerLayout.closeDrawers(); return; case R.id.signOut_Fragment: new CheckLoginStatus(this, 0).execute(); new Send_Session_Logout(this).execute(); drawerLayout.closeDrawers(); return; } FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.Navigation_Main_Layout, fragment); fragmentTransaction.setCustomAnimations(R.animator.enter_anim,R.animator.exit_anim); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); // Highlight the selected item has been done by NavigationView menuItem.setChecked(true); // Set action bar title setTitle(menuItem.getTitle()); // Close the navigation drawer drawerLayout.closeDrawers(); } private void settingHeaderItems(){ View HeaderLayout = navigationView.inflateHeaderView(R.layout.navigation_header_image); //Main Screen Tabs With VIew Pager headerImage = HeaderLayout.findViewById(R.id.HeaderImageView); headerImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.Navigation_Main_Layout, new EditProfile()); fragmentTransaction.setCustomAnimations(R.animator.enter_anim,R.animator.exit_anim); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); drawerLayout.closeDrawers(); } }); headerUserImage = HeaderLayout.findViewById(R.id.HeaderProfilePicture); userName = HeaderLayout.findViewById(R.id.myImageViewText); userViews = HeaderLayout.findViewById(R.id.profileViews); if (Session.getUserCover().equals("Invalid Image")){ headerImage.setBackgroundResource(R.drawable.cam_icon); }else { Log.d(TAG,"Path Of Cover Photo "+Session.getUserCover()); Bitmap coverPhoto= BitmapFactory.decodeFile(Session.getUserCover()); headerImage.setImageBitmap(coverPhoto); // Glide.with(context).load(Session.getUserCover()).apply(new RequestOptions().skipMemoryCache(true).onlyRetrieveFromCache(false).diskCacheStrategy(DiskCacheStrategy.NONE)).into(holder.HeaderImage); } Bitmap bitmap = BitmapFactory.decodeFile(Session.getUserImage()); userName.setText(Session.getUserFname()+" "+Session.getUserLname()); headerUserImage.setImageBitmap(bitmap); if (Session.getProfileCounter().equals("0")){ userViews.setText("No Profile VIsits"); } else { userViews.setText("Profile views: "+ Session.getProfileCounter()); } } @Override protected void onPostCreate(@Nullable Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } } ``` I tired alot to resolve this issue and after months of googling and stackoverflow i m still stuck in same issue. Issue example of Point 1:- When navigation drawer load first everything looks good, view pager changes title as per fragment. then if i click on Navigation Drawer's Menu which also open another fragment (For Ex: Recent Message). then title change successfully but when i press back button or trying to press home button which calls viewpager then title remain same as before i.e. Recent Message. Setting Title in each fragment like this. ``` toolbar = (Toolbar) getActivity().findViewById(R.id.Navigation_Drawer_toolbar); ImageView appLogo = toolbar.findViewById(R.id.appLogo); TextView fragmentTitle = toolbar.findViewById(R.id.activityTitle); appLogo.setImageResource(DrawableImage); fragmentTitle.setText(Title); ```
2018/07/13
[ "https://Stackoverflow.com/questions/51325051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6753279/" ]
If application have to use Navigation Drawer which should be present in all views, then Fragment should be used. And its not a bad practice. 1. Toolbar doesn't change title of fragment, when press back button or going forward by clicking button or some link. Create a method in Base Activity ``` public void setFragmentTitle(String title){ if(!TextUtils.isEmpty(title)) mTitleText.setText(title); } ``` Access this method from your individual Fragments in `onCreateView` ``` ((LandingActivity) getActivity()).setFragmentTitle(getActivity().getString(R.string.fragment_title)); ``` 2. Navigation hamburger keep showing if i change into back arrow by using: getSupportActionBar().setDisplayHomeAsUpEnabled(true); then back arrow opens drawers but not going back to last fragment. Use `onOptionItemSelected` on click of `android.R.id.home` , pop the current `Fragment` 3. Fragment State Loss when pressed back button or jumping directly to some fragment You have to mention the values which needs to be persisted and repopulate it. --- ``` public class ActivityABC....{ private String mFName; private TableSelectFragment mFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentManager fm = getSupportFragmentManager(); if (savedInstanceState != null) { mFragment=(TableSelectFragment)fm.getFragment(savedInstanceState,"TABLE_FRAGMENT"); mFName = savedInstanceState.getString("FNAMETAG"); }else{ mFragment = new TableSelectFragment(); fm.beginTransaction().add(R.id.content_frame,mFragment,"TABLE_FRAGMENT").commit(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); getSupportFragmentManager().putFragment(outState,"TABLE_FRAGMENT",mFragment); } } ``` In your Fragment ``` TableSelectFragment{ .... private String mFName; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { outState.putString("FNAMETAG", mFName); super.onSaveInstanceState(outState); } } ``` --- **EDIT 1: For Fragment Title not getting updated in BackButton press** While adding `Fragment` to backstack , do the following. In your parent Activity ``` FragmentManager fragMan = getSupportFragmentManager(); FragmentTransaction fragTrans = fragMan.beginTransaction(); LandingFrag landingFrag = LandingFrag.newInstance(); fragTrans.replace(R.id.landing_view, landingFrag,"LandingFrag"); fragTrans.addToBackStack(null); fragTrans.commit(); landingFrag.setUserVisibleHint(true); ``` Now override onBackPressed in parent Activity ``` @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { .. POP Fragment Backstack here Fragment fragment = getActiveFragment(); if(fragment instanceof LandingFrag) { LandingFrag landingFrag = (LandingFrag)fragment; landingFrag.setUserVisibleHint(true); } } public Fragment getActiveFragment() { if (getSupportFragmentManager().getBackStackEntryCount() == 0) { return null; } Fragment fragment=null; int trackBackValue = 1;//INCREASE OR DECREASE ACCORDING TO YOUR BACK STACK try { fragment = getSupportFragmentManager().getFragments().get(getSupportFragmentManager().getBackStackEntryCount() - trackBackValue); } catch (Exception e) { } return fragment; } ``` Now in LandingFrag ``` public class LandingFrag... { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setUserVisibleHint(false); ..... } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ................ ((LandingActivity) getActivity()).setFragmentTitle("Current Fragment Title"); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if(isVisibleToUser){ try { ((LandingActivity) getActivity()).setFragmentTitle("Current Fragment Title"); } catch (Exception e) { e.printStackTrace(); } } } } ```
15,193,993
I want to make a gradient border of view like the following picture: ![Image](https://i.stack.imgur.com/71ZWH.png) but I don't know how do it exactly , i.e. what the gradient color I should use to do it? how to set my view to show a border like the image? I'm using the following code to get a border: ``` self.view.layer.borderColor = [UIColor orangeColor].CGColor; self.view.layer.borderWidth = 2.0f; ```
2013/03/04
[ "https://Stackoverflow.com/questions/15193993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999607/" ]
This what i did and it worked perfectly ``` extension CALayer { func addGradienBorder(colors:[UIColor],width:CGFloat = 1) { let gradientLayer = CAGradientLayer() gradientLayer.frame = CGRect(origin: CGPointZero, size: self.bounds.size) gradientLayer.startPoint = CGPointMake(0.0, 0.5) gradientLayer.endPoint = CGPointMake(1.0, 0.5) gradientLayer.colors = colors.map({$0.CGColor}) let shapeLayer = CAShapeLayer() shapeLayer.lineWidth = width shapeLayer.path = UIBezierPath(rect: self.bounds).CGPath shapeLayer.fillColor = nil shapeLayer.strokeColor = UIColor.blackColor().CGColor gradientLayer.mask = shapeLayer self.addSublayer(gradientLayer) } } ```
44,838,742
``` file = open('data.txt') data = [] h = [i[:-1] for i in file] def maximum_cols(list): for line in h: data.append(line) y = [int(n) for n in data] x = None for value in data: value = int(value) if not x: x = value elif value > x: x = value return x maximum_cols(data) print(data) ``` So I'm trying to read a file into 2d list and then find the max value from the list and print it out. I'm so lost and stuck. I'm not sure how to proceed. Here's the code I made. I'm pretty sure there's some errors in my coding. I'm new to python and I need assistance Contents of **Data.txt:** ``` 13 45 44 98 1 17 4 2 0 1 3 1 1 1 ``` [DataFile](https://i.stack.imgur.com/QTX6z.png) [Code's; Errors](https://i.stack.imgur.com/vze9P.png)
2017/06/30
[ "https://Stackoverflow.com/questions/44838742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You seem to be looking for: ``` date -d "20170601+1 month" +%Y-%m-%d ``` When using multiple `-d` flags in the same command, `date` seems to only use the last one. And of course, feel free to replace `20170601` by `$VAR` containing any date.
511,087
I'm using this command to copy a file on a daily basis. ``` COPY "E:\ClipData.txt" "Clipboard\ClipData.txt" ``` But is there anyway without making it complicated, to copy the file after the source file has been modified? There are standalon softwares that manages to do that, but the application must be running al the time. So the cmd solution is much better.
2012/11/27
[ "https://superuser.com/questions/511087", "https://superuser.com", "https://superuser.com/users/136767/" ]
found at: <https://gist.github.com/1130675> Getting a Motorola SBG6580 into “Bridge” mode on TimeWarner Wideband > > Unplug coax cable from Motorola Hold down the white reset button on > the back panel with a pen for 30s. This resets all settings to > factory defaults. The modem will be auto-reconfigured once you plug in > the coax cable. When modem is back on plug in a computer with an > Ethernet cable into the modem. Connect to http colon slash slash 192 dot 168 dot 0 dot 1 and login > with “admin” / “motorola” Now you will make some changes: > > > Wireless -> Primary Network -> Disabled Basic -> Setup -> NAPT Mode > -> Disabled Basic -> DHCP -> No Advanced -> Options -> Rg Passthrough -> Enable Advanced -> Options -> Passthrough Mac Addresses -> Add WAN MAC address of your router 6. Connect port 1 on the Motorola modem to > the WAN port of your router. Plug the coaxial cable back into the > modem and power cycle it. > > > Setting the Motorola router to bridge mode basically makes it a media converter. Then you do everything in the other router (the ASUS) that you own. I've done this with DSL routers (used my own Cisco router), and use to work for TW (how I knew about this). Look on page 9 to [restore the factory settings](http://www.midcocomm.com/_files/files/SBG6580.pdf) so that you can get access to Rg Passthrough. If that doesn't work, [flashing the firmware](http://forums.cox.com/forum_home/internet_forum/f/5/t/722.aspx) may help.
42,475,822
I'm trying to grasp the idea of pointers but can't get the hang of it. Why does this code assign the correct value to `s`, but create a runtime error when I try to use it on `t`. ``` #include <stdio.h> #include <stdlib.h> int main(void) { char *s; char *t; printf("s: "); scanf("%s", s); printf("t: "); scanf("%s", t); return 0; } ```
2017/02/27
[ "https://Stackoverflow.com/questions/42475822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5789791/" ]
Not sure if I understand the problem, but if you want to update the *'selectedFontSizePrice'* value when select a *fontType*, I think you should call the function *fontSize* (as far as I can see is the one that modifies the value of *'selectedFontSizePrice'*) from inside the function *fontType* ``` methods: { fontType: function(selectedFont) { this.selectedFont = selectedFont.name; this.currentFonts = selectedFont.params; this.fontSize(selectedFont.params[0]); //select first value }, fontSize: function(selectedSize) { this.selectedSize = selectedSize.size; this.selectedFontSizePrice = selectedSize.price; } } ```
22,506,652
I have this JSON code which can't be changed. I want to make a C# class out of it but the problem I'm having is that the 10.0.0.1/24 can't be made into a C# class property and the 10.0.0.1/24 could be any ip address range. ``` { "addresses": { "10.0.0.1/24": [ { "version": 4, "addr": "10.0.0.36", "OS-EXT-IPS:type": "fixed" } ] } } ```
2014/03/19
[ "https://Stackoverflow.com/questions/22506652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730599/" ]
As the object contains properties that cannot be legally named in `C#` you need to either wrap them as string indexes or use an attribute the specify the property name. Firstly, you need to declare the objects to use ``` public class Foo { public Dictionary<string, List<Bar>> addresses { get; set; } } public class Bar { public int version { get; set; } public string addr { get; set; } [DataMember(Name = "OS-EXT-IPS:type")] public string OstType { get; set; } } ``` I have opted to use a `Dictionary<string, List<Bar>>` combination for the list of addresses. The key will be `10.0.0.1/24` in your example. The property `OST-EXT-IPS:type` cannot be legally translated, so this uses the attribute option. The class can then be deseralised as ``` public static string JsonExtract() { Foo obj = new Foo(); obj.addresses = new Dictionary<string, List<Bar>>() { { "10.0.0.1/24", new List<Bar>() { new Bar() { version = 4, addr = "10.0.0.36", OstType = "fixed" } } }}; JavaScriptSerializer js = new JavaScriptSerializer(); string s = js.Serialize(obj); return s; } public static Foo JsonParse() { string file = @"json.txt"; // source using (StreamReader rdr = new StreamReader(file)) { string json = rdr.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); Foo obj = js.Deserialize<Foo>(json); return obj; } } ``` This has been done using the `JavaScriptSeralizer` in the `System.Web.Script.Serialization` namespace, but a similar approach can be done via Netonsoft Json library or other libraries in use. The key is to ensure that properties are mapped to a json attribute as either sting key of an object or via a serialisation attribute.
32,472,983
Trying to delay fade 500 to 1000, but when i change `.fadeTo('500', 1);` to `.fadeTo('1000', 1);` it's not delay to fade. Same timing, no difference between 500 to 1000. **Jquery:** ``` $(".more-post").one("click", function () { $('.bottom-post').addClass('show-more').fadeTo('500', 0); setTimeout(function(){ $('.bottom-post').addClass('show-more').fadeTo('500', 1); },4000); }); ``` This *Jquery* fade very fast, So how to fade delay more `.fadeTo('1000', 1);`. Want to fade more slow. Thanks.
2015/09/09
[ "https://Stackoverflow.com/questions/32472983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4290783/" ]
When i removed the addClass() and changed **$(".more-post").one** to **$(".more-post").on** it started to work: ```js $(".more-post").on("click", function() { $('.bottom-post').fadeTo(5000, 0); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="more-post">Click me to see the fade<div> <div class="bottom-post">Fade me slow<div> ``` **OR** You can use **jqueryUI** toggleClass [here](http://jqueryui.com/toggleClass/) ```js $(".more-post").on("click", function() { $('.bottom-post').toggleClass('more-post', 3000).toggleClass("hide-post", 5000); }); $(".hide-post").on("click", function() { $('.bottom-post').toggleClass("hide-post", 3000).toggleClass('more-post', 5000); }); ``` ```css .more-post { opacity: 1; } .hide-post { opacity: 0; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <div class="more-post">Click me to see slow fading<div> <p class="bottom-post hide-post">More stuff to be faded in</p> ```
2,517,019
How do you prove that a function for example is increasing without taking the derivative of it? What is that called? Monotonicity or something? A video explaining the concept would be nice but all I have found uses derivatives which I am not allowed to use. For example prove that the function f(x) is increasing: f(x) = 12x - 4100 if x < -2, f(x) = (x-14)^3 if x >= -2
2017/11/12
[ "https://math.stackexchange.com/questions/2517019", "https://math.stackexchange.com", "https://math.stackexchange.com/users/486211/" ]
By the definition of increasing function: You take arbitrary $x\_{1},x\_{2}\in D(f)$ such that $x\_{1}\leq x\_{2}$ and show that $f(x\_{1})\leq f(x\_{2})$. Similar for decreasing. Your example is piecewise function. Try to split it on three problems. Show monotonicity for single pieces. Then try to take $x\_{1}\leq-2 \leq x\_{2}$, if necessary.
90,381
I am writing a perl script to automate certain processes on our Oracle databases. One portion of the script involves putting the script to sleep until the alert log shows the database open. I intend to do a sleep until (logevalmodule). The logevalmodule will be a sub procedure that opens and monitors the alert log using tail -f returning a true when the word OPEN appears in the log. Can anyone help me with possible solutions. I have two hurdles to make this work. The path to the alert log will not be in the same place for all the databases on the Oracle server, for example 'apps13/oracle/admin/db1/bdump' and 'apps14/oracle/admin/db2/bdump'. The other hurdle is to format the tail -f into the script. Thanks.
2009/12/02
[ "https://serverfault.com/questions/90381", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
In terms of building a Perl module to monitor stuff appearing in Log files I would strongly recommend using Perl Object Environment (POE). I've built a bunch of log monitors using it in the past and it's pretty simple and quite effective. There's a good example showing some tail monitoring\processing of a web server log on the [POE Cookbook Site here](http://poe.perl.org/?POE_Cookbook/Tail_Following_Web_Server). As far as the other part of the problem all I can suggest is set up a bunch of POE Wheels targeting each log you need to monitor, populated in some way that suits you. Personally I'd just read the desired target locations in from a file.
36,107,351
I am attempting to update some data, but the data I need to update is part of columns I need to use to select the unique records. ``` import pandas as pd data = [{'subid':'123','grade':'K'},{'subid':'123','grade':'3rd'}, {'subid':'123','grade':'6th'}, {'subid':'456','grade':'1st'},{'subid':'456','grade':'3rd'},{'subid':'456','grade':'5th'}] df = pd.DataFrame(data) df ``` I am trying to use str.replace ``` df['grade'][df['subid']== '456'].str.replace('3rd','4th') ``` I am getting the following, but can't get the df to update. ``` 3 1st 4 4th 5 5th Name: grade, dtype: object df grade subid 0 K 123 1 3rd 123 2 6th 123 3 1st 456 4 3rd 456 5 5th 456 ``` Trying to get the following as the final df ``` grade subid 0 K 123 1 3rd 123 2 6th 123 3 1st 456 4 4th 456 5 5th 456 ``` Are there better approaches to updating?
2016/03/19
[ "https://Stackoverflow.com/questions/36107351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3920609/" ]
try this: ``` In [138]: df.loc[df['subid']== '456', 'grade'] = df.grade.replace({'3rd':'4th'}) In [139]: df Out[139]: grade subid 0 K 123 1 3rd 123 2 6th 123 3 1st 456 4 4th 456 5 5th 456 ```
31,226,392
I'm working on creating a simple mine sweeper game in java using JButtons. So far I have a code that creates a 20x20 grid of JButtons, but I am unsure of how I can get my bombs randomly assigned to multimple JButtons durring the game. Here is what I have written so far: **MineSweeper Class:** ``` import javax.swing.*; import java.awt.GridLayout; public class MineSweeper extends JFrame { JPanel p = new JPanel(); bombButton points[][]= new bombButton[20][20]; public static void main(String args[]){ new MineSweeper(); } public MineSweeper(){ super("Mine Sweeper Version: Beta"); setSize(400,400); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); p.setLayout(new GridLayout(20,20)); int y=0; int counter=0; while(counter<20){ for(int x=0;x<20;x++){ points[x][y] = new bombButton(); p.add(points[x][y]); } y++; counter++; } add(p); setVisible(true); } } ``` **bombButton Class:** ``` import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.net.URL; public class bombButton extends JButton implements ActionListener { ImageIcon Bomb,zero,one,two,three,four,five,six,seven,eight; public bombButton(){ URL imageBomb = getClass().getResource("Bomb.png"); Bomb= new ImageIcon(imageBomb); URL imageZero = getClass().getResource("0.jpg"); zero= new ImageIcon(imageZero); URL imageOne = getClass().getResource("1.jpg"); one= new ImageIcon(imageOne); URL imageTwo = getClass().getResource("2.jpg"); two= new ImageIcon(imageTwo); URL imageThree = getClass().getResource("3.jpg"); three= new ImageIcon(imageThree); URL imageFour = getClass().getResource("4.jpg"); four= new ImageIcon(imageFour); URL imageFive = getClass().getResource("5.jpg"); five= new ImageIcon(imageFive); URL imageSix = getClass().getResource("6.jpg"); six= new ImageIcon(imageSix); URL imageSeven = getClass().getResource("7.jpg"); seven= new ImageIcon(imageSeven); URL imageEight = getClass().getResource("8.jpg"); eight= new ImageIcon(imageEight); this.addActionListener(this); } public void actionPerformed(ActionEvent e){ switch(){ case 0: setIcon(null); break; case 1: setIcon(Bomb); break; case 2: setIcon(one); break; case 3: setIcon(two); break; case 4: setIcon(three); break; case 5: setIcon(four); break; case 6: setIcon(five); break; case 7: setIcon(six); break; case 8: setIcon(seven); break; case 9: setIcon(eight); break; } } int randomWithRange(int min, int max) { int range = Math.abs(max - min) + 1; return (int)(Math.random() * range) + (min <= max ? min : max); } } ``` As you can see I already have a randomizer set up, I just don't know how I should implement it. Should I use (X,Y) cordinates? How do I assign my bombs to random JButtons? Thnak you to all in advance!
2015/07/05
[ "https://Stackoverflow.com/questions/31226392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5070929/" ]
Create an `ArrayList<JButton>`, fill it with all your buttons, call `Collections.shuffle(..)` on the list, and then select the first N buttons to add mines to. Having said this, my real recommendation is to chuck all this and go the MVC route where your data model, including where the mines are located, and your GUI are completely distinct. [here are some of my prior musings on this problem from 2011](https://stackoverflow.com/a/7016492/522444).
68,339,438
Nested KVM virtualization should have a small overhead, but an Android emulator inside a VM should be usable. When I launch the Android emulator inside ubuntu 20.04 guest (on ubuntu 20.04 host), it warns me that I'm on a nested virtualization and thus it will be slow. But it's painfully low, not just slow. It takes 10 minutes to boot into Android and yes, all the systems are x86\_64, even the android image. I thought this had to do with OpenGL so I enabled OpenGL virtualization on my virt-manager and thigns are still slow. I tried the same thing on my Ryzen 7 2700x which has 16 cores, I gave all cores to the VM and passed an AMD gpu to it, and Android emulator is also painfully slow. Why?
2021/07/11
[ "https://Stackoverflow.com/questions/68339438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12276541/" ]
The problem is with QXL. Somehow it's slow on the new Ubuntu. Use VirtIO video and possibly 3D acceleration
35,649,159
I am new to Angular and need your help on an issue with the `ng-repeat` of my app. **Issue:** I have an html page (`event.html`) and in the corresponding controller of the file, I make a request to a firebase collection and update an array (`$scope.events`). The issue is that the data from firebase takes a few seconds to load and by the time data arrives to `$scope.events`, `ng-repeat` has already been executed and it displays an empty screen. The items are displayed correctly the moment I hit on a button in the HTML page (`event.html`). **Sequence of events:** I have a login page (`login.html`) where I enter a user name and phone number and I click on the register button. I've configured this click on the register button to go to the new state (`event.html`). Here is the controller code for `login.html`: ``` $scope.register = function (user) { $scope.user = user.name; $scope.phonenumber = user.phonenumber; var myuser = users.child($scope.user); myuser.set({ phone : $scope.phonenumber, Eventid : " ", name : $scope.user }) var userid = myuser.key(); console.log('id is ' +userid); $state.go('event'); } ``` The controller of `event.html` (the state: `event`) has the following code: ``` var ref = new Firebase("https://glowing-torch-9862.firebaseio.com/Users/Anson/Eventid/"); var eventref = new Firebase("https://glowing-torch-9862.firebaseio.com/Events"); var myevent = " "; $scope.events = []; $scope.displayEvent = function (Eventid) { UserData.eventDescription(Eventid) //UserData.getDesc() $state.go('myevents'); //console.log(Eventid); }; function listEvent(myevents) { $scope.events.push(myevents); console.log("pushed to array"); console.log($scope.events); }; function updateEvents(myevents) { EventService.getEvent(myevents); //console.log("success"); }; ref.once('value', function (snapshot) { snapshot.forEach(function (childSnapshot) { $scope.id = childSnapshot.val(); angular.forEach($scope.id, function(key) { eventref.orderByChild("Eventid").equalTo(key).on("child_added", function(snapshot) { myevents = snapshot.val(); console.log(myevents) // testing 26 Feb listEvent(myevents); updateEvents(myevents); }); }); }); }); $scope.createEvent = function () { $state.go('list'); } ``` `event.html` contains the following code: ``` <ion-view view-title="Events"> <ion-nav-buttons side="primary"> <button class="button" ng-click="createEvent()">Create Event</button> <button class="button" ng-click="showEvent()">Show Event</button> </ion-nav-buttons> <ion-content class="has-header padding"> <div class="list"> <ion-item align="center" > <button class= "button button-block button-light" ng-repeat="event in events" ng-click="displayEvent(event.Eventid)"/> {{event.Description}} </ion-item> </div> </ion-content> </ion-view> ``` The button `showEvent` is a dummy button that I added to the HTML file to test `ng-repeat`. I can see in the console that the data takes about 2 secs to download from firebase and if I click on the 'Show Events' button after the data is loaded, `ng-repeat` works as expected. It appears to me that when `ng-repeat` operates on the array `$scope.events`, the data is not retrieved from firebase and hence its empty and therefore, it does not have any data to render to the HTML file. `ng-repeat` works as expected when I click the dummy button ('Show Event') because a digest cycle is triggerred on that click. My apologies for this lengthy post and would be really thankful if any of you could give me a direction to overcome this issue. I've been hunting in the internet and in stackoverflow and came across a number of blogs&threads which gives me an idea of what the issue is but I am not able to make my code work.
2016/02/26
[ "https://Stackoverflow.com/questions/35649159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5846266/" ]
Once you update your events array call `$scope.$apply();` or execute the code that changes the events array as a callback of the `$scope.$apply` function ``` $scope.$apply(function(){ $scope.events.push(<enter_your_new_events_name>); }) ```
2,131,964
I am writing an application that needs to record video using DirectShow - to do this, I am using the interop library DirectShowLib, which seems to work great. However, I now have the need to get a callback notification as samples are written to a file, so I can add data unit extensions. According to the msdn documentation, in C++ this is done by implementing the [IAMWMBufferPassCallback](http://msdn.microsoft.com/en-us/library/dd376037%28VS.85%29.aspx) interface, and passing the resulting object to the [SetNotify](http://msdn.microsoft.com/en-us/library/dd376040%28VS.85%29.aspx) method of a pin's IAMWMBufferPass interface. So, I created a small class that implements the IAMWMBufferPassCallback interface from DirectShowLib: ``` class IAMWMBufferPassCallbackImpl : IAMWMBufferPassCallback { private RecordingPlayer player; public IAMWMBufferPassCallbackImpl(RecordingPlayer player) { this.player = player; } public int Notify(INSSBuffer3 pNSSBuffer3, IPin pPin, long prtStart, long prtEnd) { if (player.bufferPin == pPin && !player.firstBufferHandled) { player.firstBufferHandled = true; //do stuff with the buffer.... } return 0; } } ``` I then retrieved the IAMWMBufferPass interface for the required pin, and passed an instance of that class to the SetNotify method: ``` bufferPassCallbackInterface = new IAMWMBufferPassCallbackImpl(this); IAMWMBufferPass bPass = (IAMWMBufferPass)DSHelper.GetPin(pWMASFWriter, "Video Input 01"); hr = bPass.SetNotify(bufferPassCallbackInterface); DsError.ThrowExceptionForHR(hr); ``` No exception is thrown, indicating that the SetNotify method succeeded. Now, the problem is, that the Notify method in my callback object never gets called. The video records without a problem, except for the fact that the callback is not getting executed at all. Is it a problem with the way I am doing the interop?
2010/01/25
[ "https://Stackoverflow.com/questions/2131964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/114400/" ]
As Ignacio says, something may be overriding the php.ini setting. You can definitively set the timeout for that script using `set_time_limit` ``` set_time_limit(600); ``` You can also set it to 0, which removes any time restriction - although this is not best practice. 400 seconds is a huge amount of time for a query - have you looked into adding indexes on commonly used columns in your db?
2,048,271
I have a simple bootloader, which initializes and prepares SDRAM. Then it loads an application from the Flash and starts it at some address in the RAM. After the application has finished its execution, the system does restart. There is no system stack. Now, I would like this bootloader receives control back after an application finished its execution. The bootloader (let's call it OS) must also read an application's return code. How can an application return a value to the calling OS and how the calling OS gets control back? I suppose, it can be done using interrupts - OS has a special resident function joined with some interrupt and every application just calls this interrupt at the end of its own execution. But how can a return code be read by OS if there is no system stack?
2010/01/12
[ "https://Stackoverflow.com/questions/2048271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215571/" ]
Normally you would leave a return code in one or more registers, but since you're in control, you can leave it wherever you like! When an application is interrupted, the interrupt handling routine needs to save the application's state somewhere, which will probably mean copying from shadow registers to a predefined location in memory. If an application surrenders control back to the OS (through a software interrupt / sytem call) then you need to define your own calling convention for which registers arguments are placed in, and the event handler needs to follow this before passing control back to the OS. You probably want to make the calling convention match up with that of your c compiler as much as possible, to keep things easy for yourself.
54,051,762
A user predicts a team winner for a given match. Depending on which team was predicted and on whether the prediction is correct or not, different score is awarded based on the chosen team’s odds. Consider the following two SQL tables and their fields. [![Matches table](https://i.stack.imgur.com/mnwmD.png)](https://i.stack.imgur.com/mnwmD.png) and [![enter image description here](https://i.stack.imgur.com/HUqbC.png)](https://i.stack.imgur.com/HUqbC.png) I would like a query which sums up all users odds if the predictions were correct (meaning `predictions.team_id` needs to match with `matches.match_winner`) for tournament ID 30. The end result should look like this [![enter image description here](https://i.stack.imgur.com/ELLdq.png)](https://i.stack.imgur.com/ELLdq.png) Matthew predicted correctly match 5 and 7 (odds 3.4 + 2.4), total 5.8 points. Neville predicted correctly match 7 and 9 (odds 2.4 + 2.0), total 4.4 points
2019/01/05
[ "https://Stackoverflow.com/questions/54051762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3861691/" ]
Use an aggredated query with a conditional `SUM` like : ``` SELECT p.username, SUM(CASE WHEN m.match_winner = m.team_a THEN m.team_a_odds ELSE m.team_b_odds END) FROM predictions p INNER JOIN matches m ON p.match_id = m.id AND p.team_id = m.match_winner WHERE p.tournament_id = 30 GROUP BY p.username ```
22,899,868
Currently I'm using auto layout with storyboard to dynamically resize custom `UITableViewCell`'s. Everything is working as it should except there is memory leak when scrolling. I know the problem is from calling ``` [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; ``` from inside ``` - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath ``` My question is this, what would be the best way to create a reference cell? How to load a cell from storyboard without `dequeueReusableCellWithIdentifier`? And is it ok to maybe call `dequeueReusableCellWithIdentifier` from `viewDidLoad` and create a reference cell as a property? I need reference cell for sizing purposes. Thanks for any help.
2014/04/06
[ "https://Stackoverflow.com/questions/22899868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3190423/" ]
Regarding how to create reference cell (see original question), there are couple of options as I can see: 1. create a custom cell with XIB, great article here -> [a link](http://useyourloaf.com/blog/2012/06/07/prototype-table-cells-and-storyboards.html)! * this was pointed out to me by @smileyborg, thanks! 2. create your custom cell in code, along with constraints. 3. create your custom cell in storyboard as prototype cell * after that there are 2 options: + drag and drop custom cell from table view to the storyboard scene, as a top level nib object (not part of the view hierarchy), and simply create outlet to it. + copy custom cell and paste it to the storyboard scene. When using it this way, there is no need to register original cell with table for dequeue. + minor problem with both approaches is that once you drag and drop custom cell to the storyboard scene, you will not be able to see it visually and arrange UI. * great article here -> [a link](https://stackoverflow.com/questions/9498010/custom-views-with-storyboard)! Thanks everyone for help!
393,491
I recently ran a full update on my Manjaro-System, afterwards I opened QGIS and got the following message. > > qgis: error while loading shared libraries: libproj.so.15: cannot open shared object file: No such file or directory > > > I solved this by reinstalling QGIS to the current LTR (3.16.5). However, when I opened my current project containing a PostGIS-Layer it could not connect to this layer. I went into pgAdmin and checked. The database is still there and working. I can open any table, that has no geometry/geography column, but when I try to display the data of the table, that is not connecting in QGIS (containing one geography column) I get the following error: > > ERROR: could not load library "/usr/lib/postgresql/postgis-3.so": libproj.so.15: cannot open shared object file: No such file or directory SQL state: 58P01 > > > I checked online and found [PostGIS 2.5 error while compiling from source on Ubuntu Server 18.04](https://gis.stackexchange.com/questions/297175), indicating, that I may have to update my `proj` package. I checked and apparently it is the outdated version 6.3.2, which is still in the package manager. I manually updated to 8.0.0-1 but this didn't solve the problem and also caused the same QGIS error in the console again. Currently the version setup is: 1. QGIS: Version 3.16.5 2. Postgres: Version 12.6-1 3. PostGIS: Version 3.0.3-1 4. proj: Version 6.3.2-1 5. Manjaro: KDE-Plasma 5.21.3 6. Kernel: 4.19.183-1-Manjaro I think it has something to do with `proj` but I don't know, what exactly is wrong and don't want to dabble without a clue.
2021/04/10
[ "https://gis.stackexchange.com/questions/393491", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/39195/" ]
Seems like you have more than on proj library installed. This is known as a cause of trouble. You have to choose one proj version and get rid of other dangling proj libs than you might have around. I'm not familiar with manjaro. Use `find` or other similar tool to find out all `libproj` files, like: ``` find /usr/lib/ -name libproj.so'*' -print ``` You you find other version that were not the ones installed by your proj package version 6.3.2-1, just remove them. What is your GDAL version and which PROJ version it depends? ### Check GDAL dependency To know which proj version GDAL depends on, we can use `ldd`. ``` ldd $(which gdalinfo) ``` To get just the output we want: ``` ldd $(which gdalinfo) | grep -E 'proj|geos' libgeos_c.so.1 => /usr/lib/x86_64-linux-gnu/libgeos_c.so.1 (0x00007f6cae6e8000) libproj.so.15 => /usr/local/lib/libproj.so.15 (0x00007f6caa184000) libgeos-3.7.1.so => /usr/lib/x86_64-linux-gnu/libgeos-3.7.1.so (0x00007f6ca7d42000) ``` ### Check Postgis dependency The same works to know the exact Postgis dependencies. Looking at the error you got, you (PostgreSQL) are using `/usr/lib/postgresql/postgis-3.so`. Check this: ``` ldd /usr/lib/postgresql/postgis-3.so ```
13,108,522
While building an application using AngularJs I asked my self if the following is good practice I have "AppController" and every other controller is child of it. AppController has something like this. ``` $scope.layout = { sidebar: false, searchbar: true}; ``` Now, child controllers should be able to change these values: ``` $rootScope.sidebar = true; ``` In this case, my child module is totally dependent on root controller and if I want this child controller works inside some other application I have to make sure parent controller of that other app always have $scope.layout object. Is this good practice? Would it be better to build layout module used by both, parent and child controllers? Like code bellow: ``` angular.module("app.ui", []) .factory("Layout", [function(){ var _sidebar = false; var searchbar = true; var sidebar = function(flag){ if(flag !== undefined) _sidebar = flag; return _sidebar; } var searchbar = function(flag){ if(flag !== undefined) _searchbar = flag; return _searchbar; } return { sidebar : sidebar, searchbar : searchbar } }]) ```
2012/10/28
[ "https://Stackoverflow.com/questions/13108522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155639/" ]
Whilst there may be other architectural approaches to what you want to do (e.g. look into the documentation on the *scope* property of directive declarations and its facilities for binding specific properties in the parent scope using @, = and &), generally Services are indeed a good option for sharing access to common data. You could simplify it a bit, if you don't have extra logic that must happen when the values are updated: ``` angular.module("app.ui", []) .service("Layout", function() { this.sidebar = false; this.searchbar = true; }) ``` If you inject this service into your controllers and add it to their scope, you can update it and listen for changes like this: ``` .controller("AppCtl", function($scope, Layout) { $scope.Layout = Layout; // Method called by a search button, say $scope.search = function() { Layout.searchbar = true; } $scope.$watch("Layout.searchbar", function(newVal, oldVal) { // Do something in this scope if value has been changed from elsewhere }); }); ```
12,943
Here is another easier riddle to solve but I hope you enjoy the rhymes. > > Here I am in my perfect state. > > > Friends of mine in some way relate. > > > But what confines me isn't straight. > > > Is it none, one, or many? That's to debate! > > > If you still don't know, it's not too late. I gave some hints, but you're doing great! Now don't be shy and participate, But remember not to over concentrate! What is it, and what is the 'debate' about? Hint #1: > > Don't concentrate on 'perfect state' so much as the word state was more so for the rhyme. I would focus more on line 3. > > > Hint #2: > > That you're in my realm, don't postulate! > > > Hint #3: > > To one number I associate. > > > Note: Hint #2 might not help too much (or be 100% accurate), but I was able to rhyme it :) --- *If you enjoyed this riddle, some of my other rhyming riddles can be found [here](https://puzzling.stackexchange.com/search?q=%5Brhyme%5D%20user%3A11244%20is%3Aquestion)*.
2015/04/29
[ "https://puzzling.stackexchange.com/questions/12943", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/11244/" ]
The answer is: > > **A circle** > > > Here I am in my perfect state. > > A circle can be 'perfectly round' > > > Friends of mine in some way relate. > > Other shapes can be round, and share many of the same properties (area, perimeter etc.) > > > But what confines me isn't straight. > > The circumference(perimeter) of a circle isn't straight. > > > Is it none, one, or many? That's to debate! > > How many edges does a circle have: zero, one, infinite? Some people often argue over this number. > > > Hint #2: ``` That you're in my realm, don't postulate! ``` > > Circles are 2 dimensional, and we live in the 3rd dimension. (We couldn't live in the 2nd dimension) > > > Hint #3: ``` To one number I associate. ``` > > π is associated with circles. > > >
99,819
Consider this example: ``` team <- rep(c("A","B","C"), times=c(7,4,10)) trip <- rep(NA,length(team)) for(i in 1:length(unique(team))){ trip[which(team==unique(team)[i])] <- 1:days[i] } obs < -c(rnorm(days[1],100,30), rnorm(days[1],100,5), rnorm(days[1],100,15)) data <- data.frame(team, trip, obs) boxplot(obs~team, data) ``` It is pretty clear that the variance in each team is different, but the mean is similar. How can I infer this statistically? How can I compare intra-group (within-group) variance with the inter-group (between-group) variance?
2014/05/23
[ "https://stats.stackexchange.com/questions/99819", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/46061/" ]
*I'm not sure if I completely follow your thinking, but I can update this if it isn't what you're looking for.* In general we compare the intra-group variance with the inter-group variance with the [ANOVA](http://en.wikipedia.org/wiki/Analysis_of_variance). (By the way, the more usual terms are within-group variance and between-group variance.) The standard use of the ANOVA may not be what you are after, though. It is used, ultimately, to determine if the means are the same (that's the inter-group variance part). In addition, it assumes that the group variances (intra-) are the same in order for the check of the inter-group variance to be valid. If you want to know if the intra-group variances are the same, you can use Levene's test, which is an ANOVA on the absolute differences of each point from its group mean. In R, the function is `leveneTest(obs, team, center=mean)` in the car package ([documentation](http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/car/html/leveneTest.html)). For a slightly more robust version, you can get the absolute value of the differences from the *median* and run an ANOVA on them instead. In that case, it is called the [Brown-Forcythe test](http://en.wikipedia.org/wiki/Brown%E2%80%93Forsythe_test). That is actually the default for `leveneTest` (ironically), so you can just drop the `center=mean` part. I discuss these tests here: [Why use Levene's test of equality of variance rather than F ratio?](https://stats.stackexchange.com/a/24024/7290) If you believe you have substantial heteroscedasticity, but want to test if your means differ as well, there are a number of methods available. I discuss them here: [Alternatives to one-way ANOVA for heteroscedastic data](https://stats.stackexchange.com/a/91881/7290).
3,416,893
Like the title says I have expression : $xy+xz+yz$. With $x\,\,,\,\,y\,\,,\,\,z\,\,\in \mathbb{C}$. I found this linear transformation : $(x\,\,,\,\,y\,\,,\,\,z)\mapsto (u\,\,,\,\,v\,\,,\,\,w\,\,) : \mathbb{C} \mapsto \mathbb{C}$ : $ x=-u-i\frac{1}{2}\sqrt{2}v $ $ y=-i\frac{1}{2}\sqrt{2}v-w $ $ z=\frac{1}{2}u +\frac{1}{2}w $ . which gives me : $xy+xz+yz \mapsto u^2+v^2+w^2$ My question: What is the most general form of linear transformations that map $xy+xz+yz$ to $u^2+v^2+w^2$? Hope someone can help me with this, I don't see how to proceed. Thanks in advance! NB: Edited question after receiving comments and answers to reflect the fact that we're working in $\mathbb{C}$.
2019/10/31
[ "https://math.stackexchange.com/questions/3416893", "https://math.stackexchange.com", "https://math.stackexchange.com/users/364527/" ]
Here is not the most general solution but a way to determine logically an adequate transformation. In a first step, a linear transformation with real coefficients can be used on the initial quadratic form (reduction to proper axes), using a kind of Gauss reduction : $$\left(\frac{x+y+2z}{2}\right)^2-\left(\frac{x-y}2\right)^2-z^2\tag{1}$$ which has the form $$U^2-V^2-W^2\tag{2}$$ exhibiting a signature (+,-,-) (see an identical development in (<https://math.stackexchange.com/q/1714385>)). It is important to remark that (2) is as general as (1), therefore can be substituted to it. In a second step, if we set $U=u$, $V=iv$ and $W=iw$ in (2); we get the desired expression: $$u^2+v^2+w^2\tag{3}$$ Remark : (1) shows that level sets $xy+yz+zx=k$ are hyperboloids of 2 sheets.
4,330,074
According to MPI 2.2 standard Section 4.1: to create a new data type we have to define a typemap which is a sequence of (type, displacement) pairs. The displacements *are not required* to be positive, increasing, nor distinct. * Suppose I define a typemap of the following sequence: {(double, 0), (char,0)} this does not make sense, yet possible, how can a standard provide so much flexibility?
2010/12/01
[ "https://Stackoverflow.com/questions/4330074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337194/" ]
Build the string you intend to pass. So instead of ``` example <- sqlQuery(myDB,"SELECT * FROM dbo.my_table_fn (x)") ``` do ``` example <- sqlQuery(myDB, paste("SELECT * FROM dbo.my_table_fn (", x, ")", sep="")) ``` which will fill in the value of `x`.
52,177
I am trying to download the contents of a ROM chip [following this tutorial](http://www.nycresistor.com/2012/07/07/stick-a-straw-in-its-brain-and-suck-how-to-read-a-rom/) however the chip is surface mounted and I can't remove it to put it in a breadboard. I don't want to solder wires to the chip but there has to be a way of attaching them other than holding loose wires to the pins. Specifically [This chip](http://www.datasheetcatalog.org/datasheet/Xicor/mXyyzyrw.pdf)
2012/12/25
[ "https://electronics.stackexchange.com/questions/52177", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/17231/" ]
**Update** Here is a good list of micro grabbers/test clips (or whatever you want to call them): <http://www.jameco.com/jameco/products/prodds/684481-ds01.pdf> --- As mentioned, it would be helpful if we knew the board and the chip. But without that information here is what I recommend. First off, you need to buy some [micro grabbers](http://www.pomonaelectronics.com/pdf/d6490_100.pdf). These will allow you to connect to individual pins on medium sized surface mount components (usually around .5mm pitch). They look like this: ![Micro grabber](https://i.stack.imgur.com/OaF89.jpg)![micrograbber](https://i.stack.imgur.com/5Yafh.jpg) Now if you power to board and listen in on the bus, you can gather needed information like i2c address, etc. and see how active it is. From here you may be able to dump the memory without any ill effects. Otherwise you can use [my method for removing surface mount parts](https://electronics.stackexchange.com/a/51620/9730) to **only remove the data communication pins**. Place something non-conductive between the pin and the pcb board so it won't make contact. Then read out the memory like you planned. This will make it much easier for you to resolder the two or so pins you removed back on, and is easier on the chip than completely removing it and trying to power it, etc. If you don't have or want to get micro-grabbers, you can very carefully place a ~22 gauge solid wire under the pin but on top of the non-conductive material, so that the wire is making contact with the pin. This will be hard to keep from disconnecting but with a bit of work you will get the hang of it. If at all possible, I would stay away from soldering wires directly to the pins!
8,751,396
I need a regular expression to match this URL to enable URL rewriting. <http://www.somewhere.com/index.php?route=common/home> This is an OpenCart website. UPDATE: I am trying to use the regular expression to perform URL Rewriting on IIS7. The first part of the URL doesn't need exact domain name matching but I need the to get a resulting URL as follows <http://www.somewhere.com/common/home>
2012/01/05
[ "https://Stackoverflow.com/questions/8751396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Tested in Velocity 1.6. ``` #foreach ($element in $string.split(";")) $element #end ```
24,850,618
When I create a new multi-dimensional array (in this case an array of objects) ``` public Block[][] block = new Block[50][70]; ``` What is the difference between: ``` block.length ``` and ``` block[0].length ``` and then what is ``` block[1].length ```
2014/07/20
[ "https://Stackoverflow.com/questions/24850618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3857871/" ]
If you think of `Block[][]` as being rows and columns of `Block`, and each row being a `Block[]` of columns, and an array of rows would be a `Block[][]`, then: ``` block.length // the number of rows block[0].length // the number of columns on row 0 block[1].length // the number of columns on row 1 // etc ```
32,320,879
Say I have a series of commits after origin/master: ``` 5------4--------3-------2--------1 (master) (HEAD) ``` I want to squash 4 through 1 together into one commit, with the changes in 1 taking precedence in case of any conflict. Meaning the changes introduced in 1 will stay in the squash, and override any conflicts. (And if there are any new changes or files introduced in 4-2 which 1 does not conflict with, then those changes will stay) How can I do this?
2015/08/31
[ "https://Stackoverflow.com/questions/32320879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1502780/" ]
*Code stub* ``` int count = countPrevElementsWithSameName(node); if (count != 0 || hasNextElementWithSameName(node)) builder.append("[").append(count + 1).append("]"); ``` *Helper methods* ``` private static final boolean hasNextElementWithSameName(Node node) { String name = node.getNodeName(); for (Node next = node.getNextSibling(); next != null; next = next.getNextSibling()) if (next.getNodeType() == Node.ELEMENT_NODE) // only look at elements return next.getNodeName().equals(name); // stop on first element after "node" return false; } private static final int countPrevElementsWithSameName(Node node) { String name = node.getNodeName(); int count = 0; for (Node prev = node.getPreviousSibling(); prev != null; prev = prev.getPreviousSibling()) if (prev.getNodeType() == Node.ELEMENT_NODE) { // only look at elements if (! prev.getNodeName().equals(name)) break; // stop when element name changes count++; // count elements of same name as "node" } return count; } ```
3,672,959
I ran into a bit of confusion when applying the exponent rule: $x^a/x^b = x^{a-b}$ Then when $4^x/2^x$ why does it equal $2^x$ if we apply the rule above then wouldn't it be: $(4/2)^{x-x}$ ? Thank you!
2020/05/13
[ "https://math.stackexchange.com/questions/3672959", "https://math.stackexchange.com", "https://math.stackexchange.com/users/684991/" ]
If S is convergent then $e^{-n^2x}\to 0$, which it only does if $x>0$. If $x\le 0$ then $-n^2x\ge 0$ and hence $\sum\_{n\in\mathbb{N}} e^{-n^2x}\ge \sum\_{n\in\mathbb{N}} e^{0}= \sum\_{n\in\mathbb{N}}1=\infty$. (contraposition)
163,807
We have two Drupal environments: dev and prod. We use dev to stage content before it goes to production. We also have prod, where content is created and then have to manually re-create those changes back on dev. Is there a way to combine/merge content changes between the two environments simply/easily? This is purely content (i.e. nodes) and not code or configuration.
2015/06/30
[ "https://drupal.stackexchange.com/questions/163807", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/21770/" ]
Just use `views-view-unformatted--(your view block name).html.twig`. Eg. If your view name is Slideshow, use views-view-unformatted--slideshow.html.twig This is a good reference point - <http://redcrackle.com/blog/drupal-8/theme-views-templates>
24,199,395
I just passed the data from one ViewController to another viewController using below process I want to display the data in UITextField in SecondViewController. Passed value must be a int value. ``` [[NSNotificationCenter defaultCenter] postNotificationName:@"sendString" object:userID]; ``` Change viewDidload method in which you want to get string. ``` -(void)viewDidLoad: ``` { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ThingYouWantToDoWithString:) name:@"sendString" object:nil]; } ``` - (void)ThingYouWantToDoWithString:(NSNotification *)notification{ passedUserID = [notification object]; NSLog("%@", passedUserID); ``` }
2014/06/13
[ "https://Stackoverflow.com/questions/24199395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` @property(nonatomic,assign) NSInteger userid; ``` in both the view controllers then ``` SecondViewController *svc=[[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil]; svc.passedUserID=userId; [self.navigationController pushViewController:svc animated:YES]; NSLog(@"%@",passedUsrID); ``` and don't forget mention %d for integer.
33,839,685
``` #include <iostream> #include <string> using namespace std; class rom2dec { public: void roman(); int convert(); void print(); void get(); private: int M, D, C, L, X, V, I; char romanNumeral; }; void rom2dec::roman() { M = 1000; D = 500; C = 100; L = 50; X = 10; V = 5; I = 1; } int rom2dec::convert() { if(romanNumeral == 'I' || 'i') { cout << 1; } else if(romanNumeral == 'V' || 'v') { cout << 5; } else if(romanNumeral == 'X' || 'x') { cout << 10; } else if(romanNumeral == 'L' || 'l') { cout << 50; } else if(romanNumeral == 'C' || 'c') { cout << 100; } else if(romanNumeral == 'D' || 'd') { cout << 500; } else if (romanNumeral == 'M' || 'm') { cout << 1000; } else if(romanNumeral != 'I' && romanNumeral != 'i' && romanNumeral != 'V' && romanNumeral != 'v' && romanNumeral != 'X' && romanNumeral != 'x' && romanNumeral != 'L' && romanNumeral != 'l' && romanNumeral != 'C' && romanNumeral != 'c' && romanNumeral != 'D' && romanNumeral != 'd' && romanNumeral != 'M' && romanNumeral != 'm') { cout << "Error! Not a valid value!" << endl; } return romanNumeral; } void rom2dec::print() { cout << romanNumeral << endl; } void rom2dec::get(){ } int main() { char romanNumeral; cout << "Please enter a number in Roman numerals to be converted: " << endl; cin >> romanNumeral; return 0; } ``` I get no errors when I build the program, but when I debug and try to convert a Roman numeral to a decimal I get no decimal. All suggestions welcome and if there is a simpler way to write the last else if please let me know. Thanks.
2015/11/21
[ "https://Stackoverflow.com/questions/33839685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5369934/" ]
The `findRoot()` function does not return anything after making the first recursive call. What you want is the following: ``` if (node.pId !== '') { return findRoot(getParentNode(node.pId, treeDataOld)); } ```
61,316,049
Good morning! I try to COUNT rows in my table 'audit' in column 'audit\_process\_completed' based on the months. The value in the column 'audit\_process\_completed' is a date format: YYYY-MM-DD. To get the COUNT of the current month i use the code below. Is there a function or possibility to say something like: "MONTH(CURDATE(**-1**)) and so on? I would like to have the COUNT for each last six months. Edit: I have from another function the month value (eg. January -> 01) available. May be i can use this value for a select function. Expected output is the number of rows where the date in column 'audit\_process\_completed' is in the selection. Development Enviroment: MySQL Xampp Local ``` SELECT count(*) FROM `audit` WHERE uid = 10 AND cid = 12345 AND MONTH(`audit_process_completed`) = MONTH(CURDATE()) AND YEAR(`audit_process_completed`) = YEAR(CURDATE()) ```
2020/04/20
[ "https://Stackoverflow.com/questions/61316049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13024256/" ]
If you just return `$0`, that adds a level of optionality The return value of ```swift [RequestParameter.param1: "value1", .param2: nil] ``` is a `[RequestParameter: String?]`, which introduces double-optionality. Either do this: ```swift extension Dictionary { func nilFiltered<Wrapped>() -> [Key: Any] where Value == Wrapped? { compactMapValues { $0 } } } ``` or if you don't actually need `Any`, avoid that rubbish! ```swift extension Dictionary { func nilFiltered<Wrapped>() -> [Key: Wrapped] where Value == Wrapped? { compactMapValues { $0 } } } ``` Here's an alternative that I don't like. ```swift extension Dictionary { func nilFiltered() -> [Key: Any] { compactMapValues { if case nil as Value? = $0 { return nil } return $0 } } } ```
2,068,731
The answer to this question is $10 \choose 6$. However, I find this odd. Why would it be a combination in this case and not a permutation? Ordering does not matter in combinations from my understanding, this would mean that **$001 = 010$**, which seems counterintuitive. I do not understand why I have to use combinations for this problem. -**edit**- To clarify the issue, when I have two people {Bob, Alice}. I can only make 1 combination, since {Bob, Alice} and {Alice, Bob} are the same. However in a bitstring of two, I can have 01 and 10, wich are not the same.
2016/12/22
[ "https://math.stackexchange.com/questions/2068731", "https://math.stackexchange.com", "https://math.stackexchange.com/users/401303/" ]
A bit string of length 10 with 6 zeros can be described by a list of the 6 "places" where the zeroes sit. This involves choosing 6 numbers from the 10 possible places, hence 10 choose 6.
17,811,136
I am new to c# - I want to trigger button click event on pressing enter. My code not working properly - issue is that when i press enter on submitting some value, it displays messagebox which it should show but on pressing Enter for OK button of Messagebox, it automatically triggers button click event again even i don't press enter or enter any other value. ``` public partial class Form1 : Form { int n1, n2 = 0; private static readonly Random getrandom = new Random(); private static readonly object syncLock = new object(); public int GetRandomNumber(int min, int max) { lock (syncLock) { // synchronize return getrandom.Next(min, max); } } public int tQuestion() { n1 = GetRandomNumber(2, 11); n2 = GetRandomNumber(2, 11); string tQues = n1 + " x " + n2 + " = "; label1.Text = tQues; return 0; } public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { tQuestion(); } private void label1_Click(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { textBox1.KeyDown += new KeyEventHandler(tb_KeyDown); } public void button1_Click(object sender, EventArgs e) { string tAns = textBox1.Text; int answer = n1 * n2; string tOrgAns = answer.ToString(); if (tAns == tOrgAns) MessageBox.Show("Your answer is Corect", "Result", MessageBoxButtons.OK,MessageBoxIcon.Exclamation ); else MessageBox.Show("Your answer is WRONG", "Result", MessageBoxButtons.OK, MessageBoxIcon.Stop); textBox1.Text = ""; textBox1.Focus(); tQuestion(); } static void tb_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { button1_Click(sender, e); } } ``` Moreover, code only works if i remove `static` from `static void tb_KeyDown(object sender, KeyEventArgs e)` - otherwise it gives error: > > An object reference is required for the non-static field, method, or > property > > > Please help me - i am new to c# & .Net
2013/07/23
[ "https://Stackoverflow.com/questions/17811136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You are calling while textbox is focused. Better option is to create a separate function and call that from both. I have made changes to your code. It's working for me. You need to link `tb_keyDown` event with `keyDown` property in Textbox Properties. Try this code: ``` public partial class Form1 : Form { int n1, n2 = 0; private static readonly Random getrandom = new Random(); private static readonly object syncLock = new object(); public int GetRandomNumber(int min, int max) { lock (syncLock) { // synchronize return getrandom.Next(min, max); } } public int tQuestion() { n1 = GetRandomNumber(2, 11); n2 = GetRandomNumber(2, 11); string tQues = n1 + " x " + n2 + " = "; label1.Text = tQues; return 0; } public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { tQuestion(); } private void label1_Click(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { //make it empty. You need to attach tb_KeyDown event in properties } public void button1_Click(object sender, EventArgs e) { CheckAnswer(); } void tb_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { CheckAnswer(); } } private void CheckAnswer() { string tAns = textBox1.Text; int answer = n1 * n2; string tOrgAns = answer.ToString(); if (tAns == tOrgAns) MessageBox.Show("Your answer is Corect", "Result", MessageBoxButtons.OK,MessageBoxIcon.Exclamation ); else MessageBox.Show("Your answer is WRONG", "Result", MessageBoxButtons.OK, MessageBoxIcon.Stop); textBox1.Text = ""; textBox1.Focus(); tQuestion(); } } ```
40,178,843
I have placed the following CSS code to make the placeholder text 'disappear' on focus. It works for the first (4) fields of the form, however for the large message box it does not seem to be working! ``` input:focus::-webkit-input-placeholder { color:transparent; } input:focus:-moz-placeholder { color:transparent; } /* Firefox 18- */ input:focus::-moz-placeholder { color:transparent; } /* Firefox 19+ */ input:focus:-ms-input-placeholder { color:transparent; } /* oldIE ;) */ ``` The URL is <http://dfb.a2c.myftpupload.com/products/garment-conveyor/> and the form is at the bottom of the page! Any help or suggestions as to why the 'How can we help?' section of the form does not seem to be affected by the above code! Thanks -EDIT- It seems to be working in Internet Explorer just not Google Chrome!
2016/10/21
[ "https://Stackoverflow.com/questions/40178843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use "screen". "Screen is a console application that allows you to use multiple terminal sessions within one window. The program operates within a shell session and acts as a container and manager for other terminal sessions, similar to how a window manager manages windows." (ref: [info](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-screen-on-an-ubuntu-cloud-server)) ``` apt-get install screen # Create a session called "my_app" screen -S my_app # Now you are inside another shell xvfb-run npm start # After that, you can detach the screen or close the connection ``` When you want to connect again to the screen, you must use reattach option `-r`. ``` screen -r my_app ``` To list active screens: ``` screen -ls ``` More options and info about `screen` command: <https://www.rackaid.com/blog/linux-screen-tutorial-and-how-to/>
20,555,212
I have HTML table. This is one of the rows: ``` <tr class="mattersRow"> <td colspan="4"> … </td> <td class="editableCell qbmatter" colspan="14"> … </td> <td class="editableCell workDate" colspan="4"> … </td> <td class="editableCell hours" colspan="2"> … </td> <td class="editableCell person" colspan="6"> … </td> <td class="rate" colspan="2"> … </td> <td class="editableCell amount" colspan="4"> … </td> <td align="center"> <input id="check4" type="checkbox"></input> </td> </tr> ``` Last column contains check box. When I check/uncheck it I want to add/remove css class for this row. ``` $("input[type=checkbox]").click(function () { if ($(this).is(':checked')) { // Mark this Row Yellow $(this).closest('tr').addClass('warning'); } else { // Remove Yellow mark and put back danger if needs $(this).closest('tr').removeClass('warning'); } }); ``` This class makes whole row Yellow color. Basically I want to do this with some effect. For example when I uncheck, this "Yellow" is falling down... How to do this in jQuery? Is it possible?
2013/12/12
[ "https://Stackoverflow.com/questions/20555212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2348899/" ]
You can do this with CSS but it will only function in modern browsers that support CSS `transitions`: ``` tr { -webkit-transition : background-color 500ms ease-in-out; -moz-transition : background-color 500ms ease-in-out; -ms-transition : background-color 500ms ease-in-out; -o-transition : background-color 500ms ease-in-out; transition : background-color 500ms ease-in-out; } ``` Here is a demo: <http://jsfiddle.net/eh3ER/1/> Note: This is only to fade in/out the color, doing something like a "push" or "pull" animation will require multiple elements (I believe). Also, here is a great resource for browser support on many features: <http://caniuse.com/#feat=css-transitions> (this link will take you directly to CSS `transitions`)
29,468,500
Requirement: 1) creating split zips file in multiple segments(say size - 1 GB/500 MB), so that they can be downloaded through browser. The total zip volume of all the segments could exceed 10 GB 2) the zip content could be multiple files or a folder containing sub folders and files 3) the content of the file are read from Cloud in the form of stream. The meta information for the files(like folder hierarchy) are locally available I am using DotNetZip library to achieve the task. The code is as following: ``` long length = default(long); Stream fileReadStream; long Space = default(long); string tempZipFile = string.Empty; FileZipStatus oldStatue = new FileZipStatus(); byte[] Buffer = new byte[1024 * 1024]; if (zipFileName != null && !zipFileName.ToUpper().EndsWith(".ZIP")) zipFileName += ".zip"; string strTempFolder = ""; using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { try { strTempFolderPath = tempZipOutPutFilePath + "\\"; string strTempFolderName = DateTime.Now.Ticks.ToString(); strTempFolder = strTempFolderPath + strTempFolderName; if (userFileList.Count > 0) { if (Directory.Exists(strTempFolder)) { Directory.Delete(strTempFolder); } Directory.CreateDirectory(strTempFolder); } foreach (UserFile userFile in userFileList) { WebResponse response = null; try { WebRequest request = null; IDictionary<string, object> _dictionary = new Dictionary<string, object>(); /// First FileSystemEnum fileSysEnum = FileSystemBase.GetFileSystemEnumByStorageId(userFile.StorageId); IFileSystemLib ifileSystemLocal = FileSystemFactory.GetSpecificInstance(fileSysEnum); fileReadStream = ifileSystemLocal.GetFile(userFile.FilePath, userFile.GuidName, ref request, ref response, _dictionary); long filesize = default(long); long.TryParse(ifileSystemLocal.GetFileContentLength(userFile.FilePath, userFile.GuidName).ToString(), out filesize); Space = (Space > default(long)) ? (Space + filesize) : filesize; //Now we have to store the data, so that we must access the file int dataToRead; FileStream writeStream = new FileStream(strTempFolder + "\\" + userFile.FileName, FileMode.Create, FileAccess.Write); while ((dataToRead = fileReadStream.Read(Buffer, 0, Buffer.Length)) > 0) { writeStream.Write(Buffer, 0, dataToRead); } writeStream.Close(); zip.AddFile(strTempFolder + "\\" + userFile.FileName, userFile.RelativePath); fileReadStream.Close(); } catch (Exception ex) { LogManager.Trace(ex, "ZIpping Block - ZIPFileName", zipFileName + "File to zip" + userFile.GuidName); } finally { if (response != null) response.Close(); } } } catch (Exception ex) { _currentStatus = FileZipStatus.NotAvailable; oldStatue = UpdateZipStatus(ObjectZipID, Space, FileZipStatus.Failed); throw ex; } finally { } try { zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G"); zip.MaxOutputSegmentSize = 200 * 1024 * 1024; // 200 mb zip.Save(strTempFolderPath + "\\" + zipFileName); oldStatue = UpdateZipStatus(ObjectZipID, Space, FileZipStatus.Available); length = new FileInfo(strTempFolderPath + "\\" + zipFileName).Length; _currentStatus = FileZipStatus.Available; // deleting temp folder Directory.Delete(strTempFolder, true); } catch (Exception ex) { _currentStatus = FileZipStatus.NotAvailable; oldStatue = UpdateZipStatus(ObjectZipID, Space, FileZipStatus.Failed); length = default(long); throw ex; } } ``` There are a **limitation of the DotNetZip libray** used in the above code. It either needs a) files saved on disk as input. In that case folder hierarchy information could be passed for each file. or 2) if stream is passed as input, folder hierarchy information could NOT be passed for file. I need to pass in the folder hierarchy information for each file as well as read the input from stream. As the zip content could be huge(could exceed 10 GB), do not want to save the files on temporary storage in web server. Can Anyone help like how to pass folder hierarchy when creating zip file? thanks
2015/04/06
[ "https://Stackoverflow.com/questions/29468500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/728750/" ]
i got the solution. here is the code ``` private void button2_Click(object sender, EventArgs e) { using (SqlConnection sqlConn = new SqlConnection(@"Data Source=BBATRIDIP\SQLSERVER2008R2;Initial Catalog=test;Integrated Security=True")) { string query = String.Format(@"SELECT [FilePath],[FileName],[FileData] FROM [TestTable]"); SqlCommand cmd = new SqlCommand(query, sqlConn); cmd.Connection.Open(); System.IO.MemoryStream memStream = null; ZipFile zip = new ZipFile(); zip.MaxOutputSegmentSize = 1024 * 1024; // 1MB each segment size would be // the above line would split zip file into multiple files and each file //size would be 1MB using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { byte[] data = (byte[])reader["FileData"]; memStream = new System.IO.MemoryStream(data); string strFile = reader["FilePath"].ToString() + "\\" + reader["FileName"].ToString(); ZipEntry ze = zip.AddEntry(strFile, memStream); } } zip.Save(@"e:\MyCustomZip.zip"); memStream.Dispose(); MessageBox.Show("Job Done"); // here u can save the zip in memory stream also there is a overload insteaa of saving in HD } } ```
271,163
I'm not sure that this is entirely on-topic, but I'll try to make it so. I have an online service (API) and an Android application that uses it for *all actions in the app*. At the current moment, nothing is stored locally, so I have to depend on the API being online, and would like to warn the user when it's not (for whatever reason). I'm wondering what the preferred method of checking availability is. As this is the first time I've ever done this, I've tried to do my research and have come up with three potential solutions: 1. Check availability on action ------------------------------- When the user takes an action, check the API's status. Currently I'm doing this (Java): ``` public class ServiceAvailability implements Runnable { private volatile boolean available; @Override public void run() { available = false; try { HttpURLConnection connection = (HttpURLConnection) new URL("http://myservice.com").openConnection(); connection.setConnectTimeout(3000); connection.setReadTimeout(1000); connection.setRequestMethod("HEAD"); int responseCode = connection.getResponseCode(); if (200 <= responseCode && responseCode <= 399) { available = true; } } catch (IOException exception) { exception.printStackTrace(); } } public boolean isAvailable() { return available; } ``` It works just fine. Just send a HTTP HEAD request to the site and see if the response is a good one. Every time the user takes an action (e.g., runs a search, clicks someone's profile, etc.) it calls the `isAvailable()` method, and displays an error message in the event that the `available = false`. The advantage of this is that if the service goes down, the user will immediately know, and will be warned that they will not be able to use the app until the service is brought online again. I can't think of any disadvantages of this at the moment... 2. Check availability on interval --------------------------------- The other solution (that I haven't actually implemented) is run a thread in the background and HTTP HEAD the service every `X` seconds/minutes and update the status accordingly; at that point, I could call `isAvailable()` which would simply return the boolean set by the result of the HEAD request. The advantage to this is that a visual can be shown (for the duration) when the service is not online, letting the user know ahead of time that their request will not be processed. The disadvantage that I see is that while HEAD requests are very minimal in the amount of bandwidth they use, 3G users with very little data or users with slow connections might have trouble sending the HEAD and receiving the response in a timely manner. 3. Combine the two ------------------ The last approach that I see is a combination, where the thread in the background checks availability every `X` seconds, and action methods using the API also check availability through an additional HEAD request. The advantage that I see here is that the user will know (visually) when the service is offline for the duration, as well as have a fallback if the status of the API happens to change during the `X` seconds duration that the API was last checked. From what I can see, the Facebook Messenger app (iOS at least) implements this. When you open the app, it 'attempts to connect' (visual up top) and if your connection drops, it will let you know with a bright red visual. Trying to take action when you're not connected (to their service) also gives you an error. Question -------- Is there a single one of these 3 methods that are preferable, or a different method that I haven't mentioned? Furthermore, is there an actual design pattern for this (e.g., Singleton on a thread), one more preferable than what I've implemented? **Edit**: As a user of the app myself, I feel that a pretty visual telling me that I won't be able to do something before I actually *try* is better than trying and failing. Furthermore, I want to implement this in order to determine more than just an 'up' or 'down' status of the API. For example, when the API is in maintenance for an update, I want to be able to receive a `503` and let the user know visually that the service is in maintenance mode, will be online shortly, and not to panic. I'm not exactly sure how many users will be using the app in the long run, so I'm trying to prepare ahead of time in the event of API outages and maintenance. I don't have a large-scale infrastructure that can support millions of users like Facebook, so I believe that this availability check is reasonable in order to provide good (decent?) user experience, as I know for a fact that the API will not have 100% up-time. Not to mention that I'm the sole developer and the service might go down while I'm sleeping!
2015/01/26
[ "https://softwareengineering.stackexchange.com/questions/271163", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/109112/" ]
I would Check Availability on **Failed** Action. Just issue your calls normally and if you get a failure, then call the Service Availability function to verify. Assume service is up, if one gets and error, then issue the additional call to verify availability.
8,073,665
I was just reading about it on a book and wikipedia but still dont understand it 100%. I would really appreciate it if someone could explain it with an example or two. Thanks
2011/11/10
[ "https://Stackoverflow.com/questions/8073665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1038741/" ]
Say I'm looking at a map, searching for a pizza place near my block in the city. A few different strategies I could use: * Breadth first search (BFS): Look at concentric circles of blocks around my block, farther and farther outward until I find a pizza place. This will give me one of the pizza places which is closest to my block as the crow flies. * Depth first search (DFS): Follow a road until I hit a dead end, then backtrack. Eventually all possible branches will be searched, so if there's a pizza place out there somewhere then I'll find it, but it probably won't be very close to my block. * Uniform cost search (UCS): Say traffic is bad on some streets, and I'm really familiar with the city. For any given location I can say how long it will take me to get there from my block. So, looking at the map, first I search all blocks that will take me 1 minute or less to get to. If I still haven't found a pizza place, I search all blocks that will take me between 1 and 2 minutes to get to. I repeat this process until I've found a pizza place. This will give me one of the pizza places which is the closest drive from my block. Just as BFS looks like concentric circles, UFS will looks like [a contour map](http://upload.wikimedia.org/wikipedia/commons/f/fa/Cntr-map-1.jpg). Typically you will implement UCS using a priority queue to search nodes in order of least cost.
55,189,369
This works for integers, e.g.: ``` '123x'.replace(/\D/g, '') '123' ``` Which regular expression would achieve the same, but allowing only one dot? Examples: * `1` -> `1` * `1x` -> `1` * `10.` -> `10.` * `10.0` -> `10.0` * `10.01` -> `10.01` * `10.01x` -> `10.01` * `10.01.` -> `10.01`
2019/03/15
[ "https://Stackoverflow.com/questions/55189369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75265/" ]
With two replaces: ```js console.log("a12b3.1&23.0a2x".replace(/[^.\d]/g, '') .replace(/^(\d*\.?)|(\d*)\.?/g, "$1$2")); ``` The first action will remove all characters other than digits and points The second replacement matches sequences of digits possibly followed by a point, but it does so in two different ways. When such sequence occurs at the start of the string, the optional point is put *inside* the first capture group, while for all other matches, the point is *outside* the (second) capture group. There are two capture groups, but for any given match, only one of them will actually have content. So the captured content can be reproduced in either case with `$1$2`. This will include the first point, but exclude any other.
71,860,742
I have a table like this in MySQL with large number rows. ``` TABLE `Table_1` ( `InternalId` int(10) NOT NULL AUTO_INCREMENT, `Id` varchar(50) NOT NULL, `Test_Column` varchar(100) NULL, `Month` int(2) NOT NULL, `Year` int(2) NOT NULL, PRIMARY KEY (`InternalId`), KEY `IX_Id` (`Id`) ) ENGINE=InnoDB; ``` I need to query the table regularly for rows where Month / Year is in the past and Test\_Column is not NULL and perform some action on them using a query like ``` Select * From Table_1 where Test_Column is NULL AND (Year < @currentYear OR (Year = @currentYear AND Month = @currentMonth)) ``` What's the best way of creating indexes for these columns? Do I simply create an index on all 3 columns Year, Month, Test\_Column and is the fact that Test\_Column nullable something to give consideration to?
2022/04/13
[ "https://Stackoverflow.com/questions/71860742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11753405/" ]
Here's what I tried. Tested in MySQL 8.0.28: ``` alter table table_1 add column test_column_is_null bool as (test_column is null), add column date date as (date(concat(`Year`, '-', `Month`, '-01'))), add index (test_column_is_not_null, date); ``` Then I checked the EXPLAIN report for your query: ``` EXPLAIN SELECT * FROM Table_1 WHERE test_column_is_null = 1 AND date < DATE_FORMAT(NOW(), '%Y-%m-01')\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: Table_1 partitions: NULL type: range possible_keys: test_column_is_null key: test_column_is_null key_len: 6 ref: NULL rows: 1 filtered: 100.00 Extra: Using where ``` This shows that it uses the index I added, and the `key_len` shows that it is using both columns of the index (1 byte for the boolean, 3 bytes for the date, plus there's some bytes for nullability).
21,400,832
I subclassed `UIButton` in my app and there are many times when the highlight color stays even when I'm done pressing down the button. I can't figure out exactly what causes this since it only seems to happen by chance, but it seems to happen about 50% of the time. I'm very sure that this is reproducible. I often get this to happen when I have a button in a `UITableViewCell` and I click on it while the table view is still scrolling. Is there something wrong with the way I'm overriding the `setHighlighted` method in the subclass? This is my implementation: ``` @implementation SCPFormButton - (id)initWithFrame:(CGRect)frame label:(NSString *)label { self = [super initWithFrame:frame]; if (self) { UILabel *buttonLabel = [[UILabel alloc] init]; buttonLabel.attributedText = [[NSAttributedString alloc] initWithString:[label uppercaseString] attributes:kButtonLabelAttributes]; [buttonLabel sizeToFit]; buttonLabel.frame = CGRectMake(kMaxWidth / 2 - buttonLabel.frame.size.width / 2, kStandardComponentHeight / 2 - buttonLabel.frame.size.height / 2, buttonLabel.frame.size.width, buttonLabel.frame.size.height); [self addSubview:buttonLabel]; self.backgroundColor = kFormButtonColorDefault; } return self; } - (void)setHighlighted:(BOOL)highlighted { self.backgroundColor = highlighted ? kFormButtonColorHighlighted : kFormButtonColorDefault; [self setNeedsDisplay]; } @end ```
2014/01/28
[ "https://Stackoverflow.com/questions/21400832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/855680/" ]
I would try to call `super` in your `setHighlighted` override. Indeed, [Apple docs for UIControl](https://developer.apple.com/library/ios/documentation/uikit/reference/UIControl_Class/Reference/Reference.html#//apple_ref/occ/instp/UIControl/highlighted) state: > > Specify YES if the control is highlighted; otherwise NO. By default, a control is not highlighted. UIControl automatically sets and clears this state automatically when a touch enters and exits during tracking and when there is a touch up. > > > So, it seems there is some kind of state handling going on in `UIControl` associated with this. If this does not help, I would try to add a log trace so you can check which state the button is in when the touch is handled.
21,027
So I'm looking for some guidance on this topic. If I open up my exe in a Hexeditor and go to the location where the address of the string is pushed as argument I have the following: ``` 68 7C 9D F1 01 - push 01F19D7C ``` The string in the exe however is at 01ADC808. I do have the same exe but for a different language. ``` 68 78 DE F0 01 - push 01F0DE78 ``` and the string is at 01B94B0C. Looking at it in Ghidra for example, the address from the push instruction matches the location of the string. So currently my best guess is, that Ghidra aligns the data properly with info from the PE Header. I'm writing a tool that modifies that string. Patterns could be created for each version, however I'd like a rather "universal" way to solve this. Additionally, here's the overview for the Section Headers for the first example: [![enter image description here](https://i.stack.imgur.com/KjqfA.png)](https://i.stack.imgur.com/KjqfA.png) Feel free to let me know if my question was not clear enough or more information is required! Thanks in advance for any advice! :) EDIT: Forgot to mention the tool I'm writing is written in C#.
2019/04/03
[ "https://reverseengineering.stackexchange.com/questions/21027", "https://reverseengineering.stackexchange.com", "https://reverseengineering.stackexchange.com/users/28017/" ]
push 402010 is broken down like 402010 - base\_address - virtual\_address\_of\_section + file\_ptr\_to\_rawdata your data has some inconsistencies it must be a counted string or pascal string etc there is a 4 byte mismatch between the addresses 0xc/0x8 disassembly of a string push ``` 0:000> u . l4 msgbox!WinMain: 002c1000 55 push ebp 002c1001 8bec mov ebp,esp 002c1003 6a00 push 0 002c1005 6810202c00 push offset msgbox!⌂USER32_NULL_THUNK_DATA+0x4 (002c2010) 0:000> db 2c2010 l20 002c2010 57 69 6e 64 20 54 65 73-74 00 00 00 54 65 73 74 Wind Test...Test 002c2020 20 54 68 65 20 57 69 6e-64 00 00 00 00 00 00 00 The Wind....... 0:000> ? msgbox Evaluate expression: 2883584 = 002c0000 0:000> ? 2c2010 -msgbox Evaluate expression: 8208 = 00002010 0:000> .shell -ci "!dh -s msgbox" grep -A 5 #2 SECTION HEADER #2 .rdata name 206 virtual size 2000 virtual address 400 size of raw data 600 file pointer to raw data 0:000> ? 0x2010 - 0x2000 + 0x600 Evaluate expression: 1552 = 00000610 0:000> q quit: ``` dispaly on hexeditor ``` :\>xxd -g 1 -s 0x610 -l0x20 msgbox.exe 0000610: 57 69 6e 64 20 54 65 73 74 00 00 00 54 65 73 74 Wind Test...Test 0000620: 20 54 68 65 20 57 69 6e 64 00 00 00 00 00 00 00 The Wind....... ```
3,644,821
Is it possible to access the user directory "~/" in an Xcode build script phase? Right now I am trying to directly use "~/" but on compilation it complains the directory doesn't exist. Is there another way to get the user directory (or the name of the user folder)?
2010/09/05
[ "https://Stackoverflow.com/questions/3644821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425756/" ]
The `sockets` extension is not activated. You should load `php_sockets.dll` in php.ini.
24,553,651
I am developing an `IOS` application. I am using navigation controller. If I push to next page then back button title not shown previous page title in IOS 7. Back button title always "Back" in IOS 7. I set all pages titles in `viewWillAppear`, `viewDidload` like below. But it is not working. ``` self.navigationItem.title=@"Previous Page Title"; self.title = @"Previous Page Title"; ``` What can I set back button title with previous page title in IOS 7 Thanx
2014/07/03
[ "https://Stackoverflow.com/questions/24553651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/829825/" ]
If the title is large, back button shows back only.Try with short titles,like ``` self.title = @"Test"; ``` if you want Long title , go for custom back button.
20,083,086
in Global.asax.cs, I'm trying to filter out all the XHR requests in order to log them. However, both the `HttpContext.Current.Request` and the `HttpContext.Current.Response` don't seem to provide this information. Is there some property field I missed? Or is there another way of knowing if a request is XHR?
2013/11/19
[ "https://Stackoverflow.com/questions/20083086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/752462/" ]
If you're using MVC you can use the IsAjaxRequest() extension method. ``` Request.IsAjaxRequest(); ``` It's defined in System.Web.Mvc so if you don't already have a `using` statement for that namespace you'll need to add one.
799,846
Here is a homework, the result brought me some trouble. Let $p = 7$, and consider the finite field ${ \mathbb{F}}\_{p^{2}}$ , which we may represent explicitly as $${ \mathbb{F}}\_{p^{2}}\simeq {\mathbb{F}}\_{p}[i]/(i^{2} +1)=\{a+bi:a,b\in{ \mathbb{F}}\_{p}\}.$$ Now consider the elliptic curve $E/{ \mathbb{F}}\_{p^{2}}$ defined by $$y^{2} = x^{3} + (1 + i)x.$$ The group of ${ \mathbb{F}}\_{p^{2}}$ -rational points on $E$ is isomorphic to $\mathbb{Z}/6\mathbb{Z }\oplus \mathbb{Z}/6\mathbb{Z }$ and is generated by the affine points $$P\_{1} =(i,i), P\_{2} =(i+2,2i),$$ Now consider the Frobenius endomorphism $\pi\_{E}$ of $E$: 1.Prove that $\pi\_{E} = 7$ by showing that $\pi\_{E} -7$ is the zero homomorphism(remember, it is not enough to show that$E({ \mathbb{F}}\_{p})$ is in the kernel of $\pi\_{E} -7$, you need to prove that $E(\overline{{ \mathbb{F}}}\_{p})$ is in the kernel of $\pi\_{E} -7$ ). My Question: $(i)$I have no idea how to check $E(\overline{{ \mathbb{F}}}\_{p})$ is in the kernel of $\pi\_{E} -7$ ; Is there some useful method to check the kernel of some endomorphism(As $E[m]$ is so simple and cute). (ii) Can we decide the group structure $E(\overline{{ \mathbb{F}}}\_{p})$ in this exercise? 2.Then find an endomorphism $\alpha$ that satisfies $\alpha^{2} = -1$(give $\alpha$ explicitly). My Question: (iii) How to check $\alpha\neq m$ for some integer $m$?(Actually, in this exercise $End(E)$ is an order in a quaternion algebra) Here is my method:(I don't think it is a general way) Assume $\alpha=m$, $m^{2}P\_{j}=\alpha^{2}P\_{j}=-P\_{j},~j=1,2.$ We will have $6|(m^{2}+1)$, but there is no such integer satisfies this condition which contradict our assumption. Thank you for any help. :)
2014/05/18
[ "https://math.stackexchange.com/questions/799846", "https://math.stackexchange.com", "https://math.stackexchange.com/users/144652/" ]
1) Of course in principle you could write down rational maps for the map $\pi-7$ and check that this is $0$ on every point of $E$. Note that you have to consider $E(\overline{\mathbb F\_{7^2}})$ since the base field is $\mathbb F\_{7^2}$, and not $E(\overline{\mathbb F\_7})$ as you wrote. But the quickest way is using the fact that if $l\neq 7$ is a prime than you have an injective map $\varphi\colon\text{End}(E)\otimes \mathbb Z\_l\to \text{End}(T\_l(E))$ where $T\_l$ is the $l$-adic Tate module of $E$. Such a map sends an endomorphism $\phi$ to the same map seen as an endomorphism of the Tate module. Since $T\_l(E)\simeq \mathbb Z\_l\times \mathbb Z\_l$, then you can define the characteristic polynomial of the Frobenius as the characteristic polynomial of $\varphi(\pi)$. One can show that such a polynomial is independent of $l$ and in fact equals $x^2-a\_{7^2}x+7^2$ where $a\_{7^2}=7^2+1-\#E(\mathbb F\_{7^2})=14$. So this characteristic polynomial equals in your case $x^2-14x+49=(x-7)^2$. Now every endomorphism satisfies its characteristic polynomial, so you must have that $(\varphi(\pi)-7)^2=0$ as an endomorphism of $T\_l(E)$. But since $\varphi$ is injective, this means that $(\pi-7)^2=0$ as an endomorphism of $E$, and this implies that $\pi-7=0$ because $\text{End}(E)$ has no zero divisors. I don't know if you can decide the group structure of $E(\overline{\mathbb F\_{7^2}})$, but if $K$ is an extension of $\mathbb F\_{7^2}$ of degree $n$, then $\#E(K)=1+|K|-2\cdot 7^n=(7^n-1)^2$. 2) If $\alpha$ satisfies $\alpha^2=-1$, then it is automatical that $\alpha$ is not multiplication by $m$, because if you compose multiplication by $m$ with itself you get multiplication by $m^2$, which is obviously different from $-1$. I think that in your case there are only 2 choices for $\alpha$, namely the maps sending $x\mapsto -x$ and $y\mapsto \pm iy$.
306,707
In general relativity, the presence of gravity warps space-time yet clearly me accelerating will not warp space-time. It is hints at in one of the comments of this [answer](https://physics.stackexchange.com/a/197552/70392) that acceleration bends world lines but does not actually cause the warping of space time. Is this right? If it is then why could we not have acceleration warping and gravity bending world lines. If it is not why not?
2017/01/21
[ "https://physics.stackexchange.com/questions/306707", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/70392/" ]
Although "warping" is probably not an academically well-recognized term, I feel safe to assert that warping means curvature of the spacetime. Curvature of the spacetime is the property of the spacetime being of such a nature that two infinitesimally separated geodesics *(paths for which the vector generated by the parallel transport (along the path) of the tangent vector to the path at one point is also the tangent vector to the path at the resulting point)* that are parallel at a point do not remain parallel in the infinitesimal neighborhood of that point. As you can easily see, the definition of the curvature is manifestly coordinate invariant. Thus, a frame being accelerated wrt the previous frame does not make the spacetime curved if it were not curved in the original frame. So, **the reason acceleration doesn't warp spacetime is because the acceleration of a frame wrt the other has nothing to do with the coordinate invariant properties of the spacetime, rather it is just the relation between two frames**. Now, in some sense, according to the Equivalence principle, gravity and acceleration are the same things. In this context, gravity also doesn't always curve the spacetime. For example, if a box, in the deep empty space, is being pulled with some acceleration with respect to the local inertial frame then there would be gravity in the frame attached to the box but the spacetime is still flat. But, there is some distinction between this kind of gravity and a rather "genuine" gravity, for example, the kind of gravity produced by the Earth or some other matter-energy distribution. This kind of gravity, called "true gravity" by Weinberg, is defined as the sort of **gravity that makes the path followed by two neighboring free particles in the spacetime (who are initially going parallel to each other in their spacetime trajectories) converge**. By the Equivalence principle, the space-time trajectories of the particles are precisely the geodesic curves in the spacetime. **Thus, it follows that true gravity represents nothing but the curvature of spacetime.** Notice that such true gravity can also be present in the perfect vacuum without any source whatsoever, e.g., in the gravitational waves. So, coming back to your question, I would say the curvature of the spacetime *is* what is represented by "true gravity" rather than saying that gravity *causes* spacetime curvature. One might be tempted to say, based on the Einstein field equations, that the energy-momentum tensor $T\_{\mu\nu}$ causes the curvature of spacetime but as I said, the curvature can be present even without $T\_{\mu\nu}$. So, you can not call it the exclusive cause of the spacetime curvature.
34,330,695
I've built a website that stores images in 4 different sizes on the file system. It keeps the origional file size, medium, thumb, small image and resizes them as they upload. We then created the web api to allow us to build the ios/android apps. while building the apis our overseas developer then asked to provide the image dimensions along with the image file name. it took a lot of work regarding calculating the image sizes and saving them to the database. ``` { "imagefilename" : "someimage.jpg", "LargeimageHeight" : "1000", "LargeimageWidth" : "500", "mediumImageHeight" : "500", "mediumImageWidth" : "250", "smallImageHeight" : "100", "smallImageWidth" : "60" } ``` with the amount of image sections we have in the website made it a task and i want to know if this is really nessesary. Im not an ios developer but not really sure as to why the additioanl dimensions of the image need to be saved and or really needed. i thought the ios has the image feature (@3x) (@2x) (@3x) ?? or do i use 1 specific folder image size for ios ?? does this always happen in the ios world for images that the code needs to know the image dimensions for the best result? thanks
2015/12/17
[ "https://Stackoverflow.com/questions/34330695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2647906/" ]
If your iOS application show images in flow layout (like pinterest style) you must return image dimensions. Otherwise I don't think its nessesary
11,766
Is it possible to mix 2D and 3D graphics in a single OpenGL ES 2.0 game, please? I have plenty of 2D graphics in my game. The 2D graphics is represented by two triangular polygons (making up a rectangle) with texture on them. I use **orthographic** matrix to render the whole scene. However, I need to add some 3D effects into my game. Threfore, I wish to use **perspective** camera to render the meshes. Is it possible to **mix orthographic and perspective camera** in one scene? If yes, is there going to be a large performance cost for this? Is there any recommended approach to do this effectively? I wil have 90% of 2D graphics and only 10% of 3D. Target platform is OpenGL ES 2.0 (iOS, Android). I use C++ to develop. Thank you.
2011/04/29
[ "https://gamedev.stackexchange.com/questions/11766", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/2229/" ]
This is easily done. Set the view transform to orthographic for the 2D stuff, and render it. Then, before clearing the framebuffer, draw the effects with a perspective projection. The projection will only effect the geometry drawn after it, so just set the desired mode prior to drawing. This is the same way we handle HUDs in our FPS. :) The only performance impact is that your are changing a uniform variable (your project matrix), right? So, just try to batch things to minimize state changes--same old stuff.