source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0019030643.txt" ]
Q: My code to write a .txt file from my @data isn't working :(. What am I doing wrong? I am using a while loop iv. Write the following output to a new file with columns separated by tabs ("\t"): DATE, MONTH, MAX TEMP, MIN TEMP, MAX HUMID, MIN HUMID #a declare vars @riteline=(); my $headers; my $riteAline; print 'iv. Write the following output to a new file with columns separated by tabs ("\t"):'; print "\n DATE, MONTH, MAX TEMP, MIN TEMP, MAX HUMID, MIN HUMID"; $headers= ("DATE,MONTH,MAX TEMP,MIN TEMP,MAX HUMID,MIN HUMID"); $headers=~ tr/,/\t/; #first you can turn the arrays into string open (my $fh,'>', 'DATAEXPORT.txt') | die "Could not open file :( fix bugs"; $i=0; $ii=0; #the loop to match data by index and seperate with tab while (<FILE>) { chomp; if($i=0){ $fh=$headers; print "$fh\n"; $i=1; }else{ @riteline=(@DAY[$ii],"\t",@MONTH[$ii],"\t",@MAX_TEMPERATURE[$ii],"\t",@MIN_TEMPERATURE[$ii],"\t",@MAX_HUMIDITY[$ii],"\t",@MIN_HUMIDITY[$ii]); $fh=join('\t',@riteline); print "$fh\n"; $ii++ } }; close (FILE); print "HW 2 complete"; My error msg just comes up :( EDIT1: I made the following changes by a few people's gracious suggestions, but I have no output.... I am not sure why, am I doing something fundamentally wrong? The arrays DO exist btw # iv. Write the following output to a new file with columns separated by tabs ("\t"): # DATE, MONTH, MAX TEMP, MIN TEMP, MAX HUMID, MIN HUMID # a delacre @riteline = (); my $headers; print 'iv. Write the following output to a new file with columns separated by tabs ("\t"):'; print "\n DATE, MONTH, MAX TEMP, MIN TEMP, MAX HUMID, MIN HUMID"; $headers = ('DATE,MONTH,MAX TEMP,MIN TEMP,MAX HUMID,MIN HUMID'); $headers =~ tr/,/\t/; # first you can turn the arrays into string open(my $fh, '>', 'DATAEXPORT.txt') || die "Could not open file :( fix bugs"; $i = 0; $ii = 0; # the loop to match data by index and seperate with tab while (<FILE>) { chomp; if ($i == 0) { print $fh $headers, "\n"; $i = 1; } else { @riteline = ( $DAY[$ii], "\t", $MONTH[$ii], "\t", $MAX_TEMPERATURE[$ii], "\t", $MIN_TEMPERATURE[$ii], "\t", $MAX_HUMIDITY[$ii], "\t", $MIN_HUMIDITY[$ii] ); print $fh join("\t", @riteline), "\n"; print $fh @riteline, "\n"; $ii++; } } close(FILE); print "HW 2 complete"; A: Your errors come from : $fh=$headers; print "$fh\n"; and $fh=join('\t',@riteline); print "$fh\n"; You' d write: print $fh $headers,"\n"; and print $fh join("\t",@riteline),"\n"; for the last one I think you want: print $fh @riteline,"\n"; Also, don't use @DAY[$ii] but $DAY[$ii] A: My error msg just comes up :( It would because you say: open (my $fh,'>', 'DATAEXPORT.txt') | die "Could not open file :( fix bugs"; Say: open (my $fh,'>', 'DATAEXPORT.txt') || die "Could not open file :( fix bugs"; or open (my $fh,'>', 'DATAEXPORT.txt') or die "Could not open file :( fix bugs"; Of course, the other issues have been pointed out by M42 here.
[ "stackoverflow", "0034139029.txt" ]
Q: Postgres how to make more than one transaction I have a problem makin more than one insertion into the database, my problem initial it was that i couldn't insert into the table beacause i need the last id of the last record inserted. if i try to insert more records to the table, it doesn't work, why? that's because is inserted until transaction is commited,so it only will insert one record with the last id inserted. here is my java code: @Service @Transactional public class ServicioEvaluacionImpl implements ServicioEvaluacion{ @Autowired @Qualifier("sfGas") SessionFactory sf; Session session; @Autowired EncuestaDaoImpl encuestaDao; @Autowired ClienteDaoImpl clienteDao; @Autowired DelegacionDaoImpl delegacionDao; @Autowired ServicioGenericoCRUD servicioCRUD; public void guardarEvaluacion(String parametros) { JSONObject obj = new JSONObject(parametros); JSONObject cliente = obj.getJSONObject("cliente"); Integer lastIdCliente = new Integer(0); String nombre = cliente.getString("nombre"); String apellidos = cliente.getString("apellidos"); String sexo = cliente.getString("sexo"); String email = cliente.getString("email"); String area = cliente.getString("area"); String puesto = cliente.getString("puesto"); int delegacion = cliente.getInt("delegacion"); Delegacion delegacionObj = delegacionDao.getDelegacion(delegacion); Cliente clienteObj = new Cliente(); clienteObj.setNombre(nombre); clienteObj.setApellidos(apellidos); clienteObj.setEmail(email); clienteObj.setSexo(sexo); clienteObj.setPuesto(puesto); clienteObj.setArea(area); clienteObj.setDelegacion(delegacionObj); //clienteDao.setCliente(clienteObj); Transaction transaction = null; try{ Session session = sf.getCurrentSession(); //obtiene ultimo id insertado List<Object> qTemp = servicioCRUD.consultaSQL("Select max(id_cliente) from cliente;"); for(Object registro : qTemp){ lastIdCliente = Integer.parseInt(registro.toString()); } int ultimoID = lastIdCliente.intValue()+1; clienteObj.setIdCliente(ultimoID); servicioCRUD.create(clienteObj); JSONArray evaluaciones = obj.getJSONArray("evaluaciones"); JSONArray idPregunta = obj.getJSONArray("idPregunta"); JSONArray comentarios = obj.getJSONArray("comentarios"); String sugerencias = obj.getString("sugerencias"); Respuestas respuesta = new Respuestas(); Comentarios comentario = new Comentarios(); Sugerencias sugerencia = new Sugerencias(); respuesta.setCliente(clienteObj); comentario.setCliente(clienteObj); sugerencia.setCliente(clienteObj); java.util.Date date = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); sugerencia.setFecha(sqlDate); sugerencia.setSugerencia(sugerencias); for (int i = 0; i < evaluaciones.length(); i++) { transaction = session.beginTransaction(); Encuesta pregunta = encuestaDao.getEncuesta(idPregunta.getInt(i)); respuesta.setEncuesta(pregunta); int respuestaID=0; //obtiene ultimo id de respuesta qTemp = servicioCRUD.consultaSQL("SELECT max(id_respuesta) FROM respuestas"); for(Object registro : qTemp){ Integer lastIdPregunta = Integer.parseInt(registro.toString()); respuestaID = lastIdPregunta.intValue()+1; System.out.println("loop::"+i+" -ult id resp: "+ respuestaID); } respuesta.setCalificacion((short) evaluaciones.getInt(i)); respuesta.setIdRespuesta(respuestaID); //insercion respuestas respuesta.setFecha(sqlDate); servicioCRUD.create(respuesta); //si no hay comentarios no insertar if(!comentarios.getString(i).equals("")){ int commentID = 0; qTemp = servicioCRUD.consultaSQL("SELECT max(id_comentario) FROM comentarios"); for(Object registro : qTemp){ Integer lastIdComent = Integer.parseInt(registro.toString()); commentID = lastIdComent.intValue()+1; } comentario.setEncuesta(pregunta); comentario.setIdComentario(commentID); comentario.setComentario(comentarios.getString(i)); comentario.setFecha(sqlDate); servicioCRUD.create(comentario); } transaction.commit(); } transaction = session.beginTransaction(); if(!sugerencias.equals("")){ int sugerenciaID = 0; qTemp = servicioCRUD.consultaSQL("SELECT max(id_comentario) FROM comentarios"); for(Object registro : qTemp){ Integer sugerenciaIdComent = Integer.parseInt(registro.toString()); sugerenciaID = sugerenciaIdComent.intValue()+1; } sugerencia.setIdSugerencia(sugerenciaID); servicioCRUD.create(sugerencia); } transaction.commit(); }catch(Exception e){ e.printStackTrace(); transaction.rollback(); }finally{ session.flush(); } } } i tried to commit at the end of the loop but it gives an error. there is another way to fix the table sequence without the workaround? if not, what i can do? i need to insert those records in a sequence. EDIT: i fixed the problem with the table sequence, still i can't save those more than one record into the database, there is no stack trace errors this time. Stack trace: 11:03:21,812 INFO [stdout] (http-localhost-127.0.0.1-8080-3) loop::0 -ult id resp: 5 11:03:22,118 INFO [stdout] (http-localhost-127.0.0.1-8080-3) loop::1 -ult id resp: 5 11:03:22,195 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) org.hibernate.TransactionException: Transaction not successfully started 11:03:22,195 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:127) 11:03:22,196 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at com.gas.servicioImpl.ServicioEvaluacionImpl.guardarEvaluacion(ServicioEvaluacionImpl.java:163) 11:03:22,196 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at com.gas.rest.EvaluacionController.setEvaluaciones(EvaluacionController.java:24) 11:03:22,196 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 11:03:22,197 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 11:03:22,197 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 11:03:22,197 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at java.lang.reflect.Method.invoke(Method.java:606) 11:03:22,198 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) 11:03:22,198 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) 11:03:22,198 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) 11:03:22,199 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:743) 11:03:22,199 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:672) 11:03:22,200 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:82) 11:03:22,200 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919) 11:03:22,200 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851) 11:03:22,201 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953) 11:03:22,201 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855) 11:03:22,202 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) 11:03:22,202 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829) 11:03:22,202 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) 11:03:22,203 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) 11:03:22,203 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) 11:03:22,203 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:230) 11:03:22,204 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:106) 11:03:22,204 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) 11:03:22,204 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) 11:03:22,205 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) 11:03:22,205 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) 11:03:22,205 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) 11:03:22,206 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) 11:03:22,206 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) 11:03:22,207 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) 11:03:22,207 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) 11:03:22,207 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) 11:03:22,208 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) 11:03:22,208 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) 11:03:22,208 ERROR [stderr] (http-localhost-127.0.0.1-8080-3) at java.lang.Thread.run(Thread.java:745) 11:03:22,209 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/gasnaturalfenosa].[appServlet]] (http-localhost-127.0.0.1-8080-3) Servlet.service() para servlet appServlet lanzó excepción: java.lang.NullPointerException at com.gas.servicioImpl.ServicioEvaluacionImpl.guardarEvaluacion(ServicioEvaluacionImpl.java:192) [classes:] at com.gas.rest.EvaluacionController.setEvaluaciones(EvaluacionController.java:24) [classes:] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_79] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_79] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_79] at java.lang.reflect.Method.invoke(Method.java:606) [rt.jar:1.7.0_79] at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) [spring-web-3.2.13.RELEASE.jar:3.2.13.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) [spring-web-3.2.13.RELEASE.jar:3.2.13.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) [spring-webmvc-3.2.13.RELEASE.jar:3.2.13.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:743) [spring-webmvc-3.2.13.RELEASE.jar:3.2.13.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:672) [spring-webmvc-3.2.13.RELEASE.jar:3.2.13.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:82) [spring-webmvc-3.2.13.RELEASE.jar:3.2.13.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919) [spring-webmvc-3.2.13.RELEASE.jar:3.2.13.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851) [spring-webmvc-3.2.13.RELEASE.jar:3.2.13.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953) [spring-webmvc-3.2.13.RELEASE.jar:3.2.13.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855) [spring-webmvc-3.2.13.RELEASE.jar:3.2.13.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829) [spring-webmvc-3.2.13.RELEASE.jar:3.2.13.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:] at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:230) [spring-orm-3.2.13.RELEASE.jar:3.2.13.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:106) [spring-web-3.2.13.RELEASE.jar:3.2.13.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:] at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:] at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:] at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:] at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:] at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_79] A: The problem isn't your commit. It's a NullPointerException line 192. I don't know which line 192 is, but I bet it's a line outside of your transaction block. When you try to rollback the transaction, you get another Exception from the Catch - Rollback. Look for the Null variable, and you may solve your problem. You may also check if the transaction is open when you try to Rollback. Or add more try {} catch {} blocks since your code is very error prone.
[ "stackoverflow", "0044013098.txt" ]
Q: Xamarin.Android.Support.Fragment, Version=1.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile? I attempted to use Xamarin.Android.Support libraries version 25.3.1 but because of a bug I decided to downgrade back to my previous version 23.3.0. After Downgrading I am getting this error message below. whatever I tried, i cant get rid of it. I tried to delete all bin, obj, tmp etc folders. restarted VS2015, clean,rebuild... Severity Code Description Project File Line Suppression State Error Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'Xamarin.Android.Support.Fragment, Version=1.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile? File name: 'Xamarin.Android.Support.Fragment.dll' at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters) at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences(DirectoryAssemblyResolver resolver, ICollection`1 assemblies, AssemblyDefinition assembly, Boolean topLevel) at Xamarin.Android.Tasks.ResolveAssemblies.Execute(DirectoryAssemblyResolver resolver) I found out a small change in my package.config file. All below targetFramework="monoandroid71" now. Before upgrade-downgrade, they were targetFramework="monoandroid70", I replaced them manulla but, it didnt help at all. How can I fix this problem? <package id="Xamarin.Android.ShortcutBadger" version="1.1.809" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Animated.Vector.Drawable" version="23.3.0" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.CustomTabs" version="23.3.0" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.Design" version="23.3.0" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.v4" version="23.3.0" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.v7.AppCompat" version="23.3.0" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.v7.CardView" version="23.3.0" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.v7.MediaRouter" version="23.3.0" targetFramework="monoandroid71" /> <package id="Xamarin.Android.Support.v7.Palette" version="23.3.0" targetFramework="monoandroid71" /> How my settings looks like References: UPDATE: I have reinstalled all nugetpackages and succeed to run android project on 1 pc but interesting thing is same project is not running on another pc. It returns different but similar error. Severity Code Description Project File Line Suppression State Error The "ResolveLibraryProjectImports" task failed unexpectedly. System.IO.FileNotFoundException: Could not load assembly 'myApp, Version=0.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile? File name: 'myApp.dll' at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters) at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName, ReaderParameters parameters) at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName) at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.GetAssembly(String fileName) at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Extract(DirectoryAssemblyResolver res, ICollection`1 jars, ICollection`1 resolvedResourceDirectories, ICollection`1 resolvedAssetDirectories, ICollection`1 resolvedEnvironments) at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Execute() at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute() at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() myApp.Droid A: My problem is i updated xamarin form to 2.5.0.121934, Then, it shows Error "Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'Xamarin.Android.Support.Fragment, Version=1.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?" So i downgrade my xamarin.form to 2.3.4.247, then it build successfully. A: The best option here is to uninstall ALL Xamarin and Android packages from your Xamarin.Android project. Then install Xamarin.Forms again, and it will add in the correct dependencies. Alternatively, try downloading Install-Package Xamarin.Android.Support.Fragment A: I renamed the title because I had 2 following problem, they look similar indeed and both related to Android project only. First one was complaining about support.Fragment which is available above 24.x.x versions but I was using 23.0.x. This was caused probably because of downgrading from 25.3.1 version. Whatever I tried, clean bin, obj, temp, rebuild didn't help. I used command Update-Package –reinstallto reinstall all NuGet packages in the solution. This helped on one of my PC. but on another PC of mine, I was getting 2nd error as in the question. Error message below is indeed telling you that PCL project is not found under android. If you look at the Output window it will tell you that it is not found in Debug/Bin folder. When I look at my Bin folder, I saw that nothing was generated. The "ResolveLibraryProjectImports" task failed unexpectedly. System.IO.FileNotFoundException: Could not load assembly 'myApp, Version=0.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile? File name: 'myApp.dll' It looks like this was caused by a NuGet package which is using .net standard 1.0. my PCL project was still using PCL profile. This is normally no problem if you have .Net Core 1.0 libraries as stated in the article from Adam Pedley. How it was working on my other computer was because I had VS2017 installed. VS2017 installation has .Net Core automatically installed. But I was working on VS2015 and it requires separate installation. I hope this helps anyone else is having the problem.
[ "stackoverflow", "0041502232.txt" ]
Q: Java regex input from txt file I have a text file that includes some mathematical expressions. I need to parse the text into components (words, sentences, punctuation, numbers and arithmetic signs) using regular expressions, calculate mathematical expressions and return the text in the original form with the calculated numbers expressions. I done this without regular expressions (without calculation). Now I am trying to do this using regular expressions. I not fully understand how to do this correctly. The input text is like this: Pete like mathematic 5+3 and jesica too sin(3). In the output I need: Pete like mathematic 8 and jesica too 0,14. I need some advice with regex and calculation from people who know how to do this. My code: final static Pattern PUNCTUATION = Pattern.compile("([\\s.,!?;:]){1,}"); final static Pattern LETTER = Pattern.compile("([а-яА-Яa-zA-Z&&[^sin]]){1,}"); List<Sentence> sentences = new ArrayList<Sentence>(); List<PartOfSentence> parts = new ArrayList<PartOfSentence>(); StringTokenizer st = new StringTokenizer(text, " \t\n\r:;.!?,/\\|\"\'", true); The code with regex (not working): while (st.hasMoreTokens()) { String s = st.nextToken().trim(); int size = s.length(); for (int i=0; i<s.length();i++){ //with regex. not working variant Matcher m = LETTER.matcher(s); if (m.matches()){ parts.add(new Word(s.toCharArray())); } m = PUNCTUATION.matcher(s); if (m.matches()){ parts.add(new Punctuation(s.charAt(0))); } Sentence buf = new Sentence(parts); if (buf.getWords().size() != 0) { sentences.add(buf); parts = new ArrayList<PartOfSentence>(); } else parts.add(new Punctuation(s.charAt(0))); Without regex (working): if (size < 1) continue; if (size == 1) { switch (s.charAt(0)) { case ' ': continue; case ',': case ';': case ':': case '\'': case '\"': parts.add(new Punctuation(s.charAt(0))); break; case '.': case '?': case '!': parts.add(new Punctuation(s.charAt(0))); Sentence buf = new Sentence(parts); if (buf.getWords().size() != 0) { sentences.add(buf); parts = new ArrayList<PartOfSentence>(); } else parts.add(new Punctuation(s.charAt(0))); break; default: parts.add(new Word(s.toCharArray())); } } else { parts.add(new Word(s.toCharArray())); } } A: This is not a trivial problem to solve as even matching numbers can become quite involved. Firstly, a number can be matched by the regular expression "(\\d*(\\.\\d*)?\\d(e\\d+)?)" to account for decimal places and exponent formats. Secondly, there are (at least) three types of expressions that you want to solve: binary, unary and functions. For each one, we create a pattern to match in the solve method. Thirdly, there are numerous libraries that can implement the reduce method like this or this. The implementation below does not handle nested expressions e.g., sin(5) + cos(3) or spaces in expressions. private static final String NUM = "(\\d*(\\.\\d*)?\\d(e\\d+)?)"; public String solve(String expr) { expr = solve(expr, "(" + NUM + "(!|\\+\\+|--))"); //unary operators expr = solve(expr, "(" + NUM + "([+-/*]" + NUM + ")+)"); // binary operators expr = solve(expr, "((sin|cos|tan)\\(" + NUM + "\\))"); // functions return expr; } private String solve(String expr, String pattern) { Matcher m = Pattern.compile(pattern).matcher(expr); // assume a reduce method :String -> String that solve expressions while(m.find()){ expr = m.replaceAll(reduce(m.group())); } return expr; } //evaluate expression using exp4j, format to 2 decimal places, //remove trailing 0s and dangling decimal point private String reduce(String expr){ double res = new ExpressionBuilder(expr).build().evaluate(); return String.format("%.2f",res).replaceAll("0*$", "").replaceAll("\\.$", ""); }
[ "stackoverflow", "0044357373.txt" ]
Q: MySQL: Make a blog-style page with different data types at different points I'm trying to develop something similar to this with PHP and MySQL: http://a-bittersweet-life.tumblr.com/ I'd like to make a page that is mostly made up of words, but can be interspersed with images or embedded videos or other data types. I'm not sure exactly how to do this, but I have an idea: id | entry_date | text | image_link | vid_embed | sound_embed 0 | June 1st | data | null | null | null 1 | June 1st | null | data | null | null 2 | June 1st | null | data | null | null 3 | June 1st | data | null | null | null 4 | June 2nd | data | null | null | null 5 | June 2nd | null | null | data | null 6 | June 2nd | data | null | null | null 7 | June 2nd | null | data | null | null 8 | June 2nd | null | data | null | null .... .... .... So, for each blog entry, the Date is displayed first, followed by the order in which data was put into the SQL table (ordered by id): June 1st Text Image Image Text June 2nd Text Video Text Image Image Is there another way to do this, or does this seem like a fairly practical way to do it? A: This is a simple example which is use plain php. If you use some php framework you can replace some parts into more simple, but here is the GIST. I'ver created 2 functions, so you can create classes and methods or build MVC or even use this functions, it is only concept... <?php declare(strict_types = 1); // This function will provide data from DB. // Here I`ve skipped validation // because I had relied on PHP7 scalar type declarations. function getDataFromDB(int $limit, int $offset) { $db = new \PDO('mysql:dbname={YOUR_DB};host={YOUR_HOST}', '{USER}', '{PASS}'); // Here I`ve used super simple SQL, // but you can improve it // and filters by date or author or category or something else... $sql = sprintf( ' SELECT * FROM {YOUR_TABLE_NAME} ORDER BY entry_date DESC LIMIT %d OFFSET %d ', $limit, $offset ); // In this query, I`ve only provided params for pagination // because they are required on the first stage... $s = $db->prepare($sql); if (!$s->execute()) { throw new \RuntimeException($s->errorInfo()); } // Next param is very IMPORTANT, // it will group data into array with format where: // key - date and value - array of posts, like: // array ( // 'June 1st' => array ( // 0 => array ('text' => '...', 'image_link' => ...), // 1 => array ('text' => '...', 'image_link' => ...), // ), // 'June 2nd' => array ( // 0 => array ('text' => '...', 'image_link' => ...), // 1 => array ('text' => '...', 'image_link' => ...), // 2 => array ('text' => '...', 'image_link' => ...), // 3 => array ('text' => '...', 'image_link' => ...), // ) // ) return $s->fetchAll(\PDO::FETCH_GROUP | \PDO::FETCH_ASSOC); } Now you can use this function with purpose grab data from db and pass it to next function which will prepare html or json or something else... // This function will render data. function render(array $data) { $html = ''; foreach ($data as $day => $posts) { // Caption for certain day, like 'June 1st' or 'June 2nd'. $html .= sprintf('<div class="dayPosts"><div class="day">%s</div>', $day); foreach ($posts as $post) { // Particular blog post. // It is super simple HEREDOC example, // but you can do here anything you wish. $html .= <<<"BLOGPOST" <div class="post"> <h3>{$post['title']}</h3> <div class="content"> <img src="{$post['image_link']}"> <p class="text"{$post['test']}></p> <video controls> <source src="{$post['vid_embed']}" type="video/mp4"> </video> </div> </div> BLOGPOST; } $html .= '</div>'; } return $html; } Here Ive used plain php functions with purposer to prepare html, but you cna use something better liketwigorvoltorsmarty` or something else. Alsom you can put this function into view or refactor somehow... And last step, connect all together: // Now you can get and render your content. echo render(getDataFromDB(20, 0)); PS: Ti is only the raw example... But now must have idea what to do next! Hope it will help you!
[ "stackoverflow", "0050536176.txt" ]
Q: int[][] to int[] using the System.arracopy method If I want to convert an int[][] array into an int[] in java, I use the code shown underneath. final int width = 3, height = 4; final int[][] source = new int[width][height]; final int[] destination = new int[width * height]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { destination[x * width + y] = source[x][y];  } } I was just recently introduced to the System.arraycopy method. It is probably the most efficient way to copy an array in java. Therefore, I tried to implement it in a similar way shown underneath. final int width = 3, height = 4; final int[][] source = new int[width][height]; final int[] destination = new int[width * height]; for (int index = 0; index < source.length; index++) { System.arraycopy(source[index], 0, destination, source[index].length, source[index].length); } However, the resulting array is heavily distorted and does not represent the original array in any way. A: This is what you want: final int width = 3, height = 4; final int[][] source = new int[width][height]; final int[] destination = new int[width * height]; for (int i = 0; i < source.length; i++) System.arraycopy(source[i], 0, destination, i * width, height); If you want it to work in general, cases where each sub-array in source is different size, you want this: int totalLength = 0; for (int i = 0; i < source.length; i++) totalLength += source[i].length; final int[] destination = new int[totalLength]; for (int len, i = 0, index = 0; i < source.length; i++, index += len) System.arraycopy(source[i], 0, destination, index, len = source[i].length);
[ "stackoverflow", "0035384202.txt" ]
Q: Knockout Validation: Validation Summary displays required field errors at page load even though no edits were made I am using knockout validation and have it configured where it displays errors only when fields are modified. It works perfectly as long as "insertMessages" is true for the config. However, I prefer using a "validation summary" at the bottom of the form, rather than inserting validation error messages beside each field. I am binding the validation summary to the model's list of errors. The problem is the list of errors contains all errors, regardless of whether or not the corresponding viewmodel value has been modified. How can I filter to get only the errors corresponding to modified viewmodel members? My fiddle is using both display techniques: inserted messages and summarized messages. You can see that the inserted messages work as expected: only appearing on field change or submit; whereas the summarized messages appear immediately when the form loads. ko.validation.init({ errorElementClass: 'ui-state-error', decorateInputElement: true }); var model = function() { self = this; self.firstName = ko.observable().extend({ required: true }); self.lastName = ko.observable().extend({ required: true }); self.errors = ko.validation.group(this); self.submit = function() { if (self.errors().length == 0) { alert('No errors'); } else { self.errors.showAllMessages(); } return false; }; }; ko.applyBindings(new model()); Thanks. A: I found a way to filter for errors corresponding to modified observables. self.visibleErrors = ko.computed(function() { var errors = []; self.errors.forEach(function(observable) { if (ko.validation.utils.isValidatable(observable) && !observable.isValid() && observable.isModified()) { errors.push(observable.error.peek()); } }) return errors; }); Updated fiddle.
[ "serverfault", "0000189237.txt" ]
Q: I'm missing some zone files, and I need them to configure some SPF settings. How do I create them? I recently noticed that my recently setup domain, example.com, was being used to send spam. So, I decided to fix this and found some information on SPF configuration, and that I'd need to go edit the appropriate .zone file in my server. Well, that was fine and dandy and seemed pretty simple--except I don't seem to have the ones I need! Well, lo and behold, all I found (running Centos 5.5 under /var/named) were the following *.zone files: localdomain.zone and localhost.zone, none of which contained any information relative to my server's IP address or domain name. So I checked the files named.conf and named.rfc1912.zone, but neither one made reference to my domain name, example.com, or my IP address. They only make reference to localhost, it appears. Where did I go wrong in all this? I haven't found any information on creating zones to put SPF information in them, just putting SPF data in pre-existing zone files. Thanks a bunch, A: Are you sure your hosting the DNS for your domain ? It doesnt sound like you are, whios example.com have a look in the results for Name Server: and see if those point to your server, if not all the work in the world with bind wont help ;)
[ "math.stackexchange", "0000436516.txt" ]
Q: Sturm-Liouville Questions In thinking about Sturm-Liouville theory a bit I see I have no actual idea what is going on. The first issue I have is that my book began with the statement that given $$L[y] = a(x)y'' + b(x)y' + c(x)y = f(x)$$ the problem $L[y] \ = \ f$ can be re-cast in the form $L[y] \ = \ \lambda y$. Now it could be a typo on their part but I see no justification for the way you can just do that! More importantly though is the motivation for Sturm-Liouville theory in the first place. The story as I know it is as follows: Given a linear second order ode $$F(x,y,y',y'') = L[y] = a(x)y'' + b(x)y' + c(x)y = f(x)$$ it is an exact equation if it is derivable from a differential equation of one order lower, i.e. $$F(x,y,y',y'') = \frac{d}{dx}g(x,y,y').$$ The equation is exact iff $$a''(x) - b'(x) + c(x) = 0. $$ If $F$ is not exact it can be made exact on multiplication by a suitable integrating factor $\alpha(x)$. This equation is exact iff $$(\alpha(x)a(x))'' - (\alpha(x)b(x))' + \alpha(x)c(x) = 0 $$ If you expand this out you get the Adjoint operator $$L^*[\alpha(x)] \ = \ (\alpha(x)a(x))'' \ - \ (\alpha(x)b(x))' \ + \ \alpha(x)c(x) \ = 0 $$ If you expand $L^*$ you see that we can satisfy $L \ = \ L^*$ if $a'(x) \ = \ b(x)$ & $a''(x) \ = \ b'(x)$ which then turns $L[y]$ into something of the form $$L[y] \ = \ \frac{d}{dx}[a(x)y'] \ + \ c(x)y \ = \ f(x).$$ Thus we seek an integratiing factor $\alpha(x)$ so that we can satisfy this & the condition this will hold is that $\alpha(x) \ = \ \frac{1}{a(x)}e^{\int\frac{b(x)}{a(x)}dx}$ Then we're dealing with: $$\frac{d}{dx}[\alpha(x)a(x)y'] \ + \ \alpha(x)c(x)y \ = \ \alpha(x)f(x)$$ But again, by what my book said they magically re-cast this problem as $$\frac{d}{dx}[\alpha(x)a(x)y'] \ + \ \alpha(x)c(x)y \ = \ \lambda \alpha(x) y(x)$$ Then calling $$\frac{d}{dx}[\alpha(x)a(x)y'] \ + \ ( \alpha(x)c(x)y \ - \ \lambda \alpha(x) )y(x) \ = \ 0$$ a Sturm-Liouville problem. My question is, how can I make sense of everything I wrote above? How can I clean it up & interpret it, like at one stage I thought we were turning our 2nd order ode into something so that it reduces to the derivative of a first order ode so we can easily find first integrals then the next moment we're pulling out eigenvalues & finding full solutions - what's going on? I want to be able to look at $a(x)y'' \ + \ b(x)y' \ + \ c(x)y \ = \ f(x)$ & know how & why we're turning this into a Sturm-Liouville problem in a way that makes sense of exactness & integrating factors, thanks for reading! A: The first issue I have is that my book began with the statement that given $$ L[y]=a(x)y′′+b(x)y′+c(x)y=f(x) $$ the problem $L[y] = f$ can be re-cast in the form $L[y] = λy$. Now it could be a typo on their part but I see no justification for the way you can just do that! You're right: knowing nothing of spectral theory of these operators, it is very difficult to justify why this is so a priori. Here's an attempt at showing you the connection between the two forms. First, recognize that the two uses of $y$ above refer to different functions; so let's change notations. The ODE is $L[y]=f$, and the eigenvalue problem is $L[u_n]=\lambda_n u_n$. The subscript denotes that there may be a family of such solutions, indexed by a number $n$. I'm skipping some details about continuous spectra of operators, but the ideas I give can generally be extended. For now, assume that a countable sequence of $\lambda_n$ exists that solves the eigenvalue problem, and a corresponding sequence of eigenfunctions $u_n$. Your book uses the fact that these two problems are related as follows. Suppose the boundary conditions of the ODE are such that the eigenvalue problem has a sequence of solutions $u_n(x)$ for $n=1,2,\ldots$, and we found these eigenvalues and eigenfunctions by solving $L[u_n]=\lambda_n u_n$; further suppose that the function $f$ can be written by an infinite linear combination of such functions: $$ f(x) = \sum_{n=1}^\infty a_n u_n(x) $$ A sequence $a_n$ can be found for many operators and boundary conditions and functions $f$ in practice, without getting into the details. They should be in your book later on. For now, it suffices to think that we picked the "best-fit" sequence of $a_n$ that fits the function $f$. Further, let $y$ be expanded in the same set of functions: $$ y(x)=\sum_{n=1}^\infty b_n u_n(x) $$ Except this time, we don't know the $b_n$ coefficients, since we want to solve for $y$. Let's plug these into the ODE. For one side, I get $$ L[y] = \sum_{n=1}^\infty b_n L[u_n(x)] = \sum_{n=1}^\infty b_n \lambda_n u_n(x) $$ Giving $$ L[y] = f\;\;\Rightarrow\;\;\sum_{n=1}^\infty b_n \lambda_n u_n(x) = \sum_{n=1}^\infty a_n u_n(x) $$ Matching term by term, you can see that the unknown $b$ coefficients must be $b_n=a_n/\lambda_n$. Now plugging this into the solution form gives a concrete answer in terms of known quantities: $$ y(x) = \sum_{n=1}^\infty \frac{a_n}{\lambda_n} u_n(x) $$ That is the solution to our problem, but note that it is ONLY written in terms of the $u_n$ functions and some coefficients. The $u_n$ functions were chosen to solve $L[u_n]=\lambda u_n$, the eigenvalue problem, NOT the original problem. However, you can see that if you know the solution to the eigenvalue problem, you know the solution to the original problem. This is what they mean about "re-casting" the problem. Since the original problem is more complex, we solve the simpler eigenvalue problem instead, and superpose the solutions to solve the original problem. For operators of this kind, with the right conditions on the $a,b,c$ functions, this is always possible, so an ODE can be "re-cast" in terms of it's eigenvalue problem. The eigenfunctions are solutions to the operator problem, regardless of the forcing $f(x)$. Once you've solved that, you write everything in terms of these eigenfunctions and the problem simplifies nicely.
[ "stackoverflow", "0058511319.txt" ]
Q: Does kafka consumer manages its state? I have a Kafka cluster set up using three GCP VM instances. All three VMs have Zookeepers and servers running on then. I followed this guide for my set up: How to Setup Multi-Node Multi Broker Kafka Cluster in AWS I have kept all three instances in different regions in order to achieve High Availability in case of regional failure in Cloud Service (GCP or AWS, I understand it is highly unlikely). I have a topic created with replication-factor as 3. Now, suppose one region goes entirely down and only two nodes are alive. What happens to a consumer who was reading from the VM in the failed (which was working previously)? Once the services in the region come back up, would this consumer (having a unique client_id) maintain its state and read only new messages? Also, what if I have 7 VMs divided (2,2,3) across 3 regions: Is it a good idea to keep the replication factor as 7 to achieve high availability? I am thinking of 7 VMs because any of the regions go down, we still have the majority of Kafka nodes running. Is it possible to run a Kafka cluster with majority of nodes down? (E.g 4 out of 7 nodes down) A: The Kafka provide various setting to achieve high availability and can be tuned and optimize based on requirement 1. min.insync.replicas: Is the minimum number of copies will be always live at any time to continue running Kafka cluster. e.g. lets we have 3 broker nodes and one broker node got down in that case if min.insync.replicas = 2 or less cluster will keep serving request however if min.insync.replicas 3 it will stop. Please note min.insync.replicas=1 is not advisable in that case if data lost will lost forever. min.insync.replicas is a balance between higher consistency (requiring writes to more than one broker) and higher availability (allowing writes when fewer brokers are available). 2. ack(Acknowledgements): While publishing message we can set how many replica commit before producer receive acknowledge. e.g. ack is 0 means immediately acknowledge the message without waiting any commit to partition. ack is 1 means get success acknowledge after message get commit to the leader. ack is all means acknowledge after all in-sync replicas committed. leader.election.enable: You can set unclean.leader.election.enable=true on your brokers and in this case, if no replicas are in-sync, one of the out-of-sync replicas will be elected. This can lead to data loss but is favoring availability. Of course if some replicas are in-sync it will still elect one of them offsets.topic.replication.factor: should be greater than in case __consumer_offsets to have high available. __consumer_offsets is offset topic to manage topic offset so in case you have topic replication factor is 1 it may failed to consumer if one broker got down __consumer_offsets maintain committed for each topic of consumer group. Consumer always reads from a leader partition Consumers do not consume from followers, the followers only exist for redundancy and fail-over. There are possibilities that failed broker consists multiple leader partition. So in that case follower from partition on other broker will get promoted to leader. There different scenario lets follower partition doesn't have 100% in-sync with leader partition then we might loss some data. Here scenario comes how or what ack your using while publishing messages. There is trade off how many number of partition or replication is best number. I can say its depend design and choice based on discussion. Please make note large number of replica will give over burden which doing ISR with all follower partition with more memory occupied whereas very less like 1 or 2 will better performance but not high availability. Broker controller The controller is one of the brokers that has additional partition and replica management responsibilities. It has some extra responsibility and store some meta details and response in any meta details change in partition. Any of the brokers can play the role of the controller, but in a healthy cluster there is exactly one controller.Kafka broker will get relected to another controller in case controller shutdown or zookeeper lost connection. If controller is 0 or more than 1 means Broker is not healthy
[ "stackoverflow", "0033387504.txt" ]
Q: how to define constructor in intent i want to send data another activity with constructor without putextras //Recever Activity public Activity_Searching(int selected, String query) { this.Selected = selected; this.Query = query; } //Sender Activity Activity_Searching searching = new Activity_Searching(Selected, v.getText().toString()); startActivity(new Intent(context, searching.getClass())); A: its not possible because with Intent you can call a activity not object.
[ "stackoverflow", "0043960395.txt" ]
Q: Django image file is not rendering my settings file is like below, STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static', 'static_dirs'),) MEDIA_URL = '/static/images/' MEDIA_ROOT = '/Users/bhargavsaidama/5ai/source/static/images/' #MEDIA_ROOT = os.path.join(BASE_DIR,'static', 'images') (tried this too) my html loading page is like below, Note: I am directly using the file path here index.html: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> my actual html file is : {% extends "index.html" %} {% block content %} <div class="content"> <img src ='/Users/bhargavsaidama/5ai/source/5ai/static/images/Indian-economy.jpg' alt="My image"> <h2 id = "title"><font face = "Comic sans MS"> {{ post.title }} </font></h2> {% for sub_text in post.content %} <p id = "data"><font face = "Comic sans MS" size="+0.3"> {{ sub_text }} </font></p> {% endfor %} </div> {% endblock %} even I tried using: <img src ='Indian-economy.jpg' alt="My image"> .... but no luck but the output is if I am trying with a normal html file lets say: <html> <p> this is bhargav sai</p> <img src= '/Users/bhargavsaidama/5ai/source/5ai/static/images/Indian-economy.jpg' alt = 'my image'> </html> The output is: Even my direct url from local host was able to fetch the image: can anyone help me on this? A: You'd better to know how to configure and load static files, refer to official doc. As your jpg is in static/images folders, just change your actual html like this: {% extends "index.html" %} {% block content %} {% load static %} #load static directory <div class="content"> #load your static image <img src ='{% static "images/Indian-economy.jpg" %}' alt="My image"> <h2 id = "title"><font face = "Comic sans MS"> {{ post.title }} </font></h2> {% for sub_text in post.content %} <p id = "data"><font face = "Comic sans MS" size="+0.3"> {{ sub_text }} </font></p> {% endfor %} </div> {% endblock %} This will work for your case.
[ "stackoverflow", "0028888730.txt" ]
Q: Pandas: Change day I have a series in datetime format, and need to change the day to 1 for each entry. I have thought of numerous simple solutions, but none of them works for me. For now, the only thing that actually works is set the series as the index Query month and year from the index Reconstruct a new time series using year, month and 1 It can't really be that complicated, can it? There is month start, but is unfortunately an offset, that's of no use here. There seems to be no set() function for the method, and even less functionality while the series is a column, and not (part of) the index itself. The only related question was this, but the trick used there is not applicable here. A: You can use .apply and datetime.replace, eg: import pandas as pd from datetime import datetime ps = pd.Series([datetime(2014, 1, 7), datetime(2014, 3, 13), datetime(2014, 6, 12)]) new = ps.apply(lambda dt: dt.replace(day=1)) Gives: 0 2014-01-01 1 2014-03-01 2 2014-06-01 dtype: datetime64[ns] A: The other answer works, but any time you use apply, you slow your code down a lot. I was able to get an 8.5x speedup by writing a quick vectorized Datetime replace for a series. def vec_dt_replace(series, year=None, month=None, day=None): return pd.to_datetime( {'year': series.dt.year if year is None else year, 'month': series.dt.month if month is None else month, 'day': series.dt.day if day is None else day}) Apply: %timeit dtseries.apply(lambda dt: dt.replace(day=1)) # 4.17 s ± 38.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Vectorized: %timeit vec_dt_replace(dtseries, day=1) # 491 ms ± 6.48 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Note that you could face errors by trying to change dates to ones that don't exist, like trying to change 2012-02-29 to 2013-02-29. Use the errors argument of pd.to_datetime to ignore or coerce them. Data generation: Generate series with 1 million random dates: import pandas as pd import numpy as np # Generate random dates. Modified from: https://stackoverflow.com/a/50668285 def pp(start, end, n): start_u = start.value // 10 ** 9 end_u = end.value // 10 ** 9 return pd.Series( (10 ** 9 * np.random.randint(start_u, end_u, n)).view('M8[ns]')) start = pd.to_datetime('2015-01-01') end = pd.to_datetime('2018-01-01') dtseries = pp(start, end, 1000000) # Remove time component dtseries = dtseries.dt.normalize()
[ "stackoverflow", "0056837969.txt" ]
Q: Vibration on Android 9 I have this vibration method that makes my app vibrate exactly how I want on my phone (Android 6 API23). However when my friend tried it on his phone (Android 9) it did not work. It vibrated in the wrong way, constantly, and he could not even turn it off with the button in the app. How can I make my vibration work exactly the same on newer versions of Android? long[] pattern = { 0, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000}; This is the code for the vibration v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Log.d("VIBRATE ===>", "I AM VIBRATING"); // v.vibrate(VibrationEffect.createWaveform(pattern, 0)); This did not work } else { Log.d("VIBRATE ====>", "I AM VIBRATING"); v.vibrate(pattern , 0); //This do work on Android 6 } This is the method that stops the vibration. (Again works on Android 6) public static void stopVibration() { v.cancel(); } Edit my attempt So I want this to vibrate for 1 second, pause for 1 second, vibrate for 1 second and so on until a button is pressed. Do you think this code would work for Android 9 (or API > 26 I guess)? long[] mVibratePattern = new long[]{ 0, 1000, 1000, 1000, 1000, 1000, 1000, 1000}; int[] mAmplitudes = new int[]{0, 255, 255, 255, 255, 255, 255, 255}; v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Log.d("VIBRATE ===>", "I AM VIBRATING"); VibrationEffect effect = VibrationEffect.createWaveform(mVibratePattern, mAmplitudes, 0); //Will this work on Android 9? v.vibrate(effect); } else { Log.d("VIBRATE ====>", "I AM VIBRATING"); v.vibrate(pattern , 0); //This do work on Android 6 } A: So i got my hands on a Android 9 phone and this made the vibration work the same on Android 9. long[] pattern = { 0, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000}; int[] mAmplitudes = new int[]{0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0}; v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Log.d("VIBRATE ===>", "I AM VIBRATING"); VibrationEffect effect = VibrationEffect.createWaveform(pattern, mAmplitudes, 0); //This do work on Android 9 v.vibrate(effect); } else { Log.d("VIBRATE ====>", "I AM VIBRATING"); v.vibrate(pattern , 0); //This do work on Android 6 }
[ "stackoverflow", "0014897571.txt" ]
Q: Moment.js: Date between dates I'm trying to detect with Moment.js if a given date is between two dates. Since version 2.0.0, Tim added isBefore() and isAfter() for date comparison. Since there's no isBetween() method, I thought this would work: var date = moment("15/02/2013", "DD/MM/YYYY"); var startDate = moment("12/01/2013", "DD/MM/YYYY"); var endDate = moment("15/01/2013", "DD/MM/YYYY"); if (date.isBefore(endDate) && date.isAfter(startDate) || (date.isSame(startDate) || date.isSame(endDate)) ) { alert("Yay!"); } else { alert("Nay! :("); } I'm convinced there's got to be a better way to do this. Any ideas? A: In versions 2.9+ there is an isBetween function, but it's exclusive: var compareDate = moment("15/02/2013", "DD/MM/YYYY"); var startDate = moment("12/01/2013", "DD/MM/YYYY"); var endDate = moment("15/01/2013", "DD/MM/YYYY"); // omitting the optional third parameter, 'units' compareDate.isBetween(startDate, endDate); //false in this case There is an inclusive workaround ... x.isBetween(a, b) || x.isSame(a) || x.isSame(b) ... which is logically equivalent to !(x.isBefore(a) || x.isAfter(b)) In version 2.13 the isBetween function has a fourth optional parameter, inclusivity. Use it like this: target.isBetween(start, finish, 'days', '()') // default exclusive target.isBetween(start, finish, 'days', '(]') // right inclusive target.isBetween(start, finish, 'days', '[)') // left inclusive target.isBetween(start, finish, 'days', '[]') // all inclusive More units to consider: years, months, days, hours, minutes, seconds, milliseconds Note: units are still optional. Use null as the third argument to disregard units in which case milliseconds is the default granularity. Visit the Official Docs A: You can use one of the moment plugin -> moment-range to deal with date range: var startDate = new Date(2013, 1, 12) , endDate = new Date(2013, 1, 15) , date = new Date(2013, 2, 15) , range = moment().range(startDate, endDate); range.contains(date); // false A: You can use moment().isSameOrBefore(Moment|String|Number|Date|Array); moment().isSameOrAfter(Moment|String|Number|Date|Array); or moment().isBetween(moment-like, moment-like); See here : http://momentjs.com/docs/#/query/
[ "english.stackexchange", "0000425634.txt" ]
Q: Is this sentence properly written Is the following sentence correctly written? Maggie sighed, “I don't know,” she complained. Should Maggie sighed be a separate sentence? Thanks A: Try making it a separate sentence and see what happens: Maggie sighed. “I don't know,” she complained. It's fine! You now have two perfectly good sentences. We can conclude that the original "sentence" was not correctly written; it is really two sentences mistakenly joined together with a comma. Update: Technically, the original sentence has a comma splice joining what could otherwise be two independent clauses. As pointed out in comments, a comma splice often can be fixed by replacing the comma with a semicolon rather than a period (full stop). Moreover, even the prohibition of comma splices is not absolute. For example, "I came, I saw, I conquered." Commas can preserve the rhythm of a sequence of several short independent clauses. I would still argue against the comma splice in the question, partly because the two independent clauses do not establish much of a rhythm, but mainly because the insertion of the direct quote seems (to me) to spoil the rhythm a comma splice would require. A: "Maggie sighed" and "she complained" can both be used, but only one of them. It would be correct to separate Maggie sighed like you said. You can also say "I don't know", Maggie sighed in complaint but that's weird. The best option is still to just separate Maggie sighed. If you remove the dialogue part, the sentence should still be grammatically correct. I believe you can use that as a general rule: [N] Maggie sighed [""] she complained. [Y] Maggie sighed. [""] She complained.
[ "puzzling.stackexchange", "0000080058.txt" ]
Q: You can see me if you get out more I contain some very important information. You likely display me all the time. But if you were asked to name my contents, You might not remember - perhaps - And you'd likely be in a bad spot and not be able to recall. Some places folks have two of me, some places folks have one. In some seedy places I often don't exist, But if you've got lots of money, you've got lots of the thing - The thing that needs ME stuck on its back. Getting me can be a pain; the lines are often long. (At least in the U.S., this should be a dead giveaway). All the same, though you see me every day, and you use me every day (indirectly) You probably don't think about me much at all. Who am I? A: Answer: License plate I contain some very important information. The license details for the car You likely display me all the time. It's fixed to the outside of the car whether you are using it or not. But if you were asked to name my contents, You might not remember - perhaps - People are a bit rubbish at remembering the license plate contents And you'd likely be in a bad spot and not be able to recall. Some places folks have two of me, some places folks have one. Some locales have them on the front as well as the rear. In some seedy places I often don't exist, Dodgy people might remove plates or not have them in the first place But if you've got lots of money, you've got lots of the thing - The thing that needs ME stuck on its back. Cars, cars are expensive Getting me can be a pain; the lines are often long. (At least in the U.S., this should be a dead giveaway). The lines at the DMV are legendary All the same, though you see me every day, You'll see them on your own car and others every day and you use me every day (indirectly) By using the car you are using the license plate You probably don't think about me much at all. Who am I?
[ "stackoverflow", "0050524263.txt" ]
Q: Whatsapp Web - how to access data now? It used to be possible to access http://web.whatsapp.com/ with the Store object in JavaScript. A few hours ago, this stopped working. How does it update chat data now? It must save the data somewhere. A: I'm using this to get the Store again: setTimeout(function() { // Returns promise that resolves to all installed modules function getAllModules() { return new Promise((resolve) => { const id = _.uniqueId("fakeModule_"); window["webpackJsonp"]( [], { [id]: function(module, exports, __webpack_require__) { resolve(__webpack_require__.c); } }, [id] ); }); } var modules = getAllModules()._value; // Automatically locate modules for (var key in modules) { if (modules[key].exports) { if (modules[key].exports.default) { if (modules[key].exports.default.Wap) { store_id = modules[key].id.replace(/"/g, '"'); } } } } }, 5000); function _requireById(id) { return webpackJsonp([], null, [id]); } // Module IDs var store_id = 0; var Store = {}; function init() { Store = _requireById(store_id).default; console.log("Store is ready" + Store); } setTimeout(function() { init(); }, 7000); Just copy&paste on the console and wait for the message "Store is ready". Enjoy! A: To explain Pablo's answer in detail, initially we load all the Webpack modules using code based on this How do I require() from the console using webpack?. Essentially, the getAllModules() returns a promise with all the installed modules in Webpack. Each module can be required by ID using the _requireById(id) which uses the webpackJsonp(...) function that is exposed by Webpack. Once the modules are loaded, we need to identify which id corresponds to the Store. We search for a module containing exports.default.Wap and assign it's id as the Store ID. You can find more details on my github wiki here
[ "stackoverflow", "0050235547.txt" ]
Q: What processors should be combined to process large JSON files in NiFi? I would like to set up a NiFi workflow that pulls large JSON documents (between 500 MB and 3 GB), that have been gzipped from an FTP server, split the JSON objects into individual flow files, and finally convert each JSON object to SQL and insert it into a MySQL database. I am running NiFi 1.6.0, on Oracle Java 8, and Java has 1024 MB heap space set. My current flow is: GetFTP -> CompressContent -> SplitJson -> EvaluateJsonPath -> AttributesToJson -> ConvertJSONToSQL -> PutSQL This flow works great for JSON documents that are smaller. It throws Java OutOfMemory errors once a file that is larger than 400 MB enters the SplitJson processor. What changes can I make to the existing flow to enable it to process large JSON documents? A: Generally you will want to avoid splitting to a flow file per document. You will get much better performance if you can keep many documents together in a single flow file. You will want to take a look at NiFi's record processing capabilities, specifically you will want to look at PutDatabaseRecord. Here is a good intro to the record processing approach: https://www.slideshare.net/BryanBende/apache-nifi-record-processing If you absolutely have to perform splitting down to individual records per flow file, then you should at least perform a two phase split, where the first split processors splits to maybe 10k-20k per for flow file, then the second split processor splits down to 1 per flow file.
[ "stackoverflow", "0055788501.txt" ]
Q: Firebase/React/Redux Component has weird updating behavior, state should be ok I am having a chat web app which is connected to firebase. When I refresh the page the lastMessage is loaded (as the gif shows), however, for some reason, if the component is otherwise mounted the lastMessage sometimes flickers and disappears afterwards like it is overridden. When I hover over it, and hence update the component, the lastMessage is there. This is a weird behavior and I spent now days trying different things. I would be very grateful if someone could take a look as I am really stuck here. The db setup is that on firestore the chat collection has a sub-collection messages. App.js // render property doesn't re-mount the MainContainer on navigation const MainRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => ( <MainContainer> <Component {...props} /> </MainContainer> )} /> ); render() { return ( ... <MainRoute path="/chats/one_to_one" exact component={OneToOneChatContainer} /> // on refresh the firebase user info is retrieved again class MainContainer extends Component { componentDidMount() { const { user, getUserInfo, firebaseAuthRefresh } = this.props; const { isAuthenticated } = user; if (isAuthenticated) { getUserInfo(user.id); firebaseAuthRefresh(); } else { history.push("/sign_in"); } } render() { return ( <div> <Navigation {...this.props} /> <Main {...this.props} /> </div> ); } } Action // if I set a timeout around fetchResidentsForChat this delay will make the lastMessage appear...so I must have screwed up the state / updating somewhere. const firebaseAuthRefresh = () => dispatch => { firebaseApp.auth().onAuthStateChanged(user => { if (user) { localStorage.setItem("firebaseUid", user.uid); dispatch(setFirebaseAuthUser({uid: user.uid, email: user.email})) dispatch(fetchAllFirebaseData(user.projectId)); } }); }; export const fetchAllFirebaseData = projectId => dispatch => { const userId = localStorage.getItem("firebaseId"); if (userId) { dispatch(fetchOneToOneChat(userId)); } if (projectId) { // setTimeout(() => { dispatch(fetchResidentsForChat(projectId)); // }, 100); ... export const fetchOneToOneChat = userId => dispatch => { dispatch(requestOneToOneChat()); database .collection("chat") .where("userId", "==", userId) .orderBy("updated_at", "desc") .onSnapshot(querySnapshot => { let oneToOne = []; querySnapshot.forEach(doc => { let messages = []; doc.ref .collection("messages") .orderBy("created_at") .onSnapshot(snapshot => { snapshot.forEach(message => { messages.push({ id: message.id, ...message.data() }); }); }); oneToOne.push(Object.assign({}, doc.data(), { messages: messages })); }); dispatch(fetchOneToOneSuccess(oneToOne)); }); }; Reducer const initialState = { residents: [], oneToOne: [] }; function firebaseChat(state = initialState, action) { switch (action.type) { case FETCH_RESIDENT_SUCCESS: return { ...state, residents: action.payload, isLoading: false }; case FETCH_ONE_TO_ONE_CHAT_SUCCESS: return { ...state, oneToOne: action.payload, isLoading: false }; ... Main.js // ... render() { return (... <div>{React.cloneElement(children, this.props)}</div> ) } OneToOne Chat Container // without firebaseAuthRefresh I don't get any chat displayed. Actually I thought having it inside MainContainer would be sufficient and subscribe here only to the chat data with fetchOneToOneChat. // Maybe someone has a better idea or point me in another direction. class OneToOneChatContainer extends Component { componentDidMount() { const { firebaseAuthRefresh, firebaseData, fetchOneToOneChat } = this.props; const { user } = firebaseData; firebaseAuthRefresh(); fetchOneToOneChat(user.id || localStorage.getItem("firebaseId")); } render() { return ( <OneToOneChat {...this.props} /> ); } } export default class OneToOneChat extends Component { render() { <MessageNavigation firebaseChat={firebaseChat} firebaseData={firebaseData} residents={firebaseChat.residents} onClick={this.selectUser} selectedUserId={selectedUser && selectedUser.residentId} /> } } export default class MessageNavigation extends Component { render() { const { onClick, selectedUserId, firebaseChat, firebaseData } = this.props; <RenderResidentsChatNavigation searchChat={this.searchChat} residents={residents} onClick={onClick} firebaseData={firebaseData} firebaseChat={firebaseChat} selectedUserId={selectedUserId} /> } } const RenderResidentsChatNavigation = ({ residents, searchChat, selectedUserId, onClick, firebaseData, firebaseChat }) => ( <div> {firebaseChat.oneToOne.map(chat => { const user = residents.find( resident => chat.residentId === resident.residentId ); const selected = selectedUserId == chat.residentId; if (!!user) { return ( <MessageNavigationItem id={chat.residentId} key={chat.residentId} chat={chat} onClick={onClick} selected={selected} user={user} firebaseData={firebaseData} /> ); } })} {residents.map(user => { const selected = selectedUserId == user.residentId; const chat = firebaseChat.oneToOne.find( chat => chat.residentId === user.residentId ); if (_isEmpty(chat)) { return ( <MessageNavigationItem id={user.residentId} key={user.residentId} chat={chat} onClick={onClick} selected={selected} user={user} firebaseData={firebaseData} /> ); } })} </div> } } And lastly the item where the lastMessage is actually displayed export default class MessageNavigationItem extends Component { render() { const { hovered } = this.state; const { user, selected, chat, isGroupChat, group, id } = this.props; const { messages } = chat; const item = isGroupChat ? group : user; const lastMessage = _last(messages); return ( <div> {`${user.firstName} (${user.unit})`} {lastMessage && lastMessage.content} </div> ) } A: In the end it was an async setup issue. In the action 'messages' are a sub-collection of the collection 'chats'. To retrieve them it is an async operation. When I returned a Promise for the messages of each chat and awaited for it before I run the success dispatch function, the messages are shown as expected.
[ "stackoverflow", "0038753791.txt" ]
Q: Is there a way to see what characters are in the types in ctype.h? I am writing a C program that involves going through a .txt file and finding all the printable characters (or possibly graphical characters) that are not used in the file. I know that the header file ctype.h defines several character classes (e.g. digits, lowercase letters, uppercase letters, etc.) and provides functions to check whether or not a given character belongs to each of the classes, but I'm not sure whether it's possible to do the inverse (i.e. checking all the characters in a class for something). I need something that lists or defines all of the characters in each type, ideally an array or enumerated type. A: Dunno if this is helpful, but I wrote a program to classify characters based on those found in a given file. It wouldn't be hard to fix it to go over the characters (bytes) in the range 0..255 unconditionally. #include <stdio.h> #include <ctype.h> #include <limits.h> static void classifier(FILE *fp, char *fn) { int c; int map[UCHAR_MAX + 1]; size_t i; printf("%s:\n", fn); for (i = 0; i < UCHAR_MAX + 1; i++) map[i] = 0; printf("Code Char Space Upper Lower Alpha AlNum Digit XDig Graph Punct Print Cntrl\n"); while ((c = getc(fp)) != EOF) { map[c] = 1; } for (c = 0; c < UCHAR_MAX + 1; c++) { if (map[c] == 1) { int sp = isspace(c) ? 'X' : ' '; int up = isupper(c) ? 'X' : ' '; int lo = islower(c) ? 'X' : ' '; int al = isalpha(c) ? 'X' : ' '; int an = isalnum(c) ? 'X' : ' '; int dg = isdigit(c) ? 'X' : ' '; int xd = isxdigit(c) ? 'X' : ' '; int gr = isgraph(c) ? 'X' : ' '; int pu = ispunct(c) ? 'X' : ' '; int pr = isprint(c) ? 'X' : ' '; int ct = iscntrl(c) ? 'X' : ' '; int ch = (pr == 'X') ? c : ' '; printf("0x%02X %-4c %-6c%-6c%-6c%-6c%-6c%-6c%-6c%-6c%-6c%-6c%-6c\n", c, ch, sp, up, lo, al, an, dg, xd, gr, pu, pr, ct); } } } The extra trick that my code pulled was using setlocale() to work in the current locale rather than the C locale: #include <locale.h> int main(int argc, char **argv) { setlocale(LC_ALL, ""); filter(argc, argv, 1, classifier); return(0); } The filter() function processes the arguments from argv[1] (usually optind is passed instead of 1, but there is no conditional argument processing in this code) to argv[argc-1], reading the files (or reading standard input if there are no named files). It calls classifier() for each file it opens — and handles the opening, closing, etc.
[ "stackoverflow", "0018460904.txt" ]
Q: How can I find if some commit is included in branch? During development we commit into trunk, when time comes we create branch to be tested separately and further turned into tag. My question is: is there a simple way to find out whether some commit, that we made into trunk some some days ago, is inside our branch? Different flavour of this question: how can I find out when the branch was created? (In other words, my branch can miss some commit if it was done after the branch was created. I want to ensure that commit is inside branch. One way to check this is probably to make a --dry-run merge for all revisions) A: Is there a simple way to find out whether some commit, that we made into trunk some some days ago, is inside our branch? This could be asking for two different things: You made a change to both trunk and the branch in the same commit. A svn log -v will show you this information. You could also do a svn log --xml on both the trunk and branch. Store the revisions in a hash for the branch, and then when you parse the output of the trunk, you can see if there is a duplicate revision on the branch. You did a merge, so the changes in a particular revision in trunk is in your branch. in this case, you could look at the svn:mergeinfo property on the branch which will show you what truck revisions have been merged into the branch. A svn plist -v -R svn:mergeinfo will find all svn:mergeinfo properties on any files or directories in the entire directory tree and show you which revisions were merged in. Different flavour of this question: how can I find out when the branch was created? To find out when a branch was created: svn log -v --stop-on-copy -r1:HEAD /usr/of/branch | head This will show all revisions on the branch from lowest to highest, so it will show you the first revision on that branch. The head limits the output. You shouldn't need more than 10 lines. The -v flag will show what revision was copied and from what source. The output will look something like this: r160214 | dweintraub | 2013-04-23 13:41:43 -0400 (Tue, 23 Apr 2013) | 1 line Changed paths: A /branches/4.8 (from /trunk:160213) Creating a release branch for 4.8 release ----------------------------------------------------------------- The 4.8 branch was created on April 23, 2013 by me from revision 160213 of trunk.
[ "gamedev.stackexchange", "0000121933.txt" ]
Q: How to handle interaction with the map in a 2D-RPG-typed TileMap? Sorry if this is a long post, but I'd like to explain the context before asking my question ^^" I'm currently working on my "first" game (the more advance one, at least). It'll be a 2D-ARPG where the player will be able to interact with the map, by doing things like chopping tree, farming, mining, etc... As it is my first game, I didn't really know where to go so I started by implementing basics functionalities, and i added more while the game took shape. With that in mind, the first thing I did is implementing a TileMapReader that take JSON files generated by Tiled, and render it on screen. I've kept the structure Tiled use (github.com/bjorn/tiled/wiki/JSON-Map-Format) in order to store the tiles : The Map have a list of Layer, and each Layer as a list of "gid", corresponding to a Tile in the Tile Set. I generate my map directly from the Tile Set, without creating a Tile Object ... So my map really is just a bunch of Integers, corresponding to a Tile id. I generate then the display by pasting the right piece of the Tile Set at the right place on the map. After that, I start implementing a Camera that could be move around the Map, and then a Player character who can move around too. Currently, the player is an instance of a "Body" class that is store with a x;y location in a field on the Map Object, and is display on a specific empty Layer like any other Tiles (except the sprites come from other external pictures, and not the Tile Set). I linked the control and the Camera to the character, and here I go ! Walking-in-forest simulator 2016 ! So now, I want to start implementing interaction like collision and so. The problem is that I really can't decide how to do this. The two first thing I'd like to add to the game are interactions with the trees : collisions and chopping. Since the beginning, trees are just collections of tiles on different Layers, like the rest of the map. But I think I have to make them as Object entity, just like my "Body" ... To do so, I've thought of servals ways : I could parse my Map Tile by Tile, and store my tree-tile's position in order to create my tree, but I find it way to difficult since I don't really know wish Tiles in the Tile Set are the tree-tiles, so I don't know theirs gid. Moreover, a tree is composed of servals Tiles, placed on servals Layers. So it'll be a pain to locate a single tree correctly on the map. Finally, the problems multiplies themselves if I add other entity like water or rocks ... Another idea was to create another Map in which I store all the entity as Objects (and use the tile map for ground and water only). But if I do that, would the Tile Map really be useful ? wouldn't it be better to just randomly-generate a Map entity-full directly ? And since I want to add farming in the future, grass tiles would be passed on the Object-Map too, right ? So the Tile Map will become completely obsolete ... I decided to go with the second one, but here again, I had to pick a way to store this second Map. I wanted to go with a Tree-like Graph in which I would separate different sections of the map (like each node is 1/2 of it's parent node, and the last Nodes are the different entity with their positions). That would help a lot for the collision's detection, but I think it still really complicate to implement ... So here my questions : is my approach on this player-world interactions correct ? since it is my first "big" game, I really would like to know if I'm doing it right or not ... and if not, how can I handle this interactions properly ? I'm posting these here, hopping that there is a simple answer to it (even "just do it" would do ^^ (even if some explanation would be really nice)) and that this post will not be be closed for being too broad ^^" A: The method I would choose for this is to just use your existing map for as much as possible. This is essentially your first approach. Yes, you will need to figure out the IDs of trees (and other relevant objects), but on the plus side you don't need to make any changes to how you're creating maps, storing them, loading them, rendering them... Regarding collision. You don't need to search for the trees and store them as different objects, necessarily. All you really care about is the locations of the tree base, the other tiles of the trees don't effect collision as you can walk behind them. You will need to encode this data somewhere that the id for tree base (or water, or rock) is a non-passable tile. Using your existing layers (it looks like multiple layers will have non-passable tiles), as your player is walking around you can iterate through the layers to check if they are about to walk into a non-passable tile and stop the movement. If you plan on using layers that you can both walk under and on (eg- bridges that you can across and under) then you will need to adjust which layers you're checking for collision. int[] SolidTiles = { 1, 2, 5 }; // You may consider loading this from a data file. // Determines whether the tile at (x,y) can be passed through. bool IsTilePassable(int x, int y) { for (int i = MinLayer; i <= MaxLayer; i++) { int tile = Map.GetLayer(i).GetTileAt(x, y); if (SolidTiles.Contains(tile)) { return false; } } return true; } Regarding interaction. Let's extend this approach to accommodate interactions with the tiles. Instead of using some array of IDs, you can create some objects that contain as much information as you want. Then you just need to query these objects to find out about them. You only need to create as many info objects as you have different types of tiles. 100 trees on your map? No need to create 100 objects to track them, they're all the same type of object, just use a single info object which contains information common to them all (heck, maybe even different kinds of trees can use the same shared info object). As these objects hold only common shared information, note that they do not contain information like the tile's position. The map already knows where the tiles are. class TileInfo { // Returns whether a tile can be passed through. bool IsSolid(); // Returns an object describing the interaction possible with this tile. InteractionInfo GetInteraction(); } Now your collision method can look something like this: // Determines whether the tile at (x,y) can be passed through. bool IsTilePassable(int x, int y) { for (int i = MinLayer; i <= MaxLayer; i++) { int tileId = Map.GetLayer(i).GetTileAt(x, y); // This TileInfoFactory is essentially a Dictionary of int -> TileInfo. // At some point earlier you would initialize these objects, possibly // loading them from a file. // It may be useful to create a default TileInfo which it can fall back on when an // ID is not defined. This will allow you to skip writing definitions for // some tile types and only write definitions for ones that actually have an impact // (eg- trees, rocks). TileInfo tile = TileInfoFactory.GetTileInfo(tileId); if (tile.IsSolid()) { return false; } } return true; } Now interacting with tiles is basically the same logic as colliding with them: // Interacts with the tile located at (x, y) void Interact(int x, int y) { for (int i = MinLayer; i <= MaxLayer; i++) { int tileId = Map.GetLayer(i).GetTileAt(x, y); TileInfo tile = TileInfoFactory.GetTileInfo(tileId); InteractionInfo interaction = tile.GetInteraction(); if (null != interaction) { // You will need to decide how your engine performs an interaction. interaction.Execute(); return; } } } The interaction info object can contain information like what kind of player animation to show (eg- chopping) as well as how it effects the world state. For instance, once you interact with a tree, it may be chopped down and thus not on the map anymore, so you need to update the map. class InteractionInfo { List<MapChange> _mapChanges; // Called when the player has finished interacting with the tile at (x, y) void Finished(int x, int y) { foreach (MapChange change in _mapChanges) { change.Apply(x, y); } } } class MapChange { int _layer; int _offsetX; int _offsetY; int _newTileId; void Apply(int x, int y) { Map.GetLayer(_layer).SetTileAt(x + _offsetX, y + _offsetY, _newTileId); } } Finally, I assume you will want to save your map between play sessions. Simply serialize it back into JSON and save it on disk. I recommend using a different filename than what the base state is saved as so you can start your game over. When you load the game, you can first check if, say, "map-saveslot1.json" exists before defaulting to the base "map.json"
[ "stackoverflow", "0038451352.txt" ]
Q: Redux state is nested after call an action I habe a small problem: my reducer const initialObject = { counter: 0, messages: [] }; function message(state = initialObject, action) { switch(action.type) { case actions.ADD_MESSAGE: return state; // do nothing just return the same state, expect to equal initialObject default: return state; } } const testApp = combineReducers({ message }); in my main file I have a call on action let store = createStore(reducers); let unsubscribe = store.subscribe(() => console.log(store.getState()) ); store.dispatch(actions.addMessage("sine text")); And the problem is, the object I see in the console after "subscribe" it is nested... any idea why? This happens only after an action call. A: Yes, this is because of this line const testApp = combineReducers({ message }); In ES6, this { message } is the same as this: { message: message } So your state is an object, with keys. In this example it has only one key: message From the Readme: https://www.github.com/reactjs/redux/blob/master/docs/basics/Reducers.md All combineReducers() does is generate a function that calls your reducers with the slices of state selected according to their keys, and combining their results into a single object again. It’s not magic.
[ "stackoverflow", "0047420567.txt" ]
Q: mocha: setting varibles on `this` is antipattern? I am confused by the following two pieces of codes: code1: describe('suit', function(){ before(() => { this.suitData = 'suitdata'; }); beforeEach(() => { this.testData = 'testdata'; }); it('test', done => { console.log(this.suitData)// => suitdata console.log(this.testData)// => testdata }) }); code2: describe('suit', function(){ const suitData = 'suitdata'; const testData = 'testdata'; before(() => { }); beforeEach(() => { }); it('test', done => { console.log(suitData)// => suitdata console.log(testData)// => testdata }) }); which one is better, code1 or code2? I think code1 is kind of anti-pattern. Am I right? Thanks A: I would not use this to store values. Risk of a Clash Between Mocha's Values and Yours The this context already contains some values set by Mocha as part of its public API (this.timeout, for instance) and there are some values that are not formally documented but can be useful to use (this.test, for instance). If you set variables on this you may run into a clash with Mocha's variables. If you overwrite the this.timeout function with a string, for instance, then you cannot use call this.timeout if you want to change the timeout. In a large suite where you've been using this.timeout for your own purpose, it may be costly to fix the clash later. And there's the issue that a name that does not clash now, may clash in a future release of Mocha. If you use closures as in your 2nd example, then there cannot be any clash. Unexpected Behavior of this Boneskull, one of the owners of Mocha on GitHub, said in a comment: I would strongly urge users to not use this for storing values, ever. This was in the context of an issue report that was showing unexpected results while using this to store values. Here's another issue about unexpected behavior regarding this. The way this is managed between tests is not something that has been documented, so people imagine that it'll work in a certain way, but it does not. The changes that would need to be made would require a new major version of Mocha. Conversely, if you use scopes like in your second example, how the variables are created and changed is always crystal-clear from a) knowing JavaScript and b) reading the documentation of Mocha (because you need to know something about the order in which hooks and tests are run).
[ "meta.stackoverflow", "0000337363.txt" ]
Q: Jobs vs Careers vs Developer Story vs Talent This current question is closely connected to my previous questions, so they should be recalled here. From the very beginning I haven't understand the use of distinct Careers account and integrated Jobs within SO account. OK, you did it and let it be. However, misconceptions and disrepancies were not long in coming. In the latter question I was answered: Careers was not a site used exclusively by employers, users were able to search for and apply for jobs with the CV on the site and that brought more confusion than ever. I thoroughly read introduction of Jobs, and doubled introduction (1, 2) of Developer Story, but have still no clear idea of the difference between them. The evolution of job search on SO as I see it: Careers >> Jobs on SO >> Developer Story Each historical stage was probably better than previous one, but the question(s) I very interested in lays in the technical side: Is account on certain resource linked to another resources and in what way? How do they interconnected? Does deleting/changing account on one resource affect all other resources? Are they bound to StackExchange account and could they be changed separately? Should I give up some of them if I am not employer or they are both-sided (employee + employer)? Now I am facing four different but overlapping services: SO Jobs | Careers | Developer Story | Talent Can anybody answer above questions referring to these services? A: Now I am facing four different but overlapping services: SO Jobs | Careers | Developer Story | Talent Careers is gone. It's been replaced by Jobs (the candidate-facing side, integrated into SO) and Talent (the employer-facing side; separate site). Developer Story is a feature of Jobs and set to replace the traditional CV, although there's a traditional view for those who prefer it. Is account on certain resource linked to another resources and in what way? How do they interconnected? Does deleting/changing account on one resource affect all other resources? Are they bound to StackExchange account and could they be changed separately? Should I give up some of them if I am not employer or they are both-sided (employee + employer)? Jobs is part of Stack Overflow. Everything jobs-related, in particular your developer story, is linked to your Stack Overflow account. Talent is a separate site which uses a separate account. If you're using both (as a candidate and as an employer, respectively), you can manage both accounts individually. For example, changing your Talent password does not automatically change your Stack Overflow password.
[ "stackoverflow", "0022862704.txt" ]
Q: How to Make Existing PDF Text Searchable using any Java Library? With OCR Any java library? How to make searchable text using any java library? Open source or Paid. how to apply OCR to pdf using PDFBox? how to make pdf text searchable programmatically using pdfbox I searched alot. Didn't find any solution. Can anyone paste code for OCR PDFBox. A: Try Apache PDFBox. To extract text: Textextraction.
[ "salesforce.stackexchange", "0000265988.txt" ]
Q: Goal in Journey Builder not Evaluating I am trying to define a goal based on an engagement metrics. Specifically i have a Journey that uses a Data Extension as a Source. Then I have created another Data Extension where i keep the tracking data (in my case opens) which i retrieve via SQL and shows me the people that have opened the emails send from the Journey. I want to be able to set the goal in my journey for 50% of the population to have opened the email. I have created a 1:Many relationship in Contact Builder and in the Goal i am using this secondary data extension for defining the Goal Criteria. Print screens below. Goal for this Journey stays at 0% in the UI. I can confirm that the SQL pulls the correct data. Giulietta. A: The goal evaluation depends upon whether it is set to remove the contacts from the journey or not. If the exit option is not set, the goal is evaluated each time a wait period expires. In your case, at the end of the 1 day wait. I would suggest that you update your wait activities to 1 or 2 minutes so that the goal can be evaluated quickly. Reference: Goals
[ "tex.stackexchange", "0000176896.txt" ]
Q: Making custom line width scale according to predefined line widths I'm creating some custom shape definitions in TikZ, and I want certain parts of the shapes to have thicker line widths than the rest. However, I still want to be able to scale the line thickness as normal. Consider an example where my custom shape is made up of 0.4pt (thin) lines and 1.2pt (very thick) lines for a figure with default (thin) line width. If I increase the line thickness of the figure from thin to very thick, the shape should have line widths of 1.2pt and 3.6pt. How can I achieve this? Wild attempts like [line width=+0.8pt] did nothing. \documentclass[11pt,border=2pt]{standalone} \usepackage[utf8]{inputenc} \usepackage{tikz} \def\mic(#1)(#2)(#3);{ \begin{scope}[shift={(#1)},rotate={#2},scale={#3}] \draw (0,0) circle (0.22); \draw % this is where I need help (-0.22,-0.3) -- (-0.22,0.3); \end{scope} } \begin{document} \begin{tikzpicture} % [line width=thick] for instance \mic(0,0)(0)(1); \end{tikzpicture} \end{document} A: What about this? \tikzset{ thicker/.style={line width=#1\pgflinewidth}, thicker/.default={2}, } \def\mic(#1)(#2)(#3);{ \begin{scope}[shift={(#1)},rotate={#2},scale={#3}] \draw (0,0) circle (0.22); \draw[thicker=1.5] % this is where I need help (-0.22,-0.3) -- (-0.22,0.3); \end{scope} } \begin{tikzpicture} % [line width=thick] for instance \mic(0,0)(0)(1); \begin{scope}[xshift=1cm, very thick] \mic(0,0)(0)(1); \end{scope} \end{tikzpicture} The style [thicker] multiplies the current line width by the factor you specify (2 by default).
[ "stackoverflow", "0034871317.txt" ]
Q: Collection of checkboxes I have a list of items and I want to display a total for the selected items. The list of items is diplayed twice so if I check some item in the first list is checked also the same item in the second list. The problem is that it doesn't calculates the sum (it displays Nan). function Item(id, name, price) { this.id = id; this.name = name; this.price = price; } var listOfItems = [ new Item(1, 'item1', 25), new Item(2, 'item2', 30), new Item(3, 'item3', 50) ]; function viewModel() { var self = this; self.items = ko.observableArray(listOfItems); self.selectedItem = ko.observableArray(); self.Total = ko.computed(function() { var count = 0; ko.utils.arrayForEach(self.selectedItem(), function(r) { count += r.price; }); return count; }); }; ko.applyBindings(new viewModel()); <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script> <ul data-bind="foreach: items"> <li> <input type="checkbox" value="" data-bind="checkedValue: id, checked: $parent.selectedItem"><span data-bind="text: name"></span> </li> </ul> <ul data-bind="foreach: items"> <li> <input type="checkbox" value="" data-bind="checkedValue: id, checked: $parent.selectedItem"><span data-bind="text: name"></span> </li> </ul> <div data-bind="text:Total"></div> A: I've modified your sample: function Item(id, name, price) { this.id = id; this.name = name; this.price = price; this.checked = ko.observable(false); } var listOfItems = [ new Item(1, 'item1', 25), new Item(2, 'item2', 30), new Item(3, 'item3', 50) ]; function viewModel() { var self = this; self.items = ko.observableArray(listOfItems); self.Total = ko.computed(function() { //return self.items().filter(function(item) { return item.checked(); }).length; return self.items().reduce(function(sum, item) { return item.checked() ? sum + item.price : sum; }, 0); }); }; ko.applyBindings(new viewModel()); <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script> <ul data-bind="foreach: items"> <li> <input type="checkbox" value="" data-bind="checkedValue: id, checked: checked"><span data-bind="text: name"></span> </li> </ul> <ul data-bind="foreach: items"> <li> <input type="checkbox" value="" data-bind="checkedValue: id, checked: checked"><span data-bind="text: name"></span> </li> </ul> <div data-bind="text:Total"></div>
[ "stackoverflow", "0022618331.txt" ]
Q: Sitecore 7 ContentSearch crawling failure: "Crawler : AddRecursive DoItemAdd failed" When we try to rebuild our Lucene (ContentSearch) indexes, our CrawlingLog is filled up with these exceptions: 7052 15:08:21 WARN Crawler : AddRecursive DoItemAdd failed - {5A1E50E4-46B9-42D5-B743-1ED10D15D47E} Exception: System.AggregateException Message: One or more errors occurred. Source: mscorlib at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) at System.Threading.Tasks.Task.Wait() at System.Threading.Tasks.Parallel.PartitionerForEachWorker[TSource,TLocal](Partitioner`1 source, ParallelOptions parallelOptions, Action`1 simpleBody, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally) at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally) at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body) at Sitecore.ContentSearch.AbstractDocumentBuilder`1.AddItemFields() at Sitecore.ContentSearch.LuceneProvider.CrawlerLuceneIndexOperations.GetIndexData(IIndexable indexable, IProviderUpdateContext context) at Sitecore.ContentSearch.LuceneProvider.CrawlerLuceneIndexOperations.BuildDataToIndex(IProviderUpdateContext context, IIndexable version) at Sitecore.ContentSearch.LuceneProvider.CrawlerLuceneIndexOperations.Add(IIndexable indexable, IProviderUpdateContext context, ProviderIndexConfiguration indexConfiguration) at Sitecore.ContentSearch.SitecoreItemCrawler.DoAdd(IProviderUpdateContext context, SitecoreIndexableItem indexable) at Sitecore.ContentSearch.HierarchicalDataCrawler`1.CrawlItem(Tuple`3 tuple) Nested Exception Exception: System.ArgumentOutOfRangeException Message: Index and length must refer to a location within the string. Parameter name: length Source: mscorlib at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) at Sitecore.Data.ShortID.Encode(String guid) at Sitecore.ContentSearch.FieldReaders.MultiListFieldReader.GetFieldValue(IIndexableDataField indexableField) at Sitecore.ContentSearch.FieldReaders.FieldReaderMap.GetFieldValue(IIndexableDataField field) at Sitecore.ContentSearch.LuceneProvider.LuceneDocumentBuilder.AddField(IIndexableDataField field) at System.Threading.Tasks.Parallel.<>c__DisplayClass32`2.<PartitionerForEachWorker>b__30() at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask) at System.Threading.Tasks.Task.<>c__DisplayClass11.<ExecuteSelfReplicating>b__10(Object param0) This appears to be caused by the ShortID.Encode(string) method expecting the GUID in the string parameter to have brackets (" { " and " } ") around it. Some of our multilist field relationships were associated programmatically using Guid.ToString(), which does not include the brackets. Unfortunately, these values cause the ShortID.Encode() method to choke. A: First things first: find all the places you call MultiListField.Add(string) and change Guid.ToString() to Guid.ToString("B"). This will resolve the issue for all new relationships. Create a custom FieldReader class to replace the standard MultiListFieldReader (we called ours CustomMultiListFieldReader). Set your custom class to inherit from Sitecore.ContentSearch.FieldReaders.FieldReader. Decompile the Sitecore.ContentSearch.FieldReaders.MultiListFieldReader.GetFieldValue(IIndexableDataField) method into your custom class. Before the if (ID.IsID(id)) line, add the following code: if (!str.StartsWith("{") && !str.EndsWith("}")) id = String.Format("{{{0}}}", str); In your index configuration (we added ours to the default, Sitecore.ContentSearch.DefaultIndexConfiguration.config) change the fieldReaderType for the MultiList fields to your custom type. (This can be found in your config at sitecore/contentSearch/configuration/defaultIndexConfiguration/fieldReaders/mapFieldByTypeName/fieldReader.) Full disclosure: I don't love this approach because if the default implementation of the MultiListFieldReader ever changed, we'd be without those changes. But this allows the items to be included in the index without reformatting all of the GUIDs in every multilist field.
[ "stackoverflow", "0011528565.txt" ]
Q: String.search() vs String.split() and iteration in JavaScript Lets say I have a string of fruit names var string = "cherries,oranges,limes" and an array of red fruit var array = ["tomatoes", "cherries", "raspberries"] in javascript if I want to find if the string has any red fruit, I can do for(var i=0; i<array.length; i+=1){ if(string.search(array[i])!=-1){ return string.search(array[i]); } How would this compare with the following? var string_array= string.split(','); for(var i=0; i<array.length; i+=1){ for(var j=0; j<string_array.length; j+=1){ if(string_array[j]==array[i]){ return string_array[j]; } } } return -1; A: This can't work ; for(var i=0; i<array.length; i+=1){ return string.search(array[i]); } You're returning at your first iteration. So, this wouldn't compare very well. BTW, if you're interested in script performance comparisons, I suggest you to try using jsperf.
[ "stackoverflow", "0030346649.txt" ]
Q: 'pthread_setname_np' was not declared in this scope I have created multiple threads in my application. I want to assign a name to each pthread so I used pthread_setname_np which worked on Ubuntu but is not working on SUSE Linux. I googled it and came to know '_np' means 'non portable' and this api is not available on all OS flavors of Linux. So now I want to do it only if the API is available. How to determine whether the api is available or not ? I need something like this. #ifdef SOME_MACRO pthread_setname_np(tid, "someName"); #endif A: You can use the feature_test_macro _GNU_SOURCE to check if this function might be available: #ifdef _GNU_SOURCE pthread_setname_np(tid, "someName"); #endif But the manual states that the pthread_setname_np and pthread_getname_np are introduced in glibc 2.12. So if you are using an older glibc (say 2.5) then defining _GNU_SOURCE will not help. So it's best to avoid these non portable function and you can easily name the threads yourself as part of your thread creation, for example, using a map between thread ID and a array such as: pthread_t tid[128]; char thr_names[128][256]; //each name corresponds to on thread in 'tid' You can check the glibc version using: getconf GNU_LIBC_VERSION A: Since this function was introduced in glibc 2.12, you could use: #if ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12))) pthread_setname_np(tid, "someName"); #endif
[ "retrocomputing.stackexchange", "0000012886.txt" ]
Q: Did any significant programs or environments take advantage of the Rexx which came with PCDOS 7 (aka PCDOS 2000)? Being an Amiga fan, I have a fondness for the Rexx language. On that platform, almost every significant program supported ARexx, allowing a high degree of interoperability and customability. So when PCDOS 7 added Rexx (after dropping MS Basic with v6), I expected good things. ... But I don't know of any. Was it just too late in DOS' lifetime for folks to take advantage of this powerful tool? Or was it inferior in some way that would not allow the benefits ARexx offered Amiga programs? I know a major feature offered on the Amiga was "ARexx ports", which were actually native AmigaOS IPC channels which ARexx made simple to use. A: The answer is a resounding no. Rexx was not a popular scripting language for DOS because it didn't offer any significant advantage over DOS batch files, besides the differing syntax which is a subjective benefit. Where Rexx really shines is as a scripting language for automating applications. That's how it was used on the Amiga. But since PC-DOS/MS-DOS is single-tasking, using a centralized script run-time to automate applications isn't nearly as practical. In a single-tasking system, it makes more sense to make applications scriptable by embedding some scripting engine within the application itself. So that was the most likely route for DOS applications that needed "scriptability". ARexx for the Amiga, and the equally popular AppleScript for classic (and newer) Macs added a scripting layer to the platform that would not find its way onto PC's until they adopted multitasking. I think the realistic equivalent to ARexx for the Amiga would be Microsoft's Visual Basic for Applications, which made its way into Windows in 1993.
[ "stackoverflow", "0051346364.txt" ]
Q: bootstrap bootslider layout issue caused by white space The problem is I am using BootSlider.js that I cam across online, and it does everything that i require it to, apart from one thing. The actual slider set white-space:none on its main div. So as you will see in the slider panels in the url above, I have text in each panel that needs to wrap. This text is in a tag. If I set white-space: wrap on the SPAN in each panel, then you will see that the more wrapping text, the further away from the top each panel sits. I have tried to see what the CSS problem is but am stuck - would be great if anyone could help? It's using bootstrap 3 no option to use 4 sadly. A: Try to add this rules to .index-inner1 .index-inner1 { display:flex; /* add this line */ flex-direction: column; /* add this line */ padding: 8px !important; min-height: 290px !important; cursor: pointer !important; }
[ "stackoverflow", "0036351199.txt" ]
Q: Textviews of custom adapter is not occupying the specified space in the screen I have got two xml files called compliance_details.xml and compliance_details_row.xml Following is my compliance_details.xml code <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginLeft="10dp" android:layout_marginTop="15dp"> <TextView android:id="@+id/taskNameLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginRight="70dp" android:layout_weight="3" android:singleLine="true" android:text="TaskName" android:textColor="#000" android:textSize="20sp" /> <TextView android:id="@+id/dueDateLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginRight="20dp" android:layout_weight="1" android:singleLine="true" android:text="Due Date" android:textColor="#000" android:textSize="20sp" /> <TextView android:id="@+id/ageingLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginRight="20dp" android:layout_weight="1" android:singleLine="true" android:text="Ageiging" android:textColor="#000" android:textSize="20sp" /> </TableRow> </TableLayout> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" android:focusable="false" android:focusableInTouchMode="false" android:paddingTop="10dp" /> </LinearLayout> and following is my compliance_details_row.xml code <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginLeft="10dp" android:layout_marginTop="15dp"> <TextView android:id="@+id/taskNameValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginRight="70dp" android:layout_weight="3" android:singleLine="true" android:text="TaskName" android:textColor="#000" android:textSize="20sp" /> <TextView android:id="@+id/dueDateValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginRight="20dp" android:layout_weight="1" android:singleLine="true" android:text="Due Date" android:textColor="#000" android:textSize="20sp" /> <TextView android:id="@+id/ageingValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginRight="20dp" android:layout_weight="1" android:singleLine="true" android:text="Ageiging" android:textColor="#000" android:textSize="20sp" /> </TableRow> </TableLayout> </LinearLayout> In my adapter, Im inflating the compliance_details_row.xml with compliance_row.xml. But when Im doing so, the elements of compliance_details_row is bit distorted. As you could see from the above picture, the compliance names should be coming under the title TaskName but the compliance names are bit distorted and also due date values are only partly visible . How can I be able to sort this out? A: You don't really need a TableLayout to achieve this. Just use a LinearLayout with weightSum. To get the desired proportions - change the weight values for each TextView. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="3"> <TextView android:id="@+id/taskNameValue" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:singleLine="true" android:text="TaskName" android:textColor="#000" android:textSize="20sp" /> <TextView android:id="@+id/dueDateValue" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:singleLine="true" android:text="Due Date" android:textColor="#000" android:textSize="20sp" /> <TextView android:id="@+id/ageingValue" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:singleLine="true" android:text="Ageiging" android:textColor="#000" android:textSize="20sp" /> </LinearLayout>
[ "stackoverflow", "0022670882.txt" ]
Q: Merge dataset without common variable (By)? Currently I have two datasets with similar variable lists. Each dataset has a procedure variable. I want to compare the frequency of the procedure variable between datasets. I created a flag in both datasets to id the source dataset, and was going to merge but don't have a common identifier. How do I merge a dataset without deleting any observations? This isn't just a simple Merge without a By function, right? Currently have: Data.a Data.b pproc proc1_numb 70 9 71 15 77 24 80 80 81 42 83 71 86 66 87 125 121 159 125 242 Want Output: pproc freq 9 1 15 1 24 1 42 1 66 1 70 1 71 2 77 1 80 2 81 1 83 1 86 1 87 1 121 1 125 2 159 1 242 1 A: If I understand your question properly, you should just concatenate the two datasets into one and rename the variable. Then you can use PROC MEANS to get the frequencies. Something like this: data all; set a b(rename=(proc1_numb=pproc)); run; proc means nway data=all noprint; class pproc; output out=want(drop=_type_ rename=(_freq_=freq)); run;
[ "stackoverflow", "0000373098.txt" ]
Q: What's the "average" requests per second for a production web application? I have no frame of reference in terms of what's considered "fast"; I'd always wondered this but have never found a straight answer... A: OpenStreetMap seems to have 10-20 per second Wikipedia seems to be 30000 to 70000 per second spread over 300 servers (100 to 200 requests per second per machine, most of which is caches) Geograph is getting 7000 images per week (1 upload per 95 seconds) A: Not sure anyone is still interested, but this information was posted about Twitter (and here too): The Stats Over 350,000 users. The actual numbers are as always, very super super top secret. 600 requests per second. Average 200-300 connections per second. Spiking to 800 connections per second. MySQL handled 2,400 requests per second. 180 Rails instances. Uses Mongrel as the "web" server. 1 MySQL Server (one big 8 core box) and 1 slave. Slave is read only for statistics and reporting. 30+ processes for handling odd jobs. 8 Sun X4100s. Process a request in 200 milliseconds in Rails. Average time spent in the database is 50-100 milliseconds. Over 16 GB of memcached. A: When I go to the control panel of my webhost, open up phpMyAdmin, and click on "Show MySQL runtime information", I get: This MySQL server has been running for 53 days, 15 hours, 28 minutes and 53 seconds. It started up on Oct 24, 2008 at 04:03 AM. Query statistics: Since its startup, 3,444,378,344 queries have been sent to the server. Total 3,444 M per hour 2.68 M per minute 44.59 k per second 743.13 That's an average of 743 mySQL queries every single second for the past 53 days! I don't know about you, but to me that's fast! Very fast!!
[ "stackoverflow", "0012469108.txt" ]
Q: Storing array of POJOs - What is the better option in java? I have POJOs parsed from JSON. Account [] accounts; class Account { Integer number; String name; String location; Date started; } I get list of accounts from JSON API call. Jackson mapper maps the resulting JSON to above POJOs. I will need to do searching and other operations on these objects. I am not sure how to store these to do the searching and to display them (in Android). ArrayList Map HashTable ... etc. Searching should be fast. I get about 500 accounts on an average. Mapping is done and I have the objects in an array now. But not sure how to go from here. More over, I am fairly new to Java Collections and Generics. So any code example with direction would help. Thanks! A: Five hundred accounts is not really a huge number, and if your application is small and gets very little use (meaning it isn't a webservice with thousands of simultaneous queries), you just might be able to get away with linear searches. Assuming that is not the case, and that seems like a good assumption, you should build indexes for those fields that you expect to query often. If you will primarily search on name you can build a hashmap with the lowercased version of the name nameIndex = new HashMap<String, Account>(); for (Account a : accountArray) { nameIndex.put(a.name.toLowerCase(), a); } Then for "exact name" searches lower case you search query then call nameIndex.get. Searching by date is also possible, but here I would expect that you will be searching by date range. In this case you might want to build an sorted list index or tree index. Then you navigate the list or tree to find the desired range. You can also do lookups by name regexes or my name proximity (bigrams, trigrams), there are lots of options. BTW, databases do this kind of thing well. You might consider just populating an embedded database like H2, though that might be overkill? It's fun to learn, though. Besides with a database you get the concurrency control and the caching for freeeeeeee! TL;DR: build hashmap or treemap or plain sorted list indexes for queries you will use frequently make, and do linear search for complex custom queries. Or, and this might be preferred: use an embedded database. A: If you're searching, and you can identify a single key on which to search, I'd recommend the HashMap, because it's O(1) for access if you have a key. HashTable is JDK 1.0 vintage; don't choose that. Here's an example, assuming that the number is unique and represents a good search choice: Account a = new Account(123456); Map<Integer, Account> accounts = new HashMap<Integer, Account>(); accounts.put(a.getNumber(), a); To access, you use the number: Account b = accounts.get(123456);
[ "ru.stackoverflow", "0000646845.txt" ]
Q: Как удалить sendmail из Debian 8? На сервере установлен Exim4 и был еще установлен Sendmail в связи с чем возникли проблемы с отправкой почты. Пытался удалить Sendmail такими командами apt-get purge sendmail и apt-get remove sendmail. Вроде как было написано что все Done.. Но. ~# service sendmail status ● sendmail.service - LSB: powerful, efficient, and scalable Mail Transport Agent Loaded: loaded (/etc/init.d/sendmail) Active: active (running) since Fri 2017-03-31 18:08:07 MSK; 17min ago Process: 434 ExecStart=/etc/init.d/sendmail start (code=exited, status=0/SUCCESS) CGroup: /system.slice/sendmail.service └─583 sendmail: MTA: accepting connections Сервер перезагружал. Как почистить это дело? A: А вот и решение вопроса. ~# apt-get purge sendmail ~# apt-get purge sendmail-base ~# apt-get purge sendmail-cf
[ "math.stackexchange", "0002743996.txt" ]
Q: Intermediate Fields and Root Fields Suppose that $F \subset K \subset E$ are fields and $E$ is the root field of some polynomial in $F[x]$. Show, by means of an example, that $K$ need not be the root field of some polynomial in $F[x]$. I have tried many examples and I cannot come up with anything. I know some basic Galois theory. Any help would be appreciated! Thanks! A: Let $F=\mathbb{Q}$, let $K=\mathbb{Q}(\sqrt[4]{2})$, and let $E$ be the root field over $\mathbb{Q}$ of the polynomial $x^4-2$. Then $K$ is not a root field over $\mathbb{Q}$, since the smallest root field over $\mathbb{Q}$ containing $K$ is $E$, and $K$ is a proper subfield of $E$ (all elements of $K$ are real, and only two of the roots of $x^4-2$ are real).
[ "stackoverflow", "0018478605.txt" ]
Q: Why this batch script not work fine? What's wrong with this script? @echo off SETLOCAL ENABLEEXTENSIONS SETLOCAL ENABLEDELAYEDEXPANSION set /P start= Input start : %=% set /P end= Input End : %=% for /l %%i IN (%start%,1,%end%) DO ( set num=0%%i set num=!num:~-2! echo wget "http://portal/excel!num!.xls" ) pause if Input start = 01, Input End = 06, work fine and excel files downloaded. Result : Input start : 01 Input End : 12 wget "http://portal/excel01.xls" wget "http://portal/excel02.xls" wget "http://portal/excel03.xls" wget "http://portal/excel04.xls" wget "http://portal/excel05.xls" wget "http://portal/excel06.xls" wget "http://portal/excel07.xls" wget "http://portal/excel08.xls" wget "http://portal/excel09.xls" wget "http://portal/excel10.xls" Press any key to continue . . . But if Input start = 01, Input End = 08 OR if Input start = 01, Input End = 09, Not work fine and excel files not downloaded. Result : Input start : 01 Input End : 08 Press any key to continue . . . Can anyone give some explanations? A: Leading zero means number is intepreted as octal. 0-7 don't matter, but there is no such number as an octal 8 or 9. You are already adding a leading 0 with the 2 SET commands, so don't enter the leading zero.
[ "academia.stackexchange", "0000119498.txt" ]
Q: Can I get a postdoc in China more than 3 years after having received my PhD? It's been 4 years since my PhD and now I'm applying for a postdoc in China. The Chinese website mentions that the age limit for applicants is 35 years and the applicants must have received their PhD within the last 3 years. I heard that Chinese universities are strict with age when it comes to postdoc positions. However, they can be more lax on post-PhD experience. A: There are two kinds of post-doctoral fellowships available in China. The more traditional Chinese post-doctoral fellowship offers you a government-recognised certificate at the end of training. The more "Western" style does not. There are additional differences having to do with employment, benefits and such that are too individual to list here. Regardless, both are two year contractual commitments. In general, the more traditional route is very strict in its requirements. You must meet age and graduation requirements and register through a common government portal. The strictness is due, in part, to closely aligned visa requirements. Thus, even if the institution to which you are applying is willing to allow you to attend four years after your PhD, the visa bureau is likely to decline this application. The more "Western" style of fellowship is much more fluid because it is, in part, more structured like an employment contract and less a training scheme. In addition, there is no need for the academic institute to issue you a government-recognised training certificate. Under this route, there is more flexibility in entry requirements. However, this route is much, much less popular in China. It may not exist in some fields of research. Good luck.
[ "homebrew.stackexchange", "0000010637.txt" ]
Q: Sanitizing bottles with StarSan I just brewed a trappist style ale and I am ready to bottle it. I am a meticulous sanitizer. Just a question though. I have always filled my buckets/carboys with 5 gallons of star sans solution to sanitize it, and since I don't have the space I would dump the solution afterwards. This is wasteful and costly, so due to a response from another question I posted here, I was planning of mixing 1 gallon of solution and thoroughly shaking it in the bottling bucket to sanitize it. Is it a bad idea to try this sanitation method on bottles I plan to age for a good while (like a 18 months)? A: What you propose will work fine. You can even keep StarSan in a spray bottle (mixed with distilled water it will last months or more) and spray down the surfaces. Although due to FDA regulations they have to list a longer contact time, Charlie Talley of 5 Star Chemical, makers of StarSan, has said that their tests show a 99.9% effectiveness after a 30 second contact time. Remember, that means simply wetting the surface, not full immersion. I usually only mix 2.5 gallons at a time for sanitizing 5-7 gal. fermenters. I could get by with less, but old habits die hard. A: This is what I do regularly for bottling. Start with clean bottles, fill (let's say) 3 bottles with starsan. After getting everything else ready to go, I'll start a pipeline: empty bottle 1 through a funnel into (new) bottle 4, then fill the just-emptied bottle 1 while emptying bottle 2 into bottle 5. Cap bottle 1. Start filling bottle 2 while transferring starsan from bottle 3 into bottle 6… and so on down the line. A: In the past I've generally done what the other answers here recommend: fill a bottle with Star San and pour from bottle to bottle. Works well except that it tends to foam up, making it more difficult to pour out. (But don't fear the foam!) I've also used a spray bottle, which is less foamy. Recently I bought a Vinator bottle rinser, which is quick and easy to use. Takes less than a cup of fluid and does a good job of spraying down the interior. The manufacturer's bottle tree is not required. http://www.northernbrewer.com/shop/vinator-bottle-rinser.html Finally, you can also consider sanitizing glass bottles in your oven. Winter is coming in the northern hemisphere, so here's a good excuse to heat up the kitchen. http://www.howtobrew.com/section1/chapter2-2-3.html
[ "physics.stackexchange", "0000134459.txt" ]
Q: Comparing work done for two accelerations Suppose at a time $t_{0}$ a car goes from 0 to 30mph at time $t_{1}$, and then maintains a speed of 30mph until $t_{2}$. After that minute it accelerates, reaching 60mph at time $t_{3}$. I want to compare the work done, particularly between $t_{0}$ and $t_{1}$, and between $t_{2}$ and $t_{3}$. The laws of work that I know are: $W = \int F \, dx = -\Delta U$. We don't know the force function and we don't know the potential energy function. We could use kinetic energy at each point and think that the only forms of energy are potential and kinetic so that they just trade off. In that case, it would seem that the kinetic energy goes from 0 to $\frac{1}{2}m(30^{2})$ so potential energy is the negative of that and work done is again $\frac{1}{2}m(30^{2})$. Then going from 30mph to 60mph you go from kinetic energy $\frac{1}{2}m(30^{2})$ to $\frac{1}{2}m(60^{2})$ which is a much higher jump in kinetic, meaning a much bigger change in potential, meaning a much larger work done. Is that basically right? A: Total work done = change in energy. So when you compute the kinetic energy at 30 mph and 60 mph, you find that you needed to do 3x as much work in the second interval. Note that you do need to convert from mph to m/s if you want to work in SI units… Leave potential energy out of it. It is not relevant in this situation. Work done = gain in kinetic energy is all you need.
[ "stackoverflow", "0012065110.txt" ]
Q: Is it possible to process a silent notification in iOS when your app is not running? I haven't found the exact answer to this elsewhere on this site. The goal is to send a silent remote notification (no user alert/badge/sound) to my app, with a custom payload, and then have the app process this even if it was not running when the notification was received. If the app was not running, is it notified and given a chance to process the (silent) notification? Or is it only notified the next time the app is launched? So far, I've only been able to confirm that you can receive a non-silent notification when the app is not running, or a silent notification when the app IS running. I haven't seen confirmation of what happens if you receive a silent notification and are not running. A: Essentially, the answer that I've been able to find so far (and @Sebrassi concurs with above) is that what I am asking for is not possible. The app does not get any processing time when a notification comes in, period, unless it is already running or the user launches it via the UI in one way or another.
[ "stackoverflow", "0034952500.txt" ]
Q: SELECT only returning 20 rows in 3rd party tool after inserting 100K rows via command line I inserted 100,000 rows in a table via Oracle 11g CMD Interface and it returns 100,000 rows inserted. But when selecting data from the table using third party software PL/SQL developer tools it returns 20 rows. How's that possible? A: When Your Insert operation finish then try to commit it then apply select operation on that table.
[ "stackoverflow", "0015033535.txt" ]
Q: Getting Number of Files in a Directory using Dropbox API Is this possible? I'm storing some files in a directory. And I want users to see the whole folder. I tried and searched, but couldn't find a way to get the count of files, or the list of files in a directory. I'm using Java, but I guess it does not matter that much. Thank you very much already. A: You can call /metadata for the desired folder, then count the number of entries in the 'contents' list where 'is_dir' is false. If you're using the official Java SDK, this call corresponds to the metadata method.
[ "stackoverflow", "0042811020.txt" ]
Q: How do I get and set ag-grid state? How can I obtain and re-set the state of an ag-grid table? I mean, which columns are being show, in what order, with what sorting and filtering, etc. Update: getColumnState and setColumnState seem to be close to what I want, but I cannot figure out the callbacks in which I should save and restore the state. I tried restoring it in onGridReady but when the actual rows are loaded, I lose the state. A: There is a very specific example on their website providing details for what you are trying to do: javascript-grid-column-definitions function saveState() { window.colState = gridOptions.columnApi.getColumnState(); window.groupState = gridOptions.columnApi.getColumnGroupState(); window.sortState = gridOptions.api.getSortModel(); window.filterState = gridOptions.api.getFilterModel(); console.log('column state saved'); } and for restoring: function restoreState() { gridOptions.columnApi.setColumnState(window.colState); gridOptions.columnApi.setColumnGroupState(window.groupState); gridOptions.api.setSortModel(window.sortState); gridOptions.api.setFilterModel(window.filterState); console.log('column state restored'); } A: I believe you are looking for this page of the Docs. This describes the column api and what functions are available to you. The functions that are of most relevance would be: getAllDisplayedColumns() - used to show what columns are able to be rendered into the display. Due to virtualization there may be some columns that aren't rendered to the DOM quite yet, iff you want only the columns rendered to the DOM then use getAllDisplayedVirtualColumns() - both functions show the order as they will be displayed on the webpage The Column object that is returned from these functions contains sort and filter attributes for each of the columns. I believe that all you need would be available to you from that function which would be called like this gridOptions.columnApi.getAllDisplayedColumns() Other functions which might be useful: Available from gridOptions.columnApi: getColumnState() - returns objects with less detail than the above funciton - only has: aggFunc, colId, hide, pinned, pivotIndex, rowGroupIndex and width setColumnState(columnState) - this allows you to set columns to hidden, visible or pinned, columnState should be what is returned from getColumnState() Available from gridOptions.api: getSortModel() - gets the current sort model setSortModel(model) - set the sort model of the grid, model should be the same format as is returned from getSortModel() getFilterModel() - gets the current filter model setFilterModel(model) - set the filter model of the grid, model should be the same format as is returned from getFilterModel() There are other functions that are more specific, if you only want to mess with pinning a column you can use setColumnPinned or for multiple columns at once use setColumnsPinned and more functions are available from the linked pages of the AG-Grid docs A: The gridReady event should do what you need it to do. What I suspect is happening is your filter state is being reset when you update the grid with data - you can alter this behaviour by setting filterParams: {newRowsAction: 'keep'} This can either by set by column, or set globally with defaultColDef. Here is a sample configuration that should work for you: var gridOptions = { columnDefs: columnDefs, enableSorting: true, enableFilter: true, onGridReady: function () { gridOptions.api.setFilterModel(filterState); gridOptions.columnApi.setColumnState(colState); gridOptions.api.setSortModel(sortState); }, defaultColDef: { filterParams: {newRowsAction: 'keep'} } }; I've created a plunker here that illustrates how this would work (note I'm restoring state from hard code strings, but the same principle applies): https://plnkr.co/edit/YRH8uQapFU1l37NAjJ9B . The rowData is set on a timeout 1second after loading
[ "stackoverflow", "0037098410.txt" ]
Q: Add another point to existing graph Opencv [ So far I know that there are limitation regarding to Opencv Plotting real time graph. So I currently modifying the code from histogram graph to plot a real time graph. Below will be my code. But the result is not as I expected as using loop to draw the graph, every time it will plot a NEW graph instant of plot on existing graph. Again, the code below work just fine. int hist_w = 700; int hist_h = 700; //image size void show_histogram(std::string const& name, cv::Mat1b const& image, cv::Mat &histImage) { double seconds = difftime( time(0), start); /// Establish the number of bins int histSize = 1000; /// Set the ranges float range[] = { 0, 1000 } ; const float* histRange = { range }; bool uniform = true; bool accumulate = false; Mat hist; /// Compute the histograms: calcHist( &image, 1, 0, Mat(), hist, 1, &histSize, &histRange, uniform, accumulate ); //Draw the histograms //int bin_w = cvRound( (double) hist_w/histSize ); int bin_w = cvRound( (double) seconds);//x-axis /// Normalize the result to [ 0, histImage.rows ] normalize(hist, hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() ); /// Draw for points,for y-axis for( int i = 1; i < histSize; i++ ) { Point ptPrev = Point( bin_w*(seconds-1), hist_h - cvRound(hist.at<float>(0,255))); Point ptNew = Point( bin_w*(seconds), hist_h - cvRound(hist.at<float>(0,255))); line( histImage, ptPrev,ptNew,cv::Scalar::all(255), 5, 8, 0 ); ptPrev = ptNew; } /// Display imshow(name, histImage); } int main( int argc, char** argv ) { //On spot video VideoCapture cap(0); // open the default camera if(!cap.isOpened()) // check if we succeeded return -1; Mat edges,gray; namedWindow("edges",1); Mat histImage( hist_h, hist_w, CV_8UC3, Scalar( 0,0,0) ); for(;;) { Mat frame; cap >> frame; // get a new frame from camera imshow("Frame",frame); cvtColor(frame, gray, CV_BGR2GRAY); GaussianBlur(gray, edges, Size(7,7), 1.5, 1.5); Canny(edges, edges, 0, 30, 3); cv::namedWindow("edges",0); cv::resizeWindow("edges", 100, 100); imshow("edges", edges); show_histogram("White Pixel",edges); if(waitKey(30) >= 0) break; } cv::waitKey(); return 0; } A: Your problem is that every iteration of the for(;;) you mentioned in the comments you are creating a new Mat histImage. You need to create it outside of the function, and pass it as an argument(by reference) to the function, make the changes and show the image. Delete these lines from the body of the function, and put them outside the for(;;) loop: int hist_w = 700; int hist_h = 700; //image size Mat histImage( hist_h, hist_w, CV_8UC3, Scalar( 0,0,0) ); Change the function signature to be: void show_histogram(std::string const& name, cv::Mat1b const& image, cv::Mat &histImage)
[ "stackoverflow", "0006930261.txt" ]
Q: Moving absolutely positioned image according to container div's position in the browser window I have a div with a relative position (div 1). It contains an image (shown as the green block) with an absolute position which by default is hidden way off to the left of the browser window. I'd like to make it so that when div 1 is in the center of the browser window as the user scrolls down, the image is moved in slightly from the left and appears on the screen. As the user begins to scroll down past div 1, I'd like the image to move back to its original offscreen position. I have attached a picture to try and make a bit more sense. I have a feeling this is possible using JavaScript or jQuery but I'm not sure how. Any help would be greatly appreciated. Ian A: You'll want to bind a handler to the scroll event of the window, and measure the ratio of how far down the page the user has scrolled - then, position the image accordingly. I built a rough prototype; you should be able to tweak sizes and positions to make it work for you. The JS for the prototype, which depends on the HTML and CSS in the JSFiddle linked above, is as follows: var $main = $('.main'); var $tgt = $('.targetMover'); var origLeft = $tgt.position().left; var maxLeft = 200; $main.scroll(function(ev){ var ratio = $main[0].scrollTop / $main[0].scrollHeight; var newLeft = origLeft + ( (maxLeft - origLeft) * ratio); $tgt.css({left:newLeft}); });
[ "stackoverflow", "0043095886.txt" ]
Q: How to initialize a struct from a json object HI i am new to swift any idea . How to initialize a struct from a json object . i could not figure out how can i do it . { "user": { "name": "cruskuaka", "email": "[email protected]", "phoneNo":"018833455" }, "address": { "house": "100", "street": "B", "town": { "town_id": "1", "town_name": "Galway city center" }, "city": { "city_id": "10", "city_name": "Galway" }, "address_id":"200", "full_address":"100, B, Galway city center,Galway" }, "delivery_instruction": "no call", "delivery_method": "1" } Here all struct : struct Contact { let user : User let address : Address let deliveryInstruction : String let deliveryMethod : String init(dictionary: [String: Any]) { self.deliveryInstruction = dictionary["delivery_instruction"] as? String ?? "" self.deliveryMethod = dictionary["delivery_method"] as? String ?? "" self.address = Address(dictionary: dictionary["address"] as? [String:Any] ?? [:]) self.user = User(dictionary: dictionary["address"] as? [String:Any] ?? [:]) } } struct User { let name : String let email : String let phoneNo : String init(dictionary : [String:Any] ) { self.name = dictionary["name"] as? String ?? "" self.email = dictionary["email"] as? String ?? "" self.phoneNo = dictionary["phoneNo"] as? String ?? "" } } struct Address { let city : City let town : Town let addressId : String let fullAddress : String let house : String let street: String init(dictionary : [String:Any] ) { self.addressId = dictionary["address_id"] as? String ?? "" self.fullAddress = dictionary["full_address"] as? String ?? "" self.house = dictionary["house"] as? String ?? "" self.street = dictionary["street"] as? String ?? "" self.city = City(dictionary: dictionary["address"] as? [String:Any] ?? [:]) self.town = Town(dictionary: dictionary["address"] as? [String:Any] ?? [:]) } } struct City { let cityId : String let cityName : String init(dictionary : [String:Any] ) { self.cityId = dictionary["city_id"] as? String ?? "" self.cityName = dictionary["city_name"] as? String ?? "" } } struct Town { let townId : String let townName : String init(dictionary : [String:Any]) { self.townId = dictionary["town_id"] as? String ?? "" self.townName = dictionary["town_name"] as? String ?? "" } } A: edit/update: Swift 4 or later you can use Codable Protocol: struct Root: Codable { let user: User let address: Address let deliveryInstruction, deliveryMethod: String } struct Address: Codable { let house, street, addressId, fullAddress: String let town: Town let city: City } struct City: Codable { let cityId, cityName: String } struct Town: Codable { let townId, townName: String } struct User: Codable { let name, email, phoneNo: String } extension Decodable { init(data: Data, using decoder: JSONDecoder = .init()) throws { self = try decoder.decode(Self.self, from: data) } init(json: String, using decoder: JSONDecoder = .init()) throws { try self.init(data: Data(json.utf8), using: decoder) } } Just don't forget to set the JSONDecoder property keyDecodingStrategy to .convertFromSnakeCase: let json = """ {"user": {"name": "crst","email": "[email protected]","phoneNo":"018833455"},"address": {"house": "100","street": "B","town":{"town_id": "1","town_name": "Galway city center"},"city":{"city_id": "10","city_name": "Galway"},"address_id":"200", "full_address":"100, B, Galway city center,Galway" },"delivery_instruction": "no call","delivery_method": "1" } """ do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let root = try decoder.decode(Root.self, from: Data(json.utf8)) print(root) } catch { print(error) } or simply: do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let root = try Root(json: json, using: decoder) // or Root(data: data, using: decoder) print(root) } catch { print(error) } This will print Root(user: __lldb_expr_112.User(name: "cruskuaka", email: "[email protected]", phoneNo: "018833455"), address: __lldb_expr_112.Address(house: "100", street: "B", addressId: "200", fullAddress: "100, B, Galway city center,Galway", town: __lldb_expr_112.Town(townId: "1", townName: "Galway city center"), city: __lldb_expr_112.City(cityId: "10", cityName: "Galway")), deliveryInstruction: "no call", deliveryMethod: "1") Original Answer (before Codable protocol) Swift 3 You have more than one error in your code, but you are in the right path. You are using the wrong key when initializing your user, city and town structs. I have also created two more initializers so you can initialize your struct with a dictionary, the json string or just its data: struct Contact: CustomStringConvertible { let user: User let address: Address let deliveryInstruction: String let deliveryMethod: String // customize the description to your needs var description: String { return "\(user.name) \(deliveryInstruction) \(deliveryMethod)" } init(dictionary: [String: Any]) { self.deliveryInstruction = dictionary["delivery_instruction"] as? String ?? "" self.deliveryMethod = dictionary["delivery_method"] as? String ?? "" self.address = Address(dictionary: dictionary["address"] as? [String: Any] ?? [:]) self.user = User(dictionary: dictionary["user"] as? [String: Any] ?? [:]) } init?(data: Data) { guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return nil } self.init(dictionary: json) } init?(json: String) { self.init(data: Data(json.utf8)) } } struct User: CustomStringConvertible { let name: String let email: String let phone: String let description: String init(dictionary: [String: Any]) { self.name = dictionary["name"] as? String ?? "" self.email = dictionary["email"] as? String ?? "" self.phone = dictionary["phoneNo"] as? String ?? "" self.description = "name: \(name) - email: \(email) - phone: \(phone)" } } struct Address: CustomStringConvertible { let id: String let street: String let house: String let city: City let town: Town let description: String init(dictionary: [String: Any] ) { self.id = dictionary["address_id"] as? String ?? "" self.description = dictionary["full_address"] as? String ?? "" self.house = dictionary["house"] as? String ?? "" self.street = dictionary["street"] as? String ?? "" self.city = City(dictionary: dictionary["city"] as? [String: Any] ?? [:]) self.town = Town(dictionary: dictionary["town"] as? [String: Any] ?? [:]) } } struct City: CustomStringConvertible { let id: String let name: String // customize the description to your needs var description: String { return name } init(dictionary: [String: Any] ) { self.id = dictionary["city_id"] as? String ?? "" self.name = dictionary["city_name"] as? String ?? "" } } struct Town: CustomStringConvertible { let id: String let name: String // customize the description to your needs var description: String { return name } init(dictionary: [String: Any]) { self.id = dictionary["town_id"] as? String ?? "" self.name = dictionary["town_name"] as? String ?? "" } } Testing the initialization from JSON: let contact = Contact(json: json) // crst no call 1 contact // crst no call 1 contact?.user // name: crst - email: [email protected] - phone: 018833455 contact?.user.name // "crst" contact?.user.email // "[email protected]" contact?.user.phone // "018833455" contact?.address // 100, B, Galway city center,Galway contact?.address.id // 200 contact?.address.street // B contact?.address.town // Galway city center contact?.address.city // Galway contact?.deliveryInstruction // "no call" contact?.deliveryMethod // 1
[ "superuser", "0000879776.txt" ]
Q: Windows Domain batchscript for netuse network shares I am using a batchscrip to run at logon on my server 2012 essentials Domain Controller... The script breaks down into 3 sections Connects to 2 folders in local PC share Connects to remote ip (wan ip) server shares Connects to local up (lan ip) server shares... This works great however ideally I would like it to do on or the other of the bottom steps, so connect ideally first by using the local server IP, and if this fails as a fall back connect using the @echo off :DELETE net use /delete * /y :SHAREA NET USE u: "\\ComputerIP\Documents" /user:user password GOTO SHAREB :SHAREB NET USE v: "\\ComputerIP\Documents\Guest Documents" /user:user password GOTO SHAREC :SHAREC NET USE w: "\\RemoteIP\Company\Documents" GOTO SHARED :SHARED NET USE x: "\\RemoteIP\Company\Documents\Guest Documents" GOTO SHAREE :SHAREE NET USE y: "\\localIP\Company\Documents" GOTO SHAREF :SHAREF NET USE z: "\\localIP\Company\Documents\Guest Documents" GOTO EOF :EOF A: If you want to do a "net use" on server1 first and if that fails do "net use" on server2 you can probably do something like this: NET USE X: \\Server1\share IF NOT EXIST X:\ ( NET USE X: \\Server2\share )
[ "stackoverflow", "0000148185.txt" ]
Q: How efficient is define in PHP? C++ preprocessor #define is totally different. Is the PHP define() any different than just creating a var? define("SETTING", 0); $something = SETTING; vs $setting = 0; $something = $setting; A: 'define' operation itself is rather slow - confirmed by xdebug profiler. Here is benchmarks from http://t3.dotgnu.info/blog/php/my-first-php-extension.html: pure 'define' 380.785 fetches/sec 14.2647 mean msecs/first-response constants defined with 'hidef' extension 930.783 fetches/sec 6.30279 mean msecs/first-response broken link update The blog post referenced above has left the internet. It can still be viewed here via Wayback Machine. Here is another similar article. The libraries the author references can be found here (apc_define_constants) and here (hidef extension). A: In general, the idea of a constant is to be constant, (Sounds funny, right? ;)) inside your program. Which means that the compiler (interpreter) will replace "FOOBAR" with FOOBAR's value throughout your entire script. So much for the theory and the advantages - if you compile. Now PHP is pretty dynamic and in most cases you will not notice a different because the PHP script is compiled with each run. Afai-can-tell you should not see a notable difference in speed between constants and variables unless you use a byte-code cache such as APC, Zend Optimizer or eAccelerator. Then it can make sense. All other advantages/disadvantages of constants have been already noted here and can be found in the PHP manual. A: php > $cat='';$f=microtime(1);$s='cowcow45';$i=9000;while ($i--){$cat.='plip'.$s.'cow';}echo microtime(1)-$f."\n"; 0.00689506530762 php > $cat='';$f=microtime(1);define('s','cowcow45');$i=9000;while ($i--){$cat.='plip'.s.'cow';}echo microtime(1)-$f."\n"; 0.00941896438599 This is repeatable with similar results. It looks to me like constants are a bit slower to define and/or use than variables.
[ "stackoverflow", "0011575393.txt" ]
Q: Overload int() in Python Say I have a basic class in Python 3 which represents some number-like data-type. I want to make it so when I have an instance, x, of this class I can call int(x) and have it call my conversion function to return the integer portion. I'm sure this is simple, but I can't seem to find out how to do it. A: You override the __int__ magic method as per the following example... class Test: def __init__(self, i): self.i = i def __int__(self): return self.i * 2 t = Test(5) print( int(t) ) # 10 A: Override the __int__() method.
[ "stackoverflow", "0042476671.txt" ]
Q: Can js forEach take other inputs function addToArr(num, arr) { arr.push(num); } theArr = [1, 2, 3, 4]; myArr = []; theArr.forEach(addToArr(ele, theArr)); console.log(myArr); I wanted to write a function that could be used in a forEach() that could take a different array as a parameter - that I could push to. A: The parameter you pass to forEach must be a function, meaning your addToArr needs to return a function. This is often called currying, partial application, or a closure. function addToArr(arr) { return function(num) { arr.push(num); }; } var arr = [1, 2, 3, 4]; var myArr = []; arr.forEach(addToArr(myArr)); console.log(myArr); In ES6 it's much easier to write with arrow functions. const addToArr = arr => num => arr.push(num);
[ "stackoverflow", "0034468816.txt" ]
Q: Adding Stamp/Watermark/Content over PDF using iTextSharp I am using following code: PdfReader PDFReader = new PdfReader("C:\\file.pdf"); FileStream Stream = new FileStream("C:\\new.pdf", FileMode.Create, FileAccess.Write); PdfStamper PDFStamper = new PdfStamper(PDFReader, Stream); for (int iCount = 0; iCount < PDFStamper.Reader.NumberOfPages; iCount++) { PdfContentByte PDFData = PDFStamper.GetOverContent(iCount + 1); BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); PDFData.BeginText(); PDFData.SetColorFill(CMYKColor.LIGHT_GRAY); PDFData.SetFontAndSize(baseFont, 80); PDFData.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "SAMPLE DOCUMENT", 300, 400, 45); PDFData.EndText(); } Stream.Close(); PDFReader.Close(); PDFStamper.Close(); But PDFStamper.Close(); throws error. Also, I am not sure whether to call PDFReader.Close(); before or after PDFStamper.Close(); And watermark is not added in PDF file. A: Your order of Close calls is all wrong: Stream.Close(); PDFReader.Close(); PDFStamper.Close(); In particular the PDFStamper requires both the PDFReader and the Stream to still be open when it is getting closed. Furthermore, unless an exception is thrown, the Stream automatically is closed during PDFStamper.Close(). Thus, use PDFStamper.Close(); PDFReader.Close(); instead. If you want to make sure that the Stream is getting closed in case of an exception, use a using statement.
[ "mathoverflow", "0000129479.txt" ]
Q: a question of Galois cohomology Let $R$ be a complete DVR with algebraically closed residue field $k$ and fractional field $K$ , $PGL(2)$ the automorphic group of projective line over $\overline K$. My question is: When $H^{1}(Gal(\overline K/K), PGL(2))=0$ ? Is this group trivial if $Char(K) \neq 2$ ? A: The claimed triviality holds (the nonabelian cohomology set is not a group though), and I don't think you need $Char(K) \neq 2$. To argue this, I will use the long exact nonabelian cohomology sequence of the central extension $1 \rightarrow \mathbf{G}_m \rightarrow GL_2 \rightarrow PGL_2 \rightarrow 1$, a segment of which reads $H^1(K, GL_2) \rightarrow H^1(K, PGL_2) \rightarrow H^2(K, \mathbf{G}_m)$. Firstly, $H^1(K, GL_2)$ is the one-point set because it classifies rank 2 vector bundles over $Spec(K)$, of which there is only the trivial one. Secondly, $K$ is a $C_1$ field by a theorem of Lang (see Serre "Galois cohomology", p. 80, II.3.3 c)), hence is of $dim \le 1$, so its Brauer group $H^2(K, \mathbf{G}_m)$ vanishes (loc. cit. for more details). The same argument shows that $H^1(K, PGL_n)$ is the one-point set for any $n$ and any $C_1$ field $K$.
[ "stackoverflow", "0029577496.txt" ]
Q: Python - object and variable errors I'm attempting to program a formula that loops until it reaches the number it is asked to loop for and give an answer to it. However, I seem to be getting variable/calling errors. def infinitesequence(n): a = 0 b = 0 for values in range(0,n+1): b = b + 2((-2**a)/(2**a)+2) a += 1 return b returns TypeError: 'int' object is not callable while def infinitesequence(n): a = 0 for values in range(0,n+1): b = b + 2((-2**a)/(2**a)+2) a += 1 return b returns UnboundLocalError: local variable 'b' referenced before assignment What is causing this error? A: 2((-2**a)/(2**a)+2) is trying to use that first 2 as a function. You are asking Python to call 2() by passing in the result of the (-2**a)/(2**a)+2 expression, and that doesn't work: >>> 2() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable Perhaps you were forgetting to use a * multiplication operator there: 2 * ((-2 ** a) / (2 ** a) + 2) Your UnboundLocal error stems from you removing the b = 0 line, which was not the cause of your original error.
[ "stackoverflow", "0057826225.txt" ]
Q: Valid AssetBundle Throws Null Reference Exception (NRE) With Any API Call This question is not about what a null reference is, this question is about why a valid AssetBundle is throwing an NRE in an API I cannot step through I have been converting my project from using the Resource folder to AssetBundles. I have tagged my scriptable objects in the "scriptableobjects" asset bundle, and I've loaded and stored that bundle in the "Assets/AssetBundles" folder. Here the code where I build my assets: public class AssetBundleManager { [MenuItem("Assets/Build AssetBundles")] static void BuildAllAssetBundles() { string assetBundleDirectory = "Assets/AssetBundles"; if (!Directory.Exists(assetBundleDirectory)) { Directory.CreateDirectory(assetBundleDirectory); } //https://docs.unity3d.com/Manual/AssetBundles-Building.html BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.UncompressedAssetBundle, BuildTarget.StandaloneWindows); } } Before looking at the code below, here is proof that the AssetBundle is not null when it is going to be used: After building the assets, I then go to actually load these assets and their resources: public class X_AssetBundleManager : MonoBehaviour { private static Maps _maps; private static AssetBundle _scriptableObjectsBundle; public static T LoadScriptableObject<T>(string assetName) where T : ScriptableObject { if (_scriptableObjectsBundle == null) { AssetBundle _scriptableObjectsBundle = AssetBundle.LoadFromFile("Assets/AssetBundles/scriptableobjects"); if (_scriptableObjectsBundle == null) { Debug.Log("Failed to load 'scriptableobjects' AssetBundle!"); return null; } } if (_scriptableObjectsBundle.Contains(assetName)) // NRE HERE { Debug.Log("DOES CONTAIN"); } else { Debug.Log("DOES NOT CONTAIN"); } try { // NRE HERE var all = _scriptableObjectsBundle.LoadAllAssets(); } catch (Exception e) { Debug.LogError(e); } T obj = _scriptableObjectsBundle.LoadAsset<T>(assetName); // NRE HERE if (obj == null) { Debug.LogError("Failed to load " + assetName + " in scriptableobjects"); } return obj; } } The _scriptableObjects variable is not null. Its a valid object. However, calling ANY api on it causes a null reference exception. I can't even step through the code to see whats null. The AssetBundle itself is not null, but any call causes this. Any advice on how to further debug this issue or what the problem might be? A: in AssetBundle _scriptableObjectsBundle = ... you overrule (hide) your already existing field variable equally named _scriptableObjectsBundle ... so this outer field _scriptableObjectsBundle still remains null! and the one you actually assign only exists within the if(_scriptableObjectsBundle == null) block &rightarrow simply remove this additional AssetBundle _scriptableObjectsBundle = AssetBundle.LoadFromFile("Assets/AssetBundles/scriptableobjects");
[ "stackoverflow", "0037194170.txt" ]
Q: How can i remove trait method collisions using traits and classes that are in different namespaces? I keep getting an php error indicating that either the method is not in the current class or there is a collision. See error: Trait method callMe has not been applied, because there are collisions with other trait methods on Src\Classes\A in C:\wamp\www\src\classes\a.php on line 72 I have tried but I could not find a solution. This is what I would like to achieve: trait A // namespace Src\Traits; { function callMe() {} } trait B // namespace Src\PowerTraits; { function callMe() {} } class A // Namespace Src\Classes; { use \Src\Traits\A; use \Src\PowerTraits\B { A::callMe insteadof B::callMe; } } When i try A::callMe insteadof callMe; i get the following error (understood, it is obviously in the wrong namespace): Could not find trait Src\Classes\callMe Also tried: \Src\Traits\A::callMe insteadof \Src\Traits\B::callMe (error, syntax error); \Src\Traits\A::callMe insteadof B::callMe (error: wrong namespace); \Src\Traits\A::callMe as NewA (error, collision warning); \Src\Traits\A::callMe as \Src\Traits\A::NewA (error, syntax error); Left alone, gives the collision warning: Trait method callMe has not been applied, because there are collisions with other trait methods How can override a trait method when the traits and the calling class are all in different namespaces? A: In regards to A::callMe insteadof B::callMe you cannot name a method following the scope resolution operator :: (Paamayim Nekudotayim) when using insteadof because PHP will look for a method by the same name. A::callMe insteadof B; you need to either use/import/alias the class name, or reference the fully qualified class with namespace \Src\Traits\A::callMe insteadof \Src\PowerTraits\B; Demo: https://3v4l.org/g1ltH <?php namespace Src\Traits { trait A { function callMe() { echo 'Trait A'; } } } namespace Src\PowerTraits { trait B { function callMe() { echo 'PowerTrait B'; } } } namespace Src\Classes { class A { use \Src\Traits\A; use \Src\PowerTraits\B { \Src\Traits\A::callMe insteadof \Src\PowerTraits\B; } } } namespace { (new \Src\Classes\A)->callMe(); } Trait A
[ "stackoverflow", "0010157376.txt" ]
Q: Sending multiple SOAP requests in one packet I am using the aonaware.com dictionary web service for my application. I need to send dozens of requests for word definitions, but that takes too long by sending them independently. How can I send multiple SOAP requests at once (in one packet)? I am using java and the service's WSDL file is located here: http://services.aonaware.com/DictService/DictService.asmx?WSDL A: How can I send multiple SOAP requests at once (in one packet)? What do you mean packet? TCP packet? You can't. SOAP is carried over HTTP which is a request/response protocol. That means each SOAP request is carried over a different POST request. What you could do is send multiple requests concurrently which means over different connections. That will be faster than sending them serially but takes resources and bandwidth. You could also check if the underlying connection is closed after the response. If it does for some reason make it persistent so that you don't re-open the TCP connections and avoid that overhead
[ "stackoverflow", "0042934280.txt" ]
Q: How to correct the ligatures of 'fi' and 'fl' in case of larger letter-spacing? I use Google font 'Roboto' and expanded letter-spacing of .3em . How in this case is posible to corect sticky ligatures of little 'f' letter in words consisting 'fl' and 'fi' ? I tried to change to font-family for 'Roboto' to 'sans' and 'sans-serif', but it looks so ridiculus in condition of expanded letter-spacing. Have you any advise? html,body{ min-width:100vw; max-width:100vw; min-height:100vh; max-height:100vh; margin: 0; padding: 0; } *{ margin: 0; padding: 0; box-sizing:0; } body { background: #CFB095;/*PANTONE 14-1315 TCX Hazelnut*/ font-family: 'Roboto', sans; font-size:24px; color: rgba(255,255,255,1); font-size: 44px; word-spacing: .5rem; letter-spacing: .35rem; text-align: center; } h1{font-size: 2rem} h2{font-size: 1.5rem; padding:3rem 0 1.5rem 0;} p{font-size: 1rem} .skip{ clip: rect(0 0 0 0); margin: -1px; overflow:hidden; display: none; position: absolute; top: -1px; left: -1px; z-index: -1; } <!DOCTYPE html> <html lang='en'> <head> <meta name='robots' content='noindex'> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1'> <title>DEMO | Typography Exploration</title> <link rel='stylesheet' type='text/css' href='https://fonts.googleapis.com/css?family=Roboto'> <link rel='stylesheet' type='text/css' href='/index_style.css'> </head> <body> <h1 class='skip'>Typography Exploration</h1> <section> <h2>Ligatures to be fixed: 'fl' 'fi'</h2> <p>Flip fly fluffy Ff. <br>Fitting for a figure fixing. <br>Affirm effect. <br>At least 'ff' is well supported in Chrome</p> </section> </body> </html> A: Use font-variant-ligatures: none;. It's well supported in modern browsers. html,body{ min-width:100vw; max-width:100vw; min-height:100vh; max-height:100vh; margin: 0; padding: 0; } *{ margin: 0; padding: 0; box-sizing:0; } body { background: #CFB095;/*PANTONE 14-1315 TCX Hazelnut*/ font-family: 'Roboto', sans; font-variant-ligatures: none; font-size:24px; color: rgba(255,255,255,1); font-size: 44px; word-spacing: .5rem; letter-spacing: .35rem; text-align: center; } h1{font-size: 2rem} h2{font-size: 1.5rem; padding:3rem 0 1.5rem 0;} p{font-size: 1rem} <link rel='stylesheet' type='text/css' href='https://fonts.googleapis.com/css?family=Roboto'> <link rel='stylesheet' type='text/css' href='/index_style.css'> <body> <h1 class='skip'>Typography Exploration</h1> <section> <h2>Ligatures to be fixed: 'fl' 'fi'</h2> <p>Flip fly fluffy Ff. <br>Fitting for a figure fixing. <br>Affirm effect. <br>At least 'ff' is well supported in Chrome</p> </section> </body>
[ "serverfault", "0000547885.txt" ]
Q: nginx: try_files not finding static files, falling back to PHP Relevant configuration: location /myapp { root /home/me/myapp/www; try_files $uri $uri/ /myapp/index.php?url=$uri&$args; location ~ \.php { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include /etc/nginx/fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root/index.php; } } I absolutely have a file foo.html in /home/me/myapp/www but when I browse to /myapp/foo.html it is handled by PHP, the final fallback in the try_files list. Why is this happening? A: If you browse to /myapp/foo.html, Nginx checks the file at /home/me/myapp/www/myapp/foo.html. When it doesn't find it there, it goes on to the fallback in the try_files list. If you need Nginx to check the file at /home/me/myapp/www/foo.html, then you'd need to use alias instead of root, in your use case. Here's the solution... location /myapp { alias /home/me/myapp/www; try_files $uri $uri/ /myapp/index.php?url=$uri&$args; location ~ \.php { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include /etc/nginx/fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root/index.php; } } Note that there is a longstanding bug that alias and try_files don't work together. Also, note that using alias may break other parts of your configuration, such as PHP processing!
[ "stackoverflow", "0046491994.txt" ]
Q: what is the correct callback in coffee for folding code in Atom I am trying to hack the tool icons coffee file by adding a shortcut to it that will allow me to fold/unfold the code in the atom editor. I have the following: @toolBar.addButton icon: 'plus' callback: 'run:Cmd+Alt+[' tooltip: 'Expand Code' iconset: 'icomoon' But obviously, it doesn't work. This is a core functionality to atom. If I hit those keys, I can successfully fold and unfold respectively with Cmd+Alt+[ and Cmd+Alt+]. Using the core callback as in core: fold or core: unfold doesn't work either Any ideas? A: You can use the Key Binding Resolver (bundled with Atom) to get the command name after pressing its shortcut. There are several commands to fold/unfold code, including these: 'editor:fold-all' 'editor:unfold-all' 'editor:fold-current-row' 'editor:unfold-current-row' 'editor:fold-selection'
[ "stackoverflow", "0032409441.txt" ]
Q: UploadiFive Forbidden File Type AMR I am using uploadifive as file uploader in my application. I am using fileType: to tell the uploader of all the supported file types. The fileType: takes MIME Types of all the supported file types. The .amr file is always forbidden by the uploader. I have tried following MIME Types for amr files audio/amr, audio/Amr, audio/AMR and audio/x-amr All of these resulted in forbidden file type. What is the correct mime type for AMR files? A: I got it working by peeking into the registry [HKEY_CLASSES_ROOT] ---> .amr The Content Type registry value was missing for the .amr file extension. I created this entry and set its value to audio/amr. The uploader is working now.
[ "stackoverflow", "0053617066.txt" ]
Q: JScrollPane is larger than JTable row I use this statement to assign a scrollPane to a Jtable. However when I add the scrollPane to any other JPanel. The height of the scrollPane is much larger than the table height. JPanel tablepane=new JPanel(); tableau= new JTable(); tableau.setModel(model); tableC=new JScrollPane(); tableC.setViewportView(tableau); A: If you want it the exact size then you can use: table.setPreferredScrollableViewportSize(table.getPreferredSize()); after you load the data into the table.
[ "ru.stackoverflow", "0000935342.txt" ]
Q: Логин в sqlcmd через jenkins использую Windows Authentication Я настраиваю CI. Настраиваю через jenkins pipline. Мне нужно запускать sql скрипт в ms sql. Использую я для этого sqlcmd команду которую прописываю в jenkinsfile. Вот так выглядит команда bat sqlcmd -e -S \"someserver\" -i \"D:\\somefile.sql\" -E В данной команде -E говорит, что для логина в sql server нужно использовать windows authentication, т.к я запускаю это на сервере должно работать(но пока я тестирую локально), это нужно для того что бы не хранить credentials от бд в репозитории (jenkinsfile лежит в репозитории). Когда в jenkins запускаю билд получаю вот такое сообщение The server principal "CS\xxxxxxxx$" is not able to access the database "xxxx" under the current security context. Я так понимаю через jenkins я не могу воспользоваться windows authentication т.е если запустить эту команду через командную строку, то тогда мой sql скрипт выполняется. A: Я уже давно решил эту проблем, хочу поделиться решением. Jenkins запускается как Windows Service поэтому нужно выставить ему права пользователя который имеет доступ к базе и тогда вам будет доступна windows authentication. Надеюсь это кому-нибудь поможет)
[ "ru.stackoverflow", "0000538206.txt" ]
Q: Транзакционная модель В рамках многопоточного приложения работа с БД осуществляется посредством использования одной и той же учётной записи. Каждый поток имеет отдельное соединение с БД. Появилась необходимость использовать транзакции. В официальной документации мне не удалось обнаружить (буду признателен за ссылку), где бы чётко оговаривалось, что транзакционная модель в InnoDb функционирует и на уровне соединений, а не только на уровне отдельных учётных записей. Возможно, что это априори, однако я некомпетентен в рассматриваемой области. Хотелось бы, по возможности, получить точный ответ. Второй вопрос вытекает из первого. Если транзакционная модель InnoDb всё же реализована на уровне отдельных соединений, то существует ли также возможность создавать отдельные, но параллельно выполняемые транзакции в рамках одного и того же соединения в одном и том же потоке? Это, скажем, может понадобиться при асинхронном выполнении. К сожалению, в документации я не увидел возможности указывать транзакциям какие-либо уникальные имена или идентификаторы. MySQL 5.7 A: Транзакционная модель функционирует, как ни странно, на уровне транзакций - группы команд между begin и commit/rollback (одиночные запросы вне открытой явно транзакции автоматически оборачиваются в транзакцию, без транзакции транзакционные хранилища не работают). В рамках одного соединения может быть много транзакций. От одного пользователя может быть много одновременных и независимых соединений, и, следовательно, конкурентных транзакций тоже может быть много. В сущности, в понятии транзакции нет ни соединения, ни пользователя. Есть только id транзакции, согласно которому вычисляется видимость актуальных версий строк в MVCC и за которым закрепляются взятые блокировки. В известных мне СУБД - mysql и postgresql - одно соединение одновременно держать две разные транзакции открытыми не может, одно соединение - только одна открытая транзакция. И не припоминаю возможности в рамках одного соединения выполнять одновременно несколько команд. Библиотека может предоставлять неблокирующий вызов, но не дождавшись конца ответа новые запросы отправлять не получится. A: В MySQL каждый тред держит соединение. Он не отслеживает, каким процессом это соединение открыто, т.е. ему без разницы, один процесс открыл кучу соединений или это куча процессов. MySQL выполняет запросы параллельно, в рамках тредной модели, но существуют блокировки: на уровне MySQL в целом: на метаданные транзакционные на уровне движка (InnoDb) на таблицы, в случае индексации, оптимизации счетчик автоинкремента на таблицу в случае записи на строки LOCK TABLE полный скан таблицы (индексация) В случае транзакций: После того как стартует транзакция - происходят какие-то изменения данных, которые пишутся в журнал, далее мы эти изменения коммитим или отменяем. Как только мы выполнили эти изменения, то они из журнала переходят в данные. На время выполнения транзакции - данные используемой табл доступны для чтения (но это зависит от уровня изоляции транзакции). В рамках одного соединения может стартовать только одна транзакция. COMMIT закрепляет транзакцию. Советую книгу MySQL. «Оптимизация производительности», там очень хорошо расписано про блокировки и транзакции.
[ "stackoverflow", "0034644587.txt" ]
Q: Regex pattern to grab all the numbers in between square brackets? I'm trying to create a regex pattern to grab all the numbers from a given string which are in between square brackets and separated by commas. The output should be like so, Number1 = 45 Number2 = 66 And so on... All I have so far is a pattern that greedy grabs everything in between square brackets. string input3; //string pattern = @"\b\w+es\b"; string pattern = @"\[(.*?)\]"; //Regex regex = new Regex("[*]"); Console.WriteLine("Enter string to search: "); input3 = Console.ReadLine(); //Console.WriteLine(input3); List<string> substrings = new List<string>(); int count = 1; foreach (Match match in Regex.Matches(input3, pattern)) { string substring = string.Format("Number{0} = '{1}'",count,match); count++; Console.WriteLine(substring); substrings.Add(substring); } string[] subStringArray = substrings.ToArray(); } Should I just create two patterns, the greedy one and then a second pattern to search the greedy output for all numbers separated by commas? Or would it be more efficient to just create a single pattern? A: You said that your string is string which are in between square brackets and separated by commas. I guess the input is something like that [1,2,3,4,5,6] So you can use this regex to get numbers var numbers = Regex.Match("[1,2,3,4,5,6]", @"\[(?<numbers>[\d,]+)\]").Groups["numbers"].Value; And then split by , to get a collection of numbers var collectionOfNumbers = numbers.Split(','); And to display this string Number1 = 45 Lets us a litle bit of LINQ to do that C# 6 syntax var strings = numbers.Split(',').Select((number, i) => $"Number{i + 1} = {number}"); Console.WriteLine(string.Join("\n", strings)) C# <= 5 syntax var strings = numbers.Split(',').Select((number, i) => string.Format("Number{0} = {1}", i+1, number)); Console.WriteLine(string.Join("\n", strings)) And this is the ouput Number1 = 1 Number2 = 2 Number3 = 3 Number4 = 4 Number5 = 5 Number6 = 6 Another example with inpunt: Foo Bar [45,66] C# 6 syntax var numbers = Regex.Match("Foo Bar [45,66]", @"\[(?<numbers>[\d,]+)\]").Groups["numbers"].Value; var strings = numbers.Split(',').Select((number, i) => $"Number{i + 1} = {number}"); Console.WriteLine(string.Join("\n", strings)) C# <= 5 syntax var numbers = Regex.Match("Foo Bar [45,66]", @"\[(?<numbers>[\d,]+)\]").Groups["numbers"].Value; var strings = numbers.Split(',').Select((number, i) => string.Format("Number{0} = {1}", i+1, number)); Console.WriteLine(string.Join("\n", strings)) The output is Number1 = 45 Number2 = 66
[ "stackoverflow", "0000825331.txt" ]
Q: Where to put ruby .gem files so that Shoes.setup can find them? A lot of questions have been asked about gem support in Shoes, but none have answered where to put them. I've got Shoes Raisins 1134 on Windows XP, and I've downloaded dbi-0.4.1.gem and am trying to get the following to work: Shoes.setup do gem 'dbi' end require 'dbi' Shoes.app ... end When I run this, I get the dialog that says Installing dbi -- Looking for dbi which sits for hours not finding the gem file. I've tried putting it in all of the following places to no avail: The folder that contains the above script D:\Program Files\Common Files\Shoes\0.r1134\ruby\gems D:\Program Files\Common Files\Shoes\0.r1134\ruby\gems\1.8\gems Which is wrong -- the folder or the code? EDIT - ANSWER: Thanks to @Pesto for the answer. I had read the quoted text, but misunderstood it to reference where Shoes PUT the installed gem files, not where it GOT the gem source. In Windows XP, the reference translates to %USERPROFILE%\Application Data\Shoes, and the install worked perfectly. Now to start playing with it ... A: The code looks fine. For example, this is just peachy: Shoes.setup do gem 'RedCloth' end require 'RedCloth' Shoes.app do para RedCloth.new('*awesome*').to_html end As to where the gems are installed, _why himself answers this: By putting your gem list in the Shoes.setup block, you’ll end up encountering the Shoes popup seen above if any of the gems happens to be absent. Gems are installed in ~/.shoes, to avoid needing superuser rights. (And just to keep Shoes away from messing with your normal Ruby stuff.)
[ "math.stackexchange", "0001137649.txt" ]
Q: A partition of Hypercube vertices into subcube graphs. We define the vertices of a hypercube graph $H_n$ by $$V(H_n)= \lbrace (x_1,x_2 ,\cdots , x_n) :x_i \in \mathbb{Z}_2\rbrace$$ Also we call a $m$-dimensional face of a hypercube a $m$-dimensional subcube. Now, let me ask my question. Is it possible to find a partition of Hypercube vertices into subcubes? I want just a partition. A: Consider the set of binary $(n-m)$-tuples $B=\{(x_1,\ldots,x_{n-m})\mid x_i=0,1\}$. For each $b\in B$, consider the set $H(b)$ of all vertices in $H_n$ that start with $b$. Then the subgraph induced by $H(b)$ is an $m$-dimensional hypercube, and the set of $H(b)$ over all $b\in B$ is your desired partition.
[ "blender.stackexchange", "0000136606.txt" ]
Q: Duplicating an object but when you move it. it distorts blender community I am struggling with a problem of when I duplicate an object that has an animation and an armature when I move it to another location using X, Y, Z axis it distorts... Duplicating... Annoying distortion... A: Your problem seems to be the following one: If you duplicate an object that has an armature, you should also duplicate the armature, otherwise it will still be influenced by the original armature, because by default it is still parented to it. On the center of my picture, my original object + armature. On the left, copied with the armature, it's not influenced anymore by the original armature but by the copied one. On the right, copied without the armature, it's still parented to the original armature. So you need either to copy object + armature or to unparent.
[ "math.stackexchange", "0000351058.txt" ]
Q: Time complexity and proof of time complexity Which is true and which false? I can't really decide which one is true and which false. Maybe in first 3 cases. $$3n^5 − 16n + 2 \in O(n^5)$$ $$3n^5 − 16n + 2 \in O(n)$$ $$3n^5 − 16n + 2 \in \Omega(n^{17})$$ $$3n^5 − 16n + 2 \in \Omega(n^5)$$ $$3n^5 − 16n + 2 \in \Theta(n^5)$$ $$3n^5 − 16n + 2 \in \Theta(n)$$ $$3n^5 − 16n + 2 \in \Theta(n^{17})$$ and how to prove this one: $$2^{(n+1)} \in O\left(\frac{3^n}n\right)$$ A: By definition, $f(n) = O(g(n))$ iff for $n$ big enough it holds that $|f(n)|\leq M |g(n)|$ for some positive constant $M$. That is, if you deal with polynomials, $$ P(n) = \sum_{k=0}^{m_1} a_k n^k,\quad Q(n) = \sum_{k=0}^{m_2} b_k n^k, \quad a_{m_1}, b_{m_2}>0 $$ the terms with the highest power dominate other terms and thus $$ P(n) = O(Q(n))\Leftrightarrow m_1\leq m_2 $$ which helps you resolving the first part of your question. For the second part, apply similar analysis and show that for $n$ big enough it holds that $$ 2^{n+1} \leq \frac{3^n}{n} \text{ that is } \left(\frac{2}{3}\right)^n\leq \frac{1}{2n} $$
[ "stackoverflow", "0003456055.txt" ]
Q: UVa 3n+1 Case Recursive Stack Overflow im trying to solve this very first challange but i get stuck, i like fast program, so i decided to use recursive method not iteration unfortunately, when the input is a big integer (100000 > input > 1000000), its often crash so i debug it, and it shows stack overflow error please help me, i dont know what to do, ive tried to change data type to unsigned long, unsigned int, etc, but none of it works here is my code, im using ANSI C #include "stdio.h" int cek(int n) { return n % 2; } int fung(int n,int c) { if (n == 1) { return c; } if (!cek(n)) { return fung(n/2,++c); } else { return fung((n*3)+1,++c); } } int comp(int i,int j,int tmp) { int temp; if (i == j) return tmp; temp = fung(i,1); if (temp > tmp) return comp(++i,j,temp); else return comp(++i,j,tmp); } int main() { int i,j,tmp; while (scanf("%d %d",&i,&j)) { if (i > j) { tmp = i; i = j; j = tmp; } printf("%d %d %d\n",i,j,comp(i,j,0)); } return 0; } PS: sorry for my stupidness, im really a newbie @_@ A: Recursion is not likely to be faster than iteration, and in fact it's likely to be slower. The call stack has a limited size, and if your recursion goes deeper than that, there's nothing you can do about it. Especially in the Collatz problem, there's no way to tell up front how many steps you'll need. Rewrite this using an iterative method instead. (If your compiler does tail call optimization, recursion might still work. But TCO is not required by the standard, so it will lead to unportable code. And apparently, your compiler does not optimize this particular tail call anyway.)
[ "anime.stackexchange", "0000002462.txt" ]
Q: How could Tosen know that Kenpachi was smiling? When Tosen fights Kenpachi in the Rescue Rukia arc, Tosen uses his bankai to combat Kenpachi. A while later, Kenpachi figures out how to defeat Tosen's bankai and smiles. Tosen somehow knew that he smiled (Because we heard his thoughts: "He's smiling?") However, Tosen is blind. How could he have known? A: When Tōsen attacks with Enma Kōrogi, He is not affected by it as anyone else (he can still smell and hear). So when he asked why Kenpachi laughs it was because he could hear him laughing. A: According to his page on the Bleach wiki: Tōsen boasts a great amount of spiritual energy. His skill in the use of his spiritual power is evident, as he uses his spiritual sense to "see". He uses his reiatsu (spiritual power) to sense things around him, for example, to know where his opponents are during a battle. He should also be able to sense what the others are doing in the same way. It would not be otherwise possible for him to be a Captain-class shinigami. The heightened sense of what people inside his bankai space are doing could also be one of the powers he gets from the bankai, because he has complete command over that space.
[ "cs.stackexchange", "0000045151.txt" ]
Q: probablistic procedure to permutate array input : $array[1...n]$ output: permutated array Our algorithm should be probablistic and complexity should be $O(n)$. Could you give me hint ? My weakness is probability theory and it is why I have a problem. A: I'm not exactly certain what you mean by probabilistic procedure as pertains to array permutation, and I'm going to assume you're looking for a random permutation of the array. I'm basing this off the formulation of the problem being very similar to an algorithm for that purpose. So lets say as a person I'd like to do this task: Well, I'd probably just write down all the possible numbers, and then pick a random one. Then I'd cross of the one I'd picked and continue until I'd crossed them all off. Spoiler as to the name of the algorithm which I mentioned: See Fisher-Yates Shuffle algorithm or Knuth Shuffle. A: First we need to define the algorithm a bit more stringently. I prefer this one. Choose a $N$-permutation $P$ with probability $U(P)$ where $U$ is a uniform distribution of the space of $N!$ permutations on $N$ values. I like to solve this in an inductive fashion. First we think about how we can do this with 1 value. Well how many permutations are there over 1 value? There is 1 such permutations. Because our uniform distribution needs to sum to unity it follows that the permutation must occur with probability. So we select it with probability 1. That is to say we always select it. Second we think about how we can generate an $N$-permutation given an $(N-1)$-permutation? How can we do this? It isn't hard to see that there are an equal number of $N$-permutations in which a number $X$ occurs in position $i$ as there are where $X$ occurs at position $j$. So if the number is the same and the permutations are uniformly distributed then it must be equally likely for a number $X$ to occur anywhere in the permutation. Thus we just need to figure out how to insert our $N$th number into the smaller permutation in a uniformly distributed way. If you want to look it up this is called the Fisher-Yates shuffle
[ "stackoverflow", "0008902087.txt" ]
Q: Retaining an Assigned Instance Variable Property I have a property that has (nonatomic, assign) as attributes. In a method, I then am retaining that variable then releasing it a line after. Static analyzer is giving warning that incorrect decrement of the reference count of object.... Can I not do this @property (nonatomic, assign) Class *iVar; [self.iVar retain]; [self.iVar removeFromSuperview]; [self insertSubview:self.iVar atIndex:self.iVar.index]; [self.iVar release]; A: Since the retain and release both happen in the same method, you might want to copy the property to a local variable and then work with that: UIView *someView = self.interestingView; [someView retain]; //...do some stuff... [someView release]; That at least provides some protection in case the "some stuff" part happens to modify self.interestingView. And it'll probably satisfy the static analyzer, too. In general, I would avoid retaining/releasing variables that back properties outside the accessors for those properties, except for a few well defined situations such as -dealloc. Similarly, avoid directly retaining/releasing the result of a property access, as in [self.foo retain]. If that property is changed before you get to the release, you end up with both a leak and, later, an over-release.
[ "electronics.stackexchange", "0000343538.txt" ]
Q: How does the BSRR register work? On the GPIOs of some ARM-based microcontrollers, you are given a register BSRR which you can write to to perform atomic changes in a ports output register. For example, to set Port A Bit 5 to a 1 you simply do GPIOA->BSRR = (1<<5) This alleviates the problem of atomicity so you do not have to perform a read-modify-write sequence. Without the BSRR you would have to do GPIOA->ODR |= (1<<5). How does the BSRR register work under the hood? Does it clear itself so that the next time you want to set a bit there isn't the previous bit still lying around. If i wanted to set bit 2 and later on set bit 6 i can do first GPIOA->BSRR = (1<<2) and then later on do GPIOA->BSRR = (1<<6) but won't bit 2 still be set from my previous call? A: There is a sort of read-modify-write but it is done in logic/hardware without any time between the read and the write. The statement in Verilog would be: GPIOA <= GPIOA | cpu_write_data; This generates logic where there is an OR gate before the register and the new data is OR-ed with the old data and stored in the register. The data bits which you write and which are SET (high) will create a 1 at those locations only. All bit which you write which are clear (low) will remain unchanged. If the bit was set it remains set, if the bit was clear it remains clear. simulate this circuit – Schematic created using CircuitLab Equivalent you can clear bits by using: GPIOA <= GPIOA & ~cpu_write_data; The data bits which you write and which are SET (high) will create a 0 at those locations only. All other bits remain unchanged. It gets a bit more complex to have all these bit-set and bit-clear operations implemented in parallel on the same register but that is just a matter of more logic (multiplexers, address decoders etc.)
[ "stackoverflow", "0058798955.txt" ]
Q: Is it possible to build a C# project as a .Netcore application if it has a .Netframework dependencies I have a .NetCore application that is fully portable (working as cross-platform). Now, I need to refer to and use a .Netframework library that I would be using its functionalities if and only if my application is running on Windows device. I found that It is possible through making the project's .csproj configuration file targets multiple SDKs (Both .NetCore and .NetFramework) like this <TargetFrameworks>net472;netcoreapp2.1</TargetFrameworks>. My question is, does building my application to target multiple frameworks (like the case above) keeps it portable (works on both Windows and Linux)? Edit: Someone marked this question as a duplicate for another question that was answered as using .Netstandard would solve the problem. I still can't see how. In my case, I have an already built .netframework class library that I don't have its source code, so I can't translate it into .netstandard and simply use it. I need to use .Netframework class library directly in my .NetCore application if it is running under Windows, is this possible? A: No. You need to use a .NET Standard class library instead: The .NET Standard enables the following key scenarios Defines uniform set of BCL APIs for all .NET implementations to implement, independent of workload. Enables developers to produce portable libraries that are usable across .NET implementations, using this same set of APIs. Reduces or even eliminates conditional compilation of shared source due to .NET APIs, only for OS APIs.
[ "stackoverflow", "0010390946.txt" ]
Q: Chrome desktop notification click to focus on content I am building desktop notification into my a chrome extension that I am working on. The functionality I need required that the user be taken to the tab that caused the notification when they click on the notification window. I can get that working using the chrome.tabs API, but what I can't manage to figure out is how to bring Chrome to the front when the notification is clicked. I know window.focus() is disabled in chrome, but this is definitely possible to do since that's the behavior of the Gmail desktop notifications. A: notification = webkitNotifications.createNotification(...) notification.onclick = function(){ window.focus(); this.cancel(); }; notification.show() ...works as expected, without any additional permissions. A: Use chrome.tabs.update(tabId, {active: true}); to focus a tab (not to be confused with chrome.windows.update). The tabId is often obtained via the Tab type. This object is passed to many methods/event listeners (sometimes via the MessageSender type). A: function msg(){ var notification = new Notification("Title", {body: "Yore message", icon: "img.jpg" }); notification.onshow = function() { setTimeout(notification.close(), 15000); }; notification.onclick = function(){ window.focus(); this.cancel(); }; } msg();
[ "stackoverflow", "0002031111.txt" ]
Q: In Python, how can I put a thread to sleep until a specific time? I know that I can cause a thread to sleep for a specific amount of time with: time.sleep(NUM) How can I make a thread sleep until 2AM? Do I have to do math to determine the number of seconds until 2AM? Or is there some library function? ( Yes, I know about cron and equivalent systems in Windows, but I want to sleep my thread in python proper and not rely on external stimulus or process signals.) A: Here's a half-ass solution that doesn't account for clock jitter or adjustment of the clock. See comments for ways to get rid of that. import time import datetime # if for some reason this script is still running # after a year, we'll stop after 365 days for i in xrange(0,365): # sleep until 2AM t = datetime.datetime.today() future = datetime.datetime(t.year,t.month,t.day,2,0) if t.hour >= 2: future += datetime.timedelta(days=1) time.sleep((future-t).total_seconds()) # do 2AM stuff A: import pause from datetime import datetime pause.until(datetime(2015, 8, 12, 2)) A: One possible approach is to sleep for an hour. Every hour, check if the time is in the middle of the night. If so, proceed with your operation. If not, sleep for another hour and continue. If the user were to change their clock in the middle of the day, this approach would reflect that change. While it requires slightly more resources, it should be negligible.
[ "stackoverflow", "0039965756.txt" ]
Q: General SQL/MySQL turning rows into columns I am currently struggling a bit with MySQL in trying to pivot a table. A simplified version of the table itself would probably be something along the lines of: dayName amount --------------------- Monday 34 Tuesday 3453 ... ... Ideally I would like to be able to turn each day into a column and each amount as its value. Any suggestion on to do it in a clean way? Thanks! A: If your rows are always the days of the week, then you can use something like this: select sum(case when dayName = 'Monday' then amount end) as 'Monday', sum(case when dayName = 'Tuesday' then amount end) as 'Tuesday' . . . from DaysOfWeek; Unfortunately, MySQL doesn't have a PIVOT function. http://sqlfiddle.com/#!9/c1a11/6
[ "stackoverflow", "0003616181.txt" ]
Q: callback function meaning What is the meaning of callback function in javascript. A: JavaScript's "callback" is function object that can be passed to some other function (like a function pointer or a delegate function), and then called when the function completes, or when there is a need to do so. For example, you can have one main function to which you can pass a function that it will call... Main function can look like this: function mainFunc(callBack) { alert("After you click ok, I'll call your callBack"); //Now lets call the CallBack function callBack(); } You will call it like this: mainFunc(function(){alert("LALALALALALA ITS CALLBACK!");} Or: function thisIsCallback() { alert("LALALALALALA ITS CALLBACK!"); } mainFunc(thisIsCallback); This is extensively used in javascript libraries. For example jQuery's animation() function can be passed a function like this to be called when the animation ends. Passing callback function to some other function doesn't guarantee that it will be called. Executing a callback call (calBack()) totally depends on that function's implementation. Even the name "call-back" is self-explanatory... =) A: It's just a name for a function that should be called back after something. It's often used with XMLHttpRequest: var x = new XMLHttpRequest(); x.onreadystatechange = function(){ if(x.readyState == 4){ callbackfunction(x.responseText); } } x.open('get', 'http://example.com/', true); x.send(null); callbackfunction is just a plain function, in this case: function callbackfunction(text){ alert("I received: " + text); } A: Besides just being a function, a callback function is an enabler for asynchronous application design. Instead of calling a function and waiting for the return value(s), potentially locking up the thread or the entire PC or UI on single threaded systems while you wait, with the async pattern you call a function, it returns before finishing, and then you can exit your code (return back to the calling OS, idle state, run loop, whatever...). Then later, the OS or asynchronous function calls your code back. The code you want it to call back is usually encapsulated in something called a "callback function". There are other uses, but this is a common one in OOP UI frameworks. With the latest iOS 4.x, you can also use nameless "blocks" for the callback. But languages that don't have blocks (or anon closures under another name) use functions for function callbacks.
[ "stackoverflow", "0034279901.txt" ]
Q: Python RSA encryption I am trying to write a RSA encryption software tool that will use the same key every single time. here is what I have so far. import Crypto from Crypto.PublicKey import RSA from Crypto import Random key = <_RSAobj @0x24b6348 n<1024>,e,d,p,q,u,private> publickey = key.publickey() encrypted = publickey.encrypt('hi', 32) print(encrypted) I get a syntax error at line 5 pointing at the < sign. I know that this is a valid private key. what is the problem and how do I fix it. Also I am using python 2.7.3 [EDIT] I get the key from this code import Crypto from Crypto.PublicKey import RSA from Crypto import Random import os random_generator = Random.new().read key = RSA.generate(1024, random_generator) print(key) raw_input() Also I am getting a 'RSA key format not supported error' from this code after the 'raw_input()' import Crypto from Crypto.PublicKey import RSA from Crypto import Random text_file = open("keyfile.txt", "w") text_file.write('<_RSAobj @0x24b6348 n<1024>,e,d,p,q,u,private>') text_file.close() raw_input() with open('keyfile.txt', 'r') as f: externKey = f.readline() key = RSA.importKey(externKey, passphrase=None) publickey = key.publickey() encrypted = publickey.encrypt('hi', 32) print(encrypted) A: First, <_RSAobj @0x24b6348 n<1024>,e,d,p,q,u,private> is not a valid key, not sure how you get this, but it is a string representation of your key as a Python object only, the actual key content is not presented, also note that you cannot rebuild the key object with this string representation. Before you do RSA encrypt with your key, you should import your key from some place like File, Generating In Memory etc. So what you should do is: key = RSA.importKey(externKey, passphrase=None) Where the externKey is a String, so you can load the key string from your key File with this way. Or: key = RSA.generate(bits, randfunc=None, progress_func=None, e=65537) Where the bits is the strength of your key, e.g 2048. Either way you will have an RSA key object (_RSAobj) returned, then you can do encryption as the rest of your code did. [EDIT] Complete Code import Crypto from Crypto.PublicKey import RSA #Quick way to generate a new key private_key = RSA.generate(1024) #Show the real content of the private part to console, be careful with this! print(private_key.exportKey()) #Get the public part public_key = private_key.publickey() #Show the real content of the public part to console print(public_key.exportKey()) #Save both keys into some file for future usage if needed with open("rsa.pub", "w") as pub_file: pub_file.write(public_key.exportKey()) with open("rsa.pvt", "w") as pvt_file: pvt_file.write(private_key.exportKey()) #Load public key back from file and we only need public key for encryption with open('rsa.pub', 'r') as pub_file: pub_key = RSA.importKey(pub_file.read()) #Encrypt something with public key and print to console encrypted = pub_key.encrypt('hello world', None) # the second param None here is useless print(encrypted) #Load private key back from file and we must need private key for decryption with open('rsa.pvt', 'r') as pvt_file: pvt_key = RSA.importKey(pvt_file.read()) #Decrypt the text back with private key and print to console text = pvt_key.decrypt(encrypted) print(text)
[ "stackoverflow", "0022182752.txt" ]
Q: drawing random image libgdx I am learning java game development with libgdx and have the following issue. I have a Rectangle array which I iterate through and draw an image according to the position of the rectangle. My Questions is how do I draw a random image every render but still keep drawing the same random image until it leaves the screen. currently it is drawing the same image but I would like know how to draw a different pipe image every iter. Thank you My Iterator Iterator<Rectangle> upperIter = upperPipes.iterator(); while(upperIter.hasNext()) { Rectangle upperpipe = upperIter.next(); upperpipe.x -= 8 * Gdx.graphics.getDeltaTime(); if(upperpipe.x < -32) upperIter.remove(); My draw method public void drawPipes(){ batch.begin(); for(Rectangle upperPipe: Pipes.lowerPipes) { batch.draw(Assets.pipeImg, upperPipe.x, upperPipe.y, upperPipe.width, upperPipe.height); batch.end(); } A: SOLVED!! I created a custom pipe class and just created an array of pipes, each new pipe object that went into the array took a random image. I iterated through the array, and called the draw method on each pipe object. Simple and it works perfect
[ "wordpress.stackexchange", "0000365788.txt" ]
Q: Need help about understand api, wp, $ syntax in WordPress plugin script I really new in Wordpress development and have a little bit of knowledge of jquery. I was trying to understand a WordPress plugin and also trying to understand the js code they wrote for the plugin. I don't understand what does the following code mean. (function( api, wp, $ ) { 'use strict'; })( wp.customize, wp, jQuery ); what is api , wp and $ at the top and wp.customize , wp , jQuery at the bottom mean? A: It's an Immediately Invoked Function Expression (IIFE) - an anonymous function that executes itself after it has been defined. The variables at the bottom are taken from the global scope and are passed as parameters to the anonymous function. So api represents wp.customize, wp represents wp and $ represents jQuery inside the function.
[ "stackoverflow", "0029023013.txt" ]
Q: How to apply JS to user added rows in tabel I'm using rails to generate a form that allows the user to click a button to add a new row to a table. As of right now, the user can click the add button and a new row appears. The trouble I'm having is with a column that is using autoNumeric to mask percent values. The JS isn't applied to the columns that the user creates dynamically. I'm using classes so I'm confused why the autoNumeric masking isn't being applied to the new rows as the user is adding them. The 'percentage' class is working on other parts of the form. # JS $(function() { $('.percentage').autoNumeric('init', {aSign: '%', pSign: 's'}); }); # the field is set to the proper class <tr class="fields"> <td><input class="percentage" placeholder="Equity %" type="text"></td> </tr> # link that adds a new row <a class="add_nested_fields" data-association="business_contacts" data-blueprint-id="business_contacts_fields_blueprint" data-target="#business_contacts" href="javascript:void(0)">Add a field</a> Each row that is added has class="fields" on it. I have tried JS's onClick but didn't get successful results. A: When your JS is run after the page load, the autoNumeric is called on all DOM elements present at the moment with .percent class. But when you add a new row, you ll need to call autoNumeric on it again. Eg: Function addRow(){ $.('.container').append(this.$row); $.('.percent').autoNumeric();} Or you can share ur js code so I can help better. $.('.add_nested_fields').click(function()$.('.percent').autoNumeric();}) Edit: solution found by the questioner @Questifier $(function() { $(document).on('nested:fieldAdded', function(event){ $('.percentage').autoNumeric('init', {aSign: '%', pSign: 's'}); })}); works perfectly. I read more about the gem after you asked me. Copy that code and make it your answer if you would like- thank you for the help.
[ "stackoverflow", "0059589330.txt" ]
Q: cpp class size with virutal pointer and inheritance class A{ virtual void a(); }; class B : A{ virtual void a(); }; class C{ virtual void a(); }; class E : A, C{ virtual void a(); }; int main(){ std::cout << (sizeof(B)) << "\n"; // 4 std::cout << (sizeof(C)) << "\n"; // 4 std::cout << (sizeof(E)) << "\n"; // 8 } in 32 bits system linux why sizeof(B) and sizeof(C) are both 4 for class C, it has a virtual function, so there is a virtual pointer hidden in class c which is 4 bytes but why class B's size is also 4. I think it exists two pointers in class B, one is for B itself since class B has a virtual function, one is for A. Then same problem for E? any help is appreciated A: No, there is only one vtable pointer in every object which uses virtual functions, independently if the virtual function was defined in the class itself or the class derives from another class which uses virtual functions. What the compiler generates is a table of function pointers, so that every class ( not instance/object ) has its own. In your example you have a table for class A, one for class B and so on. And in every object/instance you have a vtable pointer. This pointer points only to the table. If you call a virtual function via class pointer, you have the indirection over the vtable pointer and than over the vtable itself. As a result every instance of a class keeps only a single vtable pointer, pointing to the vtable for this class. As you can see, this results in the same size for every instance of every class you wrote. In the case of multiple inheritance, you will get multiple vtable pointers. A more detailed answer is already given here: vtable and multiple inheritance BTW: That you have a vtable and a vtable pointer is not guaranteed from the standards, every compiler can do what it want if the result is what we expect from the semantic. But the double indirection via vtable pointer to pointer in the table to the function is the typical implementation.
[ "stackoverflow", "0044870820.txt" ]
Q: HTML5 video: changing video src makes the page unresponsive I have a video element which i'm changing it's src attribute dynamically. After 6 different videos the page becomes unresponsive. I'm using flowplayer and angular if this makes any different. Does anyone know what happens and what is the best practice of loading new sources? This is the current code: <video autobuffer crossOrigin="anonymous" id="videoplayer"></video> var video = document.getElementById('videoplayer'); video.pause(); video.src = '/path/to/new/src/' video.load(); Thanks! A: Rather than changing src, create and delete element. It will work
[ "stackoverflow", "0053289464.txt" ]
Q: How to log game objects colliding in Unity This is my first unity project so I am fairly unfamiliar with everything the platform has. I am trying to log a message to the console when I have a my player game object run into a finish line. Both objects have Box Colliders on them and I have attached a C# script to the player object. Below is the code I have currently. void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.tag == "Finish") { Debug.Log("Finish"); } } The problem is that when I move the player into the "Finish" object no logging appears inside the console. Thanks in Advance! This is the main player inspector tab This is the finish line inspector tab A: Your script attached to the player checks for a collision with an object with the tag "Finish". Your Object "Finish Line" has tag "untagged". You have to add a tag "Finish" to it to see it working.
[ "stackoverflow", "0017916235.txt" ]
Q: Loading fields with respect to select box content I have a JSP page and in that I am using Struts2 tags for making my registration form. Now the first field is type which uses s:select tag. Now, depending on what is selected by the user I want to load next texfields on the same page below the select box. How can I do it? Here is my approach but it's not working. <s:form action="clientAction" method="post"> <s:select name="type" label="Registration Type" list="{'Student','Faculty'}" emptyOption="false" /> <s:if test="type.equals(Student)"> <s:textfield label="FirstName" name="s_fname"/> <s:textfield label="LastName" name="s_lname"/> <s:textfield label="UserName" name="s_username"/> <s:password label="Password" name="s_password"/> <s:textfield label="EmailId" name="s_email_id"/> </s:if> <s:if test="type.equals(Faculty)"> <s:textfield label="FirstName" name="fac_fname"/> <s:textfield label="LastName" name="fac_lname"/> <s:textfield label="UserName" name="fac_username"/> <s:password label="Password" name="fac_password"/> <s:textfield label="EmailId" name="fac_email"/> <s:textfield label="Course Name" name="course_name"/> <s:textfield label="Course Id" name="course_id"/> </s:if> <s:submit/> </s:form> A: You could do it with JQuery, and you don't need to load fields from the server, as well as mess up JavaScript code with JSP code. You should use css_xhtml theme to hide/show fields on change event of select box. Like in this example <s:form action="clientAction" method="post" theme="css_xhtml"> <s:select id="RegistrationType" name="type" label="Registration Type" list="{'Student', 'Faculty'}" emptyOption="false" /> <s:div id="Student" cssStyle="display: none;"> <s:textfield label="FirstName" name="s_fname"/> <s:textfield label="LastName" name="s_lname"/> <s:textfield label="UserName" name="s_username"/> <s:password label="Password" name="s_password"/> <s:textfield label="EmailId" name="s_email_id"/> <s:submit/> </s:div> <s:div id="Faculty" cssStyle="display: none;" > <s:textfield label="FirstName" name="fac_fname"/> <s:textfield label="LastName" name="fac_lname"/> <s:textfield label="UserName" name="fac_username"/> <s:password label="Password" name="fac_password"/> <s:textfield label="EmailId" name="fac_email"/> <s:textfield label="Course Name" name="course_name"/> <s:textfield label="Course Id" name="course_id"/> <s:submit/> </s:div> </s:form> <script type="text/javascript"> $(document).ready(function(){ $('#RegistrationType').change(function(){ $('#'+this.value).css('display', 'block'); if (this.value=='Student') $('#Faculty').css('display', 'none'); else $('#Student').css('display', 'none'); }); }); </script>
[ "stackoverflow", "0019455936.txt" ]
Q: Adding Fields To Devise Sign Up Using Rails 4 To start off, I'm new to rails, so I'm still getting the hang of things. I'm attempting to add two fields to the Devise sign up page, a first name field and a last name field. I've gone ahead and changed the view and the controller in order to attempt this. They look like this: Controller: class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :configure_devise_permitted_parameters, if: :devise_controller? protected def configure_devise_permitted_parameters registration_params = [:firstName, :lastName, :email, :password, :password_confirmation] if params[:action] == 'update' devise_parameter_sanitizer.for(:account_update) { |u| u.permit(registration_params << :current_password) } elsif params[:action] == 'create' devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(registration_params) } end end end View: <h2>Sign up</h2> <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> <%= devise_error_messages! %> <div><%= f.label :email %><br /> <%= f.email_field :email, :autofocus => true %></div> <div><%= f.label :password %><br /> <%= f.password_field :password %></div> <div><%= f.label :password_confirmation %><br /> <%= f.password_field :password_confirmation %></div> <div><%= f.label :firstName %><br /> <%= f.fName_field :firstName %></div> <div><%= f.label :lastName %><br /> <%= f.lName_field :lastName %></div> <div><%= f.submit "Sign up" %></div> <% end %> <%= render "devise/shared/links" %> However, I get this error when I go to view the page: undefined method `fName_field' for #<ActionView::Helpers::FormBuilder:0x00000003c89940> Where must I define those methods? or are they automatically defined somewhere else? Thanks for any help. A: With "f.something" you can just define the type of the field in the form. Try something like <%= f.text_field :lastName %> This should work. You can read about the available types of fields here: http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for
[ "stackoverflow", "0044804021.txt" ]
Q: iPhone 6s not connecting to mac osx Sierra on Vmware I am trying to connect my iPhone 6s (10.3.2) to mac osx Sierra (10.13) running on Vmware. I have changed the USB controller to USB 2.0 and have enabled all three options. Vmware sees Apple iPhone in devices list, but without any success once I am pressing Connect (Disconnect from Host). Moreover, once I unplug my iPhone from USB cable, it restarts. This behavior happens each time I try to connect it to mac osx (on vmware). Has anyone come across with this strange behavior, and if so, did you find any solution? Thanks. A: I cannot agree with the selected answer as using Windows 10, VMware 12.5.7 with High Sierra 10.3, iPhone 5s with iOS 11.0.3 and a generic cable it recognizes the device. See the images below. However, it did not work with Ubuntu 16.04, VMware 12.1.1 (also 12.5), Sierra 10.12.6 (also High Sierra 10.13), and the same iPhone. I am not sure if it is Ubuntu compatibility issue with VMware/MacOS/iOS. If someone knows, please let us know. Tip for Windows 10: 1. Scroll to the right and type 'Power Options' in the search field and click on it. 2. Click 'Change plan setting' on your chosen plan. 3. Click 'Change advanced power setting' on your chosen plan. 4. Find 'USB settings' and open. 5. Find 'USB selective suspend setting' and change it to disabled. In VMware: - Change USB settigns from 3.0 to 2.0. Also select 'Show all devices'. A: It works, however you need to edit your .vmx file. When connecting your iDevice to the host, write down it's vendor id and product id. Then open your virtual machine's .vmx file, and add the following line: usb.quirks.device0 = "0xvid:0xpid skip-reset, skip-refresh, skip-setconfig" Replace vid and pid with the digits of the values of your device. Then reboot your VM, focus on the VM and connect your iDevice.
[ "stackoverflow", "0038547325.txt" ]
Q: Write recursive data in excel from python list I have a list of webpages called: html in each and every html(i) element I extracted emails addresses. I put these emails addresses in the list: email I want to generate an excel file like this: in order to write down on an excel file all the emails addresses I found. Since each html(i) page may contain a different number of emails addresses, I would like to write a code to take into account the different number of emails found per page, automatically. My idea was something similar to this: #set the standard url to generate the full list of urls to be analyzed url = ["url1","url2", "url3", "url-n"] #get all the url pages' html codes for i in range (0,len(url): html=[urllib.urlopen(url[i]).read() for i in range(0,len(url)) ] #find all the emails in each html page. for i in range (0,len(url): emails = re.findall(r'[\w\.-]+@[\w\.-]+', html[i]) #create an excel file wb = Workbook() #Set the excel file. for i in range (0,len(html)): for j in range (0, len(emails)): sheet1.write(i, j, emails[j]) wb.save('emails contact2.xls') Of course is not working. It only writes the email addresses contained in the last element of list html. Any suggestions? A: import xlwt wb = Workbook() sheet1 = wb.add_sheet("Sheet 1") htmls = generate_htmls() #Imaginary function to pretend it's initialized. for i in xrange(len(htmls)): sheet1.write(i, 0, htmls[i]) emails = extract_emails(htmls[i]) #Imaginary function to pretend it's extracted for j in xrange(len(emails)): sheet1.write(i, j + 1, emails[i]) Assuming you extract the list emails for each html separately, this code puts the html in the 1st (index 0) column, then puts all the emails in the index + 1 (to not overwrite the first column).
[ "parenting.stackexchange", "0000021820.txt" ]
Q: My son did badly in his AS levels because he didn't work Asking this for someone else. Their son did really badly in their AS levels, as he didn't work. He did amazingly in GCSE, and had 2A*s, 7As a B and a C. They could have done so much better. However, this made him complacent and the 12 week break made him demotivated and not work throughout the entire year. Anyway, he got a B in biology, an E in chemistry, an E in maths and a D in physics. He could have done so much better. Now the parents aren't sure what to do. They have several options, with lots of pros and cons for each Also, he wants to drop biology, as he hates it. He refuses to carry on with biology as the exam was really easy, and apparently it was a fluke. Option 1: Retake the year at same school. (so do year 12 again) Pros: Can scrap poor AS results and start again. Government Funded University Cons: The new A-Levels seem horrible. The year below are not a very good year, with poor results and lots of not very nice people (chavs) Would lose current friends a year down the line when they go to university. Option 2: Retake the year at another school Pros: Fresh Start Has a good chance of going to university (long term goal) Will improve social life, and makes new friends. Cons: Risk of not making friends (slightly socially awkward as bullied at school). Gambling if school will be right, as no time for open days. Social side holding them back. There is a risk of not settling in well. Option 3: Retake AS papers and do A2 at same time Pros: Only take a year No losing friends Cons: Less social life (there is a higher chance of having new friends at a new school, and going to parties and things) Increased workload (doubled) High risk of not passing and not getting into university. Will get no offers and will have to apply through clearing for university. Are there any other plausible options? I have listed the first three options they have thought of. Note: The son does not want to go to college. He has no idea what to do either. He needs AAB for university in the total A-Level. They're in West Kent, in England. Edit: I'm what this question is about ;) I haven't taken drugs I just think I just let my social life take over my work life A: Retake year 12 at the same school. Hopefully this will have woken him up to the merits of dossing. He doesn't need to lose his current friends, but then again he will see them less in lessons and that may not be a bad thing. There needs to be a cost to him of doing this, and if he bears that cost he will have learned a great life lesson. He will still see his friends outside of lessons, and if the new crowd is a bad year that'll help him greatly. Practically, for his future desires (he wants to go to uni in the UK) he needs to retake yr 12. Going to another school means maybe not seeing his friends much at all, and that can be isolating at a time when he needs to also process his own failure.
[ "stackoverflow", "0026741659.txt" ]
Q: How do you get access to environment variables via Elasticbeanstalk configuration files (using Docker)? For example, if I wish to mount a particular volume that is defined by an environment variable. A: I ended up using the following code: --- files: "/opt/elasticbeanstalk/hooks/appdeploy/pre/02my_setup.sh": owner: root group: root mode: "000755" content: | #!/bin/bash set -e . /opt/elasticbeanstalk/hooks/common.sh EB_CONFIG_APP_CURRENT=$(/opt/elasticbeanstalk/bin/get-config container -k app_deploy_dir) EB_SUPPORT_FILES_DIR=$(/opt/elasticbeanstalk/bin/get-config container -k support_files_dir) # load env vars eval $($EB_SUPPORT_FILES_DIR/generate_env | sed 's/$/;/')
[ "stackoverflow", "0037160945.txt" ]
Q: Issue with AWS cognito sample app I am trying to run this AWS cognito sample app from https://github.com/awslabs/aws-sdk-ios-samples/tree/master/CognitoSync-Sample/Swift. I can add new data set but as soon as i try to sync/refresh i get this below error. I am not trying with any provider. Just simple sync of data. And Here is the steps i did - 1.Downloaded the sample app from github. 2.Installed AWSCognito using pod as given 3.And Created a identity pool in Amazon cognito console 4.and updated the constants in Constants.swift - static let COGNITO_REGIONTYPE = AWSRegionType.USEast1 static let COGNITO_IDENTITY_POOL_ID = "us-east-1_XXXXXXXXX" Here is the error from my console - 2016-05-11 15:43:49.643 CognitoSyncDemo[18352:6625488] AWSiOSSDKv2 [Debug] AWSCognitoSQLiteManager.m line:179 | __51-[AWSCognitoSQLiteManager initializeDatasetTables:]_block_invoke | sqlString = 'INSERT INTO CognitoMetadata(Dataset,ModifiedBy,IdentityId) VALUES (?,?,?)' 2016-05-11 15:43:49.643 CognitoSyncDemo[18352:6625488] AWSiOSSDKv2 [Debug] AWSCognitoSQLiteManager.m line:282 | __53-[AWSCognitoSQLiteManager loadDatasetMetadata:error:]_block_invoke | query = 'SELECT LastSyncCount, LastModified, ModifiedBy, CreationDate, DataStorage, RecordCount FROM CognitoMetadata WHERE IdentityId = ? and Dataset = ?' 2016-05-11 15:43:49.647 CognitoSyncDemo[18352:6625968] AWSiOSSDKv2 [Verbose] AWSURLRequestSerialization.m line:103 | -[AWSJSONRequestSerializer serializeRequest:headers:parameters:] | Request body: [{"IdentityPoolId":"us-east-1_1kBTIfzWu"}] 2016-05-11 15:43:50.942 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Debug] AWSURLResponseSerialization.m line:74 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response header: [{ Connection = close; "Content-Length" = 218; "Content-Type" = "application/x-amz-json-1.1"; Date = "Wed, 11 May 2016 10:13:50 GMT"; "x-amzn-ErrorMessage" = "1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+"; "x-amzn-ErrorType" = "ValidationException:"; "x-amzn-RequestId" = "0ec70838-1761-11e6-91c2-e77b976ab658"; }] 2016-05-11 15:43:50.942 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Verbose] AWSURLResponseSerialization.m line:79 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response body: [{"__type":"ValidationException","message":"1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+"}] 2016-05-11 15:43:50.943 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Error] AWSIdentityProvider.m line:185 | __51-[AWSAbstractCognitoIdentityProvider getIdentityId]_block_invoke169 | GetId failed. Error is [Error Domain=com.amazonaws.AWSCognitoIdentityErrorDomain Code=0 "(null)" UserInfo={__type=ValidationException, message=1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+}] 2016-05-11 15:43:50.943 CognitoSyncDemo[18352:6625968] AWSiOSSDKv2 [Verbose] AWSURLRequestSerialization.m line:103 | -[AWSJSONRequestSerializer serializeRequest:headers:parameters:] | Request body: [{"IdentityPoolId":"us-east-1_1kBTIfzWu"}] 2016-05-11 15:43:52.168 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Debug] AWSURLResponseSerialization.m line:74 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response header: [{ Connection = close; "Content-Length" = 218; "Content-Type" = "application/x-amz-json-1.1"; Date = "Wed, 11 May 2016 10:13:51 GMT"; "x-amzn-ErrorMessage" = "1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+"; "x-amzn-ErrorType" = "ValidationException:"; "x-amzn-RequestId" = "0f7792fc-1761-11e6-9ad4-59d8bf47e69e"; }] 2016-05-11 15:43:52.168 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Verbose] AWSURLResponseSerialization.m line:79 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response body: [{"__type":"ValidationException","message":"1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+"}] 2016-05-11 15:43:52.168 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Error] AWSIdentityProvider.m line:185 | __51-[AWSAbstractCognitoIdentityProvider getIdentityId]_block_invoke169 | GetId failed. Error is [Error Domain=com.amazonaws.AWSCognitoIdentityErrorDomain Code=0 "(null)" UserInfo={__type=ValidationException, message=1 validation error detected: Value 'us-east-1_1kBTIfzWu' at 'identityPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w-]+:[0-9a-f-]+}] 2016-05-11 15:43:52.169 CognitoSyncDemo[18352:6626097] AWSiOSSDKv2 [Error] AWSCognitoService.m line:176 | __36-[AWSCognito refreshDatasetMetadata]_block_invoke147 | Unable to list datasets: Error Domain=com.amazon.cognito.AWSCognitoErrorDomain Code=-4000 "(null)" What am i missing? I am very new to AWS services, any guidance would be much appreciated. Thanks, Richa A: I was using user pool id instead of identity pool id. Its resolved now.
[ "stackoverflow", "0030327289.txt" ]
Q: Write and display automatically generated html code I am generating html code out of a python list. import webbrowser food_list = [(u'John Doe', 1.73),(u'Jane Doe', 1.73), (u'Jackie O', 1.61)] def print_html(lista): print '<table>' for i in food_list: print '<tr>' print '<td>'+str(i[0]) +'</td>''<td>'+str(i[1])+'</td>' print '</tr>' print' </table>' code = print_html(food_list) print code h = open('list.html','w') h.write(code) h.close() webbrowser.open_new_tab('list.html') I cannot write "code" to an html file for displaying it. Error message: h.write(code) TypeError: expected a character buffer object I would prefer not to hardcode the html code. It must be so simple that I cannot figure it out. Thanks for the suggestion. A: You are not returning anything so you are trying to write None, do the writing in the function passing the filename and the list: def write_html(lista,f): with open(f, "w") as f: f.write('<table>') for i in lista: f.write('<tr>') f.write('<td>'+str(i[0]) +'</td>''<td>'+str(i[1])+'</td>') f.write( '</tr>') f.write('</table>') write_html(food_list,"list.html") webbrowser.open_new_tab('list.html') Output: John Doe 1.73 Jane Doe 1.73 Jackie O 1.61 You can concatenate and then write but if your goal is to just write it is easier to write as you iterate over the list. If you run your code you will see the return value at the end: In [27]: print pri print print_html In [27]: print print_html(food_list) <table> <tr> <td>John Doe</td><td>1.73</td> </tr> <tr> <td>Jane Doe</td><td>1.73</td> </tr> <tr> <td>Jackie O</td><td>1.61</td> </tr> </table> None # what you are trying to write You could also from __future__ import print_function and use print to write to the file: def write_html(lista,f): with open(f, "w") as f: print('<table>',file=f) for i in lista: print('<tr>',file=f) print('<td>'+str(i[0]) +'</td>''<td>'+str(i[1])+'</td>',file=f) print( '</tr>',file=f) print(' </table>',file=f) Or use the python2 syntax: def write_html(lista,f): with open(f, "w") as f: print >>f, '<table>' for i in lista: print >>f,'<tr>' print >>f, '<td>'+str(i[0]) +'</td>''<td>'+str(i[1])+'</td>' print >>f, '</tr>' print >>f,' </table>'
[ "stackoverflow", "0006165828.txt" ]
Q: How do I get the current screen cursor position? My objective is to get current position on the screen (out side the form), and save X, Y coords by press "C" for example. I google and found some suggestion to use api hooks, but i wonder are there a way we can do this task purely in C# code (.NET Lib) ? Please give me quick sample if possible because im new to c#. Thanks A: Just use: Cursor.Position or Control.MousePosition To get the position. You can then map the KeyPress event of the form: private void Form1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 'c') MessageBox.Show(Cursor.Position.ToString()); } The individual X and Y coordinates are two properties of the Position object. Documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.position.aspx