text
stringlengths
64
89.7k
meta
dict
Q: knife bootstrap windows winrm from Mac OS X workstation fails Running the command knife bootstrap windows winrm ec2box.amazonaws.com -r 'role[web]' -x Administrator -P 'mypassword' from my Mac OS X workstation produces the output below. Running it from a Windows workstation, the command successfully runs. Is there an extra step I need to take to get my Mac OS X workstation to communicate via WinRM correctly? I'm using this on Amazon's Windows Server 2012 AMI. It printed #39 everywhere on my terminal, not an artifact of Stack Overflow. WARNING: Could not load IOV methods. Check your GSSAPI C library for an update WARNING: Could not load AEAD methods. Check your GSSAPI C library for an update Bootstrapping Chef on ec2box.amazonaws.com ec2box.amazonaws.com "Rendering 'C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-7738-1370535154.bat' chunk 1" ec2box.amazonaws.com "Rendering 'C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-7738-1370535154.bat' chunk 2" ec2box.amazonaws.com '#39' is not recognized as an internal or external command, ec2box.amazonaws.com operable program or batch file. ec2box.amazonaws.com "Rendering 'C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-7738-1370535154.bat' chunk 3" ec2box.amazonaws.com "Rendering 'C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-7738-1370535154.bat' chunk 4" ec2box.amazonaws.com '#39' is not recognized as an internal or external command, ec2box.amazonaws.com operable program or batch file. ec2box.amazonaws.com '#39' is not recognized as an internal or external command, ec2box.amazonaws.com operable program or batch file. ec2box.amazonaws.com "Rendering 'C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-7738-1370535154.bat' chunk 5" ec2box.amazonaws.com "Rendering 'C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-7738-1370535154.bat' chunk 6" ec2box.amazonaws.com "Rendering 'C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-7738-1370535154.bat' chunk 7" ec2box.amazonaws.com "Rendering 'C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-7738-1370535154.bat' chunk 8" ec2box.amazonaws.com "Rendering 'C:\Users\ADMINI~1\AppData\Local\Temp\bootstrap-7738-1370535154.bat' chunk 9" ec2box.amazonaws.com ec2box.amazonaws.com else was unexpected at this time. ec2box.amazonaws.com C:\Users\Administrator>mkdir C:\chef ec2box.amazonaws.com ec2box.amazonaws.com C:\Users\Administrator>( ec2box.amazonaws.com echo.url = WScript.Arguments.Named("url") ec2box.amazonaws.com echo.path = WScript.Arguments.Named("path") ec2box.amazonaws.com echo.proxy = null ec2box.amazonaws.com echo.Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP") ec2box.amazonaws.com echo.Set wshShell = CreateObject( "WScript.Shell" ) ec2box.amazonaws.com echo.Set objUserVariables = wshShell.Environment("USER") ec2box.amazonaws.com echo. ec2box.amazonaws.com echo. ec2box.amazonaws.com echo.On Error Goto 0 ec2box.amazonaws.com echo. ec2box.amazonaws.com echo.objXMLHTTP.open "GET", url, false ec2box.amazonaws.com echo.objXMLHTTP.send() ec2box.amazonaws.com echo.If objXMLHTTP.Status = 200 Then ec2box.amazonaws.com echo.Set objADOStream = CreateObject("ADODB.Stream") ec2box.amazonaws.com echo.objADOStream.Open ec2box.amazonaws.com echo.objADOStream.Type = 1 ec2box.amazonaws.com echo.objADOStream.Write objXMLHTTP.ResponseBody ec2box.amazonaws.com echo.objADOStream.Position = 0 ec2box.amazonaws.com echo.Set objFSO = Createobject("Scripting.FileSystemObject") ec2box.amazonaws.com echo.If objFSO.Fileexists(path) Then objFSO.DeleteFile path ec2box.amazonaws.com echo.Set objFSO = Nothing ec2box.amazonaws.com echo.objADOStream.SaveToFile path ec2box.amazonaws.com echo.objADOStream.Close ec2box.amazonaws.com echo.Set objADOStream = Nothing ec2box.amazonaws.com echo.End if ec2box.amazonaws.com echo.Set objXMLHTTP = Nothing ec2box.amazonaws.com ) 1>C:\chef\wget.vbs ec2box.amazonaws.com ec2box.amazonaws.com C:\Users\Administrator>( ec2box.amazonaws.com echo.param( ec2box.amazonaws.com echo. [String] $remoteUrl, ec2box.amazonaws.com echo. [String] $localPath ec2box.amazonaws.com echo.) ec2box.amazonaws.com echo. ec2box.amazonaws.com echo.$webClient = new-object System.Net.WebClient; ec2box.amazonaws.com echo. ec2box.amazonaws.com echo.$webClient.DownloadFile($remoteUrl, $localPath); ec2box.amazonaws.com ) 1>C:\chef\wget.ps1 ec2box.amazonaws.com C:\Users\Administrator>) else ( A: It seems to work with knife-windows 0.5.10 [tested with windows server 2008R2] Install it with: gem uninstall knife-windows gem install knife-windows -v 0.5.10 check your gems with: gem list|grep knife-windows And it should show: knife-windows (0.5.10)
{ "pile_set_name": "StackExchange" }
Q: Deselect a collectionview cell when another cell is selected I have cells with images on a viewController, I like to give the users an option to select one of the image for their title label. How do I make them select only one image, that is if they select another image I want to deselect the previous image they selected. This is what I did: func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) cell?.layer.borderWidth = 5.0 cell?.layer.borderColor = UIColor.black.cgColor collectionView.allowsMultipleSelection = false } but it is allowing me to select all cells not just one cell which I like. A: First, move collectionView.allowsMultipleSelection = false to viewDidLoad Secondly, I don't think you really have a problem with multiple selection. Rather that you don't clear the effects you put on the cell when selecting it. What you can do is to clear that i didDeselect func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) cell?.layer.borderWidth = 5.0 cell?.layer.borderColor = UIColor.black.cgColor } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) cell?.layer.borderWidth = 0 cell?.layer.borderColor = UIColor.white.cgColor }
{ "pile_set_name": "StackExchange" }
Q: Global static IP name on NGINX Ingress I'm having difficulties getting my Ingress controller running on Google Container Engine. I want to use an NGINX Ingress Controller with Basic Auth and use a reserved global static ip name (this can be made in the External IP addresses section in the Google Cloud Admin interface). When I use the gce class everything works fine except for the Basic Auth (which I think is not supported on the gce class), anenter code hered when I try to use the nginx class the Ingress Controller launches but the IP address that I reserved in the Google Cloud Admin interface will not be attached to the Ingress Controller. Does anyone know how to get this working? Here is my config file: apiVersion: extensions/v1beta1 kind: Ingress metadata: name: webserver annotations: kubernetes.io/ingress.global-static-ip-name: "myreservedipname" kubernetes.io/ingress.class: "nginx" ingress.kubernetes.io/auth-type: basic ingress.kubernetes.io/auth-realm: "Auth required" ingress.kubernetes.io/auth-secret: htpasswd spec: tls: - secretName: tls backend: serviceName: webserver servicePort: 80 A: I found a solution with helm. helm install --name nginx-ingress stable/nginx-ingress \ --set controller.service.loadBalancerIP=<YOUR_EXTERNAL_IP> You should use the external-ip and not the name you gave with gcloud. Also, in my case I also added --set rbac.create=true for permissions. A: External IP address can be attached to the Load Balancer which you can point to your Ingress controller. One major remark - the External IP address should be reserved in the same region as the Kubernetes cluster. To do it, you just need to deploy your Nginx-ingress service with type: LoadBalancer and set ExternalIP value, like this: kind: Service apiVersion: v1 metadata: name: ingress-nginx namespace: ingress-nginx labels: app: ingress-nginx spec: loadBalancerIP: <YOUR_EXTERNAL_IP> type: LoadBalancer selector: app: ingress-nginx ports: - name: http port: 80 targetPort: http - name: https port: 443 targetPort: https After deployment, Kubernetes will create a new Load Balancer with desired static IP which will be an entry-point for your Ingress. @silgon, as I see, you already tried to do it, but without a positive result. But, it should work. If not - check the region of IP address and configuration once again.
{ "pile_set_name": "StackExchange" }
Q: Calling function x from within function y and vice versa in the same program int right(int n) { if(n>0) { n--; top_lim ++; cout<<"R"; right_lim--; if(right_lim < size) return(right(n-1)); if(top_lim>0) --> return(up(n - 1)); } else { return 0; } } int up(int n) { if(n>1) { n--; top_lim --; cout<<"U"; if(right_lim < size) return(right(n-1)); if(top_lim > 0 ) return(up(n-1)); } else { return 0; } } error: [17] 'up' was not declared in this scope|--> indicates error in code .. Description of problem: The problem is to find all the possible number of paths in a n*n grid in the portion below the diagonal starting from (0,0) to (n,n) I basically call the right function first in the main function and then it should print me all paths. Is there a workaround for this? A: Add a forward declaration at the top of your code: int up(int); (Make sure to compile that code with full optimizations! :-) )
{ "pile_set_name": "StackExchange" }
Q: python system call having a difficult time understanding how to get python to call a system function... the_file = ('logs/consolidated.log.gz') webstuff = subprocess.Popen(['/usr/bin/zgrep', '/meatsauce/', the_file ],stdout=subprocess.PIPE) % dpt_search for line in webstuff.stdout: print line Trying to get python to build another file with my search string. Thanks! A: I recommend the PyMotW Subprocess page from Doug Hellmann who (quoted) "Reads the docs so you don't have to" Apart from that: f = file('sourcefile') for line in f: if 'pattern' in line: # mind the , at the end, # since there's no stripping involved # and print adds a newline without it print line, if you need to match regular expressions apart from the documentation in the Python Standard Library documentation for the re module also refer to the PyMotW Regular Expression page
{ "pile_set_name": "StackExchange" }
Q: How to drag DOM element inside canvas without going out of canvas with P5js? What I want: I have a div and I want to move it around the canvas but limit it to canvas width and height What I have: I'm using p5.dom.js library P5js code: let dragging = false; let offsetX, offsetY, onsetX, onsetY; let canvasWidth, canvasHeight; let currentDragDiv; function setup() { canvasWidth = windowWidth < 400 ? 400 : windowWidth; canvasHeight = windowHeight < 400 ? 400 : windowHeight; canvas = createCanvas(canvasWidth, canvasHeight) .mousePressed(createDiv); } function draw() { background(200); if(dragging){ if(mouseX + onsetX < canvasWidth && mouseX + offsetX > 0){ currentDragDiv.position(mouseX + offsetX, currentDragDiv.y); } if(mouseY + onsetY < canvasHeight && mouseY + offsetY > 0 ){ currentDragDiv.position(currentDragDiv.x, mouseY + offsetY); } } } function createDiv(){ let div = createDiv("") .mousePressed(function(){ dragDiv(div); }) .mouseReleased(function(){ dropDiv(div); }) .position(mouseX, mouseY); } function dropDiv(){ dragging = false; currentDragDiv = null; } function dragDiv(d){ currentDragDiv = d; dragging = true; offsetX = currentDragDiv.x - mouseX; offsetY = currentDragDiv.y - mouseY; onsetX = currentDragDiv.width + offsetX; onsetY = currentDragDiv.height + offsetY; } The Problem: This code is working great but if the user moves the mouse too quickly, the div doesn't go until the border of the canvas things like this happens (I dragged and moved the div very fast to the right and it stoped in the middle of screen). This problem makes the variable onsetX and onsetY goes wrong and mess up a lit bit deppending on how much the div is away from the canvas border. Is it possible to remove this "error" and make the div go until the border of canvas? Observations: I removed some of the code that I think it's not necessary for this question. The variables onsetX and onsetY are the oposite of offsetX and offsetY, it's the position of the border from the mouse position, but because english isn't my native language, I didn't know how to name the variable. Recommendations would be good. A: In your current code the dragging is completely omitted, if the border of the canvas is exceeded: if(mouseX + onsetX < canvasWidth && mouseX + offsetX > 0){ currentDragDiv.position(mouseX + offsetX, currentDragDiv.y); } if (mouseY + onsetY < canvasHeight && mouseY + offsetY > 0 ){ currentDragDiv.position(currentDragDiv.x, mouseY + offsetY); } Instead of that you have to limit the dragging to the range from 0 to canvasWidth respectively 0 to canvasHeight. This means you have to "clamp" the dragging to this range: function draw() { let newX, newY; background(200); if(dragging){ newX = mouseX + offsetX; if ( newX > canvasWidth ) { newX = canvasWidth - currentPostIt.width; } if ( newX < 0 ) { newX = 0; } newY = mouseY + offsetY; if ( newY > canvasHeight ) { newY = canvasHeight - currentPostIt.height; } if ( newY < 0 ) { newY = 0; } currentDragDiv.position(newX, newY); } }
{ "pile_set_name": "StackExchange" }
Q: A practical way to do healthcheck for a new server? I am currently trying to do healthcheck for a new server in data center as a first QA before using by any application side. "What is the practical way and tools to check that the server is fine to use?" About the tools, I am looking at memtest86 to test the memory and IOzone Filesystem Benchmark. But I hope there should be more other tests I should do and better tools than these two. A: I used to do a good deal of hardware troubleshooting in large datacenters, I would recommend find a bootable Linux distribution, any will do. Be sure to find one with a 64 bit image if you have a 64 bit CPU. Stresslinux contains a whole suite of tools to stress your servers, and force any hardware failures out into the open. I'm personal to the "stress" tool - it can hammer hard disk(s), memory, and processor(s). stress A quick note about memtest86+ This is not part of the stress suite, but obviously you know it exists. Definitely make sure you're using memtest86+ (emphasis on +) - it handles 64 bit systems and large allocations of memory far better than the original memtest86. Memory Testing This will spawn n processes spinning on malloc() at 256MB each. stress -m n & So you would want to divide the amount of memory you have by 256MB (roughly), to hit all of it. This will flush out any obvious errors, you'll likely see EDAC's or MCE's (depending on your processor/motherboard), or a kernel panic/hard crash. Ideally you can let it run for a few hours to get the to heat up under load. You can check syslog for those errors. CPU Testing This will spawn n processes spinning on sqrt(). stress -c n & You'll want n to be the number of cores in your system. The same concept here applies as far as letting it run for a while. Disk Subsystem Testing This requires the hard disks to be formatted in someway, if you are using RAID you'll get better results if you've already set that up prior to mounting the drives and stressing them. Change directory to the partition/area of the disk you'd like to stress. The more free space the better. cd /hard/disk/partition This will spawn n processes spinning on write() at 1GB each stress -d 32 n & Monitor disk IO with: iostat -x 5 Killing Stress To kill all stress processes, yes you can run memory, CPU, and hard disk checks simultaneously, but it makes isolating the components a bit tougher: pkill -9 -f stress Verifying Your Tests Obviously you run all these things and you need to see some kind of result or confirmation. Memory/CPU You'll just want to check syslog for things like, Machine Check Exception (MCE), Error Detection and Correction (EDAC), Out of Memory (OOM), etc. zgrep -i -P ".*(error|warn|fail|panic|edac|mce|exception|oom-killer|oops).*" /var/log/kern.log* /var/log/dmesg /var/log/daemon.log* Disk Subsystem This is probably the easiest to detect more than any other component, smartctl is usually installed on most *NIX operating systems, it's a part of the smartmontools package. The following command requires root access: The /dev/sda aspect may need to change if you have multiple disks or a RAID controller. sudo smartctl -a /dev/sda Below is some sample output of the full command, I'll specify what you should really be looking for farther down the page. SMART Attributes Data Structure revision number: 16 Vendor Specific SMART Attributes with Thresholds: ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE 1 Raw_Read_Error_Rate 0x000b 099 099 016 Pre-fail Always - 65537 2 Throughput_Performance 0x0005 136 136 054 Pre-fail Offline - 95 3 Spin_Up_Time 0x0007 121 121 024 Pre-fail Always - 320 (Average 304) 4 Start_Stop_Count 0x0012 100 100 000 Old_age Always - 18 5 Reallocated_Sector_Ct 0x0033 100 100 005 Pre-fail Always - 0 7 Seek_Error_Rate 0x000b 100 100 067 Pre-fail Always - 0 8 Seek_Time_Performance 0x0005 144 144 020 Pre-fail Offline - 28 9 Power_On_Hours 0x0012 098 098 000 Old_age Always - 15407 10 Spin_Retry_Count 0x0013 100 100 060 Pre-fail Always - 0 12 Power_Cycle_Count 0x0032 100 100 000 Old_age Always - 18 192 Power-Off_Retract_Count 0x0032 100 100 000 Old_age Always - 37 193 Load_Cycle_Count 0x0012 100 100 000 Old_age Always - 37 194 Temperature_Celsius 0x0002 253 253 000 Old_age Always - 22 (Min/Max 15/31) 196 Reallocated_Event_Count 0x0032 100 100 000 Old_age Always - 0 197 Current_Pending_Sector 0x0022 100 100 000 Old_age Always - 0 198 Offline_Uncorrectable 0x0008 100 100 000 Old_age Offline - 0 199 UDMA_CRC_Error_Count 0x000a 200 200 000 Old_age Always - 0 The main attributes you want to be aware of are the following: Reallocated_Sector_Ct This should be less than 1000 in general. These are sectors that had to be reallocated to another part of the hard disk because the previous sector wasn't healthy. Temperature_Celsius This should be less than 55, the command itself will have a min/max in some cases - but sub 55 is where we saw healthy disk operation. Current_Pending_Sector Must be 0. Offline_Uncorrectable Must be 0. UDMA_CRC_Error_Count Should be 0, a few are okay (less than 100). Also note these can be indicative of a bad SATA/SAS cable. There are many ways to stress and benchmark your servers, this is just a way I'm comfortable with and have had great results with. I hope this helps!
{ "pile_set_name": "StackExchange" }
Q: internet explorer 7 css issue cart theme which uses smarty template engine. I am able to move the shoping cart links to above the top menu and it shows Ok with IE8 firefox etc. Hovewer IE7 make an empty space. How could I make IE7 happy. I added the necessary style-sheets and tpl files. Main css files are style.css and stle.base.css. IE8 no space (source: livefilestore.com) IE7 with space (source: livefilestore.com) A: IE7 doesn't render CSS well. Create a special CSS file for IE7 and include it in your HTML as follows: <!--[if lte IE 7]> <link href="ie7.css" rel="stylesheet" type="text/css"> <![endif]--> In ie7.css, modify the margins, padding, etc. until the two versions appear identical.
{ "pile_set_name": "StackExchange" }
Q: Pluralize words ending in a tonic vowel I'm a native speaker. I'm pretty sure that the plural of tabú is tabúes, I've seen it used in writing, in the press. For similar reasons that the plural of marroquí is marroquíes. I argued with someone recently about the pluralization of menú. Observe that champú, tabú and menú are are all words of foreign origin that end in a tonic (accented u). Identical rules should apply to them. I now know that menús is correct (and so is Microsoft's documentation for Office in spanish). The question is: is menúes acceptable? incorrect? How do you pluralize: champú, tabú and menú? Can someone explain to me the definitive rule? Is it plagued with exceptions? A: There are four main cases to consider: When a noun ends in a tonic i or u, there are two accepted forms for the plural: one using -es and the other one using -s. For example: bisturíes o bisturís, carmesíes o carmesís, tisúes o tisús, tabúes o tabús.,The form ending in -es is preferred, so it is better to say bisturíes, carmesíes, tisúes, tabúes. In the case of gentilics, the plurals ending in -s are not considered incorrect, but the -es ending is preferred: israelíes, marroquíes, hindúes, bantúes. On the other side, some words from other languages only form their plural with -s: popurrís, champús, menús, tutús, vermús. The plural of the adverb sí, when used as a noun, is síes, but the plural of the musical note si is sis. In your concrete examples, the correct plural forms are champús, tabúes (preferred) or tabús (accepted), and menús. This information can be found in the literal c) of the entry for Plural of the Diccionario panhispánico de dudas.
{ "pile_set_name": "StackExchange" }
Q: Precisión de variables en C Tengo un problema con un programa que he hecho para resolver un problema matemático, que consiste en encontrar números enteros y que cumplan que el resultado x = sqrt(1141.0*y^2+1.0) sea un número entero. Si no estoy equivocado la máxima precisión se obtiene con long double como formato de variable, que es el que he usado en el programa, y, en teoría, alcanza 10^308, sin embargo como no me funcionaba correctamente he hecho una depuración del programa y me sale que sólo está manejando cifras de 18 dígitos, por lo tanto me está devolviendo como posibles soluciones valores de y que realmente no son soluciones. Por ejemplo me devuelve como posible solución el valor y=23052875, cuando para ese valor de y la x=7.7869595299999994670577156…×10^8 realmente, por lo que se ve que C está redondeando el resultado. ¿Es una limitación de C, o de la función sqrt, y, por lo tanto, no se puede resolver este problema con C? o ¿estoy utilizando mal algo y eso me está limitando la precisión? #include <stdio.h> #include <math.h> int is_int(long double x); int main() { long double x; long int y, MAX=5000000; printf("\n\tSolutions: "); for (y = 1; y < MAX; y++ ) { x = sqrt(1141.0*y*y+1.0); if (is_int(x)) { printf("\t%ld", y); } } printf("\n\n"); return 0; } int is_int (long double x) { if (floor(x) != x) { return 0; } else{ return 1; } } (aclaración sobre el programa: la variable MAX tiene un valor elegido arbitrario, pero se puede cambiar sin problemas para realizar pruebas) A: Problema El problema no es del C, sino del formato de coma flotante. En un formato de coma flotante se usan parte de los bits para contener las "cifras significativas" de la cantidad a representar (en binario) y otra parte de los bits para contener un "exponente". Esto permite que, cuando se trabaja con números muy pequeños se pueda tener mucha precisión (pues los exponentes serían negativos), y que cuando se trabaja con números grandes se pueda tener mucho rango, al ser los exponentes positivos y grandes, pero a cambio de perder precisión. En un double, efectivamente puedes representar número tan grandes como 10^308, pero eso no implica que dispongas de 308 cifras significativas. Cuanto más grande es el número, mayor es el error de representación, y una gran parte de las cifras del mismo se sustituyen por ceros (en binario), por lo que en realidad no estás representando el número que pensabas, sino una aproximación del mismo. En tu caso, cuando evalúas la expresión 1141*y*y+1 para y=23052875, el resultado sería (manteniendo todos los dígitos significativos) 601053036760921876 (lo he calculado con python, que tiene precisión arbitraria con enteros). En binario ese número es 100001010111010111101000110101101011010011011111011100010100. En cambio al representarlo como un double, todos esos dígitos no caben (son 62 bits, y un double sólo tiene 51 bits para la mantisa). Por tanto parte de ellos se eliminan (se consideran cero), y estarás representando entonces la aproximación 601053036760921856, que en binario es 100001010111010111101000110101101011010011011111011100000000, distinto del que queríamos en las últimas 5 cifras binarias. A partir de ahí, lógicamente, todo saldrá mal. Solucion Creo que para este problema, que además parece matemáticamente un problema de aritmética entera, el tipo apropiado sería el entero. Python tiene enteros de precisión arbitraria (es decir, la cantidad de bits que dedica para guardar un entero, puede crecer tanto como te permita la memoria). Pero sin necesidad de cambiar de lenguaje, si te mantienes en C, el número anterior nos cabría dentro de un unsigned long long int, pues este tipo de datos tiene 64 bits y ya hemos visto que el número en cuestión requería 62. Tienes el problema de calcular la raíz cuadrada, ya que la función sqrt() opera con double. Y naturalmente tarde o temprano volverás a quedarte sin bits a medida que y crezca. Podrías indagar en alguna de las muchas bibliotecas para precisión arbitraria para C, o cambiar de lenguaje. En python queda bastante sencillo (aunque no será tan rápido como una versión C). Actualización Pongo seguidamente una implementación en C que usa tipo de dato unsigned long long y por tanto puede llegar más lejos que la versión con double. En concreto, podría llegar hasta más de MAX=90000000, pues para este valor de y el resultado de 1141*y*y+1 aún cabe en 64 bits. #include <stdio.h> unsigned long long int isqrt(unsigned long long int n) { unsigned long long int x = n; unsigned long long int y = (x+1)/2; while (y<x) { x = y; y = (x+n/x)/2; } return x; } void main() { unsigned long long int MAX=90000000; unsigned long long y, x2, x; for (y=0; y<MAX; y++) { x2 = 1141*y*y+1; x = isqrt(x2); if (x*x == x2){ printf("\t%llu\n", y); } } } Observa que he tenido mucho cuidado de trabajar siempre con aritmética entera (he puesto 1141 y no 1141.0 por ejemplo). La función isqrt() calcula una aproximación entera de una raiz cuadrada, por el método de Newton. La raiz calculada será exacta si es entera (por ejemplo, isqrt(25) retornaría 5), pero se queda por debajo si no (por ejemplo, isqrt(26) retornaría también 5). Por eso luego elevo al cuadrado el valor retornado y lo comparo con lo que debía ser, para decidir si encontré o no una solución. En mi máquina tarda un minuto en examinar los 90000000 casos, y lamentablemente no encuentra ninguna solución. UPDATE. Como comparativa, la versión python del mismo programa, tarda 26 minutos en recorrer los 90000000 casos, cuando se ejecuta con el intérprete estándar. Ejecutándo el mismo programa python con pypy, que es otra implementación mucho más rápida especialmente para cómputo numérico, el tiempo de ejecución desciende a 1m16'!! Este tiempo es prácticamente equivalente a C, de modo que podemos dejar que python siga buscando por encima de 90000000, pues en cuanto el dato no le quepa en 64 bits, automáticamente usará más, sin límite... Esta es la versión python, que podrás comprobar es muy similar al código C anterior, pero sin declaraciones de tipos y sin llaves :-) (el operador // es el de división entera, ya que / hace división flotante, en python3) def isqrt(n): x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x MAX=90000000 for y in range(MAX): x2 = 1141*y*y+1 x = isqrt(x2) if x*x == x2: print(" %d" % y)
{ "pile_set_name": "StackExchange" }
Q: "Let's plan to meet at three o'clock" vs. "Let's meet at three o'clock" What's the differences between the two? Personally, I'd say let's meet each other at three o'clock. Is formality the only difference between them? Here is the complete conversation: A: I don't think formality comes into it, but these two individuals seem to be under the misapprehension that it sounds more formal. You could argue that, "planning to meet," allows for some flexibility, and the understanding that the plan may have to change, but in reality that would also be the assumption for, "let's meet at three," as if something comes up, plans may need to change. I would put it down to the facet of human nature that likes a little bit of self importance. "Planning to meet," is just a bit redundant.
{ "pile_set_name": "StackExchange" }
Q: Dojo custom language variants Does Dojo support creation of custom language variants to be used for with Dojo's locale and i18n Does anyone know if I am able to create a custom language variant for Dojo's locale that works with i18n?. Example define({ root: { greeting: "Hello, world!" } "de-myVariant" : true }); A: Yes, it can be done. If you have nls/SampleApp.js as: define({ root: { greeting: "Hello!" } "de" : true, "de-at": true, "de-x-mundl": true }); then there would be three sub-directories under nls: nls/de nls/de-at nls/de-x-mundl for nls/de/SampleApp.js: define(({ greeting: "Hallo!" })); for nls/de-at/SampleApp.js: define(({ greeting: "Gruß Gott!" })); and for nls/de-x-mundl/SampleApp.js: define(({ greeting: "Servus, Mundi!" })); Then if you config Dojo to get the locale as a URL parameter: <script src="./dojo/1.8.3/dojo/dojo.js" data-dojo-config="locale: location.search.substring(1).toLowerCase()"> </script> you can switch the language easily by passing the locale tag as that parameter: .../app.html?de-DE .../app.html?de-at .../app.html?de-x-Mundl Note that Dojo considers locale tags as case-sensitive and that's why the input is toLowerCase()ed and internally all the tags are kept in lower-case.
{ "pile_set_name": "StackExchange" }
Q: Regarding calculation with rigorous steps I was studying a book called Theoretical Astrophysics by Prof T Padmanavan, and in the very first chapter, i find the expression of Net Contributing Pressure ($P$) as: $$P = \frac{1}{3} \int_{0}^{\infty}n(\epsilon)p(\epsilon)v(\epsilon)d\epsilon$$ followed by relativistic momentum $P = \gamma mv$ and kinetic energy, $\epsilon = (\gamma-1)mc^2$ with $\gamma$ as the relativistic factor. By far this I understood it, but then, substituting these values in the above given expression, as: $$P = \frac{1}{3} \int_{0}^{\infty}n\epsilon\left(1+\frac{2mc^2}{\epsilon}\right)\left(1+\frac{mc^2}{\epsilon}\right)^{-1}d\epsilon$$ is not understood by me. Can anyone please help me out with proper steps to achieve this expression. Thanks in advance ! A: Thanks to @robphy for providing the answer, and with some algebraic manipulation, I got this: $$P = \frac{1}{3}\int_{0}^{\infty}np(\epsilon)v(\epsilon)d\epsilon$$ $$= \frac{1}{3}\int_{0}^{\infty}np\frac{p}{\epsilon+m}d\epsilon$$ As, $v(\epsilon) = \frac{p}{E} = \frac{\sqrt{\epsilon(\epsilon+2m)}}{\epsilon+m}$ $$= \frac{1}{3}\int_{0}^{\infty}n\frac{p^2}{\epsilon+m}d\epsilon$$ $$= \frac{1}{3}\int_{0}^{\infty}n\frac{\epsilon(\epsilon+2m)}{\epsilon+m}d\epsilon$$ As, $p=\sqrt{\epsilon(\epsilon+2m)}$ Upto this, it was normalized as $c=1$, and reconsidering that, we get: $$P = \frac{1}{3}\int_{0}^{\infty}n\frac{\epsilon(\epsilon+2mc^2)}{\epsilon+mc^2}d\epsilon$$ $$= \frac{1}{3}\int_{0}^{\infty}n\epsilon(1+\frac{2mc^2}{\epsilon})(\frac{\epsilon}{{\epsilon+mc^2}})d\epsilon$$ $$= \frac{1}{3}\int_{0}^{\infty}n\epsilon(1+\frac{2mc^2}{\epsilon})(\frac{1}{1+\frac{mc^2}{\epsilon}})d\epsilon$$ $$\therefore P = \frac{1}{3}\int_{0}^{\infty}n\epsilon(1+\frac{2mc^2}{\epsilon})(1+\frac{mc^2}{\epsilon})^{-1}d\epsilon$$
{ "pile_set_name": "StackExchange" }
Q: Create a string/var/array from part of URL using javascript/jquery? Looking to populate a view based on part of a URL. www.example.com/f/objectID I have a website with a view that loads based on the an objectID that is stored on parse.com how can I extract/interpret "objectID" from the url to populate the /f/ view? A: Take a look at the window.location object. From there you just need some string methods. var objectID = location.pathname.split('/').pop(); .split() will split the path into the fragments separated by / and .pop() will retrieve the last one. Of course, if objectID may not always be the last segment, use the proper (0-based) index to retrieve it from array returned by split. Another solution that may have better performance (shouldn't really make a difference for this use case), assumes that objectID is the last segment: var objectID = location.pathname.substring(location.pathname.lastIndexOf('/')+1); Fiddle
{ "pile_set_name": "StackExchange" }
Q: How to set QGridLayout in particular position after removing one of its widget I am using QGridLayout to add one QPushButton and one QTextEdit. but whenever i am hiding and removing QTextEdit widget then QPushButton is coming on the position of QTextEdit. Initially QPushButton is in position lets say (0,0) and QTextEdit is in position (100,0). Then on removing QTextEdit QPushButton is coming on QTextEdit position ie, at position (100,0). layout->addWidget(button1,0,0,1,1, Qt::AlignCenter); layout->addWidget(text1,0,1,1,1); On pressing delete key i am removing QTextWidget: layout->removeWidget(text1); So i think i have to set the position of QGridLayout so that everytime after removing widget it should be in its proper position. A: Based upon your screenshot it looks like the column is completely removed when you remove the QTextWidget. You can try experimenting with setting the visibility of the QTextWidget to false rather than removing it. text1->setVisible( false ); Although based upon the QGridLayout doc this may have the same result. Or when you remove the QTextEdit replace it with a QSpacerItem so the column isn't completely remove. If that still doesn't work I would next try changing your align of the QPushButton to Qt::AlignLeft. layout->addWidget(button1,0,0,1,1, Qt::AlignLeft); If you're not happy with that I would try using a QHBoxLayout rather than the QGridLayout to layout the items horizontally. Or you could always use the QHBoxLayout within the first row/column of the QGridLayout, it's ultimately up to your future use cases. For example: QHBoxLayout* hLayout = new QHBoxLayout(); hLayout->addWidget( button1, 0, Qt::AlignLeft ); hLayout->addWidget( text1, 0, Qt::AlignLeft ); qGridLayout->addLayout ( hLayout, 0, 0, Qt::AlignLeft ); Again with the QHBoxLayout and QGridLayout (might no longer need to use the grid) you may have to play with the alignments to get the results you want. Something like this might work
{ "pile_set_name": "StackExchange" }
Q: Playing sound and a program What I want to do is get an audio file to play while a def (function) is running. I've looked it up and seen that threading works but it is wayyyy to complicated for me to work out. Is there a way you guys can explain it to me? I was using winsound to play the audio file, and SND_FILENAME. A: Try this: from multiprocessing import Process def play(): #winsound stuff def function(): #functiony stuff if __name__ == '__main__': p = Process(target=play) d = Process(target=function) p.start() d.start()
{ "pile_set_name": "StackExchange" }
Q: XCode Edit Project Settings vs Edit Active Target What is the difference between these 2 options under the Project menu drop-down? Normally I just adjusted things in the Project Settings (which adjusts the info.plist, right?). Today I needed to change the name of my project. Initially i changed the Product_Name from the Edit Project Settings -> Build window. But that didnt change the name. Then I tried changing the the Product_Name from the Edit Active Target -> Build window, and that seemed to do the trick. So again, what's the difference? XCode never fails to confuse me just when im beginning to think i have it all figured out! Argh!!! A: Project settings apply to all targets in your project. Target settings apply only to that specific target. You likely have only a single target which can make the two sets of settings confusing and appear redundant. If a setting is set (appears in bold) for both the project and a target, the target setting overrides the project setting. Target settings which aren't set (do not appear in bold) are inherited from the project settings. Project settings which aren't set (do not appear in bold) are inherited from Xcode's default settings. If a setting (either project or target) is set (appears in bold) and you instead want to inherit that setting, select the setting and press Delete. I suggest you prefer using the target settings. Use the project settings for larger, multi-target projects where you really do want to share settings across targets. A: It's worth adding that properties set at project level are not automatically inherited from the different configurations / targets of your project: in order to inherit properties that are set at project level you need to set the value $(inherited) in the fields where you actually want to inherit such properties.
{ "pile_set_name": "StackExchange" }
Q: Why is the ideal gas law only valid for hydrogen? I got this question in school: Explain, based on the properties of an ideal gas, why the ideal gas law only gives good results for hydrogen. We know that the ideal gas law is $$P\cdot V=n\cdot R\cdot T$$ with $P$ being the pressure, $V$ the volume, $n$ the amount of substance, $R$ the gas constant and $T$ the temperature (Source: Wikipedia - "Ideal gas"). An ideal gas must fulfill the following: The particles do have an infinitely small volume (or no volume), The particles do not interact with each other through attraction or repulsion, The particles can interact through elastic collisions. Now, why does only hydrogen sufficiently fulfill these conditions? I initially assumed that the reason is that it has the smallest volume possible as its nucleus only consists of a single proton. However, two things confuse me: (Let's first assume that my first idea was correct and the reason is the nucleus' scale/volume) helium's nucleus consists of two protons and two neutrons. It is therefore four times as large than hydrogen's nucleus. However, hydrogen's nucleus is infinitely times larger than an ideal gas molecule (which would have no volume), so why does the difference of $4$ significantly affect the accuracy of the ideal gas law, while the difference of an infinitely times larger hydrogen (nucleus) doesn't? My first idea is not even true, as atoms do not only consist of their nucleus. In fact, most of their volume comes from their electrons. In both hydrogen and helium, the electrons are in the same atomic orbital, so the volume of the atoms is identical. Other possibilities to explain that the ideal gas law only work for hydrogen and therefore only leave the collisions or interactions. For both of these, I do not see why they should be any different for hydrogen and helium (or at least not in such a rate that it would significantly affect the validity of the ideal gas law). So where am I wrong here? Note: I do not consider this a homework question. The question is not directly related to the actual problem, but I rather question whether the initial statement of the task is correct (as I tested every possible explanation and found none to be sufficient). Update I asked my teacher and told them my doubts. They agreed with my (and yours from the answers, of course!) points but still were of the opinion that Hydrogen is the closest to an ideal gas (apparently, they were taught so in university). They also claimed that the mass of the gas is relevant (which would be the lowest for hydrogen; but I doubt that since there is no $m$ in the ideal gas equation) and that apparently, when measuring, hydrogen is closest to an ideal gas. As I cannot do any such measurements by myself, I would need some reliable sources (some research paper would be best: Wikipedia and some Q&A site including SE - although I do not doubt that you know what you are talking about - are not considered serious or reliable sources). While I believe that asking for specific sources is outside the scope of Stack Exchange, I still would be grateful if you could provide some soruces. I believe it is in this case okay to ask for reference material since it is not the main point of my question. Update 2 I asked a new question regarding the role of mass for the elasticity of two objects. Also, I'd like to mention that I do not want to talk bad about my teacher since I like their lessons a lot and they would never tell us something wrong on purpose. This is probably just a misconception. A: The short answer is ideal gas behavior is NOT only valid for hydrogen. The statement you were given in school is wrong. If anything, helium acts more like an ideal gas than any other real gas. There are no truly ideal gases. Only those that sufficiently approach ideal gas behavior to enable the application of the ideal gas law. Generally, a gas behaves more like an ideal gas at higher temperatures and lower pressures. This is because the internal potential energy due to intermolecular forces becomes less significant compared to the internal kinetic energy of the gas as the size of the molecules is much much less than their separation. Hope this helps. A: The school question is wrong. What were they thinking? (My guess is that it was a simple slip-up and they meant helium.) The ideal gas equation of state works for any gas in the limit of low density. In order to give a quantitative estimate of how well the equation models a gas, one can compare it with measurements or with other equations which do a somewhat better job of modelling the gas. An equation often used in the design of chemical processing plants is named after Peng and Robinson. But for the present question a simpler one called the van der Waals equation will do. This equation is $$ \left( p + a \frac{n^2}{V^2} \right) \left( V - n b \right) = n R T $$ where $n$ is the number of moles and $a$ and $b$ are constants which depend on the gas. This equation is not perfectly accurate, but it helps us see the accuracy of the ideal gas equation. The ideal gas is obtained in the limit where $$ a \frac{n^2}{V^2}\ll p, \;\;\; \mbox{ and } \;\;\; nb \ll V $$ The constant $a$ is owing to inter-particle attractive forces; the constant $b$ is owing to the finite size of the particles (atoms or molecules). You can look up values of $a$ and $b$ for many common gases, and thus find out how well they are approximated by the ideal gas equation at any given pressure and temperature. That is enough to answer your question. Here are the values for hydrogen and helium and a couple of other gases: $$ \begin{array}{lcc} & a & b \\ & (L^2 bar/mol^2) & (L/mol) \\ \mbox{helium} & 0.0346 & 0.0238 \\ \mbox{hydrogen} & 0.2476 & 0.02661 \\ \mbox{neon} & 0.2135 & 0.01709 \\ \mbox{nitrogen} & 1.370 & 0.0387 \end{array} $$ You see from this that helium is closest to ideal at any given pressure and temperature. This is because its inter-atomic interactions are small compared with other elements, and helium atoms are smaller than other atoms (and molecules). There is another very interesting point that is worth a mention here. It is a notable fact that all ordinary$^1$ gases behave alike once you scale the pressure and temperature in the right way. It follows that they are all equally well approximated by the ideal gas equation, if you express the pressure as a multiple of the critical pressure and the temperature as a multiple of the critical temperature. (The critical pressure and temperature correspond to the point on the liquid to vapour transition line called the critical point.) $^1$ By 'ordinary' here I am just ruling out some highly reactive gases, or some with very complicated molecules or something like that. A: The ideal gas law is routinely used in engineering for calculations regarding air, natural gas, water or other vapor, ICE exhaust gases and almost everything that is sufficiently away from condensing pressure/temperature and some other conditions like the molar volume not being too low. It works. The condition "sufficiently away from condensing pressure/temperature" is different for different gases. That's where helium and hydrogen rule - they need only a few K temperature in order to behave. Water vapor may need some 800 K in order to be an ideal-ish gas no matter of the pressure. PS: The ideal gas law is also applicable in some pretty unexpected places, like osmotic pressure (where dissolved substance behaves like it is an ideal gas in the volume of the solution).
{ "pile_set_name": "StackExchange" }
Q: Match each dosent fail for non existing json path I have json object in response. If I try an invalid path to extract value and assert it with match each it always passes. * match each karate.jsonPath(response,"$[*].non.existing.path") == ["text1"] Am I doing something wrong here? Please Not: If I give correct path and the value doesn't match with 'text1' it fails. Absolutely no issue there. Seeing issue only with invalid json path. A: Yes, this is by design. match each is actually a loop. If the number of items is zero, the match will never be applied. If you want to ensure that the array needs to be non-empty, add a second check. * def foo = [1, 2] * match foo == '#[_ > 0]' * match each foo == '#number'
{ "pile_set_name": "StackExchange" }
Q: Solution of a differential equation having a singularity (not everywhere defined) Remind me about ordinary differential equations, whose solutions are not everywhere defined (have a singularity). I want to remember the exact definition of a solution with singularity, which I studied in a university long time ago. And please, an example. A: A solution $x(t)$ of the ODE is called maximal if it is defined on an open interval and cannot be extended to any larger open interval. From "Ordinary Differential Equation". Alexander Grigorian. University of Bielefeld. Lecture Notes, April - July 2008 So the things I search for are maximal solutions. The question remains: What is the best generalization of this for PDE?
{ "pile_set_name": "StackExchange" }
Q: ¿Cómo puedo ordenar una cadena (string) de forma descendente según su longitud? ¿Cómo puedo ordenar una cadena (string) de forma descendente, es decir que desde la palabra mas larga a la mas corta? A: Supongo que podrías hacer algo asi: >>> cadena = 'hola me llamo Cesar y soy de Peru' >>> sorted(cadena.split(), key=lambda palabra: len(palabra), reverse=True) ['llamo', 'Cesar', 'hola', 'Peru', 'soy', 'me', 'de', 'y']
{ "pile_set_name": "StackExchange" }
Q: Primary Constructor + Call Super Constructor in Kotlin open class Foo constructor(a: Int) { private val _a: Int = a } open class Bar : Foo { constructor(a: Int, b: Int) : super(a) { // doSomething } constructor(a: Int, b: String) : super(a) { // doSomething } } I want to make 'constructor(a: Int, b: Int)' of 'Bar' class as the primary constructor, calling the constructor of super class. How can write it? A: Declare your primary constructor like normal and use its parameters to "invoke" a constructor of inherited class. Then move your primary constructor logic into a init block: open class Bar(a: Int, b: Int) : Foo(a) { init { // [1] init block serves as primary constructor body } constructor(a: Int, b: String) : this(a, b.toInt()) { // [2] doSomething } } This will however impose following constraints: Secondary constructor must call into primary constructor. This means you must be able to transform arguments or provide default values to it if needed. Both constructor and init blocks will be invoked (in that order: [1] and [2]). You're limiting your class to use only a single constructor from parent class. If it has more than one constructor and you want to match & call them in your child class you can not use a primary constructor.
{ "pile_set_name": "StackExchange" }
Q: How to create routing inside a modal window [ ANGULAR 5 ]? I have a requirement where i need to switch between 2 different views back and forth based on certain condition inside a modal window's body. Those 2 views are : List items (Initial view) Add new items After adding new items i need to switch to the List items view. NOTE: All these views should be displayed inside a modal windows body. So using ANGULAR 5 routing how can i create new routes / sub routes inside this modal component ? A: Create another router-outlet with a name like this <router-outlet name="modal"></router-outlet> To navigate to it in your ts, use this.router.navigate([{ outlets: { modal: 'route' }}]) while in your html, use <button md-button [routerLink]="[{outlets: {'modal': ['route']}}]">Speakers</button> you can also specify it in your routes like { path: ':id', component: YourComponent, outlet: 'modal' }
{ "pile_set_name": "StackExchange" }
Q: Getting the argument types of a constructor using Data and Typeable I'm playing around with Haskell's Data and Typeable, and I'm stuck trying to get the arguments of a function without a type variable being available in the context. Let me clarify what I mean. As long as I have the type variable a quantified like below, I can use fromConstr and obtain a list of DataType or TypeRep as I wish: constrArgs :: forall a. Data a => Constr -> [DataType] constrArgs c = gmapQ f (fromConstr c :: a) where f :: forall d. Data d => d -> DataType f _ = dataTypeOf @d undefined (I realize the undefined and fromConstr are nontotal but laziness saves us here.) However, if I try to avoid quantifying a, I can no longer do a type ascription to the result of fromConstr. I wonder if there is a way to write a function with the following type signature: constrArgs' :: Constr -> [DataType] My end goal is to write a function that gives a list of lists of DataTypes, a sublist for each constructor, each sublist containing the argument types of that constructor. Using the first version, it's not difficult to write a function with the type signature: (definition elided) allConstrArgs :: forall a. Data a => [[DataType]] The problem with this is that I cannot apply allConstrArgs to the results of itself, because there is no way to go from DataType to a type-level value. So, in order to amend that, can we write a function that has the following type? allConstrsArgs' :: DataType -> [[DataType]] I looked around in the base library but I'm failing to see how this can be achieved. A: You can't get a list of argument types out of a Constr, because it just doesn't have enough data in it: it's a bunch of strings, nothing more. However, there is a way to achieve your bigger goal: you just need to carry the Data dictionary around with you, and what better way to do it than an existential type! data D = forall a. Data a => D a allConstrArgs :: D -> [[D]] allConstrArgs d = constrArgs d <$> allConstrs d constrArgs :: D -> Constr -> [D] constrArgs (D a) c = gmapQ D $ mkConstr a c where mkConstr :: forall a. Data a => a -> Constr -> a mkConstr _ = fromConstr allConstrs :: D -> [Constr] allConstrs (D a) = case dataTypeRep $ dataTypeOf a of AlgRep constrs -> constrs _ -> [] mkD :: forall a. Data a => D mkD = D (undefined :: a) Here the type D serves solely to wrap the Data dictionary - the actual value a will always be undefined, and never actually evaluated, so that's fine. The value D thus serves as a value-level representation of a type, such that upon destructuring you get a Data instance for that type in scope. The function constrArgs takes a type representation D and a constructor Constr, and returns a list of that constructor's parameters, each represented as D as well - so now you can feed its output back into its input! It does this by using gmapQ, whose first argument type perfectly fits the D constructor. mkD is just a utility function meant to hide the unpleasantness of undefined and to be used with TypeApplications, e.g. mkD @Int. And here's usage: data X = X0 Int | X1 String deriving (Typeable, Data) data Y = Y0 String | Y1 Bool | Y2 Char deriving (Typeable, Data) data Z = ZX X | ZY Y deriving (Typeable, Data) typName :: D -> String typName (D a) = dataTypeName $ dataTypeOf a main = do -- Will print [["Prelude.Int"],["Prelude.[]"]] print $ map typName <$> allConstrArgs (mkD @X) -- Will print [["Prelude.[]"],["Bool"],["Prelude.Char"]] print $ map typName <$> allConstrArgs (mkD @Y) -- Will print [["X"],["Y"]] print $ map typName <$> allConstrArgs (mkD @Z) Note that you will need the following extensions for this to work: ScopedTypeVariables, DeriveDataTypeable, GADTs, AllowAmbiguousTypes, TypeApplications
{ "pile_set_name": "StackExchange" }
Q: Ubuntu 14.04 no sound I can hear no sound from my laptop. I installed Ubuntu 14.04 2 days ago and at first everything worked fine, but after a reboot the sound stopped. I searched for 3 hours on google and tried everything I found, but nothing helped. EDIT: I already tried the solution from the posted thread and it didn't help. EDIT2: The sound does work on headphones. But it doesn't work on speakers. It's not a hardware problem. AlsaInfo: http://www.alsa-project.org/db/?f=5b7f589a8cd035feb28d0a87bd1c79a304c5ad29 A: Try first to reload ALSA: sudo alsa force-reload If that won't help, try to reinstall ALSA and pulseaudio: sudo apt-get remove --purge alsa-base pulseaudio sudo apt-get install alsa-base pulseaudio A: None of the above worked for me on my Ubuntu 14.04. I had a fresh reinstall due to video problems, keeping my home folder alone. Then after a few shutdowns, BAM no sound! Tried all of the above solutions. Sound Troubleshooting Procedure, worked like a miracle. The steps are as follows: right from the website, verbatim: killall pulseaudio; rm -r ~/.config/pulse/* ; rm -r ~/.pulse* Wait 10 seconds, and then... pulseaudio -k Thats it! This should apprently work for Ubuntu 12 and later. More solutions are available in the link above, but this is the first thign you should try according to the Ubuntu Sound Trouble shooting procedure.
{ "pile_set_name": "StackExchange" }
Q: How does tf.nn.ctc_greedy_decoder generates output sequences in tensorflow? Given the logits (output from the RNN/Lstm/Gru in time major format i.e. (maxTime, batchSize, numberofClasses)), how does ctc greedy decoder performs decoding to generate output sequence. I found this "Performs greedy decoding on the logits given in input (best path)" on its webpage https://www.tensorflow.org/api_docs/python/tf/nn/ctc_greedy_decoder. One possibility is to select output class with maximum value at each time step, collapse repetitions and generate corresponding output sequence. Is it, ctc greedy decoder doing here or something else? Explanation using an example will be very useful. A: The operation ctc_greedy_decoder implements best path decoding, which is also stated in the TF source code [1]. Decoding is done in two steps: Concatenate most probable characters per time-step which yields the best path. Then, undo the encoding by first removing duplicate characters and then removing all blanks. This gives us the recognized text. Let's look at an example. The neural network outputs a matrix with 5 time-steps and 3 characters ("a", "b" and the blank "-"). We take the most likely character per time-step, which gives us the best path: "aaa-b". Then, we remove repeated characters and get "a-b". Finally, we remove all blanks and get "ab" as the result. More information about CTC can be found in [2] and an example on how to use it in Python is shown in [3]. [1] Implementation of ctc_greedy_decoder: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/util/ctc/ctc_decoder.h#L69 [2] Further information about CTC, best path decoding and beam search decoding: https://towardsdatascience.com/5a889a3d85a7 [3] Sample code which shows how to use ctc_greedy_decoder: https://github.com/githubharald/SimpleHTR/blob/master/src/Model.py#L94
{ "pile_set_name": "StackExchange" }
Q: How do I Display date on Aspx page? I am using asp.net webforms for the first time and am trying to display the current date in the following form: Friday, July 13 <h3>Suggested reading for <% DateTime.Now.ToString(); %></h3> However, this only displays Suggested reading for on my page. I don't know if this helps, but here is some surrounding code: <%@ Page Title="Register" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="Fake_Coupon_Site.Account.Register" %> <asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent"> <hgroup class="title"> <h1><%: Title %>.</h1> <h2>Use the form below to create a new account.</h2> <h3>Suggested reading for <% DateTime.Now.ToString(); %></h3> </hgroup> A: Try <h3>Suggested reading for <%= DateTime.Now.ToString("dddd, MMMM dd") %></h3>
{ "pile_set_name": "StackExchange" }
Q: SQL concatenate one of the columns in groups of 10 with LISTAGG() I need help writing a query that can concatenate one of the columns in groups of 10. Example: id1 | string1 id1 | string2 id1 | string3 ... id1 | string 1000 Since SQL do not allow too large concatenated strings I would like to maybe group 10 at a time so that I get: id1 | string1,string2,...,string10 id1 | string11,string12,...,string20 Thanks A: select id,listagg (str,',') within group (order by str) from (select id,str,row_number () over (partition by id order by str) - 1 as rn from t ) group by id,floor (rn / 10) ; or if you don't care about the order - select id,listagg (str,',') within group (order by null) from (select id,str,rownum - 1 as rn from t ) group by id,floor (rn / 10) ; Sample create table t as select 'id' || to_char(ceil(level/100)) as id ,'str' || lpad(to_char(level),4,'0') as str from dual connect by level <= 1000 ;
{ "pile_set_name": "StackExchange" }
Q: Strange Problem with File.Move command I have encountered a strange problem when using the File.Move command. The Programm actually moves and renames the file, but then throws me an exception that the sourcefile is not found; - what is expected because the File was moved. The Program works fine if i catch the Exception but i'm wondering why i get these exception. My Code: foreach (string str in CPM.prot.FKFinishedBad) { try { string dir = System.Configuration.ConfigurationSettings.AppSettings["ResultDir"] + "\\" + DateTime.Now.ToString("yyyy_MM_dd") + "_Bearbeitete Protokolle"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.Move(System.Configuration.ConfigurationSettings.AppSettings["ResultDir"] + "\\" + str + "_" + CPM.LastJob + ".txt", dir + "\\" + "\\" + str + "_" + CPM.LastJob + "_Nachproduziert" + ".txt"); } catch (Exception e) { } } A: Are you sure all of your files exist? It might happen that one of them is missing (which explains the exception), while the others are processed correctly. you can also check them before the move with File.Exists. Also, be careful when using empty catch blocks, they can cause a lot of headaches when debugging.
{ "pile_set_name": "StackExchange" }
Q: Could not load file or assembly 'PDFLibNet' or one of its dependencies I'm running into an issue that it says pdf lib doesn't match the .netversion I'm using. The problem is I'm using the same version on both Microsoft .NET Framework Version:2.0.50727.9031; ASP.NET Version:2.0.50727.9031; PDF Lib: v2.0.50727; LOG: Attempting download of new URL file:///C:/Projects/bin/PDFLibNet.DLL. ERR: Failed to complete setup of assembly (hr = 0x8013101b). Probing terminated. [BadImageFormatException: Could not load file or assembly 'PDFLibNet' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.] A: Figured it out for some reason it was referencing the wrong one in my webservice/BIN folder after I removed the .dll file it pulled the new one and that fixed it!
{ "pile_set_name": "StackExchange" }
Q: python3 parsing XML I have the following xml which contains email configuration for various email service providers, and I'm trying to parse these information into a dict; hostname, is_ssl, port, protocol ..etc <domains> <domain> <name>zoznam.sk</name> <description>Zoznam Slovakia</description> <service> <hostname>imap.zoznam.sk</hostname> <port>143</port> <protocol>IMAP</protocol> <authentication>PLAIN</authentication> <usernameIncludesDomain/> </service> <service> <hostname>smtp.zoznam.sk</hostname> <port>587</port> <protocol>SMTP</protocol> <authentication>PLAIN</authentication> <usernameIncludesDomain/> </service> </domain> <domain> <name>123mail.org</name> <description>123mail.org</description> <service> <hostname>imap.fastmail.com</hostname> <port>993</port> <protocol>IMAP</protocol> <ssl/> <requires/> <authentication>PLAIN</authentication> <usernameIncludesDomain/> </service> <service> <hostname>smtp.fastmail.com</hostname> <port>587</port> <protocol>SMTP</protocol> <ssl/> <requires/> <authentication>PLAIN</authentication> <usernameIncludesDomain/> </service> </domain> <domain> <name>Netvigator.com</name> <description>netvigator.com</description> <service> <hostname>corpmail1.netvigator.com</hostname> <port>995</port> <protocol>POP</protocol> <ssl/> <authentication>NONE</authentication> <usernameIncludesDomain/> </service> <service> <hostname>corpmail1.netvigator.com</hostname> <port>587</port> <protocol>SMTP</protocol> <ssl/> <authentication>NONE</authentication> <usernameIncludesDomain/> </service> </domain> </domains> I tried to parse the name for testing but could not succeed, I'm need to python. import xml.etree.ElementTree as ET configs_file = 'isp_list.xml' def parseXML(xmlfile): # create element tree object tree = ET.parse(xmlfile) # get root element root = tree.getroot() # create empty list for configs items configs = [] # iterate items for item in root.findall('domains/domain'): value = item.get('name') # test print(value) # append news dictionary to items list configs.append(item) # return items list return configs I appreciate your help. thank you. A: You can still use bs4 to generate a dict. For the if else lines you could use the more compact syntax of e.g. 'ssl' : getattr(item.find('ssl'), 'text', 'N/A') Script: from bs4 import BeautifulSoup as bs xml = ''' <domains> <domain> <name>zoznam.sk</name> <description>Zoznam Slovakia</description> <service> <hostname>imap.zoznam.sk</hostname> <port>143</port> <protocol>IMAP</protocol> <authentication>PLAIN</authentication> <usernameIncludesDomain/> </service> <service> <hostname>smtp.zoznam.sk</hostname> <port>587</port> <protocol>SMTP</protocol> <authentication>PLAIN</authentication> <usernameIncludesDomain/> </service> </domain> <domain> <name>123mail.org</name> <description>123mail.org</description> <service> <hostname>imap.fastmail.com</hostname> <port>993</port> <protocol>IMAP</protocol> <ssl/> <requires/> <authentication>PLAIN</authentication> <usernameIncludesDomain/> </service> <service> <hostname>smtp.fastmail.com</hostname> <port>587</port> <protocol>SMTP</protocol> <ssl/> <requires/> <authentication>PLAIN</authentication> <usernameIncludesDomain/> </service> </domain> <domain> <name>Netvigator.com</name> <description>netvigator.com</description> <service> <hostname>corpmail1.netvigator.com</hostname> <port>995</port> <protocol>POP</protocol> <ssl/> <authentication>NONE</authentication> <usernameIncludesDomain/> </service> <service> <hostname>corpmail1.netvigator.com</hostname> <port>587</port> <protocol>SMTP</protocol> <ssl/> <authentication>NONE</authentication> <usernameIncludesDomain/> </service> </domain> </domains> ''' data = {} soup = bs(xml, 'lxml') for domain in soup.select('domain'): name = domain.select_one('name').text data[name] = { 'name' : name, 'desc' : domain.select_one('description').text, 'services' : {} } i = 1 for item in domain.select('service'): service = { 'hostname' : item.select_one('hostname').text if item.select_one('hostname') else 'N/A', 'port' : item.select_one('port').text if item.select_one('port') else 'N/A', 'protocol' : item.select_one('protocol').text if item.select_one('protocol').text else 'N/A', 'ssl' : item.select_one('ssl').text if item.select_one('ssl') else 'N/A', 'requires' : item.select_one('requires \: ').text if item.select_one('requires \: ') else 'N/A', 'authentication' : item.select_one('authentication').text if item.select_one('authentication') else 'N/A', 'usernameincludesdomain' : item.select_one('usernameincludesdomain').text if item.select_one('usernameincludesdomain') else 'N/A' } data[name]['services'][str(i)] = service i+=1 print(data) view the structure here If you are literally converting xml to a json like structure maybe a library like untangle would work?
{ "pile_set_name": "StackExchange" }
Q: applicationDidFinishLaunching not invoked In my appdelegate.m, the applicationDidFinishLaunching is not invoked. I have read that this is due to the fact my "Application"'s delegate is not properly connected, but I don't know how to connect it. What I do is right-clicking on Application from the XIB file, and drag the delegate outlet somewhere... but don't know where. Any help appreciated. Thanks ! A: In your MainMenu.xib, make sure there's an instance of your AppDelegate class. To make one, drag a plain object (blue cube) into the list and set its class name to AppDelegate (or whatever your app delegate class name is). Also in the MainMenu.xib, to connect it, drag a connection from the Application object to your AppDelegate instance (the blue cube) and connect it to the delegate outlet. Done. A: Here's something to try if you've updated to Swift 3: Take a peek at your "AppDelegate.swift" and make sure the relevant line looks like this: func applicationDidFinishLaunching(_ aNotification: Notification) { as opposed to this: func applicationDidFinishLaunching(_ aNotification: NSNotification) { I just updated an app, and didn't think to check. The result was that my app launched, but the relevant method was never called. Obviously, you should then check for other functions you have that take Notification objects.
{ "pile_set_name": "StackExchange" }
Q: Mac OS X Server ontopic? What about questions about Mac OS X Server? Shall they go here, or would Serverfault be the better place? A: This is Apple, feel free to ask here. Note that you may have better luck on ServerFault though, if it's not a very specific Apple question. The more general server questions should probably go on SF.
{ "pile_set_name": "StackExchange" }
Q: Avatars aren't loading, with a status 301 (permanently moved) response Some avatars (including my own) aren't loading anymore, and instead I get a transparent box. This occurs particularly after I refresh a page. In my developer tools network tab, every request for an i.stack.imgur.com avatar seems to get a response of 301 (permanently moved) without content, which might explain why those avatars don't load up. Related: Is imgur currently down? A: I'm pasting the headers of a request here, too long for a comment. It's an infinite redirect, Firefox aborts after about 20 with "The page isn’t redirecting properly". GET /bv54Xm.jpg HTTP/1.1 Host: i.stack.imgur.com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Cookie: (redacted) DNT: 1 Connection: keep-alive Upgrade-Insecure-Requests: 1 HTTP/1.1 301 Moved Permanently Content-Type: text/html Content-Length: 178 Connection: keep-alive Cache-Control: max-age=604800 Date: Tue, 07 Aug 2018 19:19:49 GMT Expires: Tue, 14 Aug 2018 19:19:49 GMT Location: http://i.stack.imgur.com/bv54Xm.jpg Server: nginx Age: 2955 X-Cache: Hit from cloudfront Via: 1.1 3fcf791d8ee7abab9c778dfe6fea5b7f.cloudfront.net (CloudFront) X-Amz-Cf-Id: yc5K9NR1u1K1-ckd-EUjGRmLq5MhViMNKzKpNYAN19ADxBA66Fw_eg== Edit: fixed for me as of 2018-08-08 15:00 UTC, I understand other people still have issues. A: Update Seems that the Avatar situation came back now that I checked again, 3 hours after... Just right now I can see the avatars are back again on my Firefox. Perhaps it will appear to others after the cache takes some time:
{ "pile_set_name": "StackExchange" }
Q: Webview loadurl Opening the default browser I have created one activity along with webview and loaded some url in it.But when i loaded google url in webview it opening in device default browser but when i loaded some other urls in it,it works fine for me. Permission added in manifest - For ex - This is open in device browser WebSettings webSettings = webVw.getSettings(); webSettings.setJavaScriptEnabled(true); webVw.loadUrl("http://www.google.com"); This is opens in webview - webVw = (WebView)findViewById(R.id.webVw); WebSettings webSettings = webVw.getSettings(); webSettings.setJavaScriptEnabled(true); webVw.loadUrl("https://stackoverflow.com"); Q: Why this happens? Is there any other workaround to do it? A: You can use this: webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("url"); Check the WebView tutorial from here. Just implement the web client and set it before loadUrl. The simplest way is: myWebView.setWebViewClient(new WebViewClient());
{ "pile_set_name": "StackExchange" }
Q: scaleGroup.CreateObject() in Softlayer I'm trying to create a scale group using Java Client. How can I set NetworkComponent, Storage(San,local), LoadBalancer, and Policy ? This is a sample code to create a group object. I want to make sure this is a correct way to set. Please check my comment on the code. Thank you. Group.Service scaleGroupService = Group.service(client); Location location = new Location(); location.setName("hkg02"); Guest guest = new Guest(); guest.setDomain("softlayer.com"); guest.setHostname("hostnametest"); guest.setMaxMemory(new Long(1024)); guest.setPostInstallScriptUri("https://www.softlayer.com/script"); guest.setStartCpus(new Long(1)); guest.setDatacenter(location); guest.setHourlyBillingFlag(true); guest.setLocalDiskFlag(false); guest.setOperatingSystemReferenceCode("CENTOS_LATEST"); // To set Network component // guest.getNetworkComponents().get(0).setMaxSpeed(maxSpeed); // To set Storage // guest.setBlockDeviceTemplateGroup(blockDeviceTemplateGroup); Group scaleGroup = new Group(); scaleGroup.setCooldown(new Long(1800)); scaleGroup.setMaximumMemberCount(new Long(5)); scaleGroup.setMinimumMemberCount(new Long(1)); scaleGroup.setName("testVSI"); scaleGroup.setRegionalGroupId(new Long(102)); scaleGroup.setSuspendedFlag(false); scaleGroup.setTerminationPolicyId(new Long(2)); scaleGroup.setVirtualGuestMemberTemplate(guest); scaleGroup.setVirtualGuestMemberCount(new Long(0)); // To set Loadbalancer // scaleGroup.getLoadBalancers().set(index, loadbalancer element) // To set Policy // scaleGroup.getPolicies().set(index, policy element) Gson gson = new Gson(); System.out.println(gson.toJson(scaleGroupService.createObject(scaleGroup))); A: Here a java script to create a Scale Group defining NetworkComponent, Storage(San,local), LoadBalancer, and Policy. As you can see in the script: virtualGuestMemberTemplate.setLocalDiskFlag(false); It defines if the disks are LOCAL (true) or SAN (false). I think it is something tedious to understand, but is the way that it works, I will try to improve the script. package com.softlayer.api.ScaleGroup; import com.softlayer.api.ApiClient; import com.softlayer.api.RestApiClient; import com.softlayer.api.service.Location; import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.health.Check; import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.health.check.Type; import com.softlayer.api.service.scale.Group; import com.softlayer.api.service.scale.LoadBalancer; import com.softlayer.api.service.scale.Policy; import com.softlayer.api.service.scale.network.Vlan; import com.softlayer.api.service.scale.policy.action.Scale; import com.softlayer.api.service.virtual.Guest; import com.softlayer.api.service.virtual.disk.Image; import com.softlayer.api.service.virtual.guest.block.Device; import com.softlayer.api.service.virtual.guest.network.Component; import java.util.ArrayList; import java.util.List; /** * This script creates a Scale Group with Load Balancer and Policy * * Important Manual Page: * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group/createObject * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group/getAvailableRegionalGroups * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Scale_Group * * @license <http://sldn.softlayer.com/article/License> * @authon SoftLayer Technologies, Inc. <[email protected]> * @version 0.2.2 (master branch) */ public class CreateObject { /** * This is the constructor, is used to create a scale group */ public CreateObject() { // Declare your SoftLayer username and apiKey String username = "set me"; String apiKey = "set me"; // Create client ApiClient client = new RestApiClient().withCredentials(username, apiKey); Group.Service groupService = Group.service(client); // Define SoftLayer_Scale_Group object that you wish to create Group templateObject = new Group(); templateObject.setCooldown(new Long(1800)); templateObject.setMaximumMemberCount(new Long(5)); templateObject.setMinimumMemberCount(new Long(1)); templateObject.setName("TestRcv2"); templateObject.setRegionalGroupId(new Long(463)); templateObject.setTerminationPolicyId(new Long(2)); templateObject.setSuspendedFlag(false); // Define SoftLayer_Virtual_Guest Guest virtualGuestMemberTemplate = new Guest(); virtualGuestMemberTemplate.setHostname("rcvtest"); virtualGuestMemberTemplate.setDomain("softlayer.com"); virtualGuestMemberTemplate.setMaxMemory(new Long(1024)); virtualGuestMemberTemplate.setStartCpus(new Long(1)); // Define block devices, First Block Device Device firstBlock = new Device(); firstBlock.setDevice("0"); Image firstImage = new Image(); firstImage.setCapacity(new Long(100)); firstBlock.setDiskImage(firstImage); // Second Block Device Device secondBlock = new Device(); secondBlock.setDevice("2"); Image secondImage = new Image(); secondImage.setCapacity(new Long(400)); secondBlock.setDiskImage(secondImage); // Third Block Device Device thirdBlock = new Device(); thirdBlock.setDevice("3"); Image thirdImage = new Image(); thirdImage.setCapacity(new Long(750)); thirdBlock.setDiskImage(thirdImage); // Adding Block Devices to the template virtualGuestMemberTemplate.getBlockDevices().add(firstBlock); virtualGuestMemberTemplate.getBlockDevices().add(secondBlock); virtualGuestMemberTemplate.getBlockDevices().add(thirdBlock); // Define Location Location location = new Location(); location.setName("hou02"); virtualGuestMemberTemplate.setDatacenter(location); // Define Hourly billing and local disk virtualGuestMemberTemplate.setHourlyBillingFlag(true); virtualGuestMemberTemplate.setLocalDiskFlag(false); // Define Network Components Component networkComponent = new Component(); networkComponent.setMaxSpeed(new Long(10)); virtualGuestMemberTemplate.getNetworkComponents().add(networkComponent); // Define OS virtualGuestMemberTemplate.setOperatingSystemReferenceCode("WIN_2012-STD-R2_64"); virtualGuestMemberTemplate.setPrivateNetworkOnlyFlag(false); // Define Vlans Vlan firstVlan = new Vlan(); firstVlan.setNetworkVlanId(new Long(1072495)); Vlan secondVlan = new Vlan(); secondVlan.setNetworkVlanId(new Long(1072493)); List<Vlan> networkVlans = new ArrayList<Vlan>(); networkVlans.add(firstVlan); networkVlans.add(secondVlan); // Adding Vlans to the template templateObject.getNetworkVlans().addAll(networkVlans); // Adding Virtual Guest member template to the template templateObject.setVirtualGuestMemberTemplate(virtualGuestMemberTemplate); // Load Balancer LoadBalancer loadBalancer = new LoadBalancer(); loadBalancer.setDeleteFlag(false); loadBalancer.setPort(new Long(80)); // Set Server Id loadBalancer.setVirtualServerId(new Long(222155)); // Define TYpe Type type = new Type(); type.setKeyname("HTTP"); Check healthCheck = new Check(); healthCheck.setType(type); loadBalancer.setHealthCheck(healthCheck); // Adding Load Balancer to the template templateObject.getLoadBalancers().add(loadBalancer); // Define Policy Policy policy = new Policy(); policy.setCooldown(new Long(1800)); policy.setName("newPolicyName"); // Define Action for the policy Scale scaleActions = new Scale(); scaleActions.setScaleType("RELATIVE"); scaleActions.setAmount(new Long(4)); policy.getScaleActions().add(scaleActions); // Add Policy to the template templateObject.getPolicies().add(policy); try { Group result = groupService.createObject(templateObject); System.out.println(result); } catch (Exception e) { System.out.println("Error: " + e); } } /** * This is the main method which makes use of CreateObject method. * * @param args * @return Nothing */ public static void main(String[] args) { new CreateObject(); } } Please, let me know, any doubt or comment about it. Here another script: package com.softlayer.api.ScaleGroup; import com.google.gson.Gson; import com.softlayer.api.ApiClient; import com.softlayer.api.RestApiClient; import com.softlayer.api.service.Account; import com.softlayer.api.service.Location; import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.VirtualIpAddress; import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.VirtualServer; import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.health.Check; import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.health.check.Type; import com.softlayer.api.service.provisioning.Hook; import com.softlayer.api.service.scale.Group; import com.softlayer.api.service.scale.LoadBalancer; import com.softlayer.api.service.scale.Policy; import com.softlayer.api.service.scale.network.Vlan; import com.softlayer.api.service.scale.policy.action.Scale; import com.softlayer.api.service.security.ssh.Key; import com.softlayer.api.service.virtual.Guest; import com.softlayer.api.service.virtual.disk.Image; import com.softlayer.api.service.virtual.guest.block.Device; import com.softlayer.api.service.virtual.guest.network.Component; /** * This script creates a Scale Group with Load Balancer and Policy * * Important Manual Page: * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group/createObject * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group/getAvailableRegionalGroups * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Scale_Group * * @license <http://sldn.softlayer.com/article/License> * @authon SoftLayer Technologies, Inc. <[email protected]> * @version 0.2.2 (master branch) */ public class CreateObject { /** * This is the constructor, is used to create a scale group */ public CreateObject() { // Declare your SoftLayer username and apiKey String username = "set me"; String apiKey = "set me"; // Create client and services ApiClient client = new RestApiClient().withCredentials(username, apiKey); Group.Service groupService = Group.service(client); com.softlayer.api.service.scale.termination.Policy.Service terminationPolicyService = com.softlayer.api.service.scale.termination.Policy.service(client); Account.Service accountService = Account.service(client); VirtualIpAddress.Service virtualIpAddressService = VirtualIpAddress.service(client); /** * Group Configuration * Group Details */ String groupName = "RuberCuellartest3"; String region = "na-usa-south-1"; String datacenter = "hou02"; String terminationPolicy = "Newest"; /** * Network * Vlans */ Long[] networkVlans = {new Long(1244), new Long(1318)}; /** * Group Settings */ Long minimumMemberCount = new Long(1); Long maximumMemberCount = new Long(5); Long cooldown = new Long(1800); /** * Member Configuration * Member Details */ String hostname = "rcvtest"; String domain = "softlayer.com"; /** * Computing Instance */ Long cores = new Long(1); Long ram = new Long(8); Long speed = new Long(100); String[] sshKeys = {"tonny", "Rahul"}; /** * Operating System */ String operatingSystem = "WIN_2012-STD-R2_64"; /** * Storage * diskType options "SAN" and "LOCAL" */ //String diskType = "SAN"; //Long[] sizes = {new Long(100), new Long(200), new Long(400)}; String diskType = "SAN"; Long[] sizes = {new Long(100), new Long(100)}; /** * Post-Install Script * Fill with the post provision script name or fill with the url script that you wish to set */ String namePostInstall = "Neo4j"; /** * Local Load Balancer */ String virtualIp = "173.193.117.96"; String serviceGroup = "DNS"; Long serviceGroupPort = new Long(53); Long port = new Long(100); String serviceHealthCheckType = "HTTP"; /** * Policies * Policy Name */ String policyName = "PolicyNameRuber"; Long policyCooldown = new Long(1800); /** * Action Options: * 1. Scale group to quantity (absolute) = ABSOLUTE * 2. Scale group by percentage = PERCENT * 3. Scale group by quantity = RELATIVE */ String action = "PERCENT"; Long amountAction = new Long(100); /** * Define SoftLayer_Scale_Group object that you wish to create */ Group templateObject = new Group(); templateObject.setName(groupName); templateObject.setRegionalGroupId(getRegionalGroupId(groupService, region)); templateObject.setTerminationPolicyId(getTerminationPolicy(terminationPolicyService, terminationPolicy)); templateObject.setCooldown(cooldown); templateObject.setMaximumMemberCount(maximumMemberCount); templateObject.setMinimumMemberCount(minimumMemberCount); templateObject.setSuspendedFlag(false); // Define SoftLayer_Virtual_Guest Guest virtualGuestMemberTemplate = new Guest(); virtualGuestMemberTemplate.setHostname(hostname); virtualGuestMemberTemplate.setDomain(domain); virtualGuestMemberTemplate.setMaxMemory(ram); virtualGuestMemberTemplate.setStartCpus(cores); String[] devices = {"0", "2", "3", "4", "5", "6"}; for(int i = 0; i<sizes.length ; i++){ Device firstBlock = new Device(); firstBlock.setDevice(devices[i]); Image firstImage = new Image(); firstImage.setCapacity(sizes[i]); firstBlock.setDiskImage(firstImage); virtualGuestMemberTemplate.getBlockDevices().add(firstBlock); } // Define Location Location location = new Location(); location.setName(datacenter); virtualGuestMemberTemplate.setDatacenter(location); // Define Hourly billing and local disk virtualGuestMemberTemplate.setHourlyBillingFlag(true); if(diskType.equals("LOCAL")) { virtualGuestMemberTemplate.setLocalDiskFlag(true); }else{virtualGuestMemberTemplate.setLocalDiskFlag(false);} // Network Components Component networkComponent = new Component(); networkComponent.setMaxSpeed(speed); virtualGuestMemberTemplate.getNetworkComponents().add(networkComponent); // OS virtualGuestMemberTemplate.setOperatingSystemReferenceCode(operatingSystem); virtualGuestMemberTemplate.setPrivateNetworkOnlyFlag(false); // Ssh key for(int i = 0; i<sshKeys.length; i++) { Key newKey = new Key(); newKey.setId(getSshKeys(accountService, sshKeys[i])); virtualGuestMemberTemplate.getSshKeys().add(newKey); } // Provision Script if(namePostInstall != "") { virtualGuestMemberTemplate.setPostInstallScriptUri(getPostInstallScript(accountService, namePostInstall)); } // Network Vlans for(int i = 0; i<networkVlans.length; i++) { Vlan vlan = new Vlan(); vlan.setNetworkVlanId(getVlanId(accountService, networkVlans[i])); templateObject.getNetworkVlans().add(vlan); } // Adding Virtual Guest member template to the template templateObject.setVirtualGuestMemberTemplate(virtualGuestMemberTemplate); // Load Balancer LoadBalancer loadBalancer = new LoadBalancer(); loadBalancer.setDeleteFlag(false); loadBalancer.setPort(port); // Set Server Id loadBalancer.setVirtualServerId(getVirtualServerId(accountService, serviceGroupPort, virtualIp)); // Define Type Type type = new Type(); type.setKeyname(serviceHealthCheckType); Check healthCheck = new Check(); healthCheck.setType(type); loadBalancer.setHealthCheck(healthCheck); // Adding Load Balancer to the template templateObject.getLoadBalancers().add(loadBalancer); // Define Policy Policy policy = new Policy(); policy.setCooldown(policyCooldown); policy.setName(policyName); // Define Action for the policy Scale scaleActions = new Scale(); scaleActions.setScaleType(action); scaleActions.setAmount(amountAction); policy.getScaleActions().add(scaleActions); // Add Policy to the template templateObject.getPolicies().add(policy); Gson gson = new Gson(); System.out.println(gson.toJson(templateObject)); try { Group result = groupService.createObject(templateObject); System.out.println(result); } catch (Exception e) { System.out.println("Error: " + e); } } /** * Retrieves rion identifier * @param region string * @return region identifier */ public Long getRegionalGroupId(Group.Service groupService, String region) { Long regionId = new Long(0); for(com.softlayer.api.service.location.Group regionalGroup : groupService.getAvailableRegionalGroups()) { if(regionalGroup.getName().equals(region)) { regionId = regionalGroup.getId(); } } return regionId; } /** * Returns policy termination identifier * @param policyService * @param name * @return Policy termination identifier */ public Long getTerminationPolicy(com.softlayer.api.service.scale.termination.Policy.Service policyService, String name) { Long id = new Long(0); for(com.softlayer.api.service.scale.termination.Policy policy : policyService.getAllObjects()) { if(policy.getName().equals(name)) { id = policy.getId(); } } return id; } /** * Retrieves a network vlan identifier * @param accountService Account Service * @param vlanNumber The number of vlan * @return Vlan's identifier */ public Long getVlanId(Account.Service accountService, Long vlanNumber) { Long vlanId = new Long(0); for(com.softlayer.api.service.network.Vlan vlan : accountService.getNetworkVlans()) { if(vlan.getVlanNumber().equals(vlanNumber)) { vlanId = vlan.getId(); } } return vlanId; } public Long getVirtualServerId(Account.Service accountService, Long serviceGroupPort, String ipAddress) { Long serverId = new Long(0); accountService.withMask().adcLoadBalancers().ipAddress().ipAddress(); accountService.withMask().adcLoadBalancers().virtualServers(); for(VirtualIpAddress virtualIpAddress : accountService.getObject().getAdcLoadBalancers()) { if(virtualIpAddress.getIpAddress().getIpAddress().equals(ipAddress)) { for(VirtualServer virtualServer : virtualIpAddress.getVirtualServers()) { if(virtualServer.getPort().equals(serviceGroupPort)) { serverId = virtualServer.getId(); } } } } return serverId; } /** * Retrieves ssh key's identifier * @param accountService Account Service * @param name Label's name from ssh key * @return The Ssh Key's identifier */ public Long getSshKeys(Account.Service accountService, String name) { Long id = new Long(0); for(Key key : accountService.getSshKeys()) { if(key.getLabel().equals(name)) { id = key.getId(); } } return id; } /** * Retrieves Post Provision URI * @param accountService Account Service * @param postInstallName The name from post install script * @return The Provision script URI */ public String getPostInstallScript(Account.Service accountService, String postInstallName) { String script = ""; for(Hook hook : accountService.getPostProvisioningHooks()) { if(hook.getName().equals(postInstallName)) { script = hook.getUri(); return script; } } return postInstallName; } /** * This is the main method which makes use of CreateObject method. * * @param args * @return Nothing */ public static void main(String[] args) { new CreateObject(); } }
{ "pile_set_name": "StackExchange" }
Q: How would I know why a move is good or not? When I play chess on say lichess.org, I can see whether my move is good or not according to Stockfish. I can see why some moves are obvious blunders or mistakes, but for some other moves I don't really know why said move is bad/good. Is there a heuristic or engine or some rules I can use to see why a move is good or bad? A: As far as I know, there is no engine that does what you are looking for. An engine is a program that does nothing more than take certain positional and material elements into account, and gives it an evaluation. It does not break down the elements and show you how it evaluated each of them. Sometimes, it can be obvious because the analysis is a clear win of material, but most of chess is more deeply hidden than that....sometimes VERY deeply hidden. I found a site that does what you are asking. It takes those evaluations, and tries to put words and understanding to the numbers. You it on one of the problems with chess-analysis software for weaker players, and that is that it just shows the strongest move per the computer, without any explanation why. There are some programs, like the ChessBase programs that, using their "Tactical Analysis" feature, attempt to give some explanation to the moves, but they are all wanting. That said, decodechess.com seems to do better than most for newbies. As a USCF Master, the explanations are pretty good from what I can see, and the underlying "engine" is the same Stockfish that you use. Although a premium account is $99/year (right now, 50% off with the promo code "getserious". for the record, I have no affiliation with the site, nor am I a member), you can create an account, and "decode", or analyze three games per day for free. If you like it, I would jump on the promo. A: Heuristics can only get you so far, at the end of the day chess is a highly contextual game which means, in order to understand why a given move is good or bad, you can never do without the concrete assessment of lines of play that can arise from that move. Obviously, one cannot go to arbitrary depths in the calculations, so at some point you need to make a judgement, based on your experience and positional understanding, and stop your calculations and evaluate the reached positions. On the one hand, learning more about chess principles will render your calculations more efficient, as you'll get better at dismissing the irrelevant move candidates. It will also allow you to evaluate more accurately the intermediate and end positions that you reach at the end of your calculations. On the other hand, experience and practice will improve your tactical awareness, calculation speed and the depth you can see without moving the pieces. When it comes to understanding why an engine evaluates a move as good or bad, if at first according to your calculations and your knowledge of chess principles it is not clear to you, then you should simply rely on the concrete lines of play and explore them with/without the engine. In other words, in a live analysis session, simply play out the main lines that ensue with and without the move you're trying to understand, then compare them. The comparison will better highlight the impact of the move on the consequent positions. This does not mean you can expect to understand any move in any positions, because chess is a highly complex game, and with time, as you get better at it, you'll discover deeper concepts and layers of reasoning behind a move or plan. These discussions basically mean that in order to evaluate a move, concrete play and principle-based assessment of positions will always and unavoidably go hand in hand. Think of for instance how we find positional combinations (other combinations would be mating ones, or ones that win material) in chess: First we spot an idea (e.g. doubling our opponent's pawns), then we calculate the relevant variations (such as the repercussion of intermezzo check moves), and last, we evaluate the final positions (e.g. in terms of king safety, material balance, pawn structure etc). Therefore to find a combination, the concrete and positional assessment are both required. Let's end with an example: A typical Dragon position, and say we played the move 8.Qd2 in the diagram below, and afterwards learned that the engine did not like it at all. Then we see the engine suggests immediately 8...Ng4!! attacking the bishop on e3 first chance given! A strategic blunder by white to allow the trade of the dark-squared B for a N. Strategically, if the trade of the g4 knight with the e3 bishop happens, then black will stand really well thank to their dark squared bishop dominating the long diagonal. So we realise 8.Qd2 was premature as first we needed to secure the g4 square with e.g. 8.f3 then Qd2 can be played having ensured we preserve our dark-squared bishop. This entails the principled approach to understanding Ng4, since the dark-squared bishop is vital to black's play in the Dragon variation of the Sicilian. Next question should be: "but can white really not avoid the trade by some dynamic play?" By their nature, these questions cannot be answered by the mere application of chess principles, instead, one needs to concretely go through some of the possible lines of play for white and see what kinds of positions they are leading too. For instance, starting from 9.Nxc6 with the idea to play Bd4 trading the bishops in case of 9...bxc6 (left diagram, green marks white moves, red black's). But then we need to step back again, and consider what if black recaptures on c6 with the d pawn (right diagram) and thus preventing Bd4? Then we need to assess which side has a better development and minor piece coordination after the trade of queens, and the fun continues... 9...bxc6 9...dxc6 [title "Sicilian Dragon, example 1: why 8.Qd2 is bad?"] [fen ""] [startply "15"] 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 O-O 8. Qd2 Ng4 9. Nxc6 dxc6 (9...bxc6 10. Bd4) 10. Qxd8 Rxd8 11. Bf4
{ "pile_set_name": "StackExchange" }
Q: Active Record - Get records where association doesn't exists I have a model A which has_many of my B model (so the B model references the A with a foreign_key a_id). I would like to get all A records which are not referenced by any B records. Which is the more efficient way to do that with active record? Thanks! A: As of Rails 5: A.left_outer_joins(:bs).where(bs: { a_id: nil }) The output of the SQL is: SELECT "as".* FROM "as" LEFT OUTER JOIN "bs" ON "bs"."a_id" = "a"."id" WHERE "bs.a_id" IS NULL A: The detail may depend on your database, indexes you created, and data you store but I'd recommend giving subqueries a try: A.where.not(id: B.select(:a_id)) On PostgreSQL this will result in single query like: SELECT * FROM as WHERE id NOT IN (SELECT a_id FROM bs)
{ "pile_set_name": "StackExchange" }
Q: how to wait for image load before querying with jQuery Example: http://jsfiddle.net/forgetcolor/rZSCg/3/ Given a div set to overflow:auto, that will (likely) contain an image larger than its window, I'm trying to figure out a way to wait for that image to load before querying its properties. The property I'm after is it's inner width, minus its scrollbar. Thanks to a previous stackoverflow question (http://stackoverflow.com/questions/10692598/how-to-get-innerwidth-of-an-element-in-jquery-without-scrollbar) I've got a technique to do it, but this only works with a small tiny image, or one in the cache. When it gets a large image, the code that does the query executes before the image is done loading. What I want is a way to wait for that image to load before doing the query. Any ideas? Full example: http://jsfiddle.net/forgetcolor/rZSCg/3/ Javascript: // using a random appended to the URL to simulate non-cached // varying images var r = Math.floor((Math.random()*100000)+1); $('#box1').html("<img src='http://lorempixel.com/output/fashion-q-c-1920-1920-4.jpg?"+r+"' />"); var helperDiv = $('<div />'); $('#box1').append(helperDiv); $('#iw').text("inner width is: " + helperDiv.width()); helperDiv.remove(); A: var r = Math.floor((Math.random()*100000)+1); var newImage = new Image() $(newImage).load(function(){ $('#iw').text("inner width is: " + newImage.width); }); newImage.src = 'http://lorempixel.com/output/fashion-q-c-1920-1920-4.jpg?'+r The problem you are encountering is abit more complex. Images from the DOM have odd loading behaviors, where onload events do not always fire. So placing the image into a div then waiting for the DOM element to fire onload, is not going to work. As a result we need the built in javascript image object. (recently learned) that this object will solve both your problems. First as long as you set your .load listener before you set the image source, it will fire onload every time in every browser. After the load has occurred, because its an image object, you don't need to add it to the page to get it's height and width, those properties are built in.
{ "pile_set_name": "StackExchange" }
Q: Configuring iPod on Linux I use Fedora 13 and very recently I brought a new Apple iPod shuffle. I would like to know whether I can transfer music into my iPod without using iTunes. I tried using gtkpod and RhythmicBox, but that is of no avail. A: I'm not sure about state now but Apple is know for play of cat and mouse. You may find one day that update of software of iPod had broken its compatibly with Linux by completly redesigning its format. Until one day someone reverse engeneer the new format and supplied patches for projects. It lasts as long as Apple would not decide to switch format again. In short: iPod is not the best player for Linux enthusiast but when you have it you may be able to use it. PS. Also Banshee have iPod support
{ "pile_set_name": "StackExchange" }
Q: find the number of equivalence classes of $\mathbb R$. Let $\mathscr X$ be the set of all nonempty sub sets of the set $\{1,2,3,...,10\}. $Define the relation $\mathscr R$ on $\mathscr X$ by: for all $A,B \in \mathscr X, A\mathscr RB$ if and only if the smallest element of $A$ is equal to the smallest element of $B$. (a) find the number of equivalence classes of $\mathbb R$. (b) find the number of elements in the equivalence class $[\{2,6,7\}]$. I am thinking this would be the number of subsets containing the element 2 of the set $\{1,3,4,...,10\}$ so it would be $2^9$? (c) find the number of four-element sets which are elements of the equivalence class $[\{2,6,7\}]$. Also this would be like choosing a 3-element subset from the set $\{1,3,4,...,10\}$ so ${9 \choose 3}$? A: Hints to each: a) Consider looking at the single element subsets and notice how these compare to multi-element subsets in terms of using the equivalence. I suspect it is the cardinality of X that is the answer here but I'll leave it to you to prove that. b) Would {1,2,3} be in the same class? In this case, 1 is the smallest element while the given set has 2 as its smallest element so it isn't quite that simple. c) If you fix the error in the previous case this should be relatively easy to see that you are close but not quite right.
{ "pile_set_name": "StackExchange" }
Q: Authentication no longer works after GET to POST change I used the PHP code below to successfully get the timeline of a Twitter user (REST API / OAuth 1.0a) Now I would like to follow a user on Twitter. I needed to change the GET to a POST request for it and now the code no longer works. Error: [code] => 32 [message] => Could not authenticate you. What needs to be changed to make it work? PHP: // ("x" = I removed the values) $token = "x"; $token_secret = "x"; $consumer_key = "x"; $consumer_secret = "x"; $host = 'api.twitter.com'; /* // NOT WORKING: $method = 'POST'; $path = '/1.1/friendships/create.json'; // api call path */ // WORKS: $method = 'GET'; $path = '/1.1/statuses/user_timeline.json'; // api call path $query = array( // query parameters 'screen_name' => 'twitter', //'count' => '2' ); $oauth = array( 'oauth_consumer_key' => $consumer_key, 'oauth_token' => $token, 'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended 'oauth_timestamp' => time(), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_version' => '1.0' ); $oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting $query = array_map("rawurlencode", $query); $arr = array_merge($oauth, $query); // combine the values THEN sort asort($arr); // secondary sort (value) ksort($arr); // primary sort (key) // http_build_query automatically encodes, but our parameters // are already encoded, and must be by this point, so we undo // the encoding step $querystring = urldecode(http_build_query($arr, '', '&')); $url = "https://$host$path"; // mash everything together for the text to hash $base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring); // same with the key $key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret); // generate the hash $signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true))); // this time we're using a normal GET query, and we're only encoding the query params // (without the oauth params) $url .= "?".http_build_query($query); $oauth['oauth_signature'] = $signature; // don't want to abandon all that work! ksort($oauth); // probably not necessary, but twitter's demo does it // also not necessary, but twitter's demo does this too function add_quotes($str) { return '"'.$str.'"'; } $oauth = array_map("add_quotes", $oauth); // this is the full value of the Authorization line $auth = "OAuth " . urldecode(http_build_query($oauth, '', ', ')); // if you're doing post, you need to skip the GET building above // and instead supply query parameters to CURLOPT_POSTFIELDS $options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"), //CURLOPT_POSTFIELDS => $postfields, CURLOPT_HEADER => false, CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false); // do our business $feed = curl_init(); curl_setopt_array($feed, $options); $json = curl_exec($feed); curl_close($feed); $twitter_data = json_decode($json); print_R($twitter_data); ?> A: You specified the method being used for the signature, but you didn't actually make a POST request. You have to set curl_setopt($feed, CURLOPT_POST, true) and curl_setopt($feed, CURLOPT_POSTFIELDS, $query) instead of adding your parameters to the URL as query string. For more information about POST requests with CURL, visit the documentation page. It's a file upload there, but the only difference is the @ that you have to drop. Note: If Twitter requires the data to be in application/x-www-form-urlencoded format, you have to use http_build_query instead of passing an array for the CURLOPT_POSTFIELDS option.
{ "pile_set_name": "StackExchange" }
Q: Best practice for including from include files I was wondering if there is some pro and contra having include statements directly in the include files as opposed to have them in the source file. Personally I like to have my includes "clean" so, when I include them in some c/cpp file I don't have to hunt down every possible header required because the include file doesn't take care of it itself. On the other hand, if I have the includes in the include files compile time might get bigger, because even with the include guards, the files have to be parsed first. Is this just a matter of taste, or are there any pros/cons over the other? What I mean is: sample.h #ifdef ... #include "my_needed_file.h" #include ... class myclass { } #endif sample.c #include "sample.h" my code goes here Versus: sample.h #ifdef ... class myclass { } #endif sample.c #include "my_needed_file.h" #include ... #include "sample.h" my code goes here A: There's not really any standard best-practice, but for most accounts, you should include what you really need in the header, and forward-declare what you can. If an implementation file needs something not required by the header explicitly, then that implementation file should include it itself. A: The language makes no requirements, but the almost universally accepted coding rule is that all headers must be self sufficient; a source file which consists of a single statement including the include should compile without errors. The usual way of verifying this is for the implementation file to include its header before anything else. And the compiler only has to read each include once. If it can determine with certainty that it has already read the file, and on reading it, it detects the include guard pattern, it has no need to reread the file; it just checks if the controling preprocessor token is (still) defined. (There are configurations where it is impossible for the compiler to detect whether the included file is the same as an earlier included file. In which case, it does have to read the file again, and reparse it. Such cases are fairly rare, however.)
{ "pile_set_name": "StackExchange" }
Q: Polymer dom-repeat don't load attributes to child elements I have the following code in a Polymer web component: <template is="dom-repeat" items="{{sections}}"> <paper-item data-page="{{item.name}}" on-tap="changeTab" sectionid="{{item.id}}">{{item.name}}</paper-item> </template> where sections is defined as follows: sections: { type: Array, value: [ { name: 'Chaquetas', id: '1' }, { name: 'Camisas', id: '2' }, { name: 'Pantalones', id: '3' }, { name: 'Faldas', id: '4' }, { name: 'Chaquetas', id: '5' } ] } My problem is that after rendering the HTML, the properties data-page and sectionid are not shown in the element inspector on <paper-item>, while item.name shows correctly, as shown below. <paper-item class="style-scope blackbart-app x-scope paper-item-0" role="option" tabindex="0" aria-disabled="false"> Chaquetas </paper-item> (...) Can someone explain to me what I am missing? Thanks in advance. A: The current code you have binds item.name to a property of <paper-item> named dataPage; and item.id to a property named sectionid. Properties would not appear in the inspector as an attribute on your element. To bind an attribute, use Polymer's attribute-binding syntax (i.e., attr-name$=binding): <paper-item data-page$="[[item.name]]" sectionid$="[[item.id]]"> HTMLImports.whenReady(() => { Polymer({ is: 'x-foo', properties: { items: { type: Array, value: () => [{ name: 'Chaquetas', id: '1' }, { name: 'Camisas', id: '2' }, { name: 'Pantalones', id: '3' }, { name: 'Faldas', id: '4' }, { name: 'Chaquetas', id: '5' }] } } }); }); <head> <base href="https://polygit.org/polymer+1.7.0/components/"> <script src="webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="polymer/polymer.html"> <link rel="import" href="paper-menu/paper-menu.html"> <link rel="import" href="paper-item/paper-item.html"> </head> <body> <x-foo></x-foo> <dom-module id="x-foo"> <template> <paper-menu> <template is="dom-repeat" items="[[items]]"> <paper-item data-page$="[[item.name]]" sectionid$="[[item.id]]">[[item.name]]</paper-item> </template> </paper-menu> </template> </dom-module> </body> codepen
{ "pile_set_name": "StackExchange" }
Q: Keep batch file from waiting for completion of opened file[s]? I am making a Batch file to run a collection of AHK (AutoHotKey) script files, with the intent of placing in in my startup folder. However I have run into a problem when executing the batch file, it only starts the first script and then pauses, presumably waiting for the script to finish, which it never will (due to the nature of AHK scripts). How can I get it to continue on without waiting for one file to be finished? I figure this is probably a simple issue as I am not super swift with batch files yet, but I couldn't find anything with some googling. A: Starting a Program See start /? and call /? for help on all three ways. Specify a program name c:\windows\notepad.exe In a batch file the batch will wait for the program to exit. When typed the command prompt does not wait for graphical programs to exit. If the program is a batch file control is transferred and the rest of the calling batch file is not executed. Use Start command start "" c:\windows\notepad.exe Start starts a program and does not wait. Console programs start in a new window. Using the /b switch forces console programs into the same window, which negates the main purpose of Start. Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try start shell:cache Use Call command Call is used to start batch files and wait for them to exit and continue the current batch file.
{ "pile_set_name": "StackExchange" }
Q: Change Sublime Text 3 Bracket/Indent Rules In Sublime Text 3, I want to change auto bracket rules. By default, I get this class extends Parent implements Interface { } but I want this class extends Parent implements Interface { } how can I accomplish this. A: You can just create a new snippet, and put it in your user package folder. The original snippet that ships with Sublime Text is: <snippet> <content><![CDATA[class ${1:${TM_FILENAME/(.*?)(\..+)/$1/}} ${2:extends ${3:Parent} }${4:implements ${5:Interface} }{ $0 }]]></content> <tabTrigger>cl</tabTrigger> <scope>source.java</scope> <description>javaclass</description> </snippet> You can create a new one and move the opening parenthesis down where you want it <snippet> <content><![CDATA[class ${1:${TM_FILENAME/(.*?)(\..+)/$1/}} ${2:extends ${3:Parent} }${4:implements ${5:Interface} } { $0 }]]></content> <tabTrigger>cl</tabTrigger> <scope>source.java</scope> <description>javaclass</description> </snippet>
{ "pile_set_name": "StackExchange" }
Q: Limits of Batch, REST API: how to get 2000+ records, not just 250? This code works, but I can get only 250 records even if on other side 2000+ records. I think my batch is incorrect. How can I make a few callouts per 1 time to get 2000+ records from service side? Callout: public class Callout { public static List<Instrument__c> instrumentsList; public static HttpRequest createRequestForService(String token){ HttpRequest finalRequest = new HttpRequest(); finalRequest.setHeader('Authorization','Bearer ' + token); finalRequest.setHeader('Content-Type','application/json'); finalRequest.setHeader('accept','application/json'); finalRequest.setMethod('GET'); finalRequest.setEndpoint('https://name.salesforce.com/services/data/v44.0/query/?q=SELECT+Name+FROM+InstrumentFromService__c'); return finalRequest; } public class WrapperClass { public Integer totalSize; public Boolean done; public String nextRecordsUrl; public Instrument__c[] records; } public class WebToken{ public String WEBTOK{get;set;} } public static void getResult() { Http ourHttp = new Http(); HttpRequest requestForToken = 'get_right_token_is_here'; HttpResponse responseToken = ourHttp.send(requestForToken); OAuth2 objAuthenticationInfo = (WebToken)JSON.deserialize(responseToken.getbody(), WebToken.class); if(objAuthenticationInfo.WEBTOK != null) { HttpRequest requestForService = createRequestForService(objAuthenticationInfo.WEBTOK); HttpResponse responseService = ourHttp.send(requestForService); instrumentsList = ((WrapperClass)JSON.deserialize(responseService.getBody(), WrapperClass.class)).records; for(Instrument__c ins : instrumentsList) { ins.Id = null; } return responseService; } else return null; } } Batch: global class BatchClass implements Database.Batchable<Integer>, Database.AllowsCallouts { global Integer operationsQuantity = 1; global Iterable<Integer> start(Database.BatchableContext BC){ List<Integer> scope = new List<Integer>(); for(Integer i = 1; i <= operationsQuantity; i++){ scope.add(i); } return scope; } global void execute(Database.BatchableContext BC, List<Integer> scope){ List<Instrument__c> mainList = new List<Instrument__c>(); for(Integer i : scope){ HttpResponse res = CalloutResume.getCalloutResponseContents(); List<Instrument__c> instrumentsList = Callout.instrumentsList; mainList.addAll(instrumentsList); } upsert mainList Name; } global void finish(Database.BatchableContext BC){ } } A: The REST API has a Query Options Header, which allows you to specify a maximum size between 200 and 2,000. However, each response payload is also limited in size, so the system automatically reduces the maximum size based on the number and type of fields you query. The default value starts at 2,000, so if you're getting a smaller return size, it means that there are too many fields or too many big fields to use the maximum response size. If you need the fields, then you can't increase the size of the batch. Your only two choices are to reduce the number of fields queried or deal with the fact that you won't be able to query any more records than that at once.
{ "pile_set_name": "StackExchange" }
Q: Create broadcastable TX offline on Windows I made a tool which created 500 transactions that I need to have broadcasted on the network. The data, nonce and other information is all available. The only thing I need is a way to create the transaction and sign it with my private key. What would be the easiest way that won't give me a headache? I don't think you even need a copy of the chain for this as its just signing. (I do not need it broadcasted to the network right now) Please no Web3 or anything else with NodeJS, because every single time I use javascript/NodeJS it takes me hours to fight through the errors NPM shoots at me. I'm probably hospitalized because of high blood pressure before the libraries even finished installing so please think of my health Anyways I've been searching for quite a while so if someone could save me out of the fire, I'd be grateful! A: If web3 inside geth is okay with you, first import the private key into geth via geth account import, and then just run this in the geth console (replacing the addresses, nonce, and value): web3.personal.unlockAccount('0x123abc...') web3.eth.signTransaction({ from: '0x123abc...', to: '0xdef789...', value: '1234567000000000000', gas: 21000, gasPrice: '1000000000', nonce: 1, chainId: 1 }) As an alternative, MyEtherWallet supports creating offline transactions, too. The website can be downloaded and executed completely offline.
{ "pile_set_name": "StackExchange" }
Q: Logout user if they break a bashrc command I'm running a small script when a user accesses my Linux host via SSH. This script should verify and/or set up Google Authenticator MFA access for the user. Right now it works as intended with one caveat - at any moment during the MFA configuration process, if the user (ie) CTRL+C's, the setup wizard is interrupted, but the SSH session continues. I need it to log out the user trying to access. How can I achieve this? This is what I have added at the bottom of my .bashrc file (please note that this is very new to me and that I'm open to criticism/improvements on my current attempt). # MFA validation/configuration if [[ -n $SSH_CONNECTION ]] ; then echo "SSH connection to remote host successful." echo "testing if MFA is configured..." # is this test enough? file="$HOME/.google_authenticator" if [ -f "$file" ] ; then printf "MFA configured, you may proceed.\n" else printf "MFA not configured; running setup wizard.\n" # the command runs, but the else bit is never reached if google-authenticator ; then # I reach this point if I go to the end of the wizard echo "MFA setup successful" else # this point is never reached echo "MFA setup failed - logging you out" exit fi fi fi A: You can add line trap '' 2 at start of you script to disable CTRL+C and trap 2 in end to enable CTRL+C functional. This will prevent user from brake you script execution. Note that this should be added to /etc/bashrc, making it system wide and not user-modifiable https://www.cyberciti.biz/faq/unix-linux-shell-scripting-disable-controlc/
{ "pile_set_name": "StackExchange" }
Q: Proof of the formula for the exterior derivative in terms of the covariant derivative. SETUP Everything is smooth. Consider the ring $\Omega^{p}(M)$ of sections of the exterior powers of the cotangent bundle $\Lambda^{p}(T^{*}M)$ over a manifold $M$. Purely in terms of the smooth structure, we define the exterior derivative as the map $\operatorname{d}:\Omega^{p}(M)\to\Omega^{p+1}(M)$ whose action on $\phi\in\Omega^{p}(M)$ is defined by $$\operatorname{d}\!\phi\bigg(\bigotimes_{k=0}^{p}X_{k}\bigg) = \sum_{i=0}^{p}(-1)^{i}X_{i}\left(\phi\Big(\bigotimes_{k\neq i}X_{k}\Big)\right) + \sum_{i<j}(-1)^{i+j}\phi\Big(\left[X_{i},X_{j}\right],\bigotimes_{k\neq i,j}X_{k}\Big)$$ where the $X_{k}$ are $p+1$ sections of the tangent bundle $TM\to M$, and the tensor products are taken in order. On the other hand, if we have a connection on the frame bundle we may inherit a covariant derivative $\nabla$ in $TM$ and then in every tensor bundle $T^{n}_{m}M$, including the subbundles $\Lambda^{p}(T^{*}M)$. If the connection is torsion free, then we may express the exterior derivative in terms of the covariant derivative by (using abstract index notation) $$(\operatorname{d}\phi)_{a_0\dots a_p} = (p+1)\nabla_{[a_0}\phi_{a_1\dots a_p]} \in\Omega^{p+1}(M)$$ for every $\phi\in\Omega^{p}(M)$. This construction is well defined for vector valued forms (elements of $\Omega^{p}(M,E)$), however at the moment I'm just interested in the following... ...QUESTION Is there a coordinate-free proof (say, using abstract index notation) to see that the second definition is equivalent to the first, when $\phi\in\Omega^{p}(M)$? I've just finished a proof using Penrose graphical notation, however it is rather lengthy. Maybe I was not ingenuous enough. Does anybody here know of a good one? A: Althought there are better ways to do this, I wanted to close the question posting my own answer. This is a refined version of the proof I was refering to when I posted the question. We start with $$(\operatorname{d}\phi)\left(\bigotimes_{k=0}^{p}X_{k}\right) = \sum_{i=0}^{p}(-1)^{i}X_{i}\left(\phi\left(\bigotimes_{k\neq i}X_{k}\right)\right) + \sum_{i<j}(-1)^{i+j}\phi\left(\left[X_{i},X_{j}\right],\bigotimes_{k\neq i,j}X_{k}\right)$$ Let's denote the two terms in the RHS by $(A)$ and $(B)$. Now we expand $(A)$ as follows So at the end we recognize that $$(A) = (p+1)\nabla_{[a_0}\phi_{a_1\dots a_p]}\left(\bigotimes_{k=0}^{p}X_{k}\right)^{a_0 \dots a_p} - (B)$$ Hence $$(\operatorname{d}\phi)\left(\bigotimes_{k=0}^{p}X_{k}\right) = (A) + (B) = (p+1)\nabla_{[a_0}\phi_{a_1\dots a_p]}\left(\bigotimes_{k=0}^{p}X_{k}\right)^{a_0 \dots a_p}$$ Since the $X_i$ are arbitrary, we finally have $$(\operatorname{d}\phi)_{a_0 \dots a_p} = (p+1)\nabla_{[a_0}\phi_{a_1\dots a_p]} \hspace{2cm} \square$$
{ "pile_set_name": "StackExchange" }
Q: Jquery UI selectable table cell outline Ok so I'm using Jquery UI Selectable to highlight some cells in a table. I would like to be able to add a border around the highlighted cells using like a 2px border. This way each time you highlight a section you can tell the separation between each section that has been highlighted. I am also hoping I can achieve this result with overlapping sections. I've done quite a bit of reading and haven't really seen anyone trying to do this yet. So I'm wondering if someone might be able to point me in the right direction on how to achieve this effect. Here's a fiddle of my example and some code below. var shadeColor = $(".color-pallet > .active").css("background-color"); applySelectable = function() { $(".block-tools > .shade-btn").click(function() { var $this = $(this); if (!$this.hasClass("active")) { $this.siblings().removeClass("active"); $this.addClass("active"); } }); $(".color-pallet > span").click(function() { var $this = $(this); if (!$this.hasClass("active")) { $this.siblings().removeClass("active"); $this.addClass("active"); shadeColor = $(this).css("background-color"); } }); // keep selected shade color selected after new question if (shadeColor !== $(".color-pallet > .active")) { $(".color-pallet > span").filter(function(){ var color = $(this).css("background-color"); if (color === shadeColor) { $(this).click(); }; }); } $(".blocks").bind("mousedown", function(e) { e.metaKey = true; }).selectable({ filter: "td", selecting: function (event, ui) { if ($('.block-shade').hasClass("active")) { $(ui.selecting).addClass('marked').css("background-color", shadeColor); } else { $(ui.selecting).removeClass('marked').css("background-color", ""); } userAns = $('.marked').length+""; } }); }; applySelectable(); Thank you in advance for you time. EDIT: For bonus points, can someone tell me when im dragging a selection, why is the containers height growing and creating a scroll bar? This has been seriously bugging me for some time and I chose to ignore it but I guess while I'm here maybe someone could explain this as well? A: Huh... here is some kind of solution, i've added 4 css classes, and some ugly code... but it is working... $(".blocks").bind("mousedown", function(e) { e.metaKey = true; }).selectable({ filter: "td", selecting: function (event, ui) { if ($('.block-shade').hasClass("active")) { $(ui.selecting).addClass('marked').css("background-color", shadeColor); $(ui.selecting).addClass('top'); $(ui.selecting).addClass('left'); $(ui.selecting).addClass('bottom'); $(ui.selecting).addClass('right'); if($(ui.selecting).prev().hasClass('marked')) { $(ui.selecting).removeClass('left'); $(ui.selecting).prev().removeClass('right'); } if($(ui.selecting).next().hasClass('marked')) { $(ui.selecting).removeClass('right'); $(ui.selecting).next().removeClass('left'); } top_elem=$(ui.selecting).parent().prev('tr').find('td'); // console.log(top_elem); $(top_elem).each(function(i) { if($(this).hasClass('marked')) { if($(this).offset().left==$(ui.selecting).offset().left) { $(this).removeClass('bottom'); $(ui.selecting).removeClass('top'); } } }); bottom_elem=$(ui.selecting).parent().next('tr').find('td'); $(bottom_elem).each(function(i) { if($(this).hasClass('marked')) { if($(this).offset().left==$(ui.selecting).offset().left) { $(this).removeClass('top'); $(ui.selecting).removeClass('bottom'); } } }); } else { $(ui.selecting).removeClass('marked').css("background-color", ""); $(ui.selecting).removeClass('top'); $(ui.selecting).removeClass('left'); $(ui.selecting).removeClass('bottom'); $(ui.selecting).removeClass('right'); } userAns = $('.marked').length+""; } }); }; applySelectable(); }); DEMO: http://jsfiddle.net/wh2ehzo3/10/ However, overlapping is really, really tricky IF YOU WANT to KEEP borders on overlapping parts.. test... (just OUTER border of both shapes is saved, i hope you will see what i mean) Idea: check siblings -> remove classes accordingly, if there is .marked element, check up and down rows -> do the same...
{ "pile_set_name": "StackExchange" }
Q: Rxjs: How to implement Observable.first()? I'm learning RxJs and trying to understand how Observable.first() method works under the hood. Source code is pretty messy. Is there an easy way to implement this method to understand how it works? I want to understand exactly how it works inside, but not how it can be implemented. A: From the documentation we see Emits only the first value. Or emits only the first value that passes some test. So the basic behaiour (emits only the first value) is done by keeping track whether the first value has been emitted or not, with a subscriber-level field. Then predicate, resultSelector, or defaultValues are just a bit of additions to that basic code (basically a filter, a map or a default). If you want to take a look on the specific code for this operator, the relevant part is FirstSubscriber._next => FirstSubscriber._emit => FirstSubscriber._emitFinal, where it uses the this._emitted flag to track if it has emitted or not. Edit: If you wanted to define a custom Rx extension that does what first() does without using other basic operators such as take(1), I would do something like this: Observable.prototype.first = function() { const source = this; return new Observable(observer => { let hasSentValue = false; return source.subscribe( v => { if(!hasSentValue) { observer.next(v); observer.complete(); hasSentValue = true; } }, err => observer.error(err), () => { if(!hasSentValue) { observer.error("Empty stream"); } }); }); }; Note: not tested
{ "pile_set_name": "StackExchange" }
Q: Flink: writing to dev/null I want to execute my Flink Scala program without writing the result to a file. Running a program without saving the result DataSet into a DataSink isn't possible. So I tried <result dataset name>.writeAsText("file:///dev/null", WriteMode.OVERWRITE). That didn't work. The following error occurred: > java.io.IOException: Output path 'file:/dev/null' could not be > initialized. Canceling task... at > org.apache.flink.api.common.io.FileOutputFormat.open(FileOutputFormat.java:228) > at > org.apache.flink.api.java.io.TextOutputFormat.open(TextOutputFormat.java:77) > at > org.apache.flink.runtime.operators.DataSinkTask.invoke(DataSinkTask.java:187) > at org.apache.flink.runtime.taskmanager.Task.run(Task.java:584) at > java.lang.Thread.run(Thread.java:745) Is there a way to use a DataSink with the dev/null path? A: You can use the DiscardingOutputFormat: val data: DataSet[(String, Int)] data.output(new DiscardingOutputFormat[(String, Int)]())
{ "pile_set_name": "StackExchange" }
Q: Updating Vue instance disables certain element I am creating a roster in which assignment can be made using Vue. If I assign a person to a particular shift, then he is removed from all the preferences and we would no longer be able to navigate through different options. The close moves the preference up by 1 and the prev icon moves it down by 1 and tick makes the assignment. Have a look at the code jsfiddle. Now when an assignment is done then a delete operation is carried out. And after that, entire Vue is force updated. This delete operation disables the preference list navigation in all other table cells.Why this disabling occurs? Is there any solution to that. Also can Vue force Update be avoided? $('.assign').click(function() { app.assignNurse($(this)); app.$forceUpdate(); }); A: Please update the following line in your code. $(document).on('click','.close',function() { const curr = $(this).parent(); //console.log(curr.next()); curr.next().show(); $(this).parent().hide(); //$('.selection2').show(); //prevObj = curr; }); $(document).on('click','.assign',function() { console.log("ss"); app.assignNurse($(this)); }); $(document).on('click','.repeat',function(){ $(this).parent().hide(); //console.log($(this).parent().prev('div')); $(this).parent().prev('div').show(); //$(this).parent().remove(); }); issue is coming because you are creating element dynamically so jquery simple click event can't work on the element which is created dynamically so you need to write click event like this. Here is updated fiddle link you can check here its working perfectly.
{ "pile_set_name": "StackExchange" }
Q: Reading values from Json file I am trying to read an attribute from a Json file using this: d['text']['entities']['mention'][0]['screen_name'] Json File { "text" : { "content" : "@narendramodi Did u even know the fare of metro has been increased by 65%", "entities" : { "user_mentions" : [ ], "mention" : [ { "indices" : [ 0, 13 ], "id_str" : "18839785", "screen_name" : "narendramodi", "name" : "Narendra Modi", "id" : 18839785 } ], "hashtags" : [ ], }, } } I am trying to load many json files in Neo4J Database using py2neo library. While accesing d['text']['entities']['mention'][0]['screen_name'] in one of the json file in which "mention" : [ ], mention field is empty it says IndexError: list index out of range Error is pretty obvious but how should I handle this? A: You could just use try/except block. Like try: data = d['text']['entities']['mention'][0]['screen_name'] ... except IndexError: data = None # or handle this case in other way
{ "pile_set_name": "StackExchange" }
Q: Controller return `false` while DashboardController return `true` I am running laravel 6.11 and by default we have this class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function __construct() { dd(Auth::check()); } } and I have defined my controller like this, class DashboardController extends Controller { /** * Display dashboard * * @return \Illuminate\Http\Response */ public function index() { dd(Auth::check()); } } Now the user successfully login, and visiting same page, dashboard at different time Controller return false while DashboardController return true Why is that? A: As of Laravel 5.3, you can't access the session (including Auth) in the controller constructor. You can, however, define a middleware closure in the constructor that will have access to the session. class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function __construct() { $this->middleware(function ($request, $next) { dd(Auth::check()); }); } }
{ "pile_set_name": "StackExchange" }
Q: Knockout: Uncaught ReferenceError: Invalid left-hand side in assignment I am trying to change an attribute in my model like this usersProfile.friendRequestStatus() = 'DECLINED';, but i keep getting the error : usersprofilemodel.js:86 Uncaught ReferenceError: Invalid left-hand side in assignment at Object.success (usersprofilemodel.js:86) at fire (jquery.js:3119) at Object.fireWith [as resolveWith] (jquery.js:3231) at done (jquery.js:9275) at XMLHttpRequest.callback (jquery.js:9685) I am a bit confused though, because I feel I am doing everything right. This is my knockout mmdel: function usersProfileModel(data) { var usersProfile = ko.mapping.fromJS(data); usersProfile.mutualFriendsPercentage = ko.pureComputed(function() { if (usersProfile.mutualFriendsCount() > 0) { return (usersProfile.mutualFriendsCount() / usersProfile.friendsCount()) * 100; } else { return 0; } }); usersProfile.addFriend = function() { showNotification('top-right', 'info', 'Awaiting response', 250, 2000); }; usersProfile.removeFriend = function(parent) { $.get("http://localhost:8080/dashboard/friendrequest/remove/" + parent.user.userName(), function(data, status) { if (data.isSuccessful) { usersProfile.friendRequestStatus() = 'DECLINED'; showNotification('top-right', 'success', 'user has been removed', 250, 2500); } }); }; return usersProfile; } Can someone please explain what is causing this, I feel I am doing it right. A: Since friendRequestStatus has been mapped into a KO observable, you should just be able to do: usersProfile.friendRequestStatus('DECLINED');
{ "pile_set_name": "StackExchange" }
Q: left join with where in right table I have this Join: Table mmp_user 151 users Table MMP_MMPUBLISH_LOG URL's access select user.name as 'Usuário',count(log.referer) as 'Número de Acessos' from mmp_user user left JOIN MMP_MMPUBLISH_LOG log on (user.id=log.user_id) where log.event_date between '2015-08-01' and '2015-08-08' group by user.id order by count(log.referer) desc expected outcome: 151 lines obtained results: 11 lines Help me please A: try with this SELECT u.name as 'Usuário',count(log.referer) as 'Número de Acessos' FROM mmp_user u LEFT JOIN ( SELECT user_id, referer FROM MMP_MMPUBLISH_LOG WHERE event_date BETWEEN '2015-08-01' AND '2015-08-08' ) log ON u.id=log.user_id group by u.id order by count(log.referer) desc ps. next time don't use 'user', it's not clear
{ "pile_set_name": "StackExchange" }
Q: Link an user to his profile page How do I link the logged in user to his profile page? {% if user.is_authenticated %} <a href= "{% url 'blog:profile' userProfile.user %}">Profile</a> Here are the involved parts: views.py @login_required def profile(request, profile_id): if profile_id == "0": if request.user.is_authenticated: userProfile = UserProfile.objects.get(pk=profile_id) else: userProfile = UserProfile.objects.get(pk=profile_id) return render_to_response('blog/profile.html', {'userProfile':userProfile}, RequestContext(request)) urls.py url(r'^profile/(?P<profile_id>\d+)/$', views.profile), models.py class UserProfile(models.Model): user = models.OneToOneField(User) bio = models.TextField(max_length=500, blank = True, default=('keine Angabe'), null=True) image = models.FileField(null=True, blank=True) def __unicode__(self): return self.user.username A: In you template you are trying to use url tag with named urls even though you haven't passed name keyword argument to url function in your urlpatterns. In your urls function pass name argument, like this: url(r'^profile/(?P<profile_id>\d+)/$', views.profile, name='profile'), make sure you namespaced the app as 'blog' in your root url conf. In your template to access current user's profile id by request context's user object. Like this: {% if user.is_authenticated %} <a href= "{% url 'blog:profile' user.userprofile.id %}">Profile</a>
{ "pile_set_name": "StackExchange" }
Q: Backbone view doesn't render template passed to it I need to be able to pass different template IDs to different routes. (function() { window.App = { Models: {}, Collections: {}, Views: {}, Router: {} }; var vent = _.extend({}, Backbone.Events); _.templateSettings.interpolate = /\[\[(.+?)\]\]/g; App.Router = Backbone.Router.extend({ routes: { '' : 'index', 'send-message' : 'sendMessage', '*other' : 'other' }, index: function() { t = new (App.Collections.Tables.extend({ url: 'main-contact'}))(); tables = App.Views.Tables({ collection: t, template: 'mainContactTemplate' }); $('#web-leads').html(tables.el); }, sendMessage: function() { // t = new (App.Collections.Tables.extend({ url: 'send-message'}))(); // tables = new App.Views.Tables.extend({ collection: t, template: template('sendMessageTemplate')}); // $('#web-leads').html(tables.el); }, other: function() { } }); // Main Contact App.Models.Table = Backbone.Model.extend({}); App.Collections.Tables = Backbone.Collection.extend({ model: App.Models.Table, initialize: function(models, options) { this.fetch({ success: function(data) { //console.log(data.models); } }); if (options) { this.url = this.url || options.url; } } }); App.Views.Tables = Backbone.View.extend({ tagName: 'ul', initialize: function() { this.collection.on('reset', this.render, this); }, render: function() { return this.collection.each(this.addOne, this); }, addOne: function(model) { var t = new App.Views.Table({ model: model}); this.$el.append(t.render().el); return this; } }); App.Views.Table = Backbone.View.extend({ tagName: 'li', initialize: function(options) { this.template = options.template; console.log(this.options); }, retrieveTemplate: function(model) { return _.template($('#' + this.template).html(), model); }, render: function() { this.$el.html(this.retrieveTemplate(this.model.toJSON())); return this; } }); new App.Router(); Backbone.history.start(); })(); But I get an error than n is undefined. I think I need to pass this.template into my retrieveTemplate function. But shouldn't it already be set? This code works, by the way, if I hard code in the name of the template ID in the retrieveTemplate function. EDIT: the template isn't being passed from the call in the router. That's where this is breaking down. EDIT: I took out the call to extend in the second line of the index route and now I get this._configure is not a function WORKING VERSION: (function() { window.App = { Models: {}, Collections: {}, Views: {}, Router: {} }; var vent = _.extend({}, Backbone.Events); _.templateSettings.interpolate = /\[\[(.+?)\]\]/g; App.Router = Backbone.Router.extend({ routes: { '' : 'index', 'send-message' : 'sendMessage', '*other' : 'other' }, index: function() { var t = new (App.Collections.Tables.extend({ url: 'main-contact'}))(); var tables = new (App.Views.Tables.extend({ collection: t, options: {template: 'mainContactTemplate' }}))(); $('#web-leads').html(tables.render().el); }, sendMessage: function() { // t = new (App.Collections.Tables.extend({ url: 'send-message'}))(); // tables = new App.Views.Tables.extend({ collection: t, template: template('sendMessageTemplate')}); // $('#web-leads').html(tables.el); }, other: function() { } }); // Main Contact App.Models.Table = Backbone.Model.extend({}); App.Collections.Tables = Backbone.Collection.extend({ model: App.Models.Table, initialize: function(models, options) { this.fetch({ success: function(data) { //console.log(data.models); } }); if (options) { this.url = this.url || options.url; } } }); App.Views.Tables = Backbone.View.extend({ tagName: 'ul', initialize: function(options) { this.collection.on('reset', this.render, this); this.template = this.options.template; }, render: function() { this.collection.each(this.addOne, this); return this; }, addOne: function(model, options) { //console.log(model); var t = new App.Views.Table({ model: model, template: this.options.template}); this.$el.append(t.render().el); return this; } }); App.Views.Table = Backbone.View.extend({ tagName: 'li', initialize: function(options) { //console.log(this.options); this.template = this.options.template; }, retrieveTemplate: function(model) { return _.template($('#' + this.template).html(), model); }, render: function() { //console.log(this); this.$el.html(this.retrieveTemplate(this.model.toJSON())); return this; } }); new App.Router(); Backbone.history.start(); })(); A: Your router says this: tables = App.Views.Tables({ collection: t, template: 'mainContactTemplate' }); So you're giving a template: '...' to App.Views.Tables. The initialize in App.Views.Tables looks like this: initialize: function() { this.collection.on('reset', this.render, this); } so it ignores the template option. If we look at App.Views.Table (singular!), we see this: initialize: function(options) { this.template = options.template; console.log(this.options); } but App.Views.Table is instantiated without a template option: var t = new App.Views.Table({ model: model}); You need to fix how you use App.Views.Table. Backbone will put a view's constructor options in this.options for you so you just need to say: var t = new App.Views.Table({ model: model, template: this.options.template }); A couple other things to consider: You have some accidental globals in your router's index method, you should have var t and var tables rather than just t and tables. A view's render method conventionally returns this so that you can say $x.append(v.render().el) so you might want to adjust your render methods to match the convention.
{ "pile_set_name": "StackExchange" }
Q: Created a restful webservice using tomcat server I created a restful webservice using netbeans created a entity class from the database and restful web services from entity class using jpa but i used tomcat as my server now the post method below wont insert the following json into the database but when i use glassfish as my server it works. Do you think I am missing any dependencies ? How can I emulate the glassfish? I am trying to insert { "acceptedGender":"both", "price":123123.00, "type":"apartment" "vacantNum":13, "hadID":4 } I have the following dependencies: javaee-api-7.0.jar javax.ejb-api.jar mysql-connector-java-5.1.42-bin.jar @POST @Override @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public void create(Students entity) { super.create(entity); }` private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "hatID") private Integer hatID; @Basic(optional = false) @Column(name = "type") private String type; @Basic(optional = false) @Column(name = "acceptedGender") private String acceptedGender; @Basic(optional = false) @Column(name = "vacantNum") private int vacantNum; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Basic(optional = false) @Column(name = "price") private BigDecimal price; // @OneToMany(cascade = CascadeType.ALL, mappedBy = "hatID") // private Collection<Reservation> reservationCollection; @JoinColumn(name = "hadID", referencedColumnName = "hadID") @ManyToOne(optional = false) private HaDetails hadID; public HaTypes(Integer hatID, String type, String acceptedGender, int vacantNum, BigDecimal price) { this.hatID = hatID; this.type = type; this.acceptedGender = acceptedGender; this.vacantNum = vacantNum; this.price = price;` Or if you dont have a solution to my problem could you recommend any provider aside from aws(dont have the time to study the docker), openshift and jelastic that could deploy a glassfish restful webservice on cloud easily. A: Glassfish is an application server, therefore it supports JAX-RS out of the box. Tomcat is just a web container and you cannot deploy a JAX-RS app and have it work without wiring it by yourself (see this: In which container do JAX-RS web services run?). If you want to run a Jersey server inside tomcat, you will need to configure it in your application's deployment descriptor. You can see answers on the following posts if you need details: How to use Jersey as JAX-RS implementation without web.xml? Create RESTful Web Service with JAX-RS and deploy it to tomcat
{ "pile_set_name": "StackExchange" }
Q: Rails3 active record pool and Sidekiq multi-thread I am using sidekiq with rails3. Sidekiq runs 25 threads default. I would like to increase multi-thread limit, I have done this by changing sidekiq.yml. So, what is the relation between pool value in database.yml and sidekiq multi-thread. What is the maximun value of mysql pool. Is it depends on server memory? sidekiq.yml :verbose: true :concurrency: 50 :pool: 50 :queues: - [queue_primary, 7] - [default, 5] - [queue_secondary, 3] database.yml production: adapter: mysql2 encoding: utf8 reconnect: false database: db_name pool: 50 username: root password: root socket: /var/run/mysqld/mysqld.sock A: Each Sidekiq job executes in one of up to 50 threads with your configuration. Inside the job, any time an ActiveRecord model needs to access the database, it uses a database connection from the pool of available connections shared by all ActiveRecord models in this process. The connection pool lets a thread take a connection or blocks until a free connection is available. If you have less connections available in your ActiveRecord database connection pool than running Sidekiq jobs/threads, jobs will be blocked waiting for a connection and possibly timeout (after ~ 5 seconds) and fail. This is why it's important that you have as many available database connections as threads in your sidekiq worker process. Unicorn is a single-threaded, multi-process server - so you shouldn't need more than one connection for each Unicorn back-end worker process. However, the database can only handle so many connections (depending on OS, hardware, and configuration limits) so you need to make sure that you are distributing your database connections where they are needed and not exceeding your maximum. For example, if your database is limited to 1000 connections, you could only run 20 sidekiq processes with 50 threads each and nothing else.
{ "pile_set_name": "StackExchange" }
Q: Authorize.net credit card payment for non US customers I have a website which gives the posibility to our clients to publish some adds on it. The add is first received and checked internaly by an add editor. Then, we are asking the client for the payement and when the payement is received, the add is published. My goal is to give the possibility to our clients to pay with their credit card. For example, send them the invoice by email with the link (or button) to a webpage where they could introduce their Credit Card number etc. The company is situated in switzerland and our Bank too. I am reading actually a lot about the Authorize.net but apparantly, we shuld have a bank in US ? Our clients are based worldwide, can this be a problem and reason for extra fees. Can we easly send invoices by email with the link for credit card payment? Thank you very much. A: I am reading actually a lot about the Authorize.net but apparantly, we shuld have a bank in US? Our clients are based worldwide, can this be a problem and reason for extra fees. Authorize.Net is currently only available in the US so you must have a US merchant account to use their services. Can we easly send invoices by email with the link for credit card payment? Yes.
{ "pile_set_name": "StackExchange" }
Q: jQuery Ajax success message shows a big HTML file I am using jQuery in my app developed using cakePHP and MySQL. In this jQuery code $.ajax({ type: "POST", url: "./updateField", data: "name="+fieldname, success: function(msg){ alert( "Data Saved: " + msg); }//success });//ajax the database operations are going correctly but if I make use of an alert statement it shows me a big HTML file... Dont know why it's coming. A: It shows a HTML because that's what you get from the server. I suppose this happens because your AJAX call doesn't actually prevent rendering the page instead of returning an XML or Json structure. I don't know what options you have in CakePHP for returning XML or Json as opposed to rendering the page, but the source of the problem is definitely on server side and not client side.
{ "pile_set_name": "StackExchange" }
Q: Why android does not handle a deeplink url which has # in the path The url http://javaexample.com/#/topics is a valid url? I am try to deeplink the above url in the app using: <intent-filter android:label="@string/app_name"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http" android:host="javaexample.com" android:pathPrefix="/#/topics" /> </intent-filter> but the terminal throwing message - Activity not started, unable to resolve Intent { act=android.intent.action.VIEW dat=http://javaexample.com/... is url http://javaexample.com/#/topics is not a valid url if it has # in the path? A: The # in a URL indicates the beginning of the fragment component, which cannot be used for deep link criteria. Even though you've structured the fragment to look like a normal URL path to human eyes, the computer does not read it this way. You'll need to reformat your URLs not to include any # character before the path.
{ "pile_set_name": "StackExchange" }
Q: How to crawl Factiva data with python Scrapy? I'm working on get the data from Factiva, in Python 3.5.2. And I have to use school login so that I could see the data. I have followed this post to try to create login spider However, I got this error: This is my code: # Test Login Spider import scrapy from scrapy.selector import HtmlXPathSelector from scrapy.http import Request login_url = "https://login.proxy.lib.sfu.ca/login?qurl=https%3a%2f%2fglobal.factiva.com%2fen%2fsess%2flogin.asp%3fXSID%3dS002sbj1svr2sVo5DEs5DEpOTAvNDAoODZyMHn0YqYvMq382rbRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQQAA" user_name = b"[my_user_name]" pswd = b"[my_password]" response_page = "https://global-factiva-com.proxy.lib.sfu.ca/hp/printsavews.aspx?pp=Save&hc=All" class MySpider(scrapy.Spider): name = 'myspider' def start_requests(self): return [scrapy.FormRequest(login_url, formdata={'user': user_name, 'pass': pswd}, callback=self.logged_in)] def logged_in(self, response): # login failed if "authentication failed" in response.body: print ("Login failed") # login succeeded else: print ('login succeeded') # return Request(url=response_page, # callback=self.parse_responsepage) def parse_responsepage(self, response): hxs = HtmlXPathSelector(response) yum = hxs.select('//span/@enHeadline') def main(): test_spider = MySpider(scrapy.Spider) test_spider.start_requests() if __name__ == "__main__": main() In order to run this code, I was using terminal command line in the top directory of the project: scrapy runspider [my_file_path]/auth_spider.py Do you know how to deal with the errors here? A: As you're using Python 3.x, "authentication failed" is a str while response.body is of type bytes. To resolve the issue, either perform the test in str: if "authentication failed" in response.body_as_unicode(): or in bytes: if b"authentication failed" in response.body:
{ "pile_set_name": "StackExchange" }
Q: Even holomorphic function on the punctured disk has a primitive Let $f$ such that $f$ is holomorphic on $\{z|0<|z|<1\}$, and $f$ is even. I need to show that f has a primitive. Any ideas? A: Write $f$ in the form of Laurent series around $0$. You get the form $f(z)=\sum_{n=-\infty}^\infty a_nz^n$. Now, if we prove that $a_{-1}=0$ then $F(z)=\sum_{n=-\infty}^{\infty}\frac{a_n}{n+1}z^{n+1}$ is a primitive function of $f$. So we just have to prove that $a_{-1}=0$ and we are done. And here we are going to use that $f$ is even. We know that $\sum_{n=-\infty}^\infty a_nz^n=f(z)=f(-z)=\sum_{n=-\infty}^\infty a_n(-z)^n$. So if we define $g(z)=f(z)-f(-z)$ then $g$ is the zero function and its Laurent expansion is $\sum_{n=-\infty}^\infty a_{2n+1}z^{2n+1}$. Because Laurent expansion is unique we conclude that $a_{2n+1}=0$ for all $n\in\mathbb{Z}$. So $a_{-1}=0$.
{ "pile_set_name": "StackExchange" }
Q: On-fly regexp modification I have the following set of strings: my @strings = {"/str1/", "/str2/", "/str3/"}; I need to modify the regular expression on-fly using something like this: foreach $string (@strings ) { if($line =~ $string) { #do something } } Unfortunately, this code doesn't seem to work as the #do something not happens. I am not pretty sure that it is correct code. Is it possible in perl at all? A: my @patterns = ("pattern1", "pattern2", "pattern3"); for my $pattern (@patterns) { if ($line =~ $pattern) { # $line matches $pattern } } or my @strings = ("string1", "string2", "string3"); for my $string (@strings) { if ($line =~ /\Q$string/) { # $line contains $string } } A: Try this: use strict; use warnings; my @regexprs = ( qr/str1/, qr/str2/, qr/str3/ ); my $line = "-- str2 --"; foreach my $re (@regexprs ) { if($line =~ $re) { print "match: $line $re\n"; } }
{ "pile_set_name": "StackExchange" }
Q: Add Space After Special Character In A Text File I need help separating multiple if statements in a file. Change: [[ "$File1" == "Word1" ]] || [[ "$File1" == "Word2" ]] || to: [[ "$File1" == "Word1" ]] || [[ "$File1" == "Word2" ]] || Everything I've found online does not work with special characters like || I think I need to use awk or sed, but I'm not sure how to get it to work. A: $ sed 's@|| @||\n@g' input [[ "$File1" == "Word1" ]] || [[ "$File1" == "Word2" ]] ||
{ "pile_set_name": "StackExchange" }
Q: JSON eliminar claves con su valor (Vacío) en javascript Tengo un json a validar y quiero eliminar los valores vacios o con la palabra 'Vacío' para no tener datos innecesarios var objeto = {clave1:"hola",clave2:"Vacío",clave3:""} la idea seria eliminar la clave2 porque tiene el valor Vacío y la calve3 porque esta vacía ("") esto es fácil seria algo así var objeto = {clave1:"hola",clave2:"Vacío",clave3:""} for (var clave in objeto) { if(objeto[clave]==""||objeto[clave]=="Vacío"){ delete objeto[clave] //eliminamos solo las claves vacias } } console.log(objeto) El problema es cuando el json es muy complejo y tiene muchos objetos hijos y hay que validar todos y quitarles las claves vacias sin saber la forma o el orden del objeto JSON a validar var objeto = { "state": "", "title": "Evaluador", "tituloPadre": "", "id": 26, "data": { "tipoLicencia": 26, "categorias": 0, "nroLicencia": { "valor": "1234", "activo": true }, "fechaEmision": { "valor": "16-12-2017", "activo": true }, "fechaVencimiento": { "valor": "22-12-2017", "activo": true }, "estatus": { "valor": "2", "activo": true }, "horasTotalesVuelo": { "valor": "21", "activo": true }, "observacionesImpresasLicencia": { "valor": "sdfg", "activo": true }, "soporteCargarLicencias": { "valor": "Vacío", "activo": true }, "habilitacionesClase": { "clasificacionHabilitacion": 1, "activo": true, "registros": [ { "idTipoHabilitacion": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 0 }, "idFuncion": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 7 }, "manufactura": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 5 }, "modelo": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 4 }, "siglasTipoDesignador": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 3 }, "tipoAeronave": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 0 }, "cantidadMotores": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 2 }, "fechaVencimiento": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 6 }, "estatus": { "clave": "", "valor": "Vacío", "edit": false, "index": 8 }, "tipoMotor": { "clave": "Vacío", "valor": "", "edit": false, "index": 1 }, "soporte": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 0 } } ] }, "habilitacionesTipo": { "clasificacionHabilitacion": 2, "activo": true, "registros": [ { "idTipoHabilitacion": { "clave": "Vacío", "valor": "", "edit": "false", "index": 0 }, "idFuncion": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 7 }, "manufactura": { "clave": "", "valor": "", "edit": "false", "index": 5 }, "modelo": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 4 }, "siglasTipoDesignador": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 3 }, "tipoAeronave": { "clave": "Vacío", "valor": "", "edit": "false", "index": 0 }, "cantidadMotores": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 2 }, "fechaVencimiento": { "clave": "Vacío", "valor": "", "edit": "false", "index": 6 }, "estatus": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 8 }, "tipoMotor": { "clave": "Vacío", "valor": "", "edit": "false", "index": 1 }, "soporte": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 9 } } ] }, "habilitacionesEspeciales": { "clasificacionhabilitacion": 3, "activo": false, "vueloInstrumental": { "activo": true, "idTipoHabilitacion": { "clave": "", "valor": 17, "edit": "false" }, "fechaVencimiento": { "clave": "Vacío", "valor": "", "edit": "false" }, "estatus": { "clave": "Vacío", "valor": "", "edit": "false" } }, "fumigacionAerea": { "activo": true, "registros": [ { "idTipoHabilitacion": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 0 }, "idFuncion": { "clave": "", "valor": "Vacío", "edit": "false", "index": 7 }, "manufactura": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 5 }, "modelo": { "clave": "", "valor": "Vacío", "edit": "false", "index": 4 }, "siglasTipoDesignador": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 3 }, "tipoAeronave": { "clave": "", "valor": "", "edit": "false", "index": 0 }, "cantidadMotores": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 2 }, "fechaVencimiento": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 6 }, "estatus": { "clave": "", "valor": "Vacío", "edit": "false", "index": 8 }, "tipoMotor": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 1 }, "soporte": { "clave": "Vacío", "valor": "", "edit": "false", "index": 9 } } ] } }, "competenciaLinguistica": { "clasificacionhabilitacion": 4, "activo": false, "registros": [ { "nivel": { "clave": "", "valor": "", "edit": "false", "index": 0 }, "duracion": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 1 }, "fechaVencimiento": { "clave": "Vacío", "valor": "", "edit": "false", "index": 2 }, "estatus": { "clave": "", "valor": "Vacío", "edit": "false", "index": 3 } } ] }, "habilitaciones": { "clasificacionHabilitacion": 5, "activo": false, "idTipoHabilitacion": { "clave": "Vacío", "valor": "", "edit": "false" }, "fechaVencimiento": { "clave": "", "valor": "", "edit": "false" }, "estatus": { "clave": "Vacío", "valor": "Vacío", "edit": "false" } }, "habilitacionesRpa": { "clasificacionHabilitacion": 6, "activo": false, "registros": [ { "idTipoHabilitacion": { "clave": "", "valor": "Vacío", "edit": "false", "index": 0 }, "fechaVencimiento": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 1 }, "estatus": { "clave": "", "valor": "Vacío", "edit": "false", "index": 2 } } ] }, "habilitacionesTripulanteVuelo": { "clasificacionHabilitacion": 5, "activo": false, "registros": [ { "idTipoHabilitacion": { "clave": "Vacío", "valor": "", "edit": "false", "index": 0 }, "fechaVencimiento": { "clave": "", "valor": "Vacío", "edit": "false", "index": 1 }, "estatus": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 2 } } ] } } } console.log(objeto) A: Para iterar un JSON dinamicamente sin saber su tamaño o forma podemos usar una funcion re cursiva Terminos Recursividad Como definición general, podemos decir que una función recursiva es aquella que se llama a si misma para resolverse. Dicho de otra manera, una función recursiva se resuelve con una llamada a si misma, cambiando el valor de un parámetro en la llamada a la función. A través de las sucesivas llamadas recursivas a la función se van obteniendo valores que, computados, sirven para obtener el valor de la función llamada originalmente. typeof El operador typeof devuelve una cadena que indica el tipo del operando sin evaluarlo. operando es la cadena, variable, palabra clave u objeto para el que se devolverá su tipo. Los paréntesis son opcionales. Solucion para resolver este problema creamos una funcion re cursiva que se llama a si misma cuando se cumpla una condición,en este caso hay que preguntar por el tipo de elemento si es un objeto entonces volvemos a ejecutar la misma funcion con el parametro del objeto que en ese momento esta siendo iterado y así hasta recorrerlo todo. function eliminarVacios(jsonx){ <--- funcion recursiva for (var clave in jsonx) { <--- for que itera el json pasado como parametro if(typeof jsonx[clave] == 'string'){ <-- preguntamos si es un 'string' if(jsonx[clave] == 'Vacío'||jsonx[clave] == ''){ <-- validamos si esta vacio o contiene la palabra 'Vacío' delete jsonx[clave] <-- eliminamos la clave que este vacia o contenga la palabra 'Vacío' } } else if (typeof jsonx[clave] == 'object') { <-- preguntamos si es un 'objeto' eliminarVacios(jsonx[clave]) <-- volvemos a ejecutar la funcion recursiva } } } Ejemplo funcional var objeto = { "state": "", "title": "Evaluador", "tituloPadre": "", "id": 26, "data": { "tipoLicencia": 26, "categorias": 0, "nroLicencia": { "valor": "1234", "activo": true }, "fechaEmision": { "valor": "16-12-2017", "activo": true }, "fechaVencimiento": { "valor": "22-12-2017", "activo": true }, "estatus": { "valor": "2", "activo": true }, "horasTotalesVuelo": { "valor": "21", "activo": true }, "observacionesImpresasLicencia": { "valor": "sdfg", "activo": true }, "soporteCargarLicencias": { "valor": "Vacío", "activo": true }, "habilitacionesClase": { "clasificacionHabilitacion": 1, "activo": true, "registros": [ { "idTipoHabilitacion": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 0 }, "idFuncion": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 7 }, "manufactura": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 5 }, "modelo": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 4 }, "siglasTipoDesignador": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 3 }, "tipoAeronave": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 0 }, "cantidadMotores": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 2 }, "fechaVencimiento": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 6 }, "estatus": { "clave": "", "valor": "Vacío", "edit": false, "index": 8 }, "tipoMotor": { "clave": "Vacío", "valor": "", "edit": false, "index": 1 }, "soporte": { "clave": "Vacío", "valor": "Vacío", "edit": false, "index": 0 } } ] }, "habilitacionesTipo": { "clasificacionHabilitacion": 2, "activo": true, "registros": [ { "idTipoHabilitacion": { "clave": "Vacío", "valor": "", "edit": "false", "index": 0 }, "idFuncion": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 7 }, "manufactura": { "clave": "", "valor": "", "edit": "false", "index": 5 }, "modelo": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 4 }, "siglasTipoDesignador": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 3 }, "tipoAeronave": { "clave": "Vacío", "valor": "", "edit": "false", "index": 0 }, "cantidadMotores": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 2 }, "fechaVencimiento": { "clave": "Vacío", "valor": "", "edit": "false", "index": 6 }, "estatus": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 8 }, "tipoMotor": { "clave": "Vacío", "valor": "", "edit": "false", "index": 1 }, "soporte": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 9 } } ] }, "habilitacionesEspeciales": { "clasificacionhabilitacion": 3, "activo": false, "vueloInstrumental": { "activo": true, "idTipoHabilitacion": { "clave": "", "valor": 17, "edit": "false" }, "fechaVencimiento": { "clave": "Vacío", "valor": "", "edit": "false" }, "estatus": { "clave": "Vacío", "valor": "", "edit": "false" } }, "fumigacionAerea": { "activo": true, "registros": [ { "idTipoHabilitacion": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 0 }, "idFuncion": { "clave": "", "valor": "Vacío", "edit": "false", "index": 7 }, "manufactura": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 5 }, "modelo": { "clave": "", "valor": "Vacío", "edit": "false", "index": 4 }, "siglasTipoDesignador": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 3 }, "tipoAeronave": { "clave": "", "valor": "", "edit": "false", "index": 0 }, "cantidadMotores": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 2 }, "fechaVencimiento": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 6 }, "estatus": { "clave": "", "valor": "Vacío", "edit": "false", "index": 8 }, "tipoMotor": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 1 }, "soporte": { "clave": "Vacío", "valor": "", "edit": "false", "index": 9 } } ] } }, "competenciaLinguistica": { "clasificacionhabilitacion": 4, "activo": false, "registros": [ { "nivel": { "clave": "", "valor": "", "edit": "false", "index": 0 }, "duracion": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 1 }, "fechaVencimiento": { "clave": "Vacío", "valor": "", "edit": "false", "index": 2 }, "estatus": { "clave": "", "valor": "Vacío", "edit": "false", "index": 3 } } ] }, "habilitaciones": { "clasificacionHabilitacion": 5, "activo": false, "idTipoHabilitacion": { "clave": "Vacío", "valor": "", "edit": "false" }, "fechaVencimiento": { "clave": "", "valor": "", "edit": "false" }, "estatus": { "clave": "Vacío", "valor": "Vacío", "edit": "false" } }, "habilitacionesRpa": { "clasificacionHabilitacion": 6, "activo": false, "registros": [ { "idTipoHabilitacion": { "clave": "", "valor": "Vacío", "edit": "false", "index": 0 }, "fechaVencimiento": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 1 }, "estatus": { "clave": "", "valor": "Vacío", "edit": "false", "index": 2 } } ] }, "habilitacionesTripulanteVuelo": { "clasificacionHabilitacion": 5, "activo": false, "registros": [ { "idTipoHabilitacion": { "clave": "Vacío", "valor": "", "edit": "false", "index": 0 }, "fechaVencimiento": { "clave": "", "valor": "Vacío", "edit": "false", "index": 1 }, "estatus": { "clave": "Vacío", "valor": "Vacío", "edit": "false", "index": 2 } } ] } } } function eliminarVacios(jsonx){ for (var clave in jsonx) { if(typeof jsonx[clave] == 'string'){ if(jsonx[clave] == 'Vacío'||jsonx[clave] == ''){ delete jsonx[clave] } } else if (typeof jsonx[clave] == 'object') { eliminarVacios(jsonx[clave]) } } } eliminarVacios(objeto) console.log(objeto)
{ "pile_set_name": "StackExchange" }
Q: Broadcast IPC on Linux I have the following requirements for an IPC mechanism on Linux: There is a single producer process, but multiple consumer processes. The consumer processes are not children of the producer process. They are brought up independently. The messages being transported are fixed size POD structs. We need to use a fixed amount of memory for this mechanism. A ring buffer like mechanism seems ideal here. The producer needs to run really fast and can never wait for the consumers. Instead it needs to overwrite entries in the fixed size buffer (for IPC) and the consumers need to detect this problem and just catch up with the producer by skipping intermediate messages in case of a wrap around. Consumers can come up and go down any time and there should be no explicit handshake between the single producer and the ephemeral consumers as they come up and go. So when consumers come up they just start reading from the latest message available and go down whenever they want without the producers ever knowing. I have the following solution right now: I am creating a ring buffer of fixed size entries that is written to by one process and read by many. The ring buffer is built on top of a memory-mapped file in /tmp. The ring buffer code is such that the producers never block waiting for any of the consumers to consume entries. Instead consumers detect when the ring buffer has wrapped around in the middle of reading/processing an entry and just catch up to the latest. I do it with a couple of producer sequences. I can expand on this if needed but doesn't seem very relevant. So producers gallop at full speed and consumers that fall behind detect that mid read corruption and skip to the latest entry. As of now this works fine. Now I am trying to figure out how to add some signaling to the mix so consumers do not have to spin reading producer sequences waiting for a new message. I have some additional requirements for the signaling part: The signaling needs to be some kind of broadcast mechanism. This follows from the one producer/multiple_consumers requirement. So multiple processes should be able to be woken up when the producers signals them. Given that the producer doesn't know about any of the consumers, it seems like we need some kind of named resource to do this signaling. The signaling mechanism needs to be composable with other regular signals that can be waited on using select/epoll_wait. The consumers that are reading form this IPC mechanism/ring_buffer are waiting on writes to other unrelated pipes/sockets etc and they use a select on these FDs. It would be ideal to be able to just produce an FD from this mechanism that consumers could just add to their select call. Similarly if the consumer is waiting on multiple such ring_buffers, we need to be able to block on all of them and wake up as soon as any of them signal. With these requirements in mind I eliminated a few options: Condition variables: We can't block on multiple of these from a consumer. They are not selectable either. Named pipes: We would need a named pipe per consumer and this implies some kind of producer/consumer handshake which we want to avoid. eventfd: eventfds are not named so seems like they are only a solution if the signaling is between parent and children processes. My scenario has processes that are started independently. Unix domain socket: There doesn't seem to be any broadcast facility here, so I am not sure if this will work without an explicit socket per consumer. This goes against the no handshake requirement. I am at a bit of a loss and don't see any other good option. To me it seems like UDP multicast will probably work. The consumers can all be part of a multicast group (create socket with SO_REUSEADDR) and the sole producer can send messages on that group to signal the consumers. But this seems really heavy weight and elaborate. Are there any other good mechanisms to make this happen? I am willing to work directly with the Futex API if it helps as long as it composes with blocking on other unrelated FDs using select/epoll. A: I recommend sending a signal, via DBus. Why roll your own IPC, when you can use a mature framework that already does what you want? This page should get you started: https://dbus.freedesktop.org/doc/dbus-tutorial.html At the end, it includes links to the Qt and GLib APIs. I've used neither, instead writing my own Boost.ASIO-based wrapper around the low-level API, though it's a rather involved undertaking. https://dbus.freedesktop.org/doc/api/html/ BTW, for sending blocks of binary data, you'll want to append an arg of type DBUS_TYPE_ARRAY of DBUS_TYPE_BYTE, to your message. Note that DBUS_TYPE_STRING can't contain zero bytes or invalid unicode sequences. Update: Another library that's recently come to my attention is called sd-bus. Here's a good overview & tutorial: http://0pointer.net/blog/the-new-sd-bus-api-of-systemd.html
{ "pile_set_name": "StackExchange" }
Q: Theory: Can JIT Compiler be used to parse the whole program first, then execute later? Normally, JIT Compiler works by reads the byte code, translate it into machine code, and execute it. This is what I understand, but in theory, is it possible to make the JIT Compiler parses the whole program first, then execute the program later as machine code? I do not know how JIT Compiler works technically and exactly, so I don't know any feasibility in this case. But theoretically, is it possible? Or am I doing it wrong? A: As Mehrdad said, it's no longer a JIT compiler, but yes, you can compile ahead of time. In .NET they have a tool called ngen.exe which does just this. A: No, this is not possible, for the simple reason that "JIT" means "Just-In-Time" and if you don't do it "Just-In-Time", then it's not a "Just-In-Time" compiler. That's like asking whether it would be possible to buy a red car, but in blue. What you are asking for, is an Ahead-Of-Time compiler, which is usually just called a compiler.
{ "pile_set_name": "StackExchange" }
Q: How to join a table with a Magento 2 repository I am trying to extend inventory stock items by joining my own table with added information. When the product page is loaded it gets the stock item via StockItemRepository::getList($criteria). So I need to somehow join on my own table here. My confusion is that with the new Magento 2 repositories rather than M1-style collections, there seems to be no option to join tables on. To give a specific example, here is the contents of that getList method: public function getList(\Magento\CatalogInventory\Api\StockItemCriteriaInterface $criteria) { $queryBuilder = $this->queryBuilderFactory->create(); $queryBuilder->setCriteria($criteria); $queryBuilder->setResource($this->resource); $query = $queryBuilder->create(); $collection = $this->stockItemCollectionFactory->create(['query' => $query]); return $collection; } The queryBuilder is a simple class that just creates the select statement from the criteria, and the collection is de-coupled from the database query entirely. Although I can add fields and filters to the criteria much like a M1 collection, I cannot see where I would add a join here. Am I barking up the wrong tree entirely, or have I missed where I would add a join? A: I've solved this by adding the join to the criteria mapper. It appears that when building a query for a collection, the criteria object contains the high-level search parameters for how you'd like to filter your data, and the mapper converts this into a Zend-Db style select. Here is what I have added to a class extending and overriding the \Magento\CatalogInventory\Model\ResourceModel\Stock\Item\StockItemCriteriaMapper class in order to add to the protected init() method to add an additional qty to stock items: protected function init() { parent::init(); $this->getSelect()->joinleft( ['qty_additional_table' => $this->getTable('cataloginventory_qty_additional')], 'main_table.item_id = qty_additional_table.item_id', ['qty_additional'] ); } (Note that I am aware that this is only one change of many needed to actually load, modify and save this extra value)
{ "pile_set_name": "StackExchange" }
Q: C# Dynamically add columns to DataTable for each Object Property When I try to use this accepted answer to dynamically add columns to my DataTable, the if condition is never true. I have tried changing the struct to a class and I have tried with and without the BindingFlags on the GetProperties. What am I missing? public partial class mainForm : Form { public DataTable DeviceDataTable; public mainForm() { InitializeComponent(); AttachToTable(new TestObject()); } public void AttachToTable(params object[] data) { for (int i = 0; i < data.Length; i++) { if (data[i].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Length > DeviceDataTable.Columns.Count) foreach (PropertyInfo info in data[i].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { DeviceDataTable.Columns.Add(info.Name, data[i].GetType()); } } DeviceDataTable.Rows.Add(data); } public struct TestObject { public static readonly string Porperty_One = "First property"; public static readonly string Porperty_Two = "Second property"; public static readonly string Porperty_Three = "Third property"; } } A: Your sample struct is bad because it has no properties, not even instance but only static fields. So Type.GetProperties won't return them. This should work as intended: public class TestObject { public string PorpertyOne => "First property"; public string PorpertyTwo => "Second property"; public string PorpertyThree => "Third property"; }
{ "pile_set_name": "StackExchange" }
Q: Space between Image CSS div#columncontents { background: black; } img.colimg03 { position: relative; right: -70px; } img.colimg02 { position: relative; right: -40px; } <div id="columncontents"> <div class="columnimage"> <img class="colimg01" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"> <img class="colimg02" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"> <img class="colimg03" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"> <img class="colimg04" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"> <img class="colimg05" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"> <img class="colimg06" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"> </div> </div> As you can see, I have separated the img class for each picture and set their position : relative and right to desire value. But its seems like long and hard way, becasue I have about 12 picture. I want to perfectly align with the DIV columncontents with 4 X 4 (4 image top and 4 image bottom) Image should be perfectly align with the container. Is there anyother way to achieve this feat? A: You can use a flexbox for this. By nature, flexbox is also responsive. UPDATE: margin added for extra space * { box-sizing: border-box; } #columncontents { display: flex; justify-content: space-between; flex-wrap: wrap; width: 100%; background-color: blue; /* For visibility only */ } div { width: 23%; margin: 1rem 0; } img { display: inline-block; max-width: 100%; height: auto; } <div id="columncontents"> <div><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"></div> <div><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"></div> <div><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"></div> <div><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"></div> <div><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"></div> <div><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"></div> <div><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"></div> <div><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVuJjUob_gNDIGlo71Z9zkBGpFhizBoKUOmaVcv2mWB9ANu50d1g"></div> </div>
{ "pile_set_name": "StackExchange" }
Q: Disabling EclipseLink cache In my application, when user logs in to the system the system reads some setting from DB and stores them on user's session. The system is performing this action by a JPA query using EclipseLink (JPA 2.0). When I change some settings in DB, and sign in again, the query returns the previous results. It seems that EclipseLink is caching the results. I have used this to correct this behavior but it does not work: query.setHint(QueryHints.cache_usage,cacheUsage.no_cache); A: If you want to set query hints, the docs recommend doing: query.setHint("javax.persistence.cache.storeMode", "REFRESH"); You can alternately set the affected entity's @Cacheable annotation @Cacheable(false) public class EntityThatMustNotBeCached { ... } A: If you're returning a some kind of configuration entity and want to be sure that data is not stale, you can invoke em.refresh(yourEntity) after returning the entity from query. This will force the JPA provider to get fresh data from the database despite the cached one. If you want to disable the L2 cache you can use <shared-cache-mode>NONE</shared-cache-mode> within <persistence-unit> in persistence.xml or use Cacheable(false) directly on your configuration entity. If you're returning plain fields instead of entities and still getting stale data you may try clearing the PersistenceContext by invoking em.clear().
{ "pile_set_name": "StackExchange" }
Q: What are the advantages for an user that is running a Bitcoin full node? I am running a Bitcoin full node Bitcoin core version v0.19.1 (64-bit). I know that is one of the most secure wallets, but the process to set up a full node is very painful, and even if you keep this full node running 24/7 you won't get paid. So I just would like to know what are the advantages for an user that is running this full node, I only can think that the network will be benefit with that somehow, but I can't see any advantage for the user. A: You validate your own UTXO without any external services that may play for your disadvantage, no middleman needed It's the most privacy-preserving and secure way of using bitcoin. Lightweight-clients have some privacy issues, not too many people are reviewing their code. The process of setting it up and using bitcoin core is a major step in one's education when it comes to bitcoin. More knowledge = advantage. You have some voting power on consensus rules, like in UASF.
{ "pile_set_name": "StackExchange" }
Q: Put a Google Chrome browser action on the side of a window I've written some very simple code (a Google Chrome extension) that gets the keywords from a Google search and display it on a browser action. (I can put the code if necessary). The thing is for practical reasons I'd like the browser action to be displayed on the side of the browser (like a sidebar). Is it possible to do this ? I've been searching and so far haven't found. A: Browser Actions can only ever appear in the top right of the screen next to the Omnibox (url bar). You can't change where they appear. If you want to create something that appears on the right of the browser, you can create a content script that will allow you to inject your own HTML, CSS and JS in to any page that the user navigates too. Using this can could create a menu or popup that is anchored to the left or right of the screen. Conent scripts don't have direct access to most of the chrome.* namespace, but you can easily use message passing to talk to your background page (which has full access) and get it to return results to your content script.
{ "pile_set_name": "StackExchange" }
Q: fill property of SVG does not working in Chrome Trouble is that I can't set value (color) in fill property in Chrome, but in Firefox it works. I tried a lot ways to do it, but there is no result. The only way I see to change color of SVG icon is via jQuery (or JavaScript) by changing id of <symbol>, which is below. Please help me solve this problem! This is what I need to work in Chrome: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style> span:hover .pathCrossBtn{ fill: blue; } </style> </head> <body> <svg width="0" height="0" style='display: none;' xmlns="http://www.w3.org/2000/svg"> <symbol viewBox="0 0 2048 2048" id="crossBtn"> <path class="pathCrossBtn" fill="red" d="M1618 1450q0 40-28 68l-136 136q-28 28-68 28t-68-28l-294-294-294 294q-28 28-68 28t-68-28l-136-136q-28-28-28-68t28-68l294-294-294-294q-28-28-28-68t28-68l136-136q28-28 68-28t68 28l294 294 294-294q28-28 68-28t68 28l136 136q28 28 28 68t-28 68l-294 294 294 294q28 28 28 68z"/> </symbol> </svg> <span> <svg class="crossBtn" viewBox="0 0 2048 2048" width="30" height="30"> <use xlink:href="#crossBtn"></use> </svg> </span> </body> </html> This is bad way to solve my problem which is not approriate for me. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </head> <body> <svg width="0" height="0" style='display: none;' xmlns="http://www.w3.org/2000/svg"> <symbol viewBox="0 0 2048 2048" id="crossBtnBlue"> <path class="pathCrossBtn" fill="blue" d="M1618 1450q0 40-28 68l-136 136q-28 28-68 28t-68-28l-294-294-294 294q-28 28-68 28t-68-28l-136-136q-28-28-28-68t28-68l294-294-294-294q-28-28-28-68t28-68l136-136q28-28 68-28t68 28l294 294 294-294q28-28 68-28t68 28l136 136q28 28 28 68t-28 68l-294 294 294 294q28 28 28 68z"/> </symbol> <symbol viewBox="0 0 2048 2048" id="crossBtnRed"> <path class="pathCrossBtn" fill="red" d="M1618 1450q0 40-28 68l-136 136q-28 28-68 28t-68-28l-294-294-294 294q-28 28-68 28t-68-28l-136-136q-28-28-28-68t28-68l294-294-294-294q-28-28-28-68t28-68l136-136q28-28 68-28t68 28l294 294 294-294q28-28 68-28t68 28l136 136q28 28 28 68t-28 68l-294 294 294 294q28 28 28 68z"/> </symbol> </svg> <span> <svg class="crossBtn" viewBox="0 0 2048 2048" width="30" height="30"> <use xlink:href="#crossBtnRed"></use> </svg> </span> <script> ;(function(){ $('.crossBtn') .mouseover(function(){ $('span svg use').attr('xlink:href','#crossBtnBlue'); }) .mouseleave(function(){ $('span svg use').attr('xlink:href','#crossBtnRed'); }) }()); </script> </body> </html> A: Use currentcolor in the path fill attribute of the <symbol> element. The currentcolor keyword represents the value of an element's color property. This lets you use the color value on properties that do not receive it by default. Then, add a color CSS property to the class of the <svg> container that will wrap the <symbol> instantiated by the <use> element. .icon { width: 30px; height: 30px; } .icon--blue { color: blue; } .icon--red { color: red; } <svg width="0" height="0" style="display: none;" xmlns="http://www.w3.org/2000/svg"> <symbol viewBox="0 0 2048 2048" id="crossBtn"> <path class="pathCrossBtn" fill="currentcolor" d="M1618 1450q0 40-28 68l-136 136q-28 28-68 28t-68-28l-294-294-294 294q-28 28-68 28t-68-28l-136-136q-28-28-28-68t28-68l294-294-294-294q-28-28-28-68t28-68l136-136q28-28 68-28t68 28l294 294 294-294q28-28 68-28t68 28l136 136q28 28 28 68t-28 68l-294 294 294 294q28 28 28 68z" /> </symbol> </svg> <svg class="icon icon--red" viewBox="0 0 2048 2048"> <use xlink:href="#crossBtn"></use> </svg> <svg class="icon icon--blue" viewBox="0 0 2048 2048"> <use xlink:href="#crossBtn"></use> </svg>
{ "pile_set_name": "StackExchange" }
Q: iOS In-App Purchases: Sandbox Invalid Product ID Background on the slightly odd setup before I get to the problem: Working on an app for a client and we're using an different iTunes developer account than the one this will eventually be published on for development and Ad-Hoc builds of an app that has Game Center and IAP integration. Obviously, we'll eventually have to duplicate our setup on the final release account, but the issue seems to be unrelated. The issue is trying to test In-App Purchases in the sandbox. We do not have any Tax/Banking info in the interim account, it was not set up in my name so I can't just add mine. Right now, every time we send an SKProductsRequest with the Product Identifier for the product I've added in the iTunes Connect portion of the account for the interim app, it is returned in the response as an invalid product identifier. This request where identifiers is an array with the string product identifier I'm trying to get: _productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithArray:identifiers]]; _productsRequest.delegate = self; And this delegate method: - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { /*Other code for handling valid responses*/ for (NSString *invalidProductId in response.invalidProductIdentifiers) { DLog(@"Invalid product id: %@" , invalidProductId); } } Returns this log for the identifer: -[InAppPurchaseManager productsRequest:didReceiveResponse:] Invalid product id: [Product ID That matches the one in ITC exactly] I know ITC is working in the interim account because all our GameCenter sandbox integration is working fine through that. Other things to note: Same results on Simulator and multiple devices. Logged out of normal iTunes/App store accounts on sim and all devices. Tried waiting 24 hours and trying again. Tried adding a different Product and trying its identifier (though I didn't wait 24 hours on this one). Took a look at this: Resolving invalid product id issue with in-app purchases? and didn't see anything terribly helpful, unfortunately. At this point, I'm stumped. Other than getting the person who set up this interim account to add their tax/banking info, is there anything I can do to actually get a valid product back from the SKProductsRequest? Any help would be greatly appreciated. Thank you! A: Wound up having to get everything moved over to the final account, which did have banking and tax info. Exact same code that returned invalid product IDs was totally fine once I set the IAP up with the same name in the other account's app. So yeah, you need the banking and tax info to even test in the sandbox. Boo-urns. A: Just wanted to confirm what DesignatedNerd said, about having to have a paid app agreement with Apple before testing can work. I had that yesterday, where we were using our account to test in app products on an app we're doing for a client. After a lot of web searching and other attempts, I happened to notice the text that said that we didn't have an agreement in place. We entered all our bank details in itunesconnect, and a little while later the message was gone, and my in app testing started to work.
{ "pile_set_name": "StackExchange" }
Q: Gravity on an Orbital Ring Added 9-15-19: Thank you all for your comments. I will be reading them through carefully. I have quickly skimmed through the answers and I do appreciate your corrections on terminology and ideas, and my equation. After I've had a chance to think through all the comments and answers, I will revise my questions and post more to see if what I put together holds up to your knowledge. Angela In my story, I have an orbital ring around Earth at geosynchronous orbit, supported by and/or connected to a series of space elevators. I have already taken care of materials, purpose, and other issues. My question is whether the ring is in free-fall orbit, so that the conditions there are zero-G, or whether because the ring is 'attached' to Earth, there will be a gravitational pull towards Earth. If there is a gravitational pull, how strong is it? Would you use the normal gravitational equation F=GMm/r2? And if so, the mass of such a massive structure will make this an interesting calculation. Would this also depend on how the ring is linked to the elevators? Thank you. A: You described the ring as "orbital" and "at geosynchronous orbit"; therefore, it's in freefall. That's what "orbit" means- in freefall, but moving sideways so fast you miss the planet completely. The fact that your orbital ring is attached to Earth simply means that if it moves relative to Earth, it'll break the tether and cause problems. The best way to avoid these problems is to put the ring in a circular orbit over the equator at geosynchronous height moving in the same direction that Earth spins- in other words, a geostationary orbit, which you've already done. The formula for Newtonian gravitational acceleration is $$ a_g = {GM \over r^2} $$ Plugging in Earth's mass and the radius of geostationary orbit, we get $$ a_g = {\left(6.674 \times 10^{-11} {N m^2 \over kg^2} \right) \times \left( 5.972 \times 10^{24} kg \right) \over \left(42164000 m\right)^2} = 0.224 {m \over s^2}$$ So people on the ring will experience about 0.02 gees of acceleration from Earth's gravity (1 gee = 9.8 m/s^2), but the ring itself (being in freefall) will be accelerating in exactly the same way. As such, people on the ring will feel weightless- they'll float around in it, just like astronauts on the ISS (or any other spacecraft in orbit). Now that I've said that, I will note that you've specifically characterized this space station as a "ring". This suggests that you'll be spinning it for artificial gravity. Just to get you started, the formula for centripetal acceleration is $$ a_c = {v^2 \over r} = {v \over t} = {r \omega \over t} $$ where $a_c$ = centripetal acceleration (i.e. the "gravity" that people standing on the inside rim of the ring will feel), $r$ is the radius of the ring, $v$ is the linear speed of the edge of the ring, $\omega$ is the angular speed of the ring (in radians per second), and $t$ is the period of the ring's rotation (i.e. the time it takes to make one full revolution). You want $a_c$ to be equal to one gee (9.8 meters per second squared); if you know how big you want the ring to be, this will tell you how fast it should spin. Also, if you spin the ring, you'll probably want it to be in the same plane as Earth's equator. A spinning ring is like a top or a gyroscope- its axis of rotation will want to point in the same direction all the time. If you mount the ring perpendicular to the tether, spin it up, and wait six hours, you'll find that the Earth (and the tether) will have rotated under it, while the ring itself has not. To keep it from crashing into the tether, you'd need to transfer all of its angular momentum somewhere else (no easy task, but doable if you have two identical rings stacked on top of each other, spinning in opposite directions- if the structure connecting them is sufficiently rigid, their angular momenta cancel out, and you can spin the whole assembly any way you want), or abandon the wheel-on-a-stick visual and mount the ring in the same plane as the tether and the Equator, like a unicycle. Finally, the whole assembly will not have any noticeable effect on the Earth's orbit unless it's a significant fraction of the mass of the Moon- and the Moon is much bigger than most asteroids. Getting something that big into orbit will not be at all feasible any time in the foreseeable future, whether it's lifted up from Earth or dragged down from interplanetary space. Edit: I should clarify that the above paragraphs were written under the assumption that your "orbital ring" was nothing more than a ring-shaped space station with some space elevators attached. The sort of thing that we could plausibly build once we figure out space elevators. However, I've been informed that this may not be the case, and that instead you may be going for a megastructure of mind-boggling scale, encircling the entire planet at geostationary altitude. In the case of a megastructure at geosynchronous altitude spinning in time with the Earth, the answer is quite simple: The ring is in freefall, and therefore anything inside will float around like in any normal-sized space station without artificial gravity. However, if you push the ring outward (by lengthening the tethers) without changing its angular speed (i.e. keeping it at 1 revolution per day), you'll start to get centrifugal gravity. Things inside the ring will "fall" toward its outside edge. We can compute how large the ring needs to be in order to get one gee of artificial gravity this way. Here's the basic equation: $$ a_c = a_g + g $$ where $a_c$ is the centripetal acceleration at the ring's edge, $a_g$ is the acceleration due to Earth's gravity at the altitude of the ring, and $g$ i our goal: standard Earth surface gravity, 9.8 m/s^2. The centripetal acceleration is the acceleration required to put an object on a circular path. Part of that, for a person standing on the ring in in our scenario, will be supplied by Earth's gravity, and the rest by the outside rim of the ring. Its that "the rest" bit that we want to be one gee. Looked at another way (specifically, from a frame of reference spinning at the same rate as Earth), $a_c$ is the centrifugal acceleration pushing the ring's occupants outward, $a_g$ is the gravitational acceleration pulling them inward, and once again, the difference is what they'll actually feel. So, plugging in the formulae for $a_c$ and $a_g$: $$ {r \omega \over t} = {GM \over r^2} + g $$ Rearranging things a bit, trying to solve for r: $$ {r^3 \omega \over t} = GM + gr^2 $$ $$ {r^3 \omega \over t} - gr^2 - GM = 0 $$ Aaaand that's a cubic equation that I don't know how to solve. Wolfram|Alpha gives a fantastically complicated solution for r, as well as a couple of equally-complicated solutions with imaginary numbers that can safely be ignored. So I'll just let WolframAlpha puzzle through the numbers on its own... and the solution turns out to be r≈1.15989×10^10 meters. That's about 17 times the radius of the Sun, 30 times farther out than the Moon, and 375 times the radius of geostationary orbits. Good luck building that! A: There would be some 'gravity' on board the station, but it would actually be in the opposite direction - away from Earth. This is because a station attached to a rotating body (Earth) by a space elevator would have to be at a distance somewhat beyond that of a geostationary orbit. The stations are being held in place by the space elevators; and if the elevators were to snap, the stations would, I believe, zoom off into an elongated elliptical orbit. Since you have one solid structure, a ring, orbiting earth, it wouldn't zoom off. Rather, it would act like a centrifuge space station... a centrifuge space station 85,000 km in diameter. The equation for determining the acceleration you get from a centrifuge is: $ a = R(\frac{2\pi}{T})^2, $ where 'a' is the acceleration, R is the radius, and T is the rotation period. At geostationary orbit, a ring station with a rotational period exactly equal to Earth's day period will find that its acceleration outward is exactly equal to the pull of Earth's gravity down, so there will be no net pull up or down. If the rotation period is constant, however (which it would be, since it's tethered to Earth by the space elevators), then increasing the orbital radius would increase the 'gravity' pulling outward, away from Earth. This is a linear relationship, so doubling the radius doubles the outward gravity. If you went and made the ring station 170,000 km in diameter, you'd have an outward gravity of about 0.45 meters per second squared, while the downward gravity would be about 0.05 meters per second squared, for a net outward gravity of about 0.4 meters per second squared, about one twenty-fourth of what you get on Earth. So, unless you wanted to make the ring absurdly huge (like, ten times the distance from the Earth to the moon huge), getting rotational gravity from a ring station tethered to Earth isn't really feasible. If you were closer than standard geostationary orbital distance to Earth, you would get downward gravity from Earth... but then the station would need to be a rigid body, holding itself up against Earth's gravity; which is, as far as we know, impossible from an engineering standpoint on account of the sheer size and mass of the station. So, long story short: The station is effectively in free-fall orbit, and while there might be some outward pull, depending on how far past geostationary orbital distance the station is, it won't be very much. A: It's microgravity (free-fall) First I would like to clarify that geosynchronous orbit and geostationary orbit are not quite the same thing, and that considering the ring is tethered by space elevators you must mean geostationary. The difference is that geostationary is a specific geosynchronous orbit that sits on the equator and rotates at a rate equal to the Earth so that any point on the orbit is always directly (or nearly) above the same point on the ground, which is necessary for a tethered space station of any kind. The only alternative would require some sort of force continuously adjusting the station's acceleration to avoid it falling to Earth. That said, anything in geostationary orbit will have basically negligible gravity. There is of course gravity, but it is just enough to keep the station in place, without pulling it downward. As massive (pun intended) as a ring structure around the Earth might be, I don't imagine it could be built large enough to actually have a strong affect on gravity, or you would end up having to adjust all the equations about the force of gravity anywhere on the planet.
{ "pile_set_name": "StackExchange" }
Q: What is the regular expression for the following strings and would the expression change if the number rolled over? What would be the following regular expressions for the following strings? 56AAA71064D6 56AAA7105A25 Would the regular expression change if the numbers rolled over? What I mean by this is that the above numbers happen to contain hexadecimal values and I don't know how the value changes one it reaches F. Using the first one as an example: 56AAA71064D6, if this went up to 56AAA71064F6 and then the following one would become 56AAA7106406, this would create a different regular expression because where a letter was allowed, now their is a digit, so does this make the regular expression even more difficult. Suggestions? A manufacturer is going to enter a range of serial numbers. The problems are that different manufacturers have different formats for serial numbers (some are just numbers, some are alpha numeric, some contain extra characters like dashes, some contain hexadacimal values which makes it more difficult because I don't know how the roll over to the next serial number). The roll over issue is the biggest problem because the serial numbers are entered as a range like 5A1B - 6F12 and without knowing how the roll over, it seems to me that storing them in the database is not as easy. I was going to have the option of giving the user the option to input the pattern (expression) and storing that in the databse, but if a character or characters changes from a digit to a letter or vice versa, then the regular expression is no longer valid for certain serial numbers. Also, the above example I gave is with just one case. There are multitude of serial numbers that would contain different expressions. A: There's no single regular expression which is "the" expression to match both of those strings. Instead, there are infinitely many which will do so. Here are two options at opposite ends of the spectrum: (56AAA71064D6)|(56AAA7105A25) .* The first will only match those two strings. The second will match anything. Both satisfy all the criteria you've given. Now, if you specify more criteria, then we'd be able to give a more reasonable idea of the regular expression to provide - and that will drive the answers to the other questions. (At the moment, the only answer that makes sense is "It depends on what regex you use.") A: I think you could do it this way for 12 characters. This will search for a 12 character phrase where each of the characters must be a capital (A or B or C or D or E or F or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 0) [A-F0-9]{12} If you're wanting to include the possibility of dashes then do this. [A-F0-9\-]{12} Or you're wanting to include the possibility of dashes plus the 12 characters then do this. But that would pick up any 12-15 character item that fit the criteria though. [A-F0-9\-]{12,15} Or if it's surrounded by spaces (AAAAHHHh...SO is stripping out my spaces!!!) [A-F0-9\-]{12} Or if it's surrounded by tabs \t[A-F0-9\-]{12}\t
{ "pile_set_name": "StackExchange" }
Q: Android custom listview inside a window i'm a complete beginner in android so i don't know how to explain it correctly,can anyone tell me how to create a custom listview inside another layout(i've seen tutorials showing how to make custom listviews out of xml files,in which they sets the contenview to the xml files and i couldn't find any tutorial to create a listview which already has other elements) ,what i'm trying to create is a windows with two listviews. When i click an item in the main listview the sub listview shows up which has a TextView, a rating bar and a button along with the itemname, almost like this image http://www.zdnet.com/i/story/60/01/054426/zdnet-box-playbook-listview.png i believe you all understand what i'm trying to create A: If what you want to do is a split view window with two diffrent Listviews that the one can pass data to another or update it in some way you need to take a look in List Fragments. There is a nice tutorial here : http://www.vogella.com/articles/AndroidFragments/article.html
{ "pile_set_name": "StackExchange" }
Q: Mysql query is working but doesn't enter the loop, PHP,MYSQL I have one table on my database that includes kategoriID,kategoriAd,kategoriEbeveyn. It is like categoryID,catagoryName and categoryParent. I want that happens that is when i try to delete main category, I can delete main category and sub categories. -World ............ +Europe ....................... *Turkey .................................**Istanbul When I try to delete, This function works for World and Europe. But Turkey and Istanbul is still in my database. I couldn't delete those because of the error. "mysql_fetch_array() expects parameter 1 to be resource, boolean given in" | kategoriID | kategoriAd | kategoriEbeveyn | | 1 | World | 0 | | 2 | Europe | 1 | | 3 | Turkey | 2 | | 4 | Istanbul | 3 | Here is my function. <?php function KategoriVeAltKategorileriSil(){ $kategoriID = $_GET['kategoriID']; mysql_query("DELETE FROM kategoriler WHERE kategoriID = ' $kategoriID '") or die (mysql_error()); $delete = mysql_query("DELETE FROM kategoriler WHERE kategoriEbeveyn = ' $kategoriID ' ") or die (mysql_error()); if($delete){ while($silinecek = mysql_fetch_array($delete)){ KategoriVeAltKategorileriSil($silenecek[' kategoriID ']); echo mysql_error(); } echo "Kategori ve alt kategorileri silindi."; }else{ echo "Silme işlemi gerçekleştirilemedi!" .mysql_error(); } } ?> Or Do i need to use Trigger? A: function deleteCategory($kategoriID) { $result=mysql_query("SELECT * FROM kategoriler WHERE kategoriEbeveyn='$kategoriID'"); if (mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) { deleteCategory($row['kategoriID']); } } mysql_query("DELETE FROM kategoriler WHERE kategoriID='$kategoriID'"); } you can use this recursive function
{ "pile_set_name": "StackExchange" }
Q: Composition of functions f, g and h Consider the function $f:\mathbb{N}\to\mathbb{N}$ given by $f(x)=2x$. 1) Find the function $g:\mathbb{N}\to\mathbb{N}$ with the property that $$g(f(x))=x$$ for all $x$ from $\mathbb{N}$. 2) Prove that there is no function $h:\mathbb{N}\to\mathbb{N}$ with the property that $$f(h(x))=x$$ for all natural $x$. A: Part $(1)$: You can choose $$g(x)=\begin{cases}\frac{x}{2}\quad\text{$x$ is even}\\0\quad\text{otherwise}\end{cases}$$ Note that $g$ maps numbers to $\mathbb{N}$. Part $(2)$: Since the domain of $f$ is $\mathbb{N}$ and $f(x)$ is even for all $x\in\mathbb{N}$, you can't have $$f(h(x))=x$$ for odd $x$.
{ "pile_set_name": "StackExchange" }
Q: Why offer both a secured login page and a non-secured login page? I note that the xp-dev.com website (delegated SVN space) offers a regular HTTP login page but this page then has link to a "secure login" which is a login page but under SSL. I wonder what the point of defaulting to HTTP was when surely an SSL login page would be better anyway? Is it a browser compatibility issue? Do any other websites do this? A: SSL is a big hit for sever performance compared with http, so I would guess that the webmaster is worried about scalability. The visitors who are concerned about high security can make the extra click to use the SSL login.
{ "pile_set_name": "StackExchange" }
Q: c# oracle problem I am using c#.net with an Oracle database. I want an example of how a dropdown list will fetch values from database name. I want to know how to make an Oracle connection in c#. I have searched the net but have not got exactly what I require. plz add comment tag to understand me. Thank you A: I would suggest that you use the Oracle provided ODP.NET. They also have some getting started tutorials that should help get you on your way. http://www.oracle.com/technology/obe/hol08/dotnet/getstarted-c/getstarted_c_otn.htm
{ "pile_set_name": "StackExchange" }
Q: Change Div Content with another file using jquery how i can change div content with jquery if i click content in sidenav and 'div id="isi"' content change in another file. <div id="mySidenav" class="sidenav"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> <a href="about.html">About</a> <a href="#">Services</a> <a href="#">Clients</a> <a href="#">Contact</a> </div> <section id="main"> <div> <span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; </span> </div> <div class="row" id="isi"> </div> sorry my English so bad A: Something like this should work $.ajax({ method: 'GET', url: 'otherfile.html', }).done(function(data) { $('#isi').html(data); })
{ "pile_set_name": "StackExchange" }
Q: Were we to remain in the Garden of Paradise forever if Adam had not sinned? I read this statement from the Catholic resource. Q. 255 A. We were not to remain in the Garden of Paradise forever even if Adam had not sinned, but after passing through the years of our probation or trial upon earth we were to be taken, body and soul, into heaven without suffering death. What is this teaching based on within the Catholic Church? There is a similar question and the answer that coincides with this statement mentions Genesis 3:22 Then the LORD God said: See! The man has become like one of us, knowing good and evil! Now, what if he also reaches out his hand to take fruit from the tree of life, and eats of it and lives forever? But I can't really see how that verse says we were not meant to stay in the paradise. A: There are two considerations here. First is that Catholics do not view the creation story as strictly literal. When we talk about the "garden of Eden', that certainly could have been a real place, but more importantly, it is symbolic of the harmonious existence humans held with the qualities of original justice, original holiness, the preternatural gifts, and the supernatural gifts. Were we to remain trapped in a walled off garden forever? No. Did God intend for us to enjoy the aforementioned gifts He gave us in the beginning for our entire extent in this world? Yes. Second, one of the many titles Catholics give to Mary is "New Eve" because Mary embodies everything Eve meant to be before she chose against God. Mary is held to never have died;however, she is not here on Earth either. Catholics hold that Mary, after her time on Earth, was assumed body & soul into Heaven. It is reasonable to believe that had Eve never sinned, she and Adam would also been granted Heaven and spared death. In short: that resource is correct with respect to Catholic beliefs.
{ "pile_set_name": "StackExchange" }
Q: Safe way to stop/abort REINDEX I am running a REINDEX but it takes long time and still working. The application using the DB is not responding right now. Is there a safe way to stop it and do it another time? PostgreSQL version is 8.4. A: Yes, it's safe. Might take a while, though. In future you might want to use "CREATE INDEX CONCURRENTLY", like dezso suggested, but first create new index, and then drop old one.
{ "pile_set_name": "StackExchange" }
Q: PHP - Naming class like a function I'd like to write a File-Class, but there is already a function in PHP which is called file(). Am I allowed to name my class like the function? <? class file{ public function __construct(){ /* DO_STH */ } } $a = new file(); ?> It works without a problem (PHP 5.4). Do you know a reason for not doing it? A: Functions and classes exist in separate namespaces and their syntax is unambiguous. There's no problem for a class to use the same name as a function.
{ "pile_set_name": "StackExchange" }
Q: Is there a Hamiltonian path for the graph of English counties? The mainland counties of England form a graph with counties as vertices and edges as touching borders. Is there a Hamiltonian path one can take? This is not homework, I just have an idea for a holiday around England where I visit every county only once! A: Let's assume we can access the Isle of Wight through Hampshire. Then the answer is yes: N.B.: This uses ceremonial counties instead of administrative counties; see comments for discussion. Edit (after a comment below): The background image from Wikipedia. I found the path mostly by luck, with the knowledge that I had to start in the Isle of Wight and finish in Cornwall.
{ "pile_set_name": "StackExchange" }
Q: DatabaseCleaner doesn't seem to clean between suits saviors. I'm having a trouble with cleaning database after each RSpec example. The thing is, that when I run rspec command, users_controller_spec.rb complains that there are more records than the example expects. Indeed the records are being created as it says if I check with rails c. when I run the this suite alone, it will be successful, so I assume it is because DatabaseCleaner doesn't clean the user records which other specs create(the number of user records matches the extra records users_controller_spec example claims to be). They are created in before :all block(if that matters). Here is my rails_helper.rb # This file is copied to spec/ when you run 'rails generate rspec:install' ENV['RAILS_ENV'] ||= 'test' require 'spec_helper' require File.expand_path('../../config/environment', __FILE__) require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! require 'devise' require 'admin/v1/dashboard_controller' # Requires supporting ruby files with custom matchers and macros, etc, in Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } # Checks for pending migrations before tests are run. # If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" config.include Devise::Test::ControllerHelpers, type: :controller config.include ControllerMacros, type: :controller # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true config.include FactoryGirl::Syntax::Methods config.infer_spec_type_from_file_location! config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.around(:each) do |example| DatabaseCleaner.cleaning do example.run end end end users_controller.rb describe 'GET #index' do it 'populates an array of users' do user1 = create(:user) user2 = create(:user) get :index expect(assigns(:users)).to match_array([user1, user2]) end it 'renders :index template' do get :index, {} expect(response).to render_template :index end end UPDATE1: this is where the extra user records are created require 'rails_helper' describe Admin::V1::MessagesController do let(:admin_user) do admin_user = double('admin_user') allow(request.env['warden']).to receive(:authenticate!).and_return(admin_user) allow(controller).to receive(:current_admin_v1_admin_user).and_return(admin_user) p '===' end before { login_admin_user admin_user } describe 'GET #index' do it 'renders :index template' do get :index, {} expect(response).to render_template :index end end describe 'GET #get_users' do before :all do @user1 = create(:user, nickname: 'hiro') @user2 = create(:user, nickname: 'elise') end context 'with params' do it 'populates an array of users matching on nickname' do get :get_users, format: :json, query: 'h' expect(assigns(:users)).to match_array([@user1]) end end context 'without params' do it 'populates an array of all users' do get :get_users, format: :json expect(assigns(:users)).to match_array([@user1, @user2]) end end end describe 'GET #get_messages' do before :all do @user1 = create(:user) @user2 = create(:user) @message1 = create(:message, user_id: @user1.id) @message2 = create(:message, user_id: @user1.id) @message3 = create(:message, user_id: @user2.id) end context 'with user_id' do it 'populates an array of messages with the user_id' do get :get_messages, format: :json, user_id: @user1.id expect(assigns(:messages)).to match_array([@message1, @message2]) end end end end A: Unfortunately RSpec's before(:all) does not play nicely with transactional tests. The code in before(:all) gets run before the transaction is opened, meaning any records created there will not be rolled back when the transaction is aborted. You are responsible for manually cleaning these items up in an after(:all). See rspec-rails#496 and Using before(:all) in RSpec will cause you lots of trouble unless you know what you are doing after(:all) do # before/after(:all) is not transactional; see https://www.relishapp.com/rspec/rspec-rails/docs/transactions DatabaseCleaner.clean_with(:truncation) end
{ "pile_set_name": "StackExchange" }
Q: Getting a Choose Country to work I want to make it possible such that when a person as soon as he clicks his country he will get redirected to a subdomain of my website. You can see it at www.test.answercup.com , but when I choose the country nothing happens. I want to make it so that when he clicks his country that page gets redirected to the respective subdomain. How do I do that? The code that I used - <div class="container2"> <span class="select"> <select> <option value disabled selected>Select country</option> <option value="be">Sri Lanka</option> <option value="ne">Pakistan</option> </select> </span> </div> A: Use a onchange event for select box <select id="selectbox" name="" onchange="javascript:location.href = this.value;"> <option value="https://www.yahoo.com/" selected>Option1</option> <option value="https://www.google.co.in/">Option2</option> <option value="https://www.gmail.com/">Option3</option> </select> OR <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="selectbox" name=""> <option value="https://www.yahoo.com/" selected>Option1</option> <option value="https://www.google.co.in/">Option2</option> <option value="https://www.gmail.com/">Option3</option> </select> <script> $(function(){ $("#selectbox").change(function() { document.location.href = $(this).val(); }); }); </script>
{ "pile_set_name": "StackExchange" }
Q: c++: Passing objects to functions I was going through a code where I encountered some problem and was able to crack this piece of code: #include <iostream> #include <stdint.h> #include <unistd.h> #include <errno.h> #include <vector> #include <sys/types.h> using namespace std; class abc { public: abc(int x,int y) { cout << "x:" << x << endl; cout << "y:" << y << endl; } virtual ~abc() {} enum example { a = 1, b = 2, c = 3, d = 4 }; }; template<typename T> class xyz { public: void some_func(abc *a) { cout<<"some_func called"<<endl; } }; int main() {} I want to call the function some_func() from main(). How should I do that. Can somebody help me with this?? A: You need to create an object of some specialization of the template class xyz and an object of the type abc. For example int main() { abc a( 10, 20 ); xyz<int> x; x.some_func( &a ); }
{ "pile_set_name": "StackExchange" }
Q: Does socket.io reconnects re-run connect? I've built a simple web application that does some communication through a node.js server using socket.io. When a user connects, node communicates back info which tells the client to subscribe to certain events. That works fine. But if you let the browser set idle, the client ends up subscribed to the events twice. The subscription process works like this: When a user connects node.js gets a 'adduser' message The two key things that hapen in that function are this: socket.on('adduser', function(data) <snip> socket.emit('nodeinfo', {node_id: NODE_ID}); socket.emit('update', {msg: 'you are connected'}); The socket.emit('nodeinfo') signals the client to subscribe to the events. So the client has socket.on('nodeinfo', function(data) { ... } The thing is it never say 'you are connected' twice, none of the console.log() functions in 'adduser' get called again on the node side. The only thing that appears to happen is node.js emits nodeinfo again (or so the client thinks) causing the client to re-subscribe. Can anyone explain to me how re-connects in socket.io work and how this may happen? A: By default the client tries to reconnect after a disconnect. This can be changed if you like: socket.io client If reconnected, the server will see a new connection and it is up to you to implement logic to identify the new connection with the previous one. So in practice - instead of implementing your adduser logic upon "connection" do it (or not) after the client sends some info to the server.
{ "pile_set_name": "StackExchange" }
Q: Hibernate interceptor and event listeners I wonder if it's possible to find out what hibernate really did to the database (i.e., committed changes). I'd like to notify another process on certain changes. I guess that the EventTypes POST_COMMIT_DELETE, POST_COMMIT_UPDATE and POST_COMMIT_INSERT should do, but given exactly zero documentation, it's only a guess. Can someone confirm? Am I missing any? I'm also unsure about how to obtain what gets really written. The PostInsertEvent contains both Object entity and Object[] state, which of the two should I trust? A side question: I'm using no XML, no Spring, no JPA, just Configuration and buildSessionFactory. Is this really the way listeners should be registered? EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory) .getServiceRegistry() .getService(EventListenerRegistry.class); registry.appendListeners(....); I'm asking as its 1. dependent on an implementation detail, 2 totally ugly, 3. nearly perfectly undiscoverable. A: Yes, it is possible to notify another process(For Example: Auditing) after committing certain changes in the DB. That is to do certain things right after the JDBC transaction(Hibernate wraps JDBC transaction ) is committed using Custom Interceptors and Events of Hibernate. You can create your own custom interceptor class by extending it by EmptyInterceptor class of hibernate. And by overriding the below afterTransactionCompletion(Transaction tx) method of EmptyInterceptor to do certain tasks after the transaction has been committed. public class AuditLogInterceptor extends EmptyInterceptor { @Override public void afterTransactionCompletion(Transaction tx) { System.out.println("Task to do after transaction "); } } The Event system can be used in addition, or as a replacement, for interceptors. Below listed are few ways to perform certain task after transaction event is completed/committed 1.Implement AfterTransactionCompletionProcess interface from org.hibernate.action package and implement the below method. documentation void doAfterTransactionCompletion(boolean success, SessionImplementor session) { //Perform whatever processing is encapsulated here after completion of the transaction. } Otherwise, you can extend your CustomDeleteAction class with EntityDeleteAction and override the above doAfterTransactionCompletion method. documentation 2.By Implementing PostDeleteEventListener and using EventType.POST_COMMIT_DELETEfor post delete. By Implementing PostInsertEventListener and using EventType.POST_COMMIT_INSERTfor post insert. By Implementing PostUpdateEventListener and using EventType.POST_COMMIT_UPDATEfor post update. Here are few examples of PostDeleteEventListener , PostUpdateEventListener and PostInsertEventListener. The Object entity of PostInsertEvent gives the entity involved in the database operation. The Object[] state of PostInsertEvent returns the session event source for this event. This is the underlying session from which this event was generated. Below link contains the documentation for PostInsertEvent Members. http://mausch.github.io/nhibernate-3.2.0GA/html/6deb23c7-79ef-9599-6cfd-6f45572f6894.htm Registering event listeners: Below MyIntegrator class shows 3 ways to register event listeners. public class MyIntegrator implements org.hibernate.integrator.spi.Integrator { public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { // As you might expect, an EventListenerRegistry is the thing with which event listeners are registered // It is a service so we look it up using the service registry final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class ); // If you wish to have custom determination and handling of "duplicate" listeners, you would have to add an // implementation of the org.hibernate.event.service.spi.DuplicationStrategy contract like this eventListenerRegistry.addDuplicationStrategy( myDuplicationStrategy ); // EventListenerRegistry defines 3 ways to register listeners: // 1) This form overrides any existing registrations with eventListenerRegistry.setListeners( EventType.AUTO_FLUSH, myCompleteSetOfListeners ); // 2) This form adds the specified listener(s) to the beginning of the listener chain eventListenerRegistry.prependListeners( EventType.AUTO_FLUSH, myListenersToBeCalledFirst ); // 3) This form adds the specified listener(s) to the end of the listener chain eventListenerRegistry.appendListeners( EventType.AUTO_FLUSH, myListenersToBeCalledLast ); } } Hence, Listeners registration to a event is dependent on implementation detail.
{ "pile_set_name": "StackExchange" }
Q: error when returning an implicit struct in coldfusion The Basics I'm running a CF10u10 box with Apache as web server on my local machine. I'm fan of cfscript and like to use the new implicit struct {} declaration Vs structNew() whenever possible. The Code Files are one component and one CFM. componentFile.cfc <cfcomponent output="false"> <cffunction name="blahExplicit" returntype="Struct"> <cfset var name = 'ColdFusion'/> <cfset var ret = structNew()/> <cftry> <cfreturn {success: true, data: name}/> <cfcatch type="any"> <cfset ret.success = false /> <cfset ret.data = cfcatch /> <cfreturn ret/> </cfcatch> </cftry> </cffunction> <cffunction name="blahImplicit" returntype="Struct"> <cfset var name = 'ColdFusion'/> <cftry> <cfreturn {success: true, data: name}/> <cfcatch type="any"> <cfreturn {success: false, data: cfcatch.detail}/> </cfcatch> </cftry> </cffunction> <cffunction name="script_blahExplicit" returntype="Struct"> <cfscript> var name = 'ColdFusion'; var ret = structNew(); try{ return {success: true, data: name}; } catch(Any err){ ret.success = false; ret.data = err.detail; return ret; } </cfscript> </cffunction> <cffunction name="script_blahImplicit" returntype="Struct"> <cfscript> var name = 'ColdFusion'; try{ return {success: true, data: name}; } catch(Any err){ return {success: false, data: err.detail}; } </cfscript> </cffunction> </cfcomponent> cfcatchErr.cfm <cfset cObj = createObject("component","componentFile")/> <cfdump var="#cObj.blahExplicit()#" label="blah Explicit"/> <cfdump var="#cObj.script_blahExplicit()#" label="blah Explicit With Script"/> <cfdump var="#cObj.script_blahImplicit()#" label="blah Implicit With Script"/> <cfdump var="#cObj.blahImplicit()#" label="blah Implicit"/> The Problem The parser throws an error stating detail is undefined in cfcatch for the blahImplicit() method. But it is all okay for the remaining methods Where as the code in blahExplicit(),script_blahExplicit(),script_blahImplicit() just works fine. The Question Why is this happening? Why is CF throwing an error even without running the code? It is throwing the error at parse time itself. I used ACF Builder and found that the control jumps to catch as soon as it reaches try. Is this a known issue or something new? Why is returning an implicit struct a problem? ScreenShot Stack Trace coldfusion.runtime.UndefinedElementException: Element DETAIL is undefined in CFCATCH. at coldfusion.runtime.CfJspPage.resolveCanonicalName(CfJspPage.java:1752) at coldfusion.runtime.CfJspPage._resolve(CfJspPage.java:1705) at coldfusion.runtime.CfJspPage._resolveAndAutoscalarize(CfJspPage.java:1854) at coldfusion.runtime.CfJspPage._resolveAndAutoscalarize(CfJspPage.java:1833) at cfcomponentFile2ecfc947108420$funcBLAHIMPLICIT.runFunction(C:\ColdFusion10\cfusion\wwwroot\fresh\componentFile.cfc:21) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:472) at coldfusion.runtime.UDFMethod$ReturnTypeFilter.invoke(UDFMethod.java:405) at coldfusion.runtime.UDFMethod$ArgumentCollectionFilter.invoke(UDFMethod.java:368) at coldfusion.filter.FunctionAccessFilter.invoke(FunctionAccessFilter.java:55) at coldfusion.runtime.UDFMethod.runFilterChain(UDFMethod.java:321) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:220) at coldfusion.runtime.TemplateProxy.invoke(TemplateProxy.java:655) at coldfusion.runtime.TemplateProxy.invoke(TemplateProxy.java:444) at coldfusion.runtime.TemplateProxy.invoke(TemplateProxy.java:414) at coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:2432) at cf62ecfm1194236173.runPage(C:\ColdFusion10\cfusion\wwwroot\fresh\cfcatchErr.cfm:5) at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:244) at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:444) at coldfusion.filter.CfincludeFilter.invoke(CfincludeFilter.java:65) at coldfusion.filter.IpFilter.invoke(IpFilter.java:64) at coldfusion.filter.ApplicationFilter.invoke(ApplicationFilter.java:449) at coldfusion.filter.MonitoringFilter.invoke(MonitoringFilter.java:40) at coldfusion.filter.PathFilter.invoke(PathFilter.java:112) at coldfusion.filter.LicenseFilter.invoke(LicenseFilter.java:30) at coldfusion.filter.ExceptionFilter.invoke(ExceptionFilter.java:94) at coldfusion.filter.BrowserDebugFilter.invoke(BrowserDebugFilter.java:79) at coldfusion.filter.ClientScopePersistenceFilter.invoke(ClientScopePersistenceFilter.java:28) at coldfusion.filter.BrowserFilter.invoke(BrowserFilter.java:38) at coldfusion.filter.NoCacheFilter.invoke(NoCacheFilter.java:46) at coldfusion.filter.GlobalsFilter.invoke(GlobalsFilter.java:38) at coldfusion.filter.DatasourceFilter.invoke(DatasourceFilter.java:22) at coldfusion.filter.CachingFilter.invoke(CachingFilter.java:62) at coldfusion.CfmServlet.service(CfmServlet.java:219) at coldfusion.bootstrap.BootstrapServlet.service(BootstrapServlet.java:89) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at coldfusion.monitor.event.MonitoringServletFilter.doFilter(MonitoringServletFilter.java:42) at coldfusion.bootstrap.BootstrapFilter.doFilter(BootstrapFilter.java:46) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:414) at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:204) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:298) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:722) Note: I like Railo too, but lets only talk about CF 10 in this case. I submitted a bug to Adobe. A: It definitely a bug in CF, so good that you logged it as such (3605215). The most expedient work-around I could come up with is to use an intermediary variable, eg: <cffunction name="blahImplicit" returntype="Struct"> <cfset var name = 'ColdFusion'/> <cftry> <cfreturn {success= true, data= name}> <cfcatch type="any"> <cfset var ret = {success= false, data= cfcatch.detail}><!--- this will prevent the error ---> <cfreturn ret> </cfcatch> </cftry> </cffunction>
{ "pile_set_name": "StackExchange" }
Q: Exporting a chart as image using lazy-highcharts gem I am able to generate the charts using lazy highcharts but i want those charts to exported as images , here is my code which I am using to generate the charts @fields= ReportHistory.all_history @h = LazyHighCharts::HighChart.new('graph') do |f| f.chart(:renderTo => 'container', :zoomType => 'x',:spacingRight=> 20) f.title(:text => 'Reports') f.xAxis(:title=>{:text => 'Days'}, :categories =>@fields.map{|x|x.Date}.last(limit=15)) f.yAxis(:title=>{:text=> 'Jobs_count', :type =>'integer' ,:max => 5000000}) f.series(:name =>'jobs_count', :data=> @fields.map{|x| x.jobs_count.to_i }.last(limit=15)) f.export(:type=> 'image/jpeg') end and in my view I to show the chart I have this <%= high_chart("my_id", @h) %> I want to have the effect like here where I can download the chart image using the export button. A: First, you need to ensure that the export module is available and loaded by your view: <%= javascript_include_tag "vendor/highcharts/highcharts.js" %> <%= javascript_include_tag "vendor/highcharts/modules/exporting.js" %> Second... there's nothing to do. As soon as the exporting modul is loaded, it will add the menu to export your graph. Notes: You may need to adapt the paths depending on your setup. The exporting.js is part of the package you download from Highcharts.
{ "pile_set_name": "StackExchange" }
Q: Append characters to a string in multiple rows in Oracle SQL I'm trying to update a single column in multiple rows by appending the string '999': UPDATE integration.ol_orders SET order_id = ((SELECT order_id FROM integration.ol_orders WHERE status = 2) || '999') WHERE status = 2 but for whatever reason, I keep getting the error of "ORA-01427: single-row subquery returns more than one row tips". So, as I iterate my n rows, I'm trying to do: a1 = a1 || '999' a2 = a2 || '999' a3 = a3 || '999' an = an || '999' Any suggestions how to go about this? edit: changed '+' to '||', still no luck A: The subquery looks unnecessary, just doing this should work: UPDATE integration.ol_orders SET order_id = order_id || '999' WHERE status = 2 If I remember right Oracle uses || for concatenation. It might be necessary to cast the order_id to a character type if it's an integer, I'm not sure about that and can't test it at the moment. (The conversion should be implicit as stated in a comment, otherwise you can use TO_CHAR() to cast it explicitly). Make sure to have a backup or copy of the table before running though...
{ "pile_set_name": "StackExchange" }