text
stringlengths
15
59.8k
meta
dict
Q: Java serialization, Kryo and the object graph Lets say I have an array arr of objects of type A in memory, each of which has a reference field pointing to the same object B. Illustration: A_1 A_2 A_3 ... A_N | | | | | | V | \--->\--> B <-----/ Note that the reference field in every object of type A points to the same object of type B. Now, I serialize the array arr containing objects of type A to an ObjectOutputStream. I then deserialize the bytes obtained in this way. I get a new array arr1. 1) Does the array arr1 have objects of type A such that they all point to the same object of type B? (I don't mean the same object before serialization, but a unique newly created object of type B) 2) In other words, does calling serialize/deserialize in Java retain the same object graph as it was before serialization? (i.e. is the newly deserialized object graph isomorphic to the old one) 3) Where is this documented? (i.e. please provide a citation) 4) The same questions 1-3, but applied to the Kryo serialization framework for Java. Thank you. A: http://docs.oracle.com/javase/6/docs/api/java/io/ObjectOutputStream.html The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written. As for my understanding of the specification, you get shared object references if the object instances to be shared go throught the same ObjectOutputStream. So when you serialize the class containing the arr array, each object written gets an ID, and for each reference that passes through the stream, only that ID is written. The deserialized graph in that case remain homogeneous with the original graph. I am sorry but I cannot help with krio library own serialization mechanism, I would be very happy to learn from someone who used it as well. EDIT about kryo: Some documentation I found: * *By default, each appearance of an object in the graph after the first is stored as an integer ordinal. This allows multiple references to the same object and cyclic graphs to be serialized. This has a small amount of overhead and can be disabled to save space if it is not needed: kryo.setReferences(false); *This (github) is the contract of the reference resolver; two implementation are given: ArrayList-based for small objects graphs, Map-based for larger ones *This is implementation of the default object array (de)serializer *Classes need to be registered for (de)serialization; each registered class can be coupled with a serializer (among which, the default Java serialization mechanism)
{ "language": "en", "url": "https://stackoverflow.com/questions/12446847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Why does atom's node version differ from apm's node version? I feel like this is causing my atom packages (terminal-plus) node-gyp problems (version mismatch expected xx, got xx) $ atom -v Atom : 1.11.0 Electron: 0.37.8 Chrome : 49.0.2623.75 Node : 5.10.0 $ apm -v apm 1.12.5 npm 3.10.5 node 4.4.5 python 2.7.12 git 2.10.0 A: Electron has it's own embedded version of Node that's distinct from whatever Node version you have installed on your system. atom -v displays Node version in Electron, while apm -v probably just displays the Node version you've installed. This is why native Node modules have to be rebuilt to target the specific version of Electron they're used in.
{ "language": "en", "url": "https://stackoverflow.com/questions/39987211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Append Next Line to Current Line I am struggling to find a way to append the next line to the current line if the timestamp matches. Here is my code so far: open(FH, "error_log:); @data = <FH> foreach $line (@data) { if ( ($line =~ /notice/)) { $line =~ s/ /,/g; my @L1 = split(/|notice|\[|\]|,mpmstats:,|\t|rdy,|bsy, +|rd,|wr,|ka,|log,|dns,|cls,|bsy:,|in,|/, $line); $line =~ s/|notice|\[|\]|,mpmstats:,|\t|rdy,|bsy,|rd,| +wr,|ka,|log,|dns,|cls,|bsy:,|in,//g; print $line; Note that I printed only to see the output. Output is the following: Wed,Jun,13,10:40:35,2012,758,42,0,29,11,0,0,2 Wed,Jun,13,10:40:35,2012,29,mod_was_ap22_http.c Wed,Jun,13,10:41:35,2012,761,39,0,34,5,0,0,0 Wed,Jun,13,10:41:35,2012,34,mod_was_ap22_http.c Wed,Jun,13,10:42:35,2012,769,31,0,22,6,0,0,3 Wed,Jun,13,10:42:35,2012,22,mod_was_ap22_http.c Wed,Jun,13,10:43:35,2012,754,46,0,29,17,0,0,0 I would like the number (29 on the 2nd line) placed in csv form after the others on the first line corresponding to the timestamp. THe rest of the line can be deleted. If the line has nothing below (ex. last line) I would like to append a zero. Thank you for your help. Here is a part of the input data as requested: [Wed Jun 13 01:41:24 2012 [error [client 10.119.84.9 File does not exist: /ebiz/b2b/IHS70prd/htdocs/offline.b2bonline.html [Wed Jun 13 01:41:25 2012 [error [client 10.119.84.9 File does not exist: /ebiz/b2b/IHS70prd/htdocs/offline.b2bonline.html [Wed Jun 13 01:41:25 2012 [error [client 10.119.84.8 File does not exist: /ebiz/b2b/IHS70prd/htdocs/offline.b2bonline.html [Wed Jun 13 01:41:28 2012 [error [client 10.119.116.8 File does not exist: /ebiz/b2b/IHS70prd/htdocs/offline.b2bonline.html [Wed Jun 13 01:41:28 2012 [error [client 10.119.84.8 File does not exist: /ebiz/b2b/IHS70prd/htdocs/offline.b2bonline.html [Wed Jun 13 01:41:34 2012 [notice mpmstats: rdy 786 bsy 14 rd 0 wr 11 ka 3 log 0 dns 0 cls 0 [Wed Jun 13 01:41:34 2012 [notice mpmstats: bsy: 11 in mod_was_ap22_http.c [Wed Jun 13 01:41:34 2012 [error [client 10.119.84.9 File does not exist: /ebiz/b2b/IHS70prd/htdocs/offline.b2bonline.html [Wed Jun 13 01:41:35 2012 [error [client 10.119.84.9 File does not exist: /ebiz/b2b/IHS70prd/htdocs/offline.b2bonline.html A: Your input is very strange. Usually, I see matched square brackets. That aside, what you want is something like this: # This assumes you have Perl 5.10 or autodie installed: failures in open, readline, # or close will die automatically use autodie; # chunks of your input to ignore, see below... my %ignorables = map { $_ => 1 } qw( [notice mpmstats: rdy bsy rd wr ka log dns cls bsy: in ); # 3-arg open is safer than 2, lexical my $fh better than a global FH glob open my $error_fh, '<', 'error_log'; # Iterates over the lines in the file, putting each into $_ while (<$error_fh>) { # Only worry about the lines containing [notice if (/\[notice/) { # Split the line into fields, separated by spaces, skip the %ignorables my @line = grep { not defined $ignorables{$_} } split /\s+/; # More cleanup s/^\[//g for @line; # remove [ from [foo # Output the line print join(",", @line); # Assuming the second line always has "in" in it, # but this could be whatever condition that fits your data... if (/\bin\b/) { # \b matches word edges, e.g., avoids matching "glint" print "\n"; } else { print ","; } } } close $error_fh; I did not compile this, so I can't guarantee that I didn't typo somewhere. The key here is that you do the first print without a newline, but end with comma. Then, add the newline when you detect that this is the second line. You could instead declare @line outside the loop and use it to accumulate the fields until you need to output them with the newline on the end. A: One way using perl. It omits lines that don't contain [notice. For each line matching it increments a variable and saves different fields in an array depending if it is odd or even (first ocurrence of [notice or the second one). perl -ane ' next unless $F[5] eq q|[notice|; ++$notice; if ( $notice % 2 != 0 ) { push @data, @F[0..4, 8, 10, 12, 14, 16, 18, 20, 22]; next unless eof; } push @data, (eof) ? 0 : $F[8]; $data[0] =~ s/\A\[//; printf qq|%s\n|, join q|,|, @data; @data = (); ' infile Assuming infile has content of your question, output would be: Wed,Jun,13,01:41:34,2012,786,14,0,11,3,0,0,0,11
{ "language": "en", "url": "https://stackoverflow.com/questions/11299004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PortAudio: short noise at start and end of sound I have piano-like application, and when I'm pressing piano key, it plays a sound. In my app I wrote my own sine wave generator. App is wrote in Qt. I think that problem is with portAudio, but I can't find any solution for this. I've recorded for you how my problem sounds: https://vocaroo.com/i/s1yiWjaJffTU And here is my generator class: soundEngine.h #ifndef SOUNDENGINE_H #define SOUNDENGINE_H #include <QThread> #include <math.h> #include "portaudio.h" #define SAMPLE_RATE (44100) #define FRAMES_PER_BUFFER (64) #define FREQUENCY 220 #ifndef M_PI #define M_PI (3.14159265) #endif #define TABLE_SIZE (200) typedef struct { float sine[TABLE_SIZE]; int phase; } paTestData; class SoundEngine : public QThread { Q_OBJECT public: bool turnOFF; void run(); static int patestCallback( const void *inputBuffer, void *outputBuffer,unsigned long framesPerBuffer,const PaStreamCallbackTimeInfo* timeInfo,PaStreamCallbackFlags statusFlags,void *userData ); void generateSine(); void removeSine(); private: paTestData data; PaStream *stream; PaError err; bool isPressed; }; #endif // SOUNDENGINE_H soundEngine.cpp #include "soundengine.h" #include <QDebug> void SoundEngine::run() { PaStreamParameters outputParameters; int i; double t; turnOFF = false; isPressed = false; static unsigned long n=0; for( i=0; i<TABLE_SIZE; i++, n++ ) { t = (double)i/(double)SAMPLE_RATE; data.sine[i] = 0; //data.sine[i] = 0.3*sin(2 * M_PI * FREQUENCY * t); /*data.sine[i] *= 1.0/2; data.sine[i] += 0.5*sin(2 * M_PI * (FREQUENCY+110) * t); data.sine[i] *= 2.0/3; data.sine[i] += (1.0/3)*sin(2 * M_PI * (FREQUENCY+60) * t); data.sine[i] *= 3.0/4; data.sine[i] += (1.0/4)*sin(2 * M_PI * (FREQUENCY+160) * t);*/ } data.phase = 0; err = Pa_Initialize(); if(err != paNoError) qDebug()<<"Błąd przy inicjalizacji strumienia:"<<Pa_GetErrorText(err); outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ if (outputParameters.device == paNoDevice) qDebug()<<"Błąd: Brak domyślnego urządzenia wyjścia!"; outputParameters.channelCount = 2; /* stereo output */ outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /*paNoFlag we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if(err != paNoError) qDebug()<<"Błąd przy otwieraniu strumienia:"<<Pa_GetErrorText(err); //err = Pa_StartStream( stream ); if(err != paNoError) qDebug()<<"Błąd przy starcie strumienia:"<<Pa_GetErrorText(err); while (turnOFF == false) { Pa_Sleep(500); } //err = Pa_StopStream( stream ); if(err != paNoError) qDebug()<<"Błąd przy zatrzymywaniu strumienia:"<<Pa_GetErrorText(err); err = Pa_CloseStream( stream ); if(err != paNoError) qDebug()<<"Błąd przy zamykaniu strumienia:"<<Pa_GetErrorText(err); Pa_Terminate(); } int SoundEngine::patestCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { paTestData *callData = (paTestData*)userData; float *out = (float*)outputBuffer; float sample; unsigned long i; (void) timeInfo; /* Prevent unused variable warnings. */ (void) statusFlags; (void) inputBuffer; for( i=0; i<framesPerBuffer; i++ ) { sample = callData->sine[callData->phase++]; *out++ = sample; /* left */ *out++ = sample; /* right */ if( callData->phase >= TABLE_SIZE ) callData->phase -= TABLE_SIZE; } return paContinue; } void SoundEngine::generateSine() { if(isPressed == false) { for(int i=0; i<TABLE_SIZE; i++) { data.sine[i] += 0.3*sin(2 * M_PI * 440 * ((double)i/(double)SAMPLE_RATE)); } isPressed = true; err = Pa_StartStream( stream ); } } void SoundEngine::removeSine() { err = Pa_StopStream( stream ); for(int i=0; i<TABLE_SIZE; i++) { data.sine[i] -= 0.3*sin(2 * M_PI * 440 * ((double)i/(double)SAMPLE_RATE)); } isPressed = false; } When I'm pressing button, function void SoundEngine::generateSine() is running - it generates sound. When I release the button, method void SoundEngine::removeSine() removes the sound. A: MODERATOR ATTENTION: This question seems to belong more to dsp.stackexchange than this forum. There's nothing wrong with either your sound or PortAudio. The sound you're hearing at the end is just the result of the audio being abruptly stopped. Take a look at the following image of a sound that has a constant amplitude through the entire duration. This sound will have an audible pop at the end. Conversely, if we attenuate the amplitude by modifying the waveform's envelope (the same sound as in image #1) so that it resembles the sound in image #2, we won't hear any abrupt change(s) in the sound at the end. In conclusion, if your goal is to completely eliminate the pops that you're hearing, fade out (or fade in) your sound(s).
{ "language": "en", "url": "https://stackoverflow.com/questions/47753325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel query latest record I've this query: I'm building a forum and I would like to show the latest message that has being posted. I'm doing that like this: return Forum::with(['users' => function($query){ $query->select('user.id', 'user.name', 'user.last_name') }]); forum model: /** * @return mixed */ public function users() { return $this->belongsToMany(User::class, 'message'); } How do I only receive the latest user. Right now I receive them all. Thanks a lot! A: public function users() { return $this->belongsToMany(User::class, 'message')->orderBy('id', 'desc'); } If you want to limit the number of users returned, append ->take(10); to take only last 10 users
{ "language": "en", "url": "https://stackoverflow.com/questions/42078761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get warnings when using 4.x only APIs when the base SDK is 3.x While i'm careful, there have been a few times when i have used iOS 4.x apis by mistake that have caused odd behaviour on the older devices. Is there anyway to get the compiler to flag their usage so i'm alerted when i have done so. Many thanks as always A: Unfortunately, there is no option in Xcode to warn you about an API that does not exists on your deployment target. However, there is a workaround to use the API: Class TheClass = NSClassFromString(@"NewerClassName"); if(TheClass != nil) { NewerClassName *newClass = [[NewerClassName alloc] init]; if(newClass != nil) { //Now, you can use NewerClassName safely } } This probably won't provide warnings for that API, but it will allow you to pass Apple's validation process.
{ "language": "en", "url": "https://stackoverflow.com/questions/4015399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.Net core - blank response when returning a JObject property I am using ASP.Net core 5.0 and want to return IEnumerable of an object as Action method response. Here is the response class: public class TestResponse { public int Id { get; set; } public string Name { get; set; } public Newtonsoft.Json.Linq.JObject PayLoad { get; set; } } This is my Action method: [HttpGet] public IEnumerable<TestResponse> TestRequest() { var testResponses = new List<TestResponse>(); testResponses.Add(new TestResponse { Id = 10, Name = "Name1", PayLoad = JObject.FromObject(new { Status = "Success", Message = "Working good, take care!"})}); testResponses.Add(new TestResponse { Id = 11, Name = "Name2", PayLoad = JObject.FromObject(new { Status = "Success", Message = "Working good, take care!" }) }); return testResponses; } When I run this, the response I see for PayLoad field is: [ { "id": 10, "name": "Name1", "payLoad": { "Status": [], "Message": [] } }, { "id": 11, "name": "Name2", "payLoad": { "Status": [], "Message": [] } } ] Why are the Status and Message fields blank? What am I missing? A: Please add package like below: <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.17" /> And your ConfigureServices method like below: public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews().AddNewtonsoftJson(); } And it works for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/72224818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: pysftp.Connection.get IOError: b35d5d74-ecb1-4a41-a9ed-5dde9b15960d Currently receiving an IOError: b35d5d74-ecb1-4a41-a9ed-5dde9b15960d when using sftp.Connection.get() I have the following code SFTP = pysftp.Connection( "xxx", username='xxx', password='xxx' ) filename = "foo" if SFTP.exists('data/{}'.format(filename)): SFTP.get('data/{}'.format(filename)) It passes the "if SFTP.exists('data/{}'.format(filename)):" line (and entering it in the console debugging returns True) so the file exists. The full error message is: File "C:\WinPython-32bit-2.7.6.3-20140407\python-2.7.6\lib\site-packages\pysftp.py", line 233, in get self._sftp.get(remotepath, localpath, callback=callback) File "C:\WinPython-32bit-2.7.6.3-20140407\python-2.7.6\lib\site-packages\paramiko\sftp_client.py", line 640, in get size = self.getfo(remotepath, fl, callback) File "C:\WinPython-32bit-2.7.6.3-20140407\python-2.7.6\lib\site-packages\paramiko\sftp_client.py", line 610, in getfo fr.prefetch() File "C:\WinPython-32bit-2.7.6.3-20140407\python-2.7.6\lib\site-packages\paramiko\sftp_file.py", line 396, in prefetch size = self.stat().st_size File "C:\WinPython-32bit-2.7.6.3-20140407\python-2.7.6\lib\site-packages\paramiko\sftp_file.py", line 239, in stat t, msg = self.sftp._request(CMD_FSTAT, self.handle) File "C:\WinPython-32bit-2.7.6.3-20140407\python-2.7.6\lib\site-packages\paramiko\sftp_client.py", line 649, in _request return self._read_response(num) File "C:\WinPython-32bit-2.7.6.3-20140407\python-2.7.6\lib\site-packages\paramiko\sftp_client.py", line 696, in _read_response self._convert_status(msg) File "C:\WinPython-32bit-2.7.6.3-20140407\python-2.7.6\lib\site-packages\paramiko\sftp_client.py", line 726, in _convert_status raise IOError(text) IOError: b35d5d74-ecb1-4a41-a9ed-5dde9b15960d
{ "language": "en", "url": "https://stackoverflow.com/questions/56779202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MSSQL mapping of uniqueidentifier Hibernate 5 My problem is that I have the following JPA entity: @Entity @Table(name = "keys") class Key( @Id @Column(name = "key_hash", length = 130, nullable = false) var keyHash: String, @Column(name = "external_id", nullable = true) var externalId: UUID? ) It works perfectly fine with Postgres, H2 etc. but the UUID mapping seems to be failing on SQL Server. With the following liquibase script: <changeSet id="keys" author="h311z"> <createTable tableName="keys"> <column name="key_hash" type="NVARCHAR(130)"> <constraints nullable="false"/> </column> <column name="external_id" type="uuid"> <constraints nullable="true"/> </column> </createTable> </changeSet> It seems like that Hibernate expects my UUID to be stored as binary(255) however, it is stored as uniqueidentifier. Is there a way to override this? If I run the liquibase migration first, then run my program I get the following exception: Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [external_id] in table [keys]; found [uniqueidentifier (Types#CHAR)], but expecting [binary(255) (Types#BINARY)] I have my own dialect for SQL Server which looks like this (using Kotlin but that shouldn't be a problem): class SQLServerUnicodeDialect : SQLServer2008Dialect() { init { registerColumnType(Types.CHAR, "nchar(1)"); registerColumnType(Types.LONGVARCHAR, "nvarchar(max)" ); registerColumnType(Types.VARCHAR, 4000, "nvarchar(\$l)") registerColumnType(Types.VARCHAR, "nvarchar(max)") registerColumnType(Types.CLOB, "nvarchar(max)" ) registerColumnType(Types.NCHAR, "nchar(1)") registerColumnType(Types.LONGNVARCHAR, "nvarchar(max)") registerColumnType(Types.NVARCHAR, 4000, "nvarchar(\$l)") registerColumnType(Types.NVARCHAR, "nvarchar(max)") registerColumnType(Types.NCLOB, "nvarchar(max)") registerColumnType(Types.VARBINARY, 4000, "varbinary($1)") registerColumnType(Types.VARBINARY, "varbinary(max)") registerColumnType(Types.BLOB, "varbinary(max)") } } I tried searching how to solve this but couldn't find anything. Even if I add the GUID type from Microsoft with registerColumnType it doesn't work. I want to support multiple databases (Postgres, SQLServer etc), so using entities with annotations like columnDefinition is not going to work. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/71563109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Tomcat 7 failed to start Web App and threw java.lang.RuntimeException: Illegal type for StackMapType: -89 I have a Web Apps that I built the jar file using JDK 1.7. I deployed it on Tomcat 7 and it threw this exception at start up. SEVERE: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/test]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1105) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1664) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) Caused by: java.lang.RuntimeException: Illegal type for StackMapType: -89 at org.apache.tomcat.util.bcel.classfile.StackMapType.setType(StackMapType.java:73) at org.apache.tomcat.util.bcel.classfile.StackMapType.<init>(StackMapType.java:65) at org.apache.tomcat.util.bcel.classfile.StackMapType.<init>(StackMapType.java:52) at org.apache.tomcat.util.bcel.classfile.StackMapEntry.<init>(StackMapEntry.java:55) at org.apache.tomcat.util.bcel.classfile.StackMap.<init>(StackMap.java:73) at org.apache.tomcat.util.bcel.classfile.Attribute.readAttribute(Attribute.java:145) at org.apache.tomcat.util.bcel.classfile.Code.<init>(Code.java:85) at org.apache.tomcat.util.bcel.classfile.Attribute.readAttribute(Attribute.java:126) at org.apache.tomcat.util.bcel.classfile.FieldOrMethod.<init>(FieldOrMethod.java:58) at org.apache.tomcat.util.bcel.classfile.Method.<init>(Method.java:72) at org.apache.tomcat.util.bcel.classfile.ClassParser.readMethods(ClassParser.java:268) at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:128) at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2101) at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1977) at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1943) at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1928) at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1322) at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878) at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119) at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5173) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 10 more I used a trial and error method and found out the jar file that I built for my app causes the issue. I searched Web and some one mentioned it could be related to version of Java compiled code and Java run time. A: After getting the hint from this post "http://marc.info/?l=tomcat-user&m=137183130517812&w=2 Christopher Schultz wrote: "I would expect this kind of thing if you used a current BCEL against a newer .class file generated for example by Java 8, which BCEL might not yet support (or at least the version Tomcat uses)." I checked the POM file and also project properties in Eclipse. I noticed even though I was using JDK 1.7 but Eclipse was compiling the code for 1.5 because I had forgot to set the correct compile settings at Project properties -> Java Compiler-> JDK Compliance I changed it from 1.5 to 1.7 and built the jar file, everything worked fine. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/21561080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: (Instagram API) Get the list of instagram users this user is followed by I want to get the list of instagram users this user is followed by.(but not for myself, for another user). I do API call GET https://api.instagram.com/v1/users/4234233244/followed-by.json?access_token=ACCESS_TOKEN like this /v1/users/user_id/followed-by.json?access_token=ACCESS_TOKEN But I receive following response {"meta":{"error_type":"APINotAllowedError","code":400,"error_message":"you cannot view this resource"}} Why? How can I do that? I set up follower_list permission scope(Actually all scopes scope=basic+follower_list+public_content+relationships+likes+comments). And He's not a private user, I think so ;). And my dev app is in Sandbox mode, and this user was added to to the Sandbox, so I can get his profile information. I know Deprecation of /users/USER-ID/follows and /users/USER-ID/followed-by But what should I do? I try to develop a great instagram client for tablet :) A: I dont think you can get other user's follower list/following list anymore. You can only get the list for the logged in user. Here is documentation: https://www.instagram.com/developer/endpoints/relationships/ https://api.instagram.com/v1/users/self/followed-by?access_token=ACCESS-TOKEN you can only get list for self, not any id A: List of users who your user follow : https://api.instagram.com/v1/users/self/follows?access_token=ACCESS-TOKEN List of users who your user is being followed by : https://api.instagram.com/v1/users/self/followed-by?access_token=ACCESS-TOKEN List of recent media from your user : https://api.instagram.com/v1/users/self/media/recent?access_token=ACCESS-TOKEN List of recent media from other users : https://api.instagram.com/v1/users/{user-Id}/media/recent?access_token=ACCESS-TOKEN More information at Instagram Endpoint Reference in left pane (below Endpints button) you will see a list of media types, each one corresponding to a page that explains all related api Interfaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/36265861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Python and Multi-Dimensional Array I'm relatively new to python so this has me scratching my head, probably because there's some concept that I have completely wrong about how this works in python. Basically, my goal is to have a multi-dimensional array/list that will consist of 3 elements - a day number, an interval number and a dictionary of data points. Within each day, there are 48 intervals, and each interval will have a single dictionary of data. What I'm having problems with is building the array the way that I want, but I cannot figure out how to make this work. Here is the relevant code. How would I assign the data to the array in the format I detailed above? Everything I try gives me an assignment error. Thanks appreciate any help! def get_intraday_data(start_date): for day in range(0, 7): if day == 0: num_rows = 49 else: num_rows = 48 for row in range(0, num_rows): if day == 0 and row <= settings.skip_row: interval = row elif day == 0 and row > settings.skip_row: interval = row - 1 elif day != 0: interval = row if day == 0 and row == settings.skip_row: pass else: daily_data['date'] = get_date(start_date, day) daily_data['interval'] = get_interval(day, row, interval) daily_data['forecast_calls'] = ( get_forecast_calls(day, row, interval)) daily_data['forecast_aht'] = get_aht(day, row, interval) daily_data['forecast_required'] = ( get_forecast_required(day, row, interval)) daily_data['calc_required'] = ( calc_required(daily_data['forecast_required'], daily_data['forecast_aht'])) daily_data['sched_open'] = ( get_sched_open(day, row, interval)) edit: I previously read the question Here, but that is for a two-dimensional list, not three...
{ "language": "en", "url": "https://stackoverflow.com/questions/34794833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using custom font in xaml I need to use custom font in xaml (c#). The font is not installed on the computer. If the font is in the application installed folder,then i can use it even if it is not installed (/Fonts/New12.ttf#New12) My problem is that the custom font is been created on the local computer and can't be in the installed folder. The problem is that i can't copy the ttf file to the application installed folder , and i don't know how to use custom font that is not on the application installed folder Is anyone have an idea ? A: Add the font to your project, change its Build Action to Content. Then just reference it inline or as part of a Style or BasedOn value like; <TextBlock FontFamily="/Fonts/New12.ttf#New12" Text="Check out my awesome font!" /> That should do it for you. A: I found the solution, For the FontFamily value you can write "ms-appdata:///local/MyFont.ttf#FontName" (where local is ApplicationData::Current->LocalFolder)
{ "language": "en", "url": "https://stackoverflow.com/questions/12752397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Filter GetRows on GoogleSheet Document via Logic Apps I am reading from a google sheet of 100,000+ records but I want to load only the records after a certain date. ( so applying filter ) . But I haven't been able to accomplish that as I do not know how to access the column name without using foreach. Here is what the data looks like from the googlesheet So basically, I would like to filter the records something like this. Timestamp ge '10/13/2021' so it will only return records for 10/13/2021 and 10/14/2021... etc. Is this possible to do that? If not, what is the best recommended way to approach this issue as i just wanted to load daily records to sql db in the next step. A: The Get rows action of the Google Sheets connector doesn't support filtering. You can only specify how many rows you want returned, and how many rows you want to skip. E.g. if you have 100,000 rows in your sheet, you can easily get the rows between 90,001 and 90,200, should you wish to do so. While you can't use this connector to retrieve filtered data from Google Sheets, you can use the Filter array action to filter the retrieved data as you wish. You might still need to use the For each loop to retrieve and filter data in chunks.
{ "language": "en", "url": "https://stackoverflow.com/questions/69578162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# convert ISO-8859-1 characters to entity number I can't seem to figure out how to convert ISO-8859-1 characters, such as é, to it's entity number being &#233;. I want to be able to take a string, such as: "Steel Décor" and have it converted to: "Steel D&#233;cor" A: Assuming you don't care about HTML-encoding characters that are special in HTML (e.g., <, &, etc.), a simple loop over the string will work: string input = "Steel Décor"; StringBuilder output = new StringBuilder(); foreach (char ch in input) { if (ch > 0x7F) output.AppendFormat("&#{0};", (int) ch); else output.Append(ch); } // output.ToString() == "Steel D&#233;cor" The if statement may need to be changed to also escape characters < 0x20, or non-alphanumeric, etc., depending on your exact needs. A: HttpUtility.HtmlEncode does that. It resides in System.Web.dll though so won't work with .NET 4 Client Profile for example. A: using LINQ string toDec(string input) { Dictionary<string, char> resDec = (from p in input.ToCharArray() where p > 127 select p).Distinct().ToDictionary( p => String.Format(@"&#x{0:D};", (ushort)p)); foreach (KeyValuePair<string, char> pair in resDec) input = input.Replace(pair.Value.ToString(), pair.Key); return input; }
{ "language": "en", "url": "https://stackoverflow.com/questions/4278371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Multiplying arrays in python I've done some tests on multiplying matrices in python using the numpy library. array1 = np.random.rand(100,100,100,100) array2 = np.random.rand(100,100,100,100) array_new1 = np.reshape(array1, (100*100, 100*100)) array_new2 = np.reshape(array2, (100*100, 100*100)) time1 = time.time() product = array1 * array2 time2 = time.time() time_tot1 = time2 - time1 time3 = time.time() product2 = array_new1 * array_new2 time4 = time.time() time_tot2 = time2 - time1 time5 = time.time() prod_einsm = np.einsum('abcd, abcd->abcd', array1, array2) time6 = time.time() time_tot3 = time6 - time5 time7 = time.time() prod_einsum2 = np.einsum('ab, ab-> ab', array_new1, array_new2) time8 = time.time() time_tot4 = time8 - time7 print time_tot1, time_tot2, time_tot3, time_tot4 In my real code, I'm working with higher dimensions and wondering how I might improve the performance. Undoubtedly, einsum is optimized well and works very fast. I also noticed the beneficial effect of using 2 dimension matrices instead 4. Is there anything else I could do? Maybe I should think of parallel programing? Any ideas and tips? ~
{ "language": "en", "url": "https://stackoverflow.com/questions/39432152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access ajax json input in restful webservice? I have an RESTful webservice that consumes a JSON response and I am making an ajax call to the web service as show below. When I am trying to invoke web service, I am getting 404 (Not Found) error. Please let me know what's the issue with my code. I searched for similar posts and I couldn't find an answer. AJAX code is: $('#addUser').click(function(){ var userDetails = getUserRegistrationFormInfo(); $.ajax ({ url: 'RestfulWS/rest/restful/addUser', contentType: 'applicaiton/json', type: "POST", data: userDetails, success: function (response) { // Success callback alert('Hey'); }}) }); function getUserRegistrationFormInfo(){ return JSON.stringify({ "userId": parseInt($('#userId').val()), "name": $('#userName').val(), "addressLine": $('#address').val(), "emaiId": $('#email').val() }); } }); And Restful web service code is: @POST @Path("/addUser") @Consumes("applicaiton/json") public Response addUser(User user){ //userMap.put(Integer.toString(user.getUserId()), user); userMap.put("123", user); return Response.ok().build(); } A: Check if there is a routing issue in your application. Try to access your REST URL from a web browser, developer console such as Firebug, or simply ping it. If you still get a 404, adjust the request URL to match your web service route, or fix the routing. Please note that the correct naming for the content type in this case is application/json. If this typo is also in your code, maybe start by adjusting it.
{ "language": "en", "url": "https://stackoverflow.com/questions/30280133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Installing mod_wsgi on WAMP server running on Windows 7 I downloaded mod_wsgi from the following location for apache 2.2 and python 2.7 (64bit). (I'm trying to get django to run on my computer). Whenever I add the following line: LoadModule wsgi_module modules/mod_wsgi.so Apache fails to start up. Can anyone tell me what the issue might be? A: These are the following things you need to do to setup Apache for Django. I assume you are using Python 2.7 (32-bit) on Windows (32-bit) with WAMP server (32-bits) installed. * *Download mod_wsgi-win32-ap22py27-3.3.so. Or download your respective .so compatible file *Change its name to mod_wsgi.so and copy it to /Program Files/Apache Software Foundation/Apache22/modules on Windows. *Open httpd.conf using Admin rights. Now, you will find a list of lines with LoadModule .... Just add LoadModule wsgi_module modules/mod_wsgi.so to that list. Your are partially done.. you can restart the apache and shouldn't find any errors. *Now you need to link it to your Django project. *In your Django project root folder, add apache folder and create django.wsgi (don't change this name) and apache_mydjango.conf. *In httpd.conf add the following line at the bottom of the page. Include "d:/projects/mysite/apache_django_wsgi.conf" Open django.wsgi and add the following lines: import os, sys sys.path.append('d:/projects/mysite') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() Open apache_djang_wsgi.conf and add: Alias /images/ "d:/projects/mysite/templates/images/" <Directory "d:/projects/mysite/images> Order allow,deny Allow from all </Directory> WSGIScriptAlias / "d:/projects/mysite/apache/django.wsgi" <Directory "d:/projects/mysite/apache"> Allow from all </Directory> <VirtualHost *:80> DocumentRoot d:/projects/mysite ServerName 127.0.0.1 </VirtualHost> Note: I am assuming your Django project hierarchy is something like this: mysite/ mysite/ settings.py urls.py, wsgi.py. manage.py <apache> / apache_django_wsgi.conf, django.wsgi Best tutorial links: * *port25.technet.com | Published my microsoft. *mod_wsgi Quick Install guide *Django site *Django site Actually I don't understand why people are unable to fix it. I've seen lots of questions on it here and I even posted few...So, I thought to write a initial setup version directly as answer A: Try the following websites for the unofficial windows binaries for python extensions http://www.kaij.org/blog/?p=123 https://github.com/kirang89/pycrumbs/pull/28 A: Just in case anyone is using this and doesn't spot it, there is an inconsistency in the steps. In Step 5 it refers to the filename apache_mydjango.conf In Step 6 it refers to the filename apache_django_wsgi.conf These should obviously both be the same name - it doesn't matter which way round you go for - but I spent a while trying to figure out why it wasn't working. A: Apart from Olly's correction, there is another error in Step6: Instead of Include "d:/projects/mysite/apache_django_wsgi.conf" it should be Include "d:/projects/mysite/apache/apache_django_wsgi.conf" I made all the steps and now can't start Apache Server anymore. The Wamp Image is red. I could restart Apache as described in Step 3. A: How I configured Apache + Django + venv For it to work you need 3 things: * *install mod_wsgi on python and apache *setup httpd.conf on apache *configure python script (usually wsgi.py) that is loaded by mod_wsgi and in turn loads your python app 1. Is described well enough in the official doc (I used the pip method). Just unpack apache distro (ApacheHaus worked for me, but not Apache Lounge, it missed some headers I think) to a standard place like C:\ or set env var MOD_WSGI_APACHE_ROOTDIR to its dir. You'll need Visual Studio Build Tools or binary distribution of mod_wsgi. Then pip install it. 2. In httpd.conf add: LoadFile ".../pythonXY/pythonXY.dll" LoadModule wsgi_module ".../mod_wsgi/server/mod_wsgi.cpXY-win_amd64.pyd" WSGIPythonHome ".../pythonXY" WSGIScriptAlias / "...\wsgi.py" Here LoadFile may be necessary if Python isn't installed the standard way. Better to include. WSGIPythonHome directive should point to main python distro (not venv as is usually said), because mod_wsgi may be somewhat not working properly. For instance now WSGIPythonPath is doing nothing at all. Alternatively, you can set PYTHONPATH or PYTHONHOME env vars accordingly. Now you can monitor error log of apache (inside its log folder by default). In case of failures apache will print mod_wsgi configuration (meaning it is installed, but couldn't start python) and/or python errors if it managed to start. 3. Inside your python script (wsgy.py) you'll need to provide function "application" (so is mod_wsgi usually compiled) which starts your app. But first point python to the modules and packages it will use, your own as well, right in the script with sys.path or site.addsitedir. Django's wsgi.py is good, just prepend all path conf there. A: Only for users running windows 64 versions. I have created wsgi. Now you only need to install python and run apache. The configurations have already been set in the package. Just download the package and follow the instructions from 'Steps to follow.txt file' present in package. You dont need to download python and apache and mod_wsgi.so from anywhere. I have compiled the so file, and compatible python and apache2 versions. So that you are ready to deploy. Just that in apache config the document root has been set to cgi-bin folder present inside Apache2. Package can be downloaded from Zip package Instructions and package usage
{ "language": "en", "url": "https://stackoverflow.com/questions/11602653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How do I present a View Controller and dismiss all others? I have about 20 View Controllers, chained together with Modal and Push segues. Now, at the last View Controller I want to switch back again to the first View Controller, as if the user has restarted the app. Unfortunately when I do this with [UIViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"InitViewController"]]; [self presentViewController:viewController animated:YES completion:nil]; all of the previous view controllers are not unloaded. Not a single viewDidUnload method is called. How can this be done? A: The instantiateViewController method creates a new copy of your view controller. Your existing view controllers aren't unloaded because iOS doesn't know that you want to 'go back', so to speak. It can't unload any of your existing view controllers because they're still in the navigation hierarchy. What you really want to do is 'rewind' your storyboard in some way. Fortunately from iOS 6 there's a much improved way to do this, through unwinding. This lets you 'backtrack' in your storyboard right back to the start, which it sounds like you want to do. The WWDC videos have some examples and walk throughs, and you might also want to look at this existing SO question: What are Unwind segues for and how do you use them? A: I found that it can be done easily by calling dismissViewControllerAnimated:completion: on the first view controller in the hierarchy. Fortunately that's all it is needed to accomplish what I wanted :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/14581538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to convert a date in Twig I'm trying to convert this: {{ "26/03/2013"|date("d/m/Y") }} in Twig but its is throwing the error Uncaught Exception: DateTime::__construct(): Failed to parse time string (26/03/2013) at position 0 (2): Unexpected character in /home/vagrant/Code/Phantom Website/vendor/twig/twig/lib/Twig/Template.php on line 218. If I pass this: {{ "03/26/2013"|date("m/d/Y") }} It works, so I imagine I need to change something related to Twigs date formatting A: The date filter is about formatting DateTime Object, so if you pass a string this will be passed to the constructor of the DateTime object then to the format method, so in your case, you need to format the string that looks good for a DateTime constructor as example {{ "2013-3-26"|date("d/m/Y") }} From the doc: The format specifier is the same as supported by date, except when the filtered data is of type DateInterval, when the format must conform to DateInterval::format instead. And also about string format: The date filter accepts strings (it must be in a format supported by the strtotime function), DateTime instances, or DateInterval instances. For instance, to display the current date, filter the word "now": Try this in this twigfiddle A: If you use /'s as delimiter the expected format is m/d/Y, To pass the date as day, month, year you need to use a - as delimiter {{ "26-03-2017" | date('d/m/Y') }} fiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/42556782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I get my dictionary to begin a new line when writing code to a file from a program? Here is my code sample, and below is an example of what I'm trying to do. Thank you in advance for the help. cards = {} import sys n = 0 while True: n += .01 cards[n] = {'name': str(input('Please enter name: ')), 'year': int(input('Please enter a year: ')), 'brand': str(input('Please enter a brand: ')), 'make': str(input('Please enter a make: ')), 'parallel': (input('parallel - Y OR N? ')), 'auto': (input('auto - Y OR N? ')), 'rookie_card': (input('rookie card - Y OR N? ')), 'numbered': (input('numbered - Y OR N? ')), 'card_num': input('Please enter a card number: '), } # 'parallel_type': # 'serial_num': print(cards) while True: choice = input('Press Y to continue or N to exit: ').capitalize() if choice == 'Y': break elif choice == 'N': print('Next input n = ', n) try: cards_file = open('cards_file.py', 'wt') cards_file.write(str(cards)) cards_file.close() except: print('Unable to write to file') sys.exit() else: print('Please enter a valid option!') This is what I am working with. Everytime my program writes onto the cards_file.py I want the dictionary to start a new line like so: cards = {1: {'name':'some_name', 'year': 'some_year', 'brand': 'brand'}, ------->{2: { -------------------new line of data---------------------} } A: Replace cards_file.write(str(cards)) With for k,v in cards.items(): cards_file.write(f'{k} : {v}\n')
{ "language": "en", "url": "https://stackoverflow.com/questions/65206181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Can we use builder to build Gtkapplication itself I am new with gtk. Can we use builder to build GtkApplication itself. using code like: <object class="GtkApplication"> A: Yes, but you'll need code that instantiates the GtkBuilder, gets the application object from it, and runs it. It's more usual to subclass GtkApplication in your code and override its virtual functions, and then inside your GtkApplication instantiate your GtkBuilder.
{ "language": "en", "url": "https://stackoverflow.com/questions/27015035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Branch.io link not showing image/thumb in Whatsapp I am creating a deep link using Branch.io in Android as explained in Branch docs, setting an image that I'd like to be the thumb for the link: BranchUniversalObject branchUniversalObject = new BranchUniversalObject() .setCanonicalIdentifier(IDENTIFIER) .setTitle("Link de Teste") .setContentDescription("This is just a test link.") .setContentImageUrl("https://image-link") .setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC) .addContentMetadata("key", value); LinkProperties linkProperties = new LinkProperties() .setFeature("sharing") .addControlParameter("$desktop_url", "http://example.com/home") .addControlParameter("$ios_url", "http://example.com/ios"); When I share the link with Facebook, the image appears correctly: Facebook sharing But when I share the link with Whatsapp, no image is displayed. Whatsapp sharing Any help? Thanks. A: Alex from Branch.io here: this should be working in WhatsApp, and I can confirm it does as expected with a test app on my end. I suspect WhatsApp doesn't like something about the image you're providing — could be the dimensions are wrong or unspecified. You could try our $og_image_height and $og_image_width params and take a look Facebook's open graph debug tool for any other errors. A: It worked for me, I just added $og_type, $og_image_width, $og_image_height and now it's working fine, I hope this can help you image implementation here
{ "language": "en", "url": "https://stackoverflow.com/questions/38961422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Mono error reading valid XML: "Read by order only possible for encoded/bare format" When reading this valid XML with Mono's System.Xml.XmlReader I get the following error: System.InvalidOperationException: Read by order only possible for encoded/bare format at System.Xml.Serialization.ClassMap.GetElement (Int32 index) [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadMembers (System.Xml.Serialization.ClassMap map, System.Object ob, Boolean isValueList, Boolean readBySoapOrder) [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadClassInstanceMembers (System.Xml.Serialization.XmlTypeMapping typeMap, System.Object ob) [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadClassInstance (System.Xml.Serialization.XmlTypeMapping typeMap, Boolean isNullable, Boolean checkType) [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadObject (System.Xml.Serialization.XmlTypeMapping typeMap, Boolean isNullable, Boolean checkType) [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadObjectElement (System.Xml.Serialization.XmlTypeMapElementInfo elem) [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadMembers (System.Xml.Serialization.ClassMap map, System.Object ob, Boolean isValueList, Boolean readBySoapOrder) [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadClassInstanceMembers (System.Xml.Serialization.XmlTypeMapping typeMap, System.Object ob) [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadClassInstance (System.Xml.Serialization.XmlTypeMapping typeMap, Boolean isNullable, Boolean checkType) [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadObject (System.Xml.Serialization.XmlTypeMapping typeMap, Boolean isNullable, Boolean checkType) [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadRoot (System.Xml.Serialization.XmlTypeMapping rootMap) [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadRoot () [0x00000] in <filename unknown>:0 at System.Xml.Serialization.XmlSerializer.Deserialize (System.Xml.Serialization.XmlSerializationReader reader) [0x00000] in <filename unknown>:0 What is the problem? What does Read by order only possible for encoded/bare format mean in the first place? Monodevelop 2.8.6.3 on Ubuntu 2012.04 running platform Mono / .NET 3.5 Mono JIT compiler 2.10.8.1 A: Mono crashes on <xsd:choice> See https://bugzilla.xamarin.com/show_bug.cgi?id=2907 A: I have posted the patch that fixes this problem. It is for trunk version (3.0.?). If you don't want to touch user's mono, you can simply copy new System.Xml.dll to folder where your program resides. Mono will use your dll instead of user's. The patch is attached to this bug: https://bugzilla.xamarin.com/show_bug.cgi?id=2907
{ "language": "en", "url": "https://stackoverflow.com/questions/11985337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing JSON in J2ME So, I've been trying for some time to parse this nested JSON string. If this was regular Java, or even php,I'm sure this would have been done long ago. Unfortunately I'm stuck with J2ME on this one. Through some searching I found that there exits a lone JSON parser. This I found through some digging on a similar question. I've tried some work on my own, with an example on another question. However, I'm still having a few difficulties. I will explain now. This is the JSON string I'm trying to parse: {"Result":"Success","Code":"200","CustomerInfo":"{\"clientDisplay\":{\"customerId\":429,\"globalCustNum\":\"0012-000000429\",\"displayName\":\"Hugo Daley\",\"parentCustomerDisplayName\":\"G-KINGSTON\",\"branchId\":12,\"branchName\":\"Bangalore_branch1244724101456\",\"externalId\":\"123000890\",\"customerFormedByDisplayName\":\"New User1244724101456\",\"customerActivationDate\":\"2012-06-17\",\"customerLevelId\":1,\"customerStatusId\":3,\"customerStatusName\":\"Active\",\"trainedDate\":null,\"dateOfBirth\":\"1950-10-10\",\"age\":61,\"governmentId\":\"100000090\",\"clientUnderGroup\":true,\"blackListed\":false,\"loanOfficerId\":17,\"loanOfficerName\":\"New User1244724101456\",\"businessActivities\":null,\"handicapped\":null,\"maritalStatus\":null,\"citizenship\":null,\"ethnicity\":null,\"educationLevel\":null,\"povertyStatus\":null,\"numChildren\":null,\"areFamilyDetailsRequired\":false,\"spouseFatherValue\":null,\"spouseFatherName\":null,\"familyDetails\":null},\"customerAccountSummary\":{\"globalAccountNum\":\"001200000001259\",\"nextDueAmount\":\"2128.0\"},\"clientPerformanceHistory\":{\"loanCycleNumber\":0,\"lastLoanAmount\":\"0.0\",\"noOfActiveLoans\":0,\"delinquentPortfolioAmount\":\"0.0\",\"totalSavingsAmount\":\"1750.0\",\"meetingsAttended\":0,\"meetingsMissed\":0,\"loanCycleCounters\":[],\"delinquentPortfolioAmountInvalid\":false},\"address\":{\"displayAddress\":null,\"city\":\"\",\"state\":\"\",\"zip\":\"\",\"country\":\"\",\"phoneNumber\":\"\"},\"recentCustomerNotes\":[{\"commentDate\":\"2012-06-17\",\"comment\":\"appr\",\"personnelName\":\"New User1244724101456\"}],\"customerFlags\":[],\"loanAccountsInUse\":[{\"globalAccountNum\":\"001200000001262\",\"prdOfferingName\":\"Hawker Loan\",\"accountStateId\":3,\"accountStateName\":\"Application Approved\",\"outstandingBalance\":\"15643.0\",\"totalAmountDue\":\"8977.0\"},{\"globalAccountNum\":\"001200000001279\",\"prdOfferingName\":\"Hazina Micro Loan\",\"accountStateId\":2,\"accountStateName\":\"Application Pending Approval\",\"outstandingBalance\":\"6439.0\",\"totalAmountDue\":\"1716.0\"},{\"globalAccountNum\":\"001200000001280\",\"prdOfferingName\":\"Car Finance\",\"accountStateId\":3,\"accountStateName\":\"Application Approved\",\"outstandingBalance\":\"381.5\",\"totalAmountDue\":\"120.0\"}],\"savingsAccountsInUse\":[{\"globalAccountNum\":\"001200000001260\",\"prdOfferingName\":\"Current Account\",\"accountStateId\":16,\"accountStateName\":\"Active\",\"savingsBalance\":\"1750.0\",\"prdOfferingId\":null}],\"customerMeeting\":{\"meetingSchedule\":\"Recur every 1 Week(s) on Monday\",\"meetingPlace\":\"KINGSTON\"},\"activeSurveys\":false,\"customerSurveys\":[],\"closedLoanAccounts\":[{\"globalAccountNum\":\"001200000001261\",\"prdOfferingName\":\"AUTO LOAN-2\",\"accountStateId\":10,\"accountStateName\":\"Cancel\",\"outstandingBalance\":\"2576.0\",\"totalAmountDue\":\"206.0\"}],\"closedSavingsAccounts\":[]}"} Don't worry this is just sample data, nothing real here. Now I require the Customers No, Name, Address, and Savings Account balance. This is the code I've used to parse it: public CustomerInfo(String jsonTxt) { try { JSONObject json = new JSONObject(jsonTxt); JSONObject customer = json.getJSONObject("CustomerInfo"); custNo = json.getString("globalCustNum"); custName = json.getString("displayName"); address = json.getString("DisplayAddress"); savAcctBal = json.getDouble("totalSavingsAmount"); } catch (final JSONException je) { je.printStackTrace(); } } This of course throws an JSONException. I've learned that the JSON Library may have a few bugs. I've done some tricks, with print statements. It turns out that it likes to consume the 1st element of the JSON string. This heavily screws up going through nested elements like we have here in the example. Is there an alternative I can use? A: Boy, do I want to shoot myself. I figured out my issue before I went to bed. My approach was correct; it was just a matter of me reading the output of Print statements wrong as well as underestimated just how nested the JSON was. Internally, the JSONOBject class stores the JSON elements, pairs, etc. in a Hashtable. The Hashtable has a side-effect where it will sort the data that's given to it. This of course through off how the JSON was ordered. I figured it was consuming some parts of the JSON, while it really was just putting them to the back...the waaay back if not the end of the JSON. This greatly through me off. I did not realise this until I just ran toString on the Hashtable itself. I then also realise that the JSON was actually more nested than I thought. The four parts I wanted to get, where in 3 different nested JSON objects. Thus, my solution was to save myself even more grief and just put the JSON through a pretty printer and looked and the structure properly. Here is my Solution code: public CustomerInfo(String jsonTxt) { try { JSONObject json = new JSONObject(jsonTxt); JSONObject customer = new JSONObject(json.getString("CustomerInfo")); JSONObject client = new JSONObject(customer.getString("clientDisplay")); custNo = client.getString("globalCustNum"); custName = client.getString("displayName"); JSONObject cph = new JSONObject(customer.getString("clientPerformanceHistory")); JSONObject caddress = new JSONObject(customer.getString("address")); address = caddress.getString("displayAddress"); savAcctBal = cph.getDouble("totalSavingsAmount"); } catch (final JSONException je) { je.printStackTrace(); } } protip: Always use a Pretty Printer on your JSON, and appreciate it's structure before you do anything. I swear this wont happen to me again. A: You can parse the JSON string by the following example public CustomerInfo(String jsonTxt) { try { JSONObject json= (JSONObject) new JSONTokener(jsonTxt).nextValue(); test = (String) json2.get("displayName"); } catch (JSONException e) { e.printStackTrace(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/11813146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Local variable ternary assignment in slim I have a slim partial like so: - name = (defined?(name) ? name : 'tags') - id = (defined?(id) ? id : ('input-' + name)) - label = defined?(label) ? label : nil - placeholder = defined?(placeholder) ? placeholder : nil - className = defined?(className) ? className : nil - prefetch = defined?(prefetch) ? prefetch : nil - displayKey = defined?(displayKey) ? displayKey : nil - valueKey = defined?(valueKey) ? valueKey : nil .input-container.tags - if label label for="#{id}" = label input type="text" id="#{id}" name="#{name}" placeholder="#{placeholder}" data-prefetch="#{prefetch}" data-displayKey="#{displayKey}" data-valueKey="#{valueKey}" When I use it (via ==render) and pass locals inside — everything is ok. But when I omit, for example, name - it is not assigning to default 'tags'. And the same is for id. They are simply empty. If I comment out assignments in the beginning — undefined variable error raises, as expected. What is wrong with assignments? A: You don't need slim. Just irb the code: name = (defined?(name) ? name : 'tags') p name #=> nil It does not work, because you implicitly define name on the left side of the statement name = .... So when Ruby interpreter evaluates defined?(name) it gives truly result. I think you already get the answer: unless defined?(name) name = 'tags' end or shorter: name ||= 'tags'
{ "language": "en", "url": "https://stackoverflow.com/questions/32572224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: PyQt5 Maya 2017 Having some trouble setting up PyQt5 with Maya 2017. I have successfully installed PyQt5 on my mac and I can write standalone applications, but when I try to import PyQt5 modules in the Maya Script Editor using (for example) from PyQt5 import QtWidgets I get the following error : Error: line 1: ImportError: file <maya console> line 1: No module named PyQt5 Not very experienced with using Python in Maya, is there some configuration I have to do? Also, does PyQt5 work with Maya 2016? A: Maya won't ship with pyqt and you need to build your own version of pyqt for maya with mayapy. You local install of pyqt won't get loaded to maya so need to compile your version yourself. This link will give a insight of that http://justinfx.com/2011/11/09/installing-pyqt4-for-maya-2012-osx/. Although maya 2017 shipping with PySide2 and you can always use Pyside rather than pyqt. like from PySide2 import QtWidgets Hope this helps. A: If you want your scripts and UIs to work on either Maya 2016 or 2017 and above, I would suggest using the Qt.py package from Marcus Ottoson. You can find it here. You can just install it somewhere on your computer and add its path to the 'path' variable in your environment variables, you can then just do: from Qt import QtWidgets, QtCore, QtGui You can then write your UIs as you would in PySide2, and they will work on all versions of Maya because Qt.py is just a wrapper choosing the proper binding available on your machine, whether it is Pyside, Pyside2, Qt5, Qt4.
{ "language": "en", "url": "https://stackoverflow.com/questions/41755976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android - How to configure proguard I use StartApp to add advertisement, anh use proguard. When I run apk file (after export application), It forces to close app. I try to use StartApp, not use proguard, the apk file has no error. Another way, I try to use proguard, not use StartApp, it also has no error. Please tell me why ? this is proguard-android-optimize.txt -optimizationpasses 5 -dontusemixedcaseclassnames -dontskipnonpubliclibraryclasses -dontpreverify -verbose -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* -keep public class * extends android.app.Activity -keep public class * extends android.app.Application -keep public class * extends android.app.Service -keep public class * extends android.content.BroadcastReceiver -keep public class * extends android.content.ContentProvider -keep public class com.android.vending.licensing.ILicensingService -keepclasseswithmembernames class * { native <methods>; } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet); } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet, int); } -keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String); } -keep class * implements android.os.Parcelable { public static final android.os.Parcelable$Creator *; } this is project.properties : proguard.config=${sdk.dir}/tools/proguard/proguard-android-optimize.txt:proguard-project.txt # Project target. target=android-20 this is code to insert StartApp in Manifest file : <activity android:name="com.startapp.android.publish.list3d.List3DActivity" android:theme="@android:style/Theme" /> <activity android:name="com.startapp.android.publish.AppWallActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:theme="@android:style/Theme.Translucent" /> this is code in java class : @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); StartAppSDK.init(this, "my developer ID", "my app ID", false); setContentView(R.layout.activity_main); StartAppAd.showSlider(this); StartAppAd.showSplash(this, savedInstanceState); } A: you should use proguard-android.txt file and add the below code Or if you are using android studio then simpy add below lines to proguard-rules.pro -keep class com.startapp.** {*;} -keepattributes Exceptions, InnerClasses, Signature, Deprecated, SourceFile,LineNumberTable, *Annotation*, EnclosingMethod -dontwarn android.webkit.JavascriptInterface
{ "language": "en", "url": "https://stackoverflow.com/questions/26523849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot start kibana-4.1.2 My environment CentOS 6.6 elasticsearch-2.0.0-rc1.rpm kibana-4.1.2-linux-x64 [root@node2 files]# sestatus SELinux status: enabled SELinuxfs mount: /selinux Current mode: permissive Mode from config file: enforcing Policy version: 24 Policy from config file: targeted I am new to ELK stack. I have installed Elasticsearch and did not change any settings. It seems to me there is no issue with Elastic search. http://localhost:9200 Outputs { "name" : "Danielle Moonstar", "cluster_name" : "elasticsearch", "version" : { "number" : "2.0.0-rc1", "build_hash" : "4757962b01a4d837af282f90df9e1fbdb68b524e", "build_timestamp" : "2015-10-01T10:06:08Z", "build_snapshot" : false, "lucene_version" : "5.2.1" }, "tagline" : "You Know, for Search" } Now, if I go to Kibana(did not change anything) and run it [root@node2 files]# /usr/local/kibana-4.1.2-linux-x64/bin/kibana It gives following errors- {"name":"Kibana","hostname":"node2.mydomain.com","pid":2253,"level":50,"err":{"message":"unknown error","name":"Error","stack":"Error: unknown error\n at respond (/usr/local/kibana-4.1.2-linux-x64/src/node_modules/elasticsearch/src/lib/transport.js:237:15)\n at checkRespForFailure (/usr/local/kibana-4.1.2-linux-x64/src/node_modules/elasticsearch/src/lib/transport.js:203:7)\n at HttpConnector. (/usr/local/kibana-4.1.2-linux-x64/src/node_modules/elasticsearch/src/lib/connectors/http.js:156:7)\n at IncomingMessage.bound (/usr/local/kibana-4.1.2-linux-x64/src/node_modules/elasticsearch/node_modules/lodash-node/modern/internals/baseBind.js:56:17)\n at IncomingMessage.emit (events.js:117:20)\n at _stream_readable.js:944:16\n at process._tickCallback (node.js:442:13)"},"msg":"","time":"2015-10-15T09:41:15.952Z","v":0} {"name":"Kibana","hostname":"node2.mydomain.com","pid":2253,"level":60,"err":{"message":"unknown error","name":"Error","stack":"Error: unknown error\n at respond (/usr/local/kibana-4.1.2-linux-x64/src/node_modules/elasticsearch/src/lib/transport.js:237:15)\n at checkRespForFailure (/usr/local/kibana-4.1.2-linux-x64/src/node_modules/elasticsearch/src/lib/transport.js:203:7)\n at HttpConnector. (/usr/local/kibana-4.1.2-linux-x64/src/node_modules/elasticsearch/src/lib/connectors/http.js:156:7)\n at IncomingMessage.bound (/usr/local/kibana-4.1.2-linux-x64/src/node_modules/elasticsearch/node_modules/lodash-node/modern/internals/baseBind.js:56:17)\n at IncomingMessage.emit (events.js:117:20)\n at _stream_readable.js:944:16\n at process._tickCallback (node.js:442:13)"},"msg":"","time":"2015-10-15T09:41:15.952Z","v":0} Not sure how to fix it? A: As Andrei Stefan suggested, Kibana 4.2.0-beta solved the issue. Wasted my whole day.
{ "language": "en", "url": "https://stackoverflow.com/questions/33145382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Decompress .Z files in apache nifi I have some files in .Z format on Linux system. I want to transfer uncompressed files to hdfs. But '''compresscontent''' processor not supports .Z format. Is there any way to do so in nifi. A: If your Linux system has the uncompress command, likely a script that runs gzip, then you can use that to decompress .Z files.
{ "language": "en", "url": "https://stackoverflow.com/questions/68635637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get new page in iText Its bit problmatic to go for new page with pdfContentByte.I'm using below code to put data after first page to next page but unfortunately iText is not generating new page. //step1 itextDocument = new com.itextpdf.text.Document(PageSize.A4, 50, 50, 30, 65); writer = PdfWriter.getInstance(itextDocument, new FileOutputStream(RESULT)); itextDocument.open(); writer.setPageEmpty(true); itextDocument.newPage(); // step 2 == design and set the postions // Measuring a String in Helvetica Font font = new Font(FontFamily.TIMES_ROMAN, 10); BaseFont romanFont = font.getCalculatedBaseFont(false); // Drawing lines to see where the text is added PdfContentByte canvas = writer.getDirectContent(); canvas.saveState(); canvas.stroke(); canvas.restoreState(); // Adding text with PdfContentByte.showTextAligned() canvas.beginText(); canvas.setFontAndSize(romanFont, 10); //=================== get data from xml and put in pdf createPDF(xmlDoc, canvas); createPDF(xmlDoc, canvas){ for(int i=0;i<300;i++){ contentByte.showTextAligned(Element.ALIGN_LEFT, "sample value", flotX, flotY, 0); } } static int flotX = 50; static int flotY = 800; how can I generate new page? Any suggestion. A: On the use of writer.setPageEmpty You use writer.setPageEmpty(true); You should use writer.setPageEmpty(false); instead to indicate that the current page shall not be considered empty. As long as it is considered empty, newPage won't change anything. Adding content to multiple pages manually If you really want to create PDF content using low level methods (i.e. directly positioning text on a PdfContentByte canvas instead of leaving the layouting to iText), you have to realize that each page has its own content canvas of which a rectangle (the crop box defaulting to the media box) is displayed while the rest remains hidden. The PdfContentByte returned by writer.getDirectContent is automatically switched when a new page is started. Thus, for content spread across pages, you have to call itextDocument.newPage exactly when you want to get to the next page, and then start filling the crop box again. Along the lines of your sample code lines: Document itextDocument = new Document(PageSize.A4, 50, 50, 30, 65); PdfWriter writer = PdfWriter.getInstance(itextDocument, new FileOutputStream(RESULT)); itextDocument.open(); PdfContentByte canvas = writer.getDirectContent(); BaseFont romanFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); // first page content canvas.setFontAndSize(romanFont, 10); canvas.beginText(); canvas.showTextAligned(Element.ALIGN_LEFT, "Line 1 on page 1", 50, 800, 0); canvas.showTextAligned(Element.ALIGN_LEFT, "Line 2 on page 1", 50, 785, 0); canvas.showTextAligned(Element.ALIGN_LEFT, "Line 3 on page 1", 50, 770, 0); canvas.showTextAligned(Element.ALIGN_LEFT, "................", 50, 755, 0); canvas.showTextAligned(Element.ALIGN_LEFT, "................", 50, 740, 0); canvas.showTextAligned(Element.ALIGN_LEFT, "................", 50, 725, 0); canvas.setFontAndSize(romanFont, 800); canvas.showTextAligned(Element.ALIGN_LEFT, "1", 0, 100, 0); canvas.endText(); itextDocument.newPage(); // first page content canvas.setFontAndSize(romanFont, 10); canvas.beginText(); canvas.showTextAligned(Element.ALIGN_LEFT, "Line 1 on page 2", 50, 800, 0); canvas.showTextAligned(Element.ALIGN_LEFT, "Line 2 on page 2", 50, 785, 0); canvas.showTextAligned(Element.ALIGN_LEFT, "Line 3 on page 2", 50, 770, 0); canvas.showTextAligned(Element.ALIGN_LEFT, "................", 50, 755, 0); canvas.showTextAligned(Element.ALIGN_LEFT, "................", 50, 740, 0); canvas.showTextAligned(Element.ALIGN_LEFT, "................", 50, 725, 0); canvas.setFontAndSize(romanFont, 800); canvas.showTextAligned(Element.ALIGN_LEFT, "2", 0, 100, 0); canvas.endText(); itextDocument.close(); This produces these two pages: Alternatively you could also create an independent, larger PdfTemplate (derived from PdfContentByte), draw all your content on it, and then show sections of it on different pages: Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("big-panel.pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(PageSize.A4.getWidth(), 3 * PageSize.A4.getHeight()); // draw all your content on tp cb.addTemplate(tp, 0, -2 * PageSize.A4.getHeight()); document.newPage(); cb.addTemplate(tp, 0, -PageSize.A4.getHeight()); document.newPage(); cb.addTemplate(tp, 0, 0); document.newPage(); cb.addTemplate(tp, 0.3333f, 0, 0, 0.3333f, PageSize.A4.getWidth() / 3, 0); document.close();
{ "language": "en", "url": "https://stackoverflow.com/questions/27737501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google Play Mobile Services - sign-in in multiple activities So i'm building a game and using Google Play Mobile Services Everything is working well IF the player is signed in and has an internet connection, else he's continuously presented with the option to login on each page navigation. My example: Activity A (main screen), the player is presented with a sign in option, the player taps cancel and proceeds to navigate to Activity B (the gamePlay), here he is presented again with the sign in option. Activity A and Activity B extend BaseGameActivity. I want it to work so that if the user chooses not to sign in or doesn't have an internet connection to not bug him again until next time he starts the app. A: Found out that should have used fragments, not activities for this as activities disconnect you and connect you to the Play Mobile Services.
{ "language": "en", "url": "https://stackoverflow.com/questions/23313818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mongoose: Aggregate query in a nested array structure I'm getting a little issue with a Mongo DB query. I have a collection called "Answers" with the following structure { "_id": ObjectId("560acfcb904a29446a6d2617"), "path_id": ObjectId("560acae1904a29446a6d2610"), "step_id": "kids", "user_id": ObjectId("559ae27684ff12e88d194eb7"), "answers": [ { "id": "kids_q", "question": "Do you have kids?", "answer": "No" } ] } As you can see answers is an array and it can have one or many objects, but always is an array. First, I want to get the total of answers in a step_id I get that using the following query using aggregate Answer.aggregate( { $match: { 'path_id': { $eq: path_id }, 'step_id': { $eq: step_id }, '' } }, { $group: { _id: { step_id: '$step_id' }, count: { $sum: 1 } } }, function( err, results ) { if ( err ) { deferred.reject( err ); } deferred.resolve( results ); } ); That works great. Second, I want to get how many of that answers match against the question and the answer. Let's use the Do you have kids? question as example, I want to know how many answers are Yes, running a query in the command line I get the correct result: db.answers.find( { path_id: ObjectId( '560acae1904a29446a6d2610' ), 'answers.0.question': 'Do you have kids?', 'answers.0.answer': 'Yes' } ) I want to translate that query into an aggregate query using mongoose and avoid to have hard coded the array answers.0.question because that answer can be stored in a random index, maybe in the index 1, maybe in the index 7. Any help is appreciated. Thanks A: Use $unwind and then $match to filter only answers to the question you are looking for: var steps = [ { $match: { 'path_id': ObjectId("560acae1904a29446a6d2610"), 'step_id': 'kids' } }, { $unwind : "$answers" }, { $match: { "answers.question": 'Do you have kids?' } }, { $group: { _id: '$answers.answer', count: { $sum: 1 } } } ]; Answer.aggregate(steps, function( err, results ) { //do whatever you want with the results } ); A: Really not sure if .aggregate() is really what you want for any of this. If I understand correctly you have these documents in your collection that has an array of answers to questions and that of course those answers are not in any set position within the array. But it also does not seem likely that any one document has more than one of the same answer type. So it seems to me is that all you really want is an $elemMatch on the array element values and determine the count of documents that contain it: Answer.count({ "path_id": "560acae1904a29446a6d2610", "answers": { "$elemMatch": { "question": "Do you have kids?", "answer": "Yes" } } },function(err,count) { }); The $elemMatch operator applies all of it's conditions just like another query to each element of the array. So multiple conditions of an "and" need to be met on the same element for it to be valid. No need to do this by index. If you wanted something broader, and then only really if it was possible for each document to contain more than one possible match in the array for those conditions, then you would use .aggregate() with a condition to filter and count the matches within the array. Answer.aggregate( [ { "$match": { "answers": { "$elemMatch": { "question": "Do you have kids?", "answer": "Yes" } } }}, { "$unwind": "$answers" }, { "$match": { "answers.question": "Do you have kids?", "answers.answer": "Yes" }}, { "$group": { "_id": "$path_id", "count": { "$sum": 1 } }} ], function(err,results) { } ); But I'd only be doing something like that if indeed you had multiple possible matches in the array and you needed multiple keys to group on within the results. So if it's just about matching documents that happen to have those details in one array entry, then just use $elemMatch for the query, and at most then just $group on the count for given keys and don't bother with filtering the array content via $unwind. Answer.aggregate( [ { "$match": { "answers": { "$elemMatch": { "question": "Do you have kids?", "answer": "Yes" } } }}, { "$group": { "_id": "$path_id", "count": { "$sum": 1 } }} ], function(err,results) { } ); So if there is really only one possible match within the array, then just count the documents instead
{ "language": "en", "url": "https://stackoverflow.com/questions/32897511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTML List step scrolling to top and bottom I have a vertical list in my HTML. There is a top arrow and bottom arrow near that list. When I click top arrow, I want this list to go up step by step and opposite for the bottom arrow. the following is my html and Angular code. <div class="verticalCarousel"> <a ng-click="scrolltoBottom();" class="scroll-to-bottom">BOTTOM</a> <ul class="nav nav-tabs verticalCarouselGroup" role="tablist" id="messagestab" > <li role="presentation"> TEST </li> <li role="presentation"> TEST </li> <li role="presentation"> TEST </li> <li role="presentation"> TEST </li> <li role="presentation"> TEST </li> <li role="presentation"> TEST </li> </ul> <a ng-click="scrolltoTop();" class="scroll-to-top">TOP</a> </div> Here is the Angular code. var i = 1; $scope.scrolltoBottom = function(){ var list = $(".verticalCarouselGroup"); var container = $(".verticalCarousel"); console.log(list.height()-list.offset().top+"= BOTTOM OF CARO") console.log(container.height()-container.offset().top+"= BOTTOM OF container") i = i+50; list.css({ 'position': 'relative', 'top':i , }); }; $scope.scrolltoTop = function(){ var list = $(".verticalCarouselGroup"); var container = $(".verticalCarousel"); console.log(list.height()-list.offset().top+"= BOTTOM OF CARO") console.log(container.height()-container.offset().top+"= BOTTOM OF container") i = i-50; list.css({ 'position': 'relative', 'top':i , }); }; I added a jsfiddle https://jsfiddle.net/arunkumarthekkoot/863z3kky/2/ A: If I understand right, you're looking for scroll down steps by steps on li elements just on clicking on the arrow ? If that's it : You could maybe use smooth scroll plugin like ui.kit and trigger a click event in setTimeout or setIntervall which scroll down on every element following an array like myListEl = ['#first', '#second', etc...]; http://getuikit.com/docs/smooth-scroll.html A: Do something like : Fiddle angular.module("testApp", []).controller('ScrollCtrl', ['$scope', function($scope) { $scope.scrolltoBottom = function() { var list = $(".verticalCarouselGroup"); list.animate({ "marginTop": "+=50px" }, "slow"); }; $scope.scrolltoTop = function() { var list = $(".verticalCarouselGroup"); list.animate({ "marginTop": "-=50px" }, "slow"); }; }]); To stop it from scrolling you can add checks for bottom and top. Hint : compare bottom top with marginTop : (list.css('marginTop'))
{ "language": "en", "url": "https://stackoverflow.com/questions/37858874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable while using Rvest and Selenium to extract text specific text located in object from LinkedIn First of all, I'm only a beginner in R so my apologies if this sound like a dumb question. Basically, I want to scape the experience section in LinkedIn and extract the name of the position. As an example, I picked the profile of Hadley Wickham. As you can see on this Screenshot, the data I need ("Chief Scientist") is located in a Span object, with the span object itself located within several Div objects. As a first attempt, I figured that I'll just try to extract directly the text from the Span objects using this code. However and unsurprisingly, it returned every text that was in other Span objects. role <-signals %>% html_nodes("span") %>% html_nodes(".visually-hidden") %>% html_text() I can isolate the text I need by subsetting "[ ]" the object but I'm gonna apply this code to several LinkedIn profiles and the order of the title will change depending on the page. So I thought "Ok maybe I need to specify to R that I want to target the Span object that is located in the experience section and not the whole page" so I thought that I'll just need to mention in the code the "#experience" so that it only pick the Span object I need. But it only returned an empty object. role <-signals %>% html_nodes("#experience") %>% html_nodes("span") %>% html_nodes(".visually-hidden") %>% html_text() I'm pretty sure I'm missing some steps here but I can't figure out what. Maybe I need to specify each objects that are between "#experience" and "span" in order for this code to work but I feel there must be a better and easier way. Hope this make sense. I spent a lot of time trying to debug this and I'm not skilled enough in scraping to find a solution on my own. A: As is, this requires RSelenium since data is rendered after the page loads and not with reading pre-defined html page. Refer here on how to launch a browser (either Chrome, Firefox, IE etc..) with the object as remdr The below snippet opens Firefox but there are other ways to launch any other browser selCommand <- wdman::selenium(jvmargs = c("-Dwebdriver.chrome.verboseLogging=true"), retcommand = TRUE) shell(selCommand, wait = FALSE, minimized = TRUE) remdr <- remoteDriver(port = 4567L, browserName = "firefox") Sys.sleep(format(runif(1,10,15),digits = 1)) remdr$open() You might have to login to LinkedIn since it won't allow viewing profiles without signing up. You will need to use the RSelenium clickElement and sendKeys functions to operate the webpage. remdr$navigate(url = 'https://www.linkedin.com/') # navigate to the link username <- remdr$findElement(using = 'id', value = 'session_key') # finding the username field username$sendKeysToElement(list('your_USERNAME')) password <- remdr$findElement(using = 'id', value = 'session_password') # finding the password field password$sendKeysToElement(list('your_PASSWORD')) remdr$findElement(using = 'xpath', value = "//button[@class='sign-in-form__submit-button']")$clickElement() # find and click Signin button Once the page is loaded, you can get the page source and use rvest functions to read between the HTML tags. You can use this extension to easily get xpath selectors for the text you want to scrape. pgSrc <- remdr$getPageSource() pgData <- read_html(pgSrc[[1]]) experience <- pgData %>% html_nodes(xpath = "//div[@class='text-body-medium break-words']") %>% html_text(trim = TRUE) Output of experience: > experience [1] "Chief Scientist at RStudio, Inc."
{ "language": "en", "url": "https://stackoverflow.com/questions/73523138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python Selenium: Click Instagram next post button I'm creating an Instagram bot but cannot figure out how to navigate to the next post. Here is what I tried #Attempt 1 next_button = driver.find_element_by_class_name('wpO6b ') next_button.click() #Attempt 2 _next = driver.find_element_by_class_name('coreSpriteRightPaginationArrow').click() Neither of two worked and I get a NoSuchElementException or ElementClickInterceptedException . What corrections do I need to make here? This is the button I'm trying to click(to get to the next post) A: I have checked your class name coreSpriteRightPaginationArrow and i couldn't find any element with that exact class name. But I saw the class name partially. So it might help if you try with XPath contains as shown below. //div[contains(@class,'coreSpriteRight')] another xpath using class wpO6b. there are 10 elements with same class name so filtered using @aria-label='Next' //button[@class='wpO6b ']//*[@aria-label='Next'] Try these and let me know if it works. I have tried below code and it's clicking next button for 10 times import time from selenium import webdriver from selenium.webdriver.common.by import By if __name__ == '__main__': driver = webdriver.Chrome('/Users/yosuvaarulanthu/node_modules/chromedriver/lib/chromedriver/chromedriver') # Optional argument, if not specified will search path. driver.maximize_window() driver.implicitly_wait(15) driver.get("https://www.instagram.com/instagram/"); time.sleep(2) driver.find_element(By.XPATH,"//button[text()='Accept All']").click(); time.sleep(2) #driver.find_element(By.XPATH,"//button[text()='Log in']").click(); driver.find_element(By.NAME,"username").send_keys('username') driver.find_element(By.NAME,"password").send_keys('password') driver.find_element(By.XPATH,"//div[text()='Log In']").click(); driver.find_element(By.XPATH,"//button[text()='Not now']").click(); driver.find_element(By.XPATH,"//button[text()='Not Now']").click(); #it open Instagram page and clicks 1st post and then it will click next post button for the specified range driver.get("https://www.instagram.com/instagram/"); driver.find_element(By.XPATH,"//div[@class='v1Nh3 kIKUG _bz0w']").click(); for page in range(1,10): driver.find_element(By.XPATH,"//button[@class='wpO6b ']//*[@aria-label='Next']" ).click(); time.sleep(2) driver.quit() A: As you can see on the picture below, the wp06b button is inside a lot of divs, in that case you might need to give Selenium that same path of divs to be able to access the button or give it a XPath. It's not the most optimized but should work fine. driver.find_element(By.XPATH("(.//*[normalize-space(text()) and normalize-space(.)='© 2022 Instagram from Meta'])[1]/following::*[name()='svg'][2]")).click() Note that the XPath leads to a svg, so basically we are clicking on the svg element itself, not in the button. A: As you can see, the next post right arrow button element locator is changing between the first post to other posts next page button. In case of the first post you should use this locator: //div[contains(@class,'coreSpriteRight')] While for all the other posts you should use this locator //a[contains(@class,'coreSpriteRight')] The second element //a[contains(@class,'coreSpriteRight')] will also present on the first post page as well, however this element is not clickable there, it is enabled and can be clicked on non-first pages only.
{ "language": "en", "url": "https://stackoverflow.com/questions/70620829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hudson Release failure with error 'Unable to tag SCM' When giving release from hudson getting the below error mavenExecutionResult exceptions not empty org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.1:prepare (default-cli) on project parent: Unable to tag SCM Provider message: The svn tag command failed. Command output: svn: E235000: In file 'subversion/libsvn_client/commit_util.c' line 479: assertion failed ((copy_mode_root && copy_mode) || ! copy_mode_root) /bin/sh: line 1: 23797 Aborted (core dumped) svn --username user --password 'pass*123' --no-auth-cache --non-interactive copy --file /tmp/maven-scm-1635387492.commit . http://codeserver.ennovate.com/source-repository/parent/tags/parent-4a.1503.2 * *I don't have any existing tag as /tags/parent-4a.1503.2/ *I checked my credential and it was correct Please help me to solve the problem A: We found the same problem. There is one more report here: https://mail-archives.apache.org/mod_mbox/subversion-users/201201.mbox/%[email protected]%3E Basically, if you have different ways to refer to the subversion server, for example, server and server.domain.com, you checkout a working copy from "server", but in the Maven root POM the SVN configuration points to server.domain.com, you will find this error. You have to enter the same name in the elemento in the root POM, and in the svn command used to check-out a project from the Subversion sever.
{ "language": "en", "url": "https://stackoverflow.com/questions/29211843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Executing stored procedures in Parallel I have 35 stored procedures that I need to run in parallel so as to reduce the execution time. I came across concept of Agent jobs here. The link suggests using this piece of code to achieve this: CREATE PROCEDURE ExecuteSQL_ByAgentJob_usp( @SqlStatemet VARCHAR(4000), @SPNameOrStmntTitle VARCHAR(100), @JobRunningUser VARCHAR(100) = NULL, @JobIdOut UNIQUEIDENTIFIER OUTPUT ) AS BEGIN SET NOCOUNT ON; DECLARE @JobId UNIQUEIDENTIFIER, @JobName VARCHAR(250) = NULL, @DBName VARCHAR(100) = DB_NAME(), @ServerName VARCHAR(100) = @@SERVERNAME --Creating Unique Job Name by combining @SPNameOrStmntTitle and a GUID. SET @JobName = @SPNameOrStmntTitle + '_' + CONVERT(VARCHAR(64), NEWID()) --Currently logged user name will be used to execute the job if not provided one. IF @JobRunningUser IS NULL SET @JobRunningUser = SUSER_NAME() --Adds a new job executed by the SQLServerAgent service EXECUTE msdb..sp_add_job @job_name = @JobName, @owner_login_name = @JobRunningUser, @job_id = @JobId OUTPUT --Targets the specified job at the specified server EXECUTE msdb..sp_add_jobserver @job_id = @JobId, @server_name = @ServerName --Tell job for its about its first step. EXECUTE msdb..sp_add_jobstep @job_id = @JobId, @step_name = 'Step1', @command = @SqlStatemet,@database_name = @DBName, @on_success_action = 3 --Preparing the command to delete the job immediately after executing the statements DECLARE @sql VARCHAR(250) = 'execute msdb..sp_delete_job @job_name=''' + @JobName + '''' EXECUTE msdb..sp_add_jobstep @job_id = @JobId, @step_name = 'Step2', @command = @sql --Run the job EXECUTE msdb..sp_start_job @job_id = @JobId --Return the Job via output param. SET @JobIdOut = @JobId END Despite of having read this over and over, I still do not understand which part of it will help execute stored procedures in parallel? If possible, please shed some light on it. I am curious as hell to know which part of the script does this magic. It is called like this : SET @Itr = 1 --Seeting the initial value. SET @RecCount = ( SELECT COUNT(*) FROM @Scripts ) -----------------PART3------------------------------------ WHILE (@Itr <= @RecCount) BEGIN SELECT @sql = t.Script FROM @Scripts t WHERE id = @Itr --Just o identify the script name getting first 10 char of the SP SET @ScriptTitle = LEFT(REPLACE(@sql, 'EXEC ', ''), 10) EXEC ExecuteSQL_ByAgentJob_usp @SqlStatemet = @sql, @SPNameOrStmntTitle = @ScriptTitle, @JobRunningUser = 'sa', @JobIdOut = @JobId OUTPUT Is it how it is called in a loop ? But I believe next iteration of loop will start only when last is done executing, so how come it runs in parallel ? A: On a side note why would you want 35 procedures to execute parallel ? to me this requirement sounds a bit unrealistic. Even if you execute two stored procedures exactly at the same time, It is not guaranteed that they will go parallel. Parallelism of executions is dependent on other factors like Query Cost, MXDOP(Maximum Degree of Parallelism), Threshold for Parallelism etc. These properties are manipulated on the server level configuration (except the MAXDOP which can be specified on query. I cannot go into too much details but my suggestion would, do not depend on Parallelism write your code in a way that it doesnt depend on queries being parallel, Also the somewhat simultaneous execution of queries is handled via Transactions. Just as a hint to have 35 procedures being executed parallel you would need 35 cores on your Sql Server and MAXDOP Set to 1 and then have them 35 procs being executed at the exact time. Seems a lot of unrealistic requirements to me :) A: You are right. Next iteration will start when the last is done. But here, you are running jobs in those iterations not the actual statements. So imagine it like sp_start_job is called in async manner. It will just start the job and return immediately. The job itself may continue to do it's steps. A: The best, and easiest, way to do it is to create an SSIS project that has 35 Execute SQL tasks in parallel and then execute the job. The learning curve on using SSIS to do this is an hour or two and you can let SQL Server use as much resources as possible to execute the tasks as fast as possible. You don't have to mess around with maxops or anything else - SSIS will do it for you. To see different ways to execute SSIS jobs try this link: http://www.mssqltips.com/sqlservertip/1775/different-ways-to-execute-a-sql-server-ssis-package/
{ "language": "en", "url": "https://stackoverflow.com/questions/29193805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excluding row from a MySQL select query based on the contents of another pivot table Given the following MySQL query... select users.id, group_concat(devices.id) as devicesIds, pois.id as poi_id, events.name as event from `users` left join `devices` on `users`.`id` = `devices`.`user_id` left join `poi_user` on `users`.`id` = `poi_user`.`user_id` left join `pois` on `pois`.`id` = `poi_user`.`poi_id` left join `events` on `events`.`poi_id` = `pois`.`id` left join `event_user` on `users`.`id` = `event_user`.`user_id` where (`events`.`startDate` > now()) group by users.id, pois.id, events.name ...which simply gets some processed fields from the different joined tables (getting only future events), grouped by several keys. Now, I need to add an additional constraint so that if there is any record in the event_user table related to that particular user + event in each case, then that row should not be returned in the main select. Any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/49155097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP programming , MySQL database i have the following SQL statement to inserts data from a table to another table but the number of the mother table is less than the child table, can anyone correct me, thanks for helping $res = mysql_query("SELECT Nid FROM admins WHERE Nid='$Nid'"); $row = mysql_fetch_row($res); if( $row > 0 ) { $sql = "INSERT INTO sickness_details (pnid, dFullName, dposition, dhospital, date) SELECT '$pnid', admins.FullName, admins.position, admins.hospital, admins.date FROM admins WHERE admins.Nid = '$Nid'"; if( mysql_query($sql) ) echo "Inserted Successfully "; else echo "Insertion Failed"; } else { echo "National Id $Nid not exist"; } A: Simply don't mention the columns you have no data for. INSERT INTO ('no_data','stuff') VALUES ('','foobar'); becomes INSERT INTO ('stuff') VALUES ('foobar'); Syntax in mysql It's a good rule of thumb to actually log the error when debugging (mysql_error) A good code highliter could help aswell. You are using a column named date. this is however a reserved word used by mysql. change it to date. Or even better change it to a name that tells me more about it. What kind of date? start? end? birthday? ... A: Use this INSERT INTO sickness_details (pnid, dFullName, dposition, dhospital, date) SELECT '$pnid', admins.FullName, admins.position, admins.hospital, NOW() FROM admins WHERE admins.Nid = '$Nid';
{ "language": "en", "url": "https://stackoverflow.com/questions/25810764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: C# - convert DeviceUniqueId (string) to int I want to get a unique id in windows phone 8 . I used DeviceUniqueId with the following code : byte[] id = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId"); iden = BitConverter.ToString(id).Replace("-", string.Empty); now I want to convert it to int how can I do that ? A: you have string iden, convert it to int like this: int devId= Convert.ToInt32(iden);
{ "language": "en", "url": "https://stackoverflow.com/questions/23543715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to initialize 2D arraylist using 2D array? I have this array int[][] currGrid = {{1,1},{1,2},{2,2}}; And this array is static so I want to create 2D arraylist using the same elements. Is there any way to create the arraylist for same in a single line without using add in Java? A: It's unclear to me whether you meant you want to convert this given 2D array to a 2D list, or wether you meant to just create a new list with these values as a one-liner. If you meant the former, you could stream the array and then stream each of its elements, and collect them: List<List<Integer>> currGridList = Arrays.stream(currGrid) .map(g -> Arrays.stream(g).boxed().collect(Collectors.toList())) .collect(Collectors.toList()); If you meant the latter, you could use List.of: List<List<Integer>> currGridList = List.of(List.of(1, 1), List.of(1, 2), List.of(2, 2));
{ "language": "en", "url": "https://stackoverflow.com/questions/67547300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: insert foreach x where not exists I have a fairly simple database consisting of three (relevant) tables: users, permissions, and user permissions. The basic premise is simple: when a user gets created, all the records in the permissions table are automatically added to the user_permissions table with a default value. This is all working fine. However, as I'm currently in development, I continue to add new permissions, which of course existing users won't have since those new permissions didn't exist in the permissions table when they were created. So, I had the brilliant idea to create a little stored procedure to automatically update the user_permissions table with all the permissions not currently existing in the user_permissions table. So, in short, what I want to do is something like (pseudocode) For each user without x permission in user_permissions, insert into user_permissions user_id and permission_id I wasn't quite sure how to do this from an SQL POV. I played with joins and "not exists" but haven't really gotten anywhere. You can play with my schema here: http://sqlfiddle.com/#!3/b0761/3 Thanks in advance for the help! EDIT: Schema: CREATE TABLE users ( user_id int IDENTITY(1, 1) NOT NULL, user_name varchar(255), PRIMARY KEY (user_id)); CREATE TABLE permissions ( permission_id int IDENTITY(1, 1) NOT NULL, permission_name varchar(255) NOT NULL, PRIMARY KEY (permission_id)); CREATE TABLE user_permissions ( user_id int NOT NULL, permission_id int NOT NULL, value tinyint DEFAULT 0 NOT NULL, PRIMARY KEY (user_id, permission_id)); ALTER TABLE user_permissions ADD CONSTRAINT FK_user_pe338140 FOREIGN KEY (permission_id) REFERENCES permissions (permission_id); ALTER TABLE user_permissions ADD CONSTRAINT FK_user_pe405324 FOREIGN KEY (user_id) REFERENCES users (user_id); INSERT INTO users(user_name) values('test_username'); INSERT INTO users(user_name) values('test_username2'); INSERT INTO permissions(permission_name) VALUES('permission_1') INSERT INTO permissions(permission_name) VALUES('permission_2') INSERT INTO user_permissions(user_id, permission_id, value) VALUES(1, 1, 1) INSERT INTO user_permissions(user_id, permission_id, value) VALUES(2, 1, 1) EDIT: Query so far SELECT a.user_id, b.permission_id, 1 as 'value' FROM USER_PERMISSIONS a right outer join PERMISSIONS b on a.permission_id = b.permission_id A: insert into user_permissions (user_id, permission_id) select u.user_id, p.permission_id from users u cross join permissions p where not exists (select 0 from user_permissions with (updlock, holdlock) where user_id = u.user_id and permission_id = p.permission_id) Reference: Only inserting a row if it's not already there A: INSERT dbo.user_permissions([user_id], permission_id, [value]) SELECT u.[user_id], p.permission_id, 1 FROM dbo.user_permissions AS u CROSS JOIN dbo.[permissions] AS p WHERE NOT EXISTS (SELECT 1 FROM dbo.user_permissions WHERE [user_id] = u.[user_id] AND permission_id = p.permission_id ) GROUP BY [user_id], p.permission_id; As an aside, you should avoid names that tend to require delimiters, e.g. user_id and permissions are keywords/reserved words. A: Mansfield, If I understand you correctly, you want to seed the user_permissions table with a value when you add a new permission. I'll also assume that you want it to default to 0. After inserting the new permission, running this code will seed the user_permissions table for all users with a default value of 0 for any permissions currently not in use. --insert into permissions(permission_name) values('newperm'); --select * from permissions insert into user_permissions(user_id, permission_id, value) select u.user_id, p.permission_id, 0 from users u cross join permissions p where p.permission_id not in(select permission_id from user_permissions) ; --select * from user_permissions; A: The below query will give you the missing userpermission rows to be inserted: select a.USER_ID,b.permission_id from users a,permissions b,user_permissions c where c.user_id <>a.user_id and c.permission_id <> b.permission_id
{ "language": "en", "url": "https://stackoverflow.com/questions/11458006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: "SQL Server doesn't exist or access denied" while importing Excel sheet into SQL Server using C# I want to import an Excel sheet into SQL Server using C#. This is my code: private void button1_Click_1(object sender, EventArgs e) { of1.Filter = "xls|*.xlsx"; if ((of1.ShowDialog()) == System.Windows.Forms.DialogResult.OK) { imagepath = of1.FileName; //image path textBox1.Text = imagepath.ToString(); } } private void loadbtn_Click(object sender, EventArgs e) { string ssqltable = comboBox1.GetItemText(comboBox1.SelectedItem); string myexceldataquery = "select * from ["+ ssqltable + "$]"; try { string sexcelconnectionstring = @"Provider = SQLOLEDB.1; Integrated Security = SSPI; Persist Security Info = True; Data Source = AMR - PC; Use Procedure for Prepare = 1; Auto Translate = True; Packet Size = 4096; Workstation ID = AMR - PC; Use Encryption for Data = False; Tag with column collation when possible = False; Initial Catalog = BioxcellDB"; string ssqlconnectionstring = "Data Source=.;Initial Catalog=Bioxcell;Integrated Security=True"; OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring); OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn); oledbconn.Open(); OleDbDataReader dr = oledbcmd.ExecuteReader(); SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring); bulkcopy.DestinationTableName = ssqltable; while (dr.Read()) { bulkcopy.WriteToServer(dr); } oledbconn.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } A message box shows this error: 0x80004005 [DBNETLIB]SQL Server doesn't exist or access denied Then I tried to check my connection string in another project and worked fine. Where is the problem? .. Sorry for bad English
{ "language": "en", "url": "https://stackoverflow.com/questions/43044630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nested exception is java.lang.NoSuchMethodError: javax/persistence/Table.indexes()[Ljavax/persistence/Index; I am getting error nested exception is java.lang.NoSuchMethodError: javax/persistence/Table.indexes()[Ljavax/persistence/Index; my controller-servlet.xml file is <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/jsp/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <beans:property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <beans:property name="url" value="jdbc:oracle:thin:" /> <beans:property name="username" value="user" /> <beans:property name="password" value="123" /> </beans:bean> <!-- Hibernate 4 SessionFactory Bean definition --> <beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <beans:property name="dataSource" ref="dataSource" /> <beans:property name="annotatedClasses"> <beans:list> <beans:value>com.company.bmdashboard.beans.BatchJob</beans:value> </beans:list> </beans:property> <beans:property name="hibernateProperties"> <beans:props> <beans:prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</beans:prop> <beans:prop key="hibernate.show_sql">true</beans:prop> <beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop> </beans:props> </beans:property> </beans:bean> <beans:bean id="bMDashboardRepository" class="com.company.bmdashboard.repositories.BMDashboardRepositoryImpl"> <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" /> </beans:bean> <beans:bean id="bMDashboardService" class="com.company.bmdashboard.services.BMDashboardServiceImpl"> <beans:property name="bMDashboardRepository" ref="bMDashboardRepository"></beans:property> </beans:bean> <context:component-scan base-package="com.company.bmdashboard" /> <tx:annotation-driven transaction-manager="transactionManager"/> <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" /> </beans:bean> </beans:beans> The jars file I have are my RepositoryImpl is @Repository public class BMDashboardRepositoryImpl implements BMDashboardRepository{ private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sf){ this.sessionFactory = sf; } @Override public ArrayList<BatchJob> retrieveAllBatchJobs() { // TODO Auto-generated method stub System.out.println("Repository Impl: in retrieve all batch jobs"); Session session= sessionFactory.getCurrentSession(); @SuppressWarnings("unchecked") List<BatchJob> allBatchJobs=session.createQuery("From BatchJob").list(); for(BatchJob bj:allBatchJobs) { System.out.println(bj.toString()); } return (ArrayList<BatchJob>) allBatchJobs; } } When I am publishing the code in webspehre, I am getting this error. I think there is some problem with jar files? thanks in advance A: I found the work around for this. I was using WAS 8.5 which provides its own JDK which supports JPA 2.0 . @Table.indexes() method was introduced in JPA 2.1 . Solution for this 1)Upgrade WAS to 9 2)Instead of using @Table annotation try using xml mapping . I used ClassName.hbm.xml.
{ "language": "en", "url": "https://stackoverflow.com/questions/52776824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: django session project cart I'm trying to display data that I put on a session for my shopping cart project that I'm developing, but here I can't recover the product whose code I passed as a parameter def index(request): mes_produits={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500}, {'code':'MLO23','nom':'pomme de terre','prix':1800}]} parcou=mes_produits['produits'] contex={'produits':parcou} return render(request,'shop/index.html',contex) def cart_add(request, code): dico={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500}, {'code':'MLO23','nom':'pomme de terre','prix':1800}]} mes_produits=dico['produits'] selected_product = next((item for item in mes_produits if item["code"] == code), None) if selected_product != None: request.session['nom']=selected_product.get('nom') request.session['prix']=selected_product.get('prix') contex={'nom':request.session['nom'],'prix':request.session['prix']} return render(request, 'cart/cart_detail.html',contex) car_detail.html {% for key,value in request.session.items %} Nom : {{value.nom}} Prix : {{value.prix}} {% endfor %} I get a blank page with the name of the keys only A: Your session object is a dict, not a list of tuple. Try this code in template: Nom : {{request.session.nom}} Prix : {{request.session.prix}} But, you have already set the vars in context, so you can do: Nom : {{nom}} Prix : {{prix}} # And your views.py def cart_add(request, code): dico={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500}, {'code':'MLO23','nom':'pomme de terre','prix':1800}]} mes_produits=dico['produits'] selected_product = next((item for item in mes_produits if item["code"] == code), None) if selected_product != None: context={ 'nom':selected_product.get('nom'), 'prix':selected_product.get('prix') } else: context = {} return render(request, 'cart/cart_detail.html',context) Maybe you do not understand session usage? https://docs.djangoproject.com/en/4.1/topics/http/sessions/
{ "language": "en", "url": "https://stackoverflow.com/questions/73786083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: TFS release management, .net core rc2 deployment to on-premise servers New to Visual Studio Team Services, previously Visual Studio Online I have a couple .net core rc2 apps. Example 1: Solution contains 1 .net core MVC app, 1 Web Api app, Multiple dependent assemblies. I've got 3 on-premise servers (Dev, QA, Staging) My dev server contains the build agent. My confusion is on how to best deploy these apps to my on-premise servers and finally to my production server on azure. Do I generate webdeploy packages? If so, where and with what? In my build definition or release definition (on tfs)? What would be the proper way to do the deployment part of these .net core rc2 apps and (using what, and in what order) is what im trying to figure out. To my understanding so far, I believe on check in (CI build), I build/deploy to all 3 environments (dev, qa, staging). With dev and qa being automatic. Staging being either automatic or approved (authorized), depending on QA results. Finally production, being manual. I understand this is not set in stone, and certain things can be done differently, but does it sound right? Oh, and all my servers are windows server 2012 r2 A: You can use build definition to build your project and generate the deployment packages and then use release definition to deploy the packages. In the release definition, you can add three environment to deploy to Dev, QA & Staging. For how to build and deploy Asp.Net Core app, please refer to this link for details: Build and deploy your ASP.NET Core RC2 app to Azure.
{ "language": "en", "url": "https://stackoverflow.com/questions/38024845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP: Is it possible to get first two character from an array value? Is it possible to get / select first two character from an array value? for example: Array Array ( [0] => 1_name [1] => 0_sex [2] => 2_age } and I need to get the first two character from each value in array's elements. So I can get this as a result if I echo them. Result First Element is 1_ Second Element is 0_ Third Element is 2_ Anyone know how to solve this? thanks A: You could use array_map to get new array with only the first two characters of each item: $input = ['1_name', '0_sex', '2_age']; var_dump(array_map(function($v) { return substr($v, 0, 2); }, $input)); A: Use a foreach loop this way: <?php $a = ["1_name", "0_sex", "2_age"]; foreach ($a as $aa) { echo substr($aa, 0, 2) . "\n"; } Output: 1_ 0_ 2_ You can use the array_map() function as well to return an array. array_map(function ($a) { return substr($a, 0, 2); }, $input); A: Using indexes will work for you as well. Source-Code index.php <?php $array = [ '1_name', '0_sex', '2_age' ]; echo 'First element is ' . $array[0][0] . $array[0][1] . '<br>'; echo 'Second element is ' . $array[1][0] . $array[1][1] . '<br>'; echo 'Third element is ' . $array[2][0] . $array[2][1] . '<br>'; Result First element is 1_ Second element is 0_ Third element is 2_
{ "language": "en", "url": "https://stackoverflow.com/questions/41211866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Insightly API with filter I have created a cUrl to get a filtered list of contacts. Regardless of me passing the filter items I always get ALL of the contacts. Here is the curl: curl -v -H "Authorization: Basic <MY API KEY>" https://api.insight.ly/v2.1/contacts?filter=LAST_NAME='Jones' Any ideas? A: Use filter like this https://api.insight.ly/v2.1/contacts?$filter=LAST_NAME%20eq%20'Jones'
{ "language": "en", "url": "https://stackoverflow.com/questions/26915223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Class reference setting itself to null somewhere in my code When im trying to call the functions in newGame(); I get a Nullpointerexception, which I have understood is my reference _c that has been set to null, but I cant figure out anywhere in my code that it sets it to null. Unless something is bugging I am missing something here. I am not sure if I need to show the other classes too, I dont think they are relevant for this matter. Here is the relevant code, I know its messy and probably not very good, but that's not the problem here! Please note that I have erased the irrelevant parts of the code(the parts where I am sure the problem cant be in). public class MainActivity extends ActionBarActivity { private String fullWord; Controller _c; static String[] charArray; MainActivity _v; static EditText letterBox; static EditText charBoxes; ViewGroup layout; ViewGroup imageLayout; ViewGroup mainLayout; static Button tryButton; static Button guessWordButton; Button newGameButton; static ImageView newImg; static EditText tempEdit; static EditText[] etCollection; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _v = new MainActivity(); newImg = (ImageView) findViewById(R.id.bild1); newImg.setImageResource(R.drawable.bstart); letterBox = (EditText) findViewById(R.id.letter); layout = (ViewGroup) findViewById(R.id.ordet); imageLayout = (ViewGroup) findViewById(R.id.images); tryButton = (Button) findViewById(R.id.try2); guessWordButton = (Button) findViewById(R.id.entireword); newGameButton = (Button) findViewById(R.id.newgame); _c = new Controller(_v,letterBox); tryButton.setOnClickListener(_c); guessWordButton.setOnClickListener(_c); newGameButton.setOnClickListener(_c); buildUI(); } public void buildUI(){ fullWord = _c.getWord(); charArray = fullWord.split("(?!^)"); etCollection = new EditText[charArray.length]; LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); for (int i = 0;i<charArray.length;i++){ charBoxes = new EditText(this); charBoxes.setId(i); charBoxes.setLayoutParams(new LayoutParams(params)); charBoxes.setFocusable(false); etCollection[i] = charBoxes; layout.addView(charBoxes); } } public void updateWord(int placeholder, String letter){ for (int i = 0;i<charArray.length;i++){ if (letter.equals(charArray[i])){ etCollection[i].setText(letter); } } } public void updateImg(int imgNumber){ newImg.setImageResource(0); switch (imgNumber){ case 1: newImg.setImageResource(R.drawable.b1); break; case 2: newImg.setImageResource(R.drawable.b2); break; case 3: newImg.setImageResource(R.drawable.b3); break; case 4: newImg.setImageResource(R.drawable.b4); break; case 5: newImg.setImageResource(R.drawable.b5); break; case 6: newImg.setImageResource(R.drawable.b6); break; case 7: newImg.setImageResource(R.drawable.b7); break; case 8: newImg.setImageResource(R.drawable.bslut); break; case 9: tryButton.setEnabled(false); guessWordButton.setEnabled(false); newImg.setImageResource(R.drawable.bslut); break; } } public void newGame(){ fullWord = _c.getWord(); charArray = fullWord.split("(?!^)"); } public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } A: My guess would be that _c.getWorld() returns a null object on which you call a method. Hence the NullPointerException.
{ "language": "en", "url": "https://stackoverflow.com/questions/25965169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: HTML & CSS - Issue with inline-block elements I've made a website where on the main div, multiple div's are displayed ( as inline-element's ) , those div's are containing an IMG and P element. Well, if I leave the P element ( or text without p tag ), everything is ok, but if I add text after the img, the coresponding div will get out of the normal position. The page is online at http://ace-acid.no-ip.org/acid-game-studios/ ( that is the working version ) And this one is the version with the problem in it -> http://ace-acid.no-ip.org/acid-game-studios-issue/ ( here you can clearly see that all the div's that have no text in it, are spaced downside... ) How can i prevent this behaviour ? Thank you all guys ^^ < EDIT > I think it's an css issue ( block element , inline-block element, fextflow, vertical align , ... ) isn't it ? b.t.w. -> the website is a fluid grid based one, so if you scale down the browser, it will show a tabled and a mobile version. the problem seems to only apear in the same row where the text is, because in the next row, the div-blocks aren't spaced down... < /EDIT > HTML code: <!doctype html> <!--[if lt IE 7]> <html class="ie6 oldie"> <![endif]--> <!--[if IE 7]> <html class="ie7 oldie"> <![endif]--> <!--[if IE 8]> <html class="ie8 oldie"> <![endif]--> <!--[if gt IE 8]><!--> <html class=""> <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>aCID Game Studios</title> <link rel="stylesheet" type="text/css" href="boilerplate.css"> <link rel="stylesheet" type="text/css"href="style.css"> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <script src="respond.min.js"></script> </head> <body> <div class="gridContainer clearfix"> <div id="div_header" align="center"> <div id="div_header_img"></div> <div id="div_menu" align="center"> <p>&lt; MENU &gt;</p> </div> </div> <div id="div_main" align="center"> <div id="div_page"> <br><br><p>&lt; PAGE &gt;</p><br><br> <div class="div_game_thumb"> <img style="vertical-align:middle" src="img/games/LegendOfAce.png" onMouseOver="this.src='img/games/LegendOfAce_hover.png'" onMouseOut="this.src='img/games/LegendOfAce.png'"/> </div> <div class="div_game_thumb"> <img src="img/games/GunsOfTheNation.png" onMouseOver="this.src='img/games/GunsOfTheNation_hover.png'" onMouseOut="this.src='img/games/GunsOfTheNation.png'"/> </div> <div class="div_game_thumb"> <img src="img/games/LegendOfAce.png" onMouseOver="this.src='img/games/LegendOfAce_hover.png'" onMouseOut="this.src='img/games/LegendOfAce.png'"/> </div> <div class="div_game_thumb"> <img src="img/games/GunsOfTheNation.png" onMouseOver="this.src='img/games/GunsOfTheNation_hover.png'" onMouseOut="this.src='img/games/GunsOfTheNation.png'"/> </div> <div class="div_game_thumb"> <img src="img/games/LegendOfAce.png" onMouseOver="this.src='img/games/LegendOfAce_hover.png'" onMouseOut="this.src='img/games/LegendOfAce.png'"/> </div> </div> </div> </div> </body> </html> CSS code: @charset "utf-8"; /* Einfache fließende Medien Hinweis: Für fließende Medien müssen Sie die Attribute 'height' und 'width' des Medium aus dem HTML-Code entfernen http://www.alistapart.com/articles/fluid-images/ */ html{ margin: 0; padding: 0; border: 0; } body { background-color: #0c0d0f; color: #3982aa; } p { margin: 0; padding: 10px; } img, object, embed, video { width: 100%; } /* IE 6 unterstützt keine maximale Breite, verwenden Sie daher eine Standardbreite von 100% */ .ie6 img { width: 100%; } .div_game_thumb { width:320px; height:350px; display:inline-block; border:1px solid #fff; } /* Dreamweaver-Eigenschaften für fließende Raster ---------------------------------- dw-num-cols-mobile: 6; dw-num-cols-tablet: 8; dw-num-cols-desktop: 14; dw-gutter-percentage: 15; Idee durch den Artikel "Responsive Web Design" von Ethan Marcotte http://www.alistapart.com/articles/responsive-web-design und "Golden Grid System" von Joni Korpi http://goldengridsystem.com/ */ /* Layout für Mobilgeräte: 480 px oder weniger. */ .gridContainer { margin-left: auto; margin-right: auto; width: 100%; padding-left: 0; padding-right: 0; } #div_header { clear: both; float: left; margin: 0; width: 100%; display: block; } #div_header_img { width: 450px; height: 150px; background-color: #999; background-position: top center; background-repeat: no-repeat; background-image: url(img/header_m.png); } #div_menu { width: 450px; height: 50px; background-color: #111; } #div_main { clear: both; float: left; margin: 0; width: 100%; display: block; min-height: 300px; } #div_page { width: 450px; min-height: 300px; background-position: top center; background-repeat: repeat-x; background-image: url(img/page_border_top.png); background-color: #000; } /* Layout für Tablet-PCs: 481 bis 768 px. Erbt Stile vom: Layout für Mobilgeräte. */ @media only screen and (min-width: 481px) { body { background-position: top center; background-repeat: repeat; background-image: url(img/bg.png); } #div_header { clear: both; float: left; width: 100%; display: block; display: block; background-position: top center; background-repeat: repeat-y; background-image: url(img/page_bg_t.png); } #div_header_img { width: 650px; height: 150px; display: block; background-image: url(img/header_t.png); } #div_menu { width: 650px; background-position: top center; background-repeat: no-repeat; background-image: url(img/menu_bg_t.png); } #div_main { clear: both; float: left; margin: 0; width: 100%; display: block; background-position: top center; background-repeat: repeat-y; background-image: url(img/page_bg_t.png); } #div_page { width: 650px; } } /* Desktoplayout: 769 bis maximal 1232 px. Erbt Stile von: den Layouts für Mobilgeräte und Tablet-PCs. */ @media only screen and (min-width: 769px) { #div_header { clear: both; float: left; width: 100%; display: block; background-image: url(img/page_bg.png); } #div_header_img { width: 1000px; height: 200px; background-image: url(img/header.png); } #div_menu { width: 1000px; background-position: top center; background-repeat: no-repeat; background-image: url(img/menu_bg.png); } #div_main { clear: both; float: left; margin: 0; width: 100%; display: block; background-image: url(img/page_bg.png); } #div_page { width: 1000px; } } A: Use vertical-align: top; on .div_game_thumb Inline elements obey to vertical alignment. Also, if you want cross-browser inline-blocks (IE7+) you need to define it like this: display: inline-block; *zoom: 1; *display: inline; *Note: The order is important. A: vertical-align: top saves the day! Put it on .div_game_thumb. You can restore the little bit of margin that disappears after doing this by adding margin: 2px 0; as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/12717633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add proper spacing in my PSV file? I have a psv file for some config for my program and it looks really bad. When I save this config from kdb it removes all the white space and it looks like this: column1|column2|column3 somevalue1|somevalue2|somevalue3 somevalue4|somevalue5|somevalue6 and I want it to look like this when I open it with a text editor like notepad or visual studio code column1 |column2 |column3 somevalue1 |somevalue2 |somevalue3 somevalue4 |somevalue5 |somevalue6 This psv file has 20000 rows so please don't tell me I have to do this manually. The reason for which I need to do this spacing is because sometimes my colleagues need to open it to modify just one thing and it is much more readable with the spacing. I work on linux and I know kdb,python and R so anything in those languages that could help me? A: This is quite crude but this q function will take an existing psv file and pad it out: pad:{m:max each count@''a:flip"|"vs/:read0 x;x 0:"|"sv/:flip m$a} It works by taking the max string length of each column and padding the rest of the values to the same width using $. The columns are then stitched back together and saved. Taking this example file contents: column1|column2|column3 somevalue1|somevalue2|somevalue3 somevalue4|somevalue5|somevalue6 somevalue7|somevalue8|somevalue9 Passing through pad in an open q session: pad `:sample.psv Gives the result: column1 |column2 |column3 somevalue1|somevalue2|somevalue3 somevalue4|somevalue5|somevalue6 somevalue7|somevalue8|somevalue9
{ "language": "en", "url": "https://stackoverflow.com/questions/57226467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change Visual Studio editor drag and drop default action In Visual Studio Community 2022's editor is there any way to change the default action from * *select; drag & drop = move *select; ctrl + drag & drop = copy to * *select; drag & drop = copy *select; ctrl + drag & drop = move
{ "language": "en", "url": "https://stackoverflow.com/questions/72292376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Avoid Storing Web.Config Connection String Passwords in TFS For example, and this is just an example, could I place something like a tag in the web.config where the connection string or parts of it would be, and then have the username and password replaced during the build release process when the build goes out to a server? A: One way is to store the connection strings in IIS and they will be applied to the web.config automatically. See this post http://forum.winhost.com/threads/setup-the-connection-string-in-web-config.7592/
{ "language": "en", "url": "https://stackoverflow.com/questions/20129606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google App Engine Error (The requested URL / was not found on this server) I am trying to create a simple web application that says Hello Udacity and upload it to Google App Engine, but I keep on getting a bunch of errors. Error message from Google App Engine: 11:57 PM Host: appengine.google.com Error parsing yaml file: Unable to assign value 'udacityassignment2' to attribute 'url': Value 'udacityassignment2' for url does not match expression '^(?:(?!\^)/.*|\..*|(\(.).*(?!\$).)$' in "C:\Users\Wealthy\Desktop\ambhelloworld\udacityassignment2\app.yaml", line 12, column 8 2013-05-27 23:57:00 (Process exited with code 1) You can close this window now. app.yaml: application: udacityassignment2 version: 1 runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /favicon\.ico static_files: favicon.ico upload: favicon\.ico - url: udacityassignment2 script: main.app libraries: - name: webapp2 version: "2.5.2" main.py: import webapp2 class MainHandler(webapp2.RequestHandler): def get(self): self.response.write('Hello Udacity!') app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True) Google App Engine console: Error: Not Found The requested URL / was not found on this server. Any assistance on how to correct this issue would be appreciated. A: The error is indicating that the url entry in your app.yaml is not valid. Try this url: /udacityassignment2 And as Tim pointed, the mapping should be app = webapp2.WSGIApplication([ ('/udacityassignment2', MainHandler) ], debug=True) A: You can make the URL entry as below to give you more flexibility when creating your url routing table - url: .* script: main.app
{ "language": "en", "url": "https://stackoverflow.com/questions/16783776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Three.js prevent Raycast through Gui I want to select objects with raycasting, but everytime i want to select something on the three.js gui, the Mousdownevent get triggered. How can i say something like "if the Gui is in front of the object, dont trigger" document.addEventListener( 'mousedown', onDocumentMouseDown, false ); function onDocumentMouseDown( event ) { if (event){} the gui is a normal three.js gui made like this: gui = new GUI( { width: 330 } ); A: One way to solve this is with jQuery and an additional control variable: $( gui.domElement ).mouseenter(function(evt) { enableRaycasting = false; } ); $( gui.domElement ).mouseleave(function() { enableRaycasting = true; } ); You can then use enableRaycasting in order to determine if raycasting should happen. Demo: https://jsfiddle.net/gnwz5ae7/
{ "language": "en", "url": "https://stackoverflow.com/questions/58202842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: You tube channels as Json I am trying to create an android app ..for that i want to know how to retrieve the particular youtube channels videos as a json Data ..?I mean I dont want to search the videos i want to display only for particular channel videos.. A: HI, Try this JSON Link http://gdata.youtube.com/feeds/api/users/UserName/uploads?&v=2&max-results=50&alt=jsonc here that content Object returns to my channel videos Reference by http://code.google.com/apis/youtube/2.0/reference.html#Response_codes_uploading_videos
{ "language": "en", "url": "https://stackoverflow.com/questions/4291313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I measure the length of an asyncio event loop? I have an application which is calling loop.run_forever() after scheduling some tasks. Those tasks will connect to web services and then schedule new tasks on the loop based on input from those services. I want to find a way of keeping track of the loop to check whether there are tasks being created which are never completing. Ideally I would measure the number of tasks in the loop periodically and write it to a file, or make it available via an http call. A: You can collect all tasks, then count them, compute some other metric of "loop length" or perform inspection. asyncio.Task.all_tasks(loop=loop) A: In python 3.10, you can get the number of tasks in the current thread like that : len(asyncio.all_tasks(asyncio.get_running_loop()))
{ "language": "en", "url": "https://stackoverflow.com/questions/42032483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Guessing random number game error Below Is My Code , I Cant figure out , how can i make the user to have only 4 tries then its say you lost , try again ? why cant this work ? i am doing something wrong in the for loop ? or should i use another loop public class JavaApplication11 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { int random = (int )(Math.random() * 10 + 1); // System.out.println("Random Number Is:"+random); double userinput = 0; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("-------------------------------------------------"); System.out.println("Welcome To The Guessing Game!"); System.out.println("-------------------------------------------------"); System.out.println("Lets Start,Guess The Number:"); System.out.println("-------------------------------------------------"); userinput=Integer.parseInt(br.readLine()); for(int i=random;i<=4;i++) { if(userinput==random) { System.out.println("-----------------------------------------"); System.out.println("You Won!"); System.out.println("-----------------------------------------"); } else { System.out.println("--------------------------------------------"); System.out.println("Wrong Guess,Try Again! Good Luck^_^"); System.out.println("--------------------------------------------"); } System.out.println("Created By XYZ!"); } } } A: for(int i=random;i<=4;i++) looks suspect: there's no reason to initialise i to the random number picked by the computer. I think you meant for (int i = 1; i <= 4; i++) instead. A: You need to put userinput=Integer.parseInt(br.readLine()); into your for loop if not successful. else { userinput=Integer.parseInt(br.readLine()); .... } also the foor loop should be for(int i=0; i < 4; i++) A: There several mistakes in your program: 1. You can not guarantee user inputs a legal number. So, U should judge if br.readLine() is a integer number. The code is: str = br.readLine(); while(!str.matches("[0-9]+")) { System.out.println("Input Format Error!! Please Re. input:"); str = br.readLine(); } userinput = Integer.parseInt(str); 2. The for loop should be coded as below if you wanna tried only 4 times: for(i = 1 ; i <= 4 ; i++) 3. In the for loop, you should have interface for Re. input when the answer is wrong. str = br.readLine(); while(!str.matches("[0-9]+")) { System.out.println("Input Format Error!! Please Re. input:"); str = br.readLine(); } userinput = Integer.parseInt(str); 4. if you wanna loop this process for many times, you should put all codes in a while(true){...} loop. A: you have to look to "random" variable !! you initialised it like : int random = (int )(Math.random() * 10 + 1); sometimes it is >4 , that's the problem caused on the For iterator A: Here are my suggestion: 1.Read user input in each try.(BufferedReader with in the loop) 2.If user win break the loop. 3.Loop should be run 4 times only, for (int i = 1; i <= 4; i++)
{ "language": "en", "url": "https://stackoverflow.com/questions/23884908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pipeline vs MapReduce in MongoDB When do I use prefer MapReduce over Pipeline in MongoDB or vice versa? I feel most of the aggregation operations are suitable for pipeline. What kind of complexity of the problem or what use case should make me go for MapReduce. A: As a general rule of thumb: When you can do it with the aggregation pipeline, you should. One reason is that the aggregation pipeline is able to use indexes and internal optimizations between the aggregation steps which are just not possible with MapReduce. Aggregation is also a lot more secure when the operation is triggered by user input. When there are any user-supplied parameters to your query, MapReduce forces you to create javascript functions through string concatenation. This opens the door for dangerous Javascript code injection vulnerabilities. The APIs used for creating aggregation pipeline objects (in most programming languages!) usually has fewer such obvious pitfalls. There are, however, still a few cases which can not be done easily or not at all with aggregation. For these cases, MapReduce has still a reason to exist. Another limitation of the aggregation framework is that the intermediate dataset after each aggregation step is limited to 100MB unless you use the allowDiskUse option, which really slows down the query. MapReduce usually behaves a lot better when you need to work with a really large dataset.
{ "language": "en", "url": "https://stackoverflow.com/questions/25474106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Citations in DT:datatable I am working on a bookdown project where we have large tables that also contain citations. We are outputting in both html and pdf. The problem is that I cannot find a way to make the citations render in the tables. For PDF output this latex workaround works: https://github.com/haozhu233/kableExtra/issues/214 However, for the html output I have been using DT:datatable and I cannot figure a way to make the references render. Is there a way to get the markdown parsed citation in the table? markdown example: --- title: "Untitled" output: html_document bibliography: ["references.bib"] --- In text citation [@chambers_2012]. A plan data.frame can render the reference if inserted as text that markdown can parse. ```{r, results='asis'} library(dplyr) library(DT) data_frame(citation = "[@chambers_2012]") ``` But not in a DT. ```{r, results='asis'} library(dplyr) library(DT) data_frame(citation = "[@chambers_2012]") %>% datatable() ``` # bibliography Sample references.bib @article{chambers_2012, title = {A cross-platform toolkit for mass spectrometry and proteomics.}, author = {Chambers, Matthew C and Maclean, Brendan and Burke, Robert and Amodei, Dario and Ruderman, Daniel L and Neumann, Steffen and Gatto, Laurent and Fischer, Bernd and Pratt, Brian and Egertson, Jarrett and Hoff, Katherine and Kessner, Darren and Tasman, Natalie and Shulman, Nicholas and Frewen, Barbara and Baker, Tahmina A and Brusniak, Mi-Youn and Paulse, Christopher and Creasy, David and Flashner, Lisa and Kani, Kian and Moulding, Chris and Seymour, Sean L and Nuwaysir, Lydia M and Lefebvre, Brent and Kuhlmann, Frank and Roark, Joe and Rainer, Paape and Detlev, Suckau and Hemenway, Tina and Huhmer, Andreas and Langridge, James and Connolly, Brian and Chadick, Trey and Holly, Krisztina and Eckels, Josh and Deutsch, Eric W and Moritz, Robert L and Katz, Jonathan E and Agus, David B and {MacCoss}, Michael and Tabb, David L and Mallick, Parag}, pages = {918-920}, url = {http://www.nature.com/doifinder/10.1038/nbt.2377}, year = {2012}, month = {oct}, urldate = {2018-01-13}, journal = {Nature Biotechnology}, volume = {30}, number = {10}, issn = {1087-0156}, doi = {10.1038/nbt.2377}, pmid = {23051804}, pmcid = {PMC3471674}, f1000-projects = {shared citations} } A: I suggest you render the citations using the RefManageR package. ```{r} library("RefManageR") bib <- ReadBib(file = "references.bib") invisible(data_frame(citation = RefManageR::TextCite(bib = bib))) ``` ```{r} data_frame(citation = RefManageR::TextCite(bib = bib, "chambers_2012", .opts = list(max.names = 1))) %>% DT::datatable() ``` Or with link: data_frame(citation = RefManageR::TextCite(bib = bib, "chambers_2012", .opts = list(style = "html", max.names = 1))) %>% DT::datatable(escape = FALSE) Check ?BibOptions for more options on output format, link type, etc. P.S. for whatever reason, the first time the function is called does not seem to fully take in consideration all options given, hence that invisible() call.
{ "language": "en", "url": "https://stackoverflow.com/questions/59556135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: innerHTML failing to inject text into markup I am learning about jQuerys animate and am building a small game where the user has to catch the box by trying to click on it and for every click the score increments by 1 point which is displayed dynamically on screen inside a <P> element. The problem is that the score is not showing in <p>. By debugging the application I can see that the score is infact being incremented so a flaw in incrementation is ruled out. The only other possibility I though that the reason was because $(document).ready was not being fired on each click but that is false because the score does infact increment. So my only solution that I can think of is that there is something going on behind the scenes with the way I have implemented .innerHTML but I cannot get my head around it. I have tried using value() instead of toString() as I initially believed that getting the actual value of variable points would return its raw numeric value but that didnt do anything. Here is the jQuery line I am having problems with: var points = 0; $(document).ready(function () { Animate(); div.on('mousedown', function () { points += 1; $('#points').innerHTML += points.toString(); }); }); And the HTML markup that it is referencing: <body> <p id="points">Total points: </p> <div id="box"></div> <script src="script.js"></script> </body> Please note that the point score needs to be added into <p> not replacing the contents of <p> for example if the point is incremented <p> will show Total Points: 1 And here is my JFiddle for a complete view of the problem A: Working Fiddle HTML <p id="points">Total points: <span id="total-points"></span></p> <div id="box"></div> Remove this Javascript $('#points').innerHTML += points.toString(); Replace with this $('#total-points').text(points); A: $(document).ready(function () { var totPoints="Total points: "; // define a variable with this string value Animate(); div.on('mousedown', function () { points += 1; $('#points').html( totPoints+ points.toString()); // concatenate and add the html alert("Points" + points.toString());// Wrote this to prove that points score IS being incremented }); }); A: Insted of using innerHtml u can direcly use $('#points').html( "Total points: "+ +points.toString()); Working jsFiddle A: Try using $("#points").html(points); this will work. using .innerHTML with jquery will give problems as jquery uses this in a different manner to pure js.
{ "language": "en", "url": "https://stackoverflow.com/questions/33931045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Detect BitLocker programmatically from c# without admin From various threads I've cobbled together how to check for BitLocker programmatically like this: private void TestBitLockerMenuItem_Click(object sender, RoutedEventArgs e) { var path=new ManagementPath(@"\ROOT\CIMV2\Security\MicrosoftVolumeEncryption") { ClassName="Win32_EncryptableVolume" }; var scope=new ManagementScope(path); path.Server=Environment.MachineName; var objectSearcher=new ManagementClass(scope, path, new ObjectGetOptions()); foreach (var item in objectSearcher.GetInstances()) { MessageBox.Show(item["DeviceID"].ToString()+" "+item["ProtectionStatus"].ToString()); } } But it only works if the process has admin privileges. It seems odd that any old Windows user can go to Explorer, right-click on a drive, and find out if it has BitLocker turned, but a program cannot seem to get this done. Does anyone know of a way to do this? A: Windows displays this in the shell by using the Windows Property System in the Win32 API to check the undocumented shell property System.Volume.BitLockerProtection. Your program will also be able to check this property without elevation. If the value of this property is 1, 3, or 5, BitLocker is enabled on the drive. Any other value is considered off. During my search for a solution to this problem, I found references to this shell property in HKEY_CLASSES_ROOT\Drive\shell\manage-bde\AppliesTo. Ultimately, this discovery lead me to this solution. The Windows Property System is a low-level API, but you can use the wrapper that's available in the Windows API Code Pack. Package Install-Package WindowsAPICodePack Using using Microsoft.WindowsAPICodePack.Shell; using Microsoft.WindowsAPICodePack.Shell.PropertySystem; Code IShellProperty prop = ShellObject.FromParsingName("C:").Properties.GetProperty("System.Volume.BitLockerProtection"); int? bitLockerProtectionStatus = (prop as ShellProperty<int?>).Value; if (bitLockerProtectionStatus.HasValue && (bitLockerProtectionStatus == 1 || bitLockerProtectionStatus == 3 || bitLockerProtectionStatus == 5)) Console.WriteLine("ON"); else Console.WriteLine("OFF"); A: The following COM method combined with reflection works with .NET 6 (and probably older versions) without requiring any external libraries. COM isn't really the most supported path but it is a good alternative. var netFwMgrType = Type.GetTypeFromProgID("Shell.Application", false); var manager = Activator.CreateInstance(netFwMgrType); var c = manager.GetType().InvokeMember("NameSpace", BindingFlags.InvokeMethod, null, manager, new object[] { "C:" }); var self = c.GetType().InvokeMember("Self", BindingFlags.GetProperty, null, c, new object[] { }); var result = self.GetType().InvokeMember("ExtendedProperty", BindingFlags.InvokeMethod, null, self, new object[] { "System.Volume.BitLockerProtection" }); You might need to add this to your csproj file depending on how you build your project. <BuiltInComInteropSupport>true</BuiltInComInteropSupport> The above doesn't work for LOCAL_SYSTEM account for some reason. So here is how you do it when you have admin privileges using WMI. Even though the question is specifically asking without admin, I think this is a good place to have this piece of code. This requires the .NET System.Management library. var result = new ManagementObjectSearcher(@"root\cimv2\security\MicrosoftVolumeEncryption", "SELECT * FROM Win32_Encryptablevolume") .Get().OfType<ManagementObject>() .Where(obj => obj.GetPropertyValue("DriveLetter").ToString() == "C:") .Select(obj => obj.GetPropertyValue("ConversionStatus")) .Cast<uint>() Note that this returns a different code than the other approach. Documented here: https://learn.microsoft.com/en-us/windows/win32/secprov/getconversionstatus-win32-encryptablevolume
{ "language": "en", "url": "https://stackoverflow.com/questions/41308245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Can i compute the "Look up names" property in Names-Field I have a Lotus Notes form with a field type "Names". On the control-tab of the field you can mark the "Look up names as each character is entered". Is there a way to compute this option based on a flag in the document? Thank you in advance! A: The only way that I know, is to use a computed subform. if the doc has the flag, show subform with field that have the property "Look up names as each character is entered". if the doc has not the flag, show subform with field that not have the property "Look up names as each character is entered". A: Using a subform as stated by adminfd is one possibility. But it has some disadvantages: * *you don't see the content of a computed subform in designer and cannot double click (inconvenient for developers). *using a lot of subforms can make loading the form very slow I usually do things like that with additional fields. I make the field itself hidden and computed with the formula: @If( YourCondition; FieldNameWithLookup; FieldNameWithoutLookup ); Then I create two fields above the hidden field, name them FieldNameWithLookup and FieldNameWithoutLookup and hide them using the same condition as in the Value- Formula of the field. Yes, it produces some overhead as there are two additional fields, that are not necessary, but I simply like this approach more. If you have existing documents, then you need the formula FieldName in the two new fields as default values and probably some code, if the Condition value for displaying one or the other field changes during different states of the document...
{ "language": "en", "url": "https://stackoverflow.com/questions/24186881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to retrieve Json from Oracle DB in spring boot I store Json as Clob in Oracle with a stored procedure using JDBC Template. Now I want to retrieve it from DB while calling from controller. How can I solve it? Which data type use to retrieve it? Should I create a field for inner fields of json as well? Because now I only hava one field for "entry" as Clob data type. Here is what I want to get: { data1:smth //I retrieved it data2: smth //I retrieved it entry: [ // Having trouble retrieving it entry1: {here is json data as well} ... ] }
{ "language": "en", "url": "https://stackoverflow.com/questions/68299886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ggplotly() ignores legend and produce different plot with ggplot legend I try to use ggplotly to run ggplot graph, but the legend label not showing the same things. Why it is? Please help. Thanks And also any idea to ignore the warning of changing to numeric data, so it doesnt show too many warning when run it through shiny. Thanks a lot The code are below structure(list(...1 = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "120", "121", "122", "123", "124", "125", "126", "127", "128", "129", "130", "131", "132", "133", "134", "135", "136", "137", "138", "139", "140", "141", "142", "143", "144", "145", "146", "147", "148", "149"), indexlist = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149), datainput = c("112069", "7377.02", "Unanswered", "675900", "Unanswered", "17323000", "1935328.98", "411079", "Unanswered", "38530.29", "96.5", "89268", "6380000", "32185.99", "102103", "Unanswered", "Question no match", "Unanswered", "Unanswered", "1441914.2080000001", "681325", "89340.307000000001", "234", "9278", "9809", "259550", "675900", "Unanswered", "168322", "Unanswered", "435708.78", "962.15899999999999", "681325", "81000", "38759", "Unanswered", "Question no match", "Unanswered", "195747", "Unanswered", "7070890", "10739506", "65430.91", "Unanswered", "61900", "Unanswered", "Unanswered", "5130068", "11556", "Unanswered", "Unanswered", "102364", "Unanswered", "103451.19", "9756559.5299999993", "16520", "644039", "16.187999999999999", "Unanswered", "Unanswered", "13154.44", "Question no match", "Question no match", "125131", "Unanswered", "Unanswered", "Unanswered", "608470.29", "Question no match", "Unanswered", "Unanswered", "Unanswered", "10496.82", "195747", "21399", "Unanswered", "214050", "1439.18", "681104", "10587765", "11816", "69528", "Unanswered", "26519409", "Question no match", "1013315", "17323000", "114016", "117723", "Unanswered", "Question no match", "555872.6", "8442.34", "1995000", "Unanswered", "7208", "152495", "372366", "132191.5", "21399", "Unanswered", "195747", "3207.89", "Unanswered", "77629", "195747", "Question no match", "Unanswered", "400", "Unanswered", "555872.6", "3291303", "110296.5", "Unanswered", "55715.991999999998", "186011", "Unanswered", "Question no match", "Unanswered", "385000", "Unanswered", "142829.75599999999", "125131", "Question no match", "20981", "Unanswered", "186011", "9701.8629999999994", "Unanswered", "102103", "5138", "4395555.97", "118398.916", "1638.58", "2749023", "Unanswered", "9394598", "20960", "17323000", "1232.19", "240468", "6963.1", "Unanswered", "348.99400000000003", "2513000", "4449880.6100000003", "Unanswered", "Unanswered", "27522854"), verification = c("Yes", "no information", "no answer", "Yes", "no answer", "Yes", "Yes", "Yes", "no information", "no information", "no information", "no information", "Yes", "Yes", "Yes", "no answer", "No", "no information", "no answer", "Yes", "Yes", "no information", "no information", "Yes", "Yes", "Yes", "Yes", "no answer", "No", "no answer", "no information", "no information", "Yes", "no information", "Yes", "no answer", "No", "no information", "Yes", "no answer", "Yes", "Yes", "Yes", "no answer", "Yes", "no answer", "no answer", "No", "No", "no answer", "no information", "Yes", "no answer", "Yes", "Yes", "Yes", "Yes", "No", "no answer", "no answer", "Yes", "no information", "No", "No", "no information", "no answer", "no answer", "No", "no information", "no answer", "no answer", "no information", "No", "Yes", "No", "no answer", "Yes", "Yes", "Yes", "Yes", "no information", "Yes", "no answer", "Yes", "no information", "Yes", "Yes", "Yes", "Yes", "no answer", "no information", "No", "no information", "Yes", "no answer", "Yes", "Yes", "Yes", "Yes", "No", "no answer", "Yes", "Yes", "no answer", "No", "Yes", "no information", "no answer", "no information", "no answer", "No", "Yes", "No", "no information", "No", "no answer", "no answer", "no information", "no answer", "Yes", "no answer", "Yes", "No", "no information", "Yes", "no answer", "no answer", "No", "no answer", "Yes", "no information", "Yes", "No", "Yes", "Yes", "no answer", "Yes", "Yes", "Yes", "Yes", "No", "No", "no answer", "no information", "Yes", "Yes", "no answer", "no answer", "Yes")), row.names = c(NA, -149L), class = c("tbl_df", "tbl", "data.frame"))->data_a p <- data_a%>% select(indexlist, datainput, verification) %>% mutate_at(c("datainput"), as.numeric)%>% drop_na(c("datainput"))%>% ggplot(aes(x=1:length(`datainput`), y=`datainput`, label= `indexlist`, color = `verification` == "Yes"))+ scale_colour_manual(name = 'Verification',breaks = c("TRUE", "FALSE"), values = c("green", "red"), labels = c("Verified", "Non-Verified"))+ geom_point(size=1.5, alpha = 0.4)+ geom_text(aes(label= ifelse(`datainput` > quantile(`datainput`, 0.975,na.rm = T), `indexlist`,"")), vjust = "inward", hjust = "inward", size = 2, color = "grey50")+ theme_minimal()+ labs(title = "datainput Details", x = "", y = "")+ theme( axis.text.x = element_text(size = 5.5), axis.text.y = element_text(size = 5.5), plot.title = element_text(color = "grey40", size = 9, face = "bold")) ggplotly(p) I have tried scale_manual_fill and colour but it doesnt work A: I have tried cleaning your data manipulation process by preparing the data before plotting. library(dplyr) library(plotly) library(ggplot2) p1 <- data_a %>% filter(grepl('\\d+', datainput)) %>% mutate(datainput = as.numeric(datainput), row = as.numeric(`...1`), verification = ifelse(verification == 'Yes', 'verified', 'Non-Verified')) %>% ggplot(aes(row, datainput, color = verification)) + scale_colour_manual(name = 'Verification', values = c("green", "red")) + geom_point(size=1.5, alpha = 0.4)+ geom_text(aes(label= ifelse(datainput > quantile(datainput, 0.975,na.rm = TRUE), indexlist,"")), vjust = -2, hjust = "inward", size = 2, color = "grey50") + theme_minimal()+ labs(title = "datainput Details", x = "", y = "")+ theme( axis.text.x = element_text(size = 5.5), axis.text.y = element_text(size = 5.5), plot.title = element_text(color = "grey40", size = 9, face = "bold")) plotly::ggplotly(p1) A: Try to keep data cleaning/preparation separate from plotting, see cleaned data and plot, now the ggplot and plotly look the same: library(tidyverse) library(plotly) # prepare the data plotData <- data_a %>% select(indexlist, datainput, verification) %>% # remove non-numeric rows before converting filter(!grepl("^[^0-9.]+$", datainput)) %>% # prepare data for plotting mutate(datainput = as.numeric(datainput), x = seq(n()), Verification = factor(ifelse(verification == "Yes", "Verified", "Non-Verified"), levels = c("Verified", "Non-Verified")), label = ifelse(datainput > quantile(datainput, 0.975, na.rm = TRUE), indexlist, "")) # then plot with clean data p <- ggplot(plotData, aes(x = x, y = datainput, color = Verification, label = label)) + scale_colour_manual(values = c("green", "red"))+ geom_point(size = 1.5, alpha = 0.4) + geom_text(vjust = "inward", hjust = "inward", size = 2, color = "grey50") + theme_minimal() + labs(title = "datainput Details", x = "", y = "") + theme(axis.text.x = element_text(size = 5.5), axis.text.y = element_text(size = 5.5), plot.title = element_text(color = "grey40", size = 9, face = "bold")) # now plotly ggplotly(p) ggplot plotly
{ "language": "en", "url": "https://stackoverflow.com/questions/66239942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dropdown hides behind a div event with a much higher z-index I have a dropdown menu that hides behind a div even though I've set for it a much higher z-index here's a screenshot. Hidhing menu A: By the amount of information I can collect after seeing that screenshot I can say it is either 1 of the following 2 problems: 1. The parent div of the div with class 'dropdown-menu' do not have "position: relative" property applied to it. 2. Two divs need to be sibling to each other to hide or show one of them behind the other using z-index (they can't have parent child relationship).
{ "language": "en", "url": "https://stackoverflow.com/questions/55921429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to correctly map texture when doing perspective warping in glsl using opengl es 2.0 I'm trying to create a four corner perspective effect using vertex shader and fragment shader. I set the vertex position infos to draw a perspective like shape, then map my texture on it. But somehow the texture is not correctly mapped. Here are two pictures to show you the problem. I find some infos from this post that texture2DProj maybe the right answer, but I don't quite understand how it works. I tried to do something like this, varying lowp vec4 TexCoordOut; uniform sampler2D Texture; void main(void) { gl_FragColor = texture2DProj(Texture, TexCoordOut); } And for the TexCoordOut I pass in {1, 0, 0, 1} {1, 1, 0, 1} {0, 1, 0, 1} {0, 0, 0, 1} to vertex shader, and varying it into fragment shader. But the result is the same. I only know how to use texture2D with vec2, how can I get the other two components of my texture coordinates to use them with texture2DProj? A: I suspect the issue is that your input coordinates are rendering a 2D shape, not a 3D one (i.e. you have a constant Z value for all 4 vertices). Rather than rendering a 2D shape, render a square which is tilted in 3D, and the varying interpolation will do the perspective correct divide for you. You can then use a normal texture2D() operation. You probably don't want projective texturing in this case - you could - but it's needlessly complicated (you still need to generate an appropriate "w" value for the texture coordinate to get the perspective divide working, so you may as well just do that per vertex and use the varying interpolator to do the heavy lifting). A: If you really want to use texture2DProj then you can copy the W coordinate from the position to the texture coordinate. For example: uniform mat4 uPrj; attribute vec2 aXY; attribute vec2 aST; varying vec4 st; void main(void) { vec4 pos=uPrj*vec4(aXY,0.0,1.0); gl_Position=pos; st=vec4(aST,0.0,pos.w); st.xy*=pos.w; // Not sure if this is needed with texture2DProj } However, I got round the problem of textures in perspective by splitting my quadrilateral into a grid of smaller quads, and then splitting each small quad into two triangles. Then you can use GLSL code like this: uniform mat4 uPrj; attribute vec2 aST; // Triangles in little squares in range [0,1]. varying vec2 st; void main(void) { vec2 xy=aST*2.0-1.0; // Convert from range [0,1] to range [-1,-1] for vertices. gl_Position=uPrj*vec4(xy,0.0,1.0); st=aST; } The above code runs fast enough (maybe even faster than texture2DProj), because the fragment shader runs for the same number of pixels, and the fragment shader can use the simpler texture2D method (no fragment projection necessary). You can reuse the net of triangles in aST for each of your quadrilaterals. Here is how I made aST in JavaScript: var nCell = 32; var nVertex = nCell * nCell * 6; var arST = prog._arST = new Float32Array(nVertex * 2); var k = 0; for (var j = 0; j < nCell; j++) { var j0 = j / nCell; var j1 = (j + 1) / nCell; for (var i = 0; i < nCell; i++) { var i0 = i / nCell; var i1 = (i + 1) / nCell; arST[k++] = i0; arST[k++] = j0; arST[k++] = i1; arST[k++] = j0; arST[k++] = i0; arST[k++] = j1; arST[k++] = i0; arST[k++] = j1; arST[k++] = i1; arST[k++] = j0; arST[k++] = i1; arST[k++] = j1; } } gl.bindBuffer(gl.ARRAY_BUFFER, prog._bufferST); gl.bufferData(gl.ARRAY_BUFFER, prog._arST, gl.STATIC_DRAW);
{ "language": "en", "url": "https://stackoverflow.com/questions/29847342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Write Files or Folder to IPFS via the HTTP API I'm confused about the HTTP API docs of IPFS。next is part of it。 /api/v0/add Add a file or directory to IPFS. //but how to add a directory by golang? it look like so simple but no a example to finish it #cURL Example curl -X POST -F file=@myfile "http://127.0.0.1:5001/api/v0/add?quiet=&quieter=&silent=&progress=&trickle=&only-hash=&wrap-with-directory=&chunker=size-262144&pin=true&raw-leaves=&nocopy=&fscache=&cid-version=&hash=sha2-256&inline=&inline-limit=32" A: I worked on the same issue and found this working shell solution: https://community.infura.io/t/ipfs-http-api-add-directory/189/8 you can rebuild this in go package main import ( "bytes" "github.com/stretchr/testify/assert" "io" "io/ioutil" "mime/multipart" "net/http" "os" "strings" "testing" ) func TestUploadFolderRaw(t *testing.T) { ct, r, err := createForm(map[string]string{ "/file1": "@/my/path/file1", "/dir": "@/my/path/dir", "/dir/file": "@/my/path/dir/file", }) assert.NoError(t, err) resp, err := http.Post("http://localhost:5001/api/v0/add?pin=true&recursive=true&wrap-with-directory=true", ct, r) assert.NoError(t, err) respAsBytes, err := ioutil.ReadAll(resp.Body) assert.NoError(t, err) t.Log(string(respAsBytes)) } func createForm(form map[string]string) (string, io.Reader, error) { body := new(bytes.Buffer) mp := multipart.NewWriter(body) defer mp.Close() for key, val := range form { if strings.HasPrefix(val, "@") { val = val[1:] file, err := os.Open(val) if err != nil { return "", nil, err } defer file.Close() part, err := mp.CreateFormFile(key, val) if err != nil { return "", nil, err } io.Copy(part, file) } else { mp.WriteField(key, val) } } return mp.FormDataContentType(), body, nil } or use https://github.com/ipfs/go-ipfs-http-client which seems to be a better way. I'm working on it and tell you when I know how to use it Greetings
{ "language": "en", "url": "https://stackoverflow.com/questions/68727572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: whats the best way to faciliate collaboration within a software org we have an org of around 300 people and certain people are very good at sharing articles, tips, blogs, etc but it usually happens within sub teams (between 5-15 people). whats the best way to scale this up to facilitate a culture of collaboration across a larger set of folks. * *Post to central WIKI instead of email links? *Reward contributors and encourage bottom up organic collaboration ? *"Force" collaboration top down ? A: You have to create an culture in which sharing is rewarded. * *Post to central WIKI instead of email links. *Reward contributors and encourage bottom up organic collaboration *"Force" collaboration top down. By "force" you mean reward and encourage. You must do all of this. And more. * *You must teach collaboration *You must assure that all managers value and reward collaboration *You must measure collaboration. Even then, you'll probably have to do even more. A: Good answer by S.Lott. I'd add: You need to make sure people can easily find things when they need them. That's partly cultural - do people think to look at the wiki, and do they know where to look. It's also about the wiki's structure & quality: * *Is it easy to navigate & search? *Is it kept up to date? *How does it mesh with other documentation (eg javadoc)? A: From my experience, forced = hated. So you have to make people want to use it, ie make it useful. A central Wiki sounds like the best solution, but it's hard to say. You might want to look into MediaWiki, Traq, or Sharepoint Services (not to be confused with Office Sharepoint). Your organization may find it encouraging if you post a list of the top contributors, editors, or visitors to the site. But that depends on how your org perceives competition. A: I wouldn't suggest a central wiki for collaboration (aside from internal specific stuff). But for sharing information found online you should encourage people to use one of the many existing systems for this. Google Reader has a really nice sharing and commenting mechanism. Delicious would also be a good fit for what you want. There's no reason to try to create a walled garden inside your organization for content that is being created outside of it. The system you create will not be as good as the ones that already exist and that will kill adoption.
{ "language": "en", "url": "https://stackoverflow.com/questions/2219405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Trying to cleanup a PS script I made I work for a k-12 district and I've been writing a script to add students in after school activities to different AD security groups so I can apply access card access specifically to their later schedules (currently all students have a standard time and we've just been leaving doors unlocked for after school stuff). Our students' after school activities are rostered in our SIS and Azure can pull all of those rosters and apply them to users. Our Access control manager only syncs with AD and not azure so I've made AD security groups and this script is attempting to sync the azure groups over to the security groups. I'm fairly new to powershell, so while I do have it working, my script is very long and took forever to figure out. I'm looking for reference on how I can shorten it $VB = Get-AzureADGroupMember -ObjectId zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz #volleybally $SOB = Get-AzureADGroupMember -ObjectId zzzzzzzzzzzzzzzzzzzzzzzzzzzz #Boys Soccer $SOG = Get-AzureADGroupMember -ObjectId xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5 #Girls Soccer $BG = Get-AzureADGroupMember -ObjectId 7xxxxxxxxxxxxxxxxxxxxxxxxxxx #Boys Golf $GG = Get-AzureADGroupMember -ObjectId xxxxxxxxxxxxxxxxxxxxxxxxxxxxx1c #Girls Golf $CC = Get-AzureADGroupMember -ObjectId zzzzzzzzzzzzzzzzzzzzzzzzzzzzz #Cross Country $FCL = Get-AzureADGroupMember -ObjectId xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx #Fall Cheerleading $SDD = Get-AzureADGroupMember -ObjectId xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx #Speech Drama & Debate #initiate SG Groups $SGCC = Get-ADGroup -Identity sample group 1 $SGFC = Get-ADGroup -Identity sample group 2 $SGFB = Get-ADGroup -Identity sample group 3 $SGGO = Get-ADGroup -Identity sample group 4 $SGSO = Get-ADGroup -Identity sample group 5 $SGVB = Get-ADGroup -Identity sample group 6 # convert azure values to AD and add to AD groups $FB= Foreach($ad in $FB) { Get-ADUser ($ad.UserPrincipalName.Split('@')[0]) } $VB = Foreach($ad in $VB) { Get-ADUser ($ad.UserPrincipalName.Split('@')[0]) # your text } $SOB = Foreach($ad in $SOB) { Get-ADUser ($ad.UserPrincipalName.Split('@')[0]) } $SOG = Foreach($ad in $SOG) { Get-ADUser ($ad.UserPrincipalName.Split('@')[0]) } $BG = Foreach($ad in $BG) { Get-ADUser ($ad.UserPrincipalName.Split('@')[0]) } $GG = Foreach($ad in $GG) { Get-ADUser ($ad.UserPrincipalName.Split('@')[0]) } $CC = Foreach($ad in $CC) { Get-ADUser ($ad.UserPrincipalName.Split('@')[0]) } $FCL = Foreach($ad in $FCL) { Get-ADUser ($ad.UserPrincipalName.Split('@')[0]) } $SDD = Foreach($ad in $SDD) { Get-ADUser ($ad.UserPrincipalName.Split('@')[0]) } #### add AD Members to SG Add-AdGroupMember -Identity $SGFB -Members $FB # Looking to simplify, To be continued I've written it the long way. Curious if anyone has ideas on how to do it better. Like I said, I'm a PS noob. A: I think you could simplify your task by using a hash table ($map) where the Keys are the GUIDs of each Azure Group and the Values are each AD Group where the Az Group members need to be added. For example: $map = @{ 'xxxxxxxxxxxx' = 'group 1', 'group 5', 'group 8' # Football 'zzzzzzzzzzzz' = 'group 2' # Volleyball 'yyyyyyyyyyyy' = 'group 3', 'group 4' # Boys Soccer # and so on here } foreach($pair in $map.GetEnumerator()) { # I think you could use `DisplayName` instead of `UserPrincipalName` here # and don't have a need to parse the UPNs $azMembers = (Get-AzureADGroupMember -ObjectId $pair.Key).DisplayName foreach($adGroup in $pair.Value) { Add-ADGroupMember -Identity $adGroup -Members $azMembers.DisplayName } } As stated in the inline comment, I believe using .DisplayName would suffice since -Members takes one of these values: * *Distinguished name *GUID (objectGUID) *Security identifier (objectSid) *SAM account name (sAMAccountName) But considering this may not be case and that doesn't work, then an easier and safer way to parse the user's UserPrincipalName rather than using .Split('@')[0] would be to use the MailAddress class, so using it the code would look like this: # here goes the `$map` too! foreach($pair in $map.GetEnumerator()) { $azMembers = [mailaddress[]] (Get-AzureADGroupMember -ObjectId $pair.Key).UserPrincipalName foreach($adGroup in $pair.Value) { Add-ADGroupMember -Identity $adGroup -Members $azMembers.User } }
{ "language": "en", "url": "https://stackoverflow.com/questions/74310371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I want to store user entered vaule in some variable and use in another function or want to some opeartion on user input data const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout, }) readline.question('Enter number 1', function (a) { readline.question('Enter number 2', function (b) { //`i want to store user entered vaule in some variable and use in another function like sum` var one = a var two = b readline.close() }) }) function sum(one,two) { return one + two } My motive is to store user entered value and perform some operation on it or store to call another function with the input value. How can I achieve that? In another language like C++ it is very simple but in node.js I am unable to figure it out. Please note that I do not want to use prompt, I want user to provide input from console A: One of the simplest way to use scoped variables within another function is to simply pass them in as arguments of the function. e.g. const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout, }) readline.question('Enter number 1', function (a) { readline.question('Enter number 2', function (b) { //`i want to store user entered vaule in some variable and use in another function like sum` const result = sum(a, b); console.log(`The result of running my function is ${result}`); readline.close() }) }) function sum(first,second) { return first + second; }
{ "language": "en", "url": "https://stackoverflow.com/questions/68710112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you you run a Twisted application via Python (instead of via Twisted)? I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example: from twisted.protocols import basic class MyChat(basic.LineReceiver): def connectionMade(self): print "Got new client!" self.factory.clients.append(self) def connectionLost(self, reason): print "Lost a client!" self.factory.clients.remove(self) def lineReceived(self, line): print "received", repr(line) for c in self.factory.clients: c.message(line) def message(self, message): self.transport.write(message + '\n') from twisted.internet import protocol from twisted.application import service, internet factory = protocol.ServerFactory() factory.protocol = MyChat factory.clients = [] application = service.Application("chatserver") internet.TCPServer(1025, factory).setServiceParent(application) However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command: twistd -y chatserver.py Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via: python chatserver.py I've Googled, but the search terms seem to be too vague to return any meaningful responses. Thanks. A: I don't know if it's the best way to do this but what I do is instead of: application = service.Application("chatserver") internet.TCPServer(1025, factory).setServiceParent(application) you can do: from twisted.internet import reactor reactor.listenTCP(1025, factory) reactor.run() Sumarized if you want to have the two options (twistd and python): if __name__ == '__main__': from twisted.internet import reactor reactor.listenTCP(1025, factory) reactor.run() else: application = service.Application("chatserver") internet.TCPServer(1025, factory).setServiceParent(application) Hope it helps! A: On windows you can create .bat file with your command in it, use full paths, then just click on it to start up. For example I use: runfileserver.bat: C:\program_files\python26\Scripts\twistd.py -y C:\source\python\twisted\fileserver.tac A: Maybe one of run or runApp in twisted.scripts.twistd modules will work for you. Please let me know if it does, it will be nice to know! A: Don't confuse "Twisted" with "twistd". When you use "twistd", you are running the program with Python. "twistd" is a Python program that, among other things, can load an application from a .tac file (as you're doing here). The "Twisted Command Prompt" is a Twisted installer-provided convenience to help out people on Windows. All it is doing is setting %PATH% to include the directory containing the "twistd" program. You could run twistd from a normal command prompt if you set your %PATH% properly or invoke it with the full path. If you're not satisfied with this, perhaps you can expand your question to include a description of the problems you're having when using "twistd". A: I haven't used twisted myself. However, you may try seeing if the twistd is a python file itself. I would take a guess that it is simply managing loading the appropriate twisted libraries from the correct path. A: I am successfully using the simple Twisted Web server on Windows for Flask web sites. Are others also successfully using Twisted on Windows, to validate that configuration? new_app.py if __name__ == "__main__": reactor_args = {} def run_twisted_wsgi(): from twisted.internet import reactor from twisted.web.server import Site from twisted.web.wsgi import WSGIResource resource = WSGIResource(reactor, reactor.getThreadPool(), app) site = Site(resource) reactor.listenTCP(5000, site) reactor.run(**reactor_args) if app.debug: # Disable twisted signal handlers in development only. reactor_args['installSignalHandlers'] = 0 # Turn on auto reload. import werkzeug.serving run_twisted_wsgi = werkzeug.serving.run_with_reloader(run_twisted_wsgi) run_twisted_wsgi() old_app.py if __name__ == "__main__": app.run()
{ "language": "en", "url": "https://stackoverflow.com/questions/1897939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Classic ASP: How to reload the page, preserve url parameters and add a new one? I'm working with a "Multi-Language Page" - And I want to change the language and preserve all url parameters in the page - because the page is using this values. ex: page.com/demo.asp?name=John&color=Blue If the user click on language and change the language I need to: 1- Send a new parameter - Here I guess - the best way to do this is send another parameter like this: page.com/demo.asp?name=John&color=Blue&lang=ES right? Then I create a link on "ES" option with this URL. > create_url = > Request.ServerVariables("URL")&"?"&Request.ServerVariables("Query_String") > new_url = REPLACE(create_url, "&lang=", "&newlang=") The REPLACE works to avoid multiples "&lang" on the url if the user change the language many times. and HTML: <a href="<%=new_url%>&lang=ES">ES</a> <a href="<%=new_url%>&lang=EN">EN</a> <a href="<%=new_url%>&lang=PT">PT</a> <a href="<%=new_url%>&lang=FR">FR</a> When I click the link - page is reload - all parameters still valids - and I can add the "LANG" now. but... MY ISSUE: IF I HAVE NO ONE PARAMETERS IN THE URL - and "&LANG" is the FIRST I got a BUG... because I will pass this: page.com/demo.asp?&LANG=ES and the correct way is page.com/demo.asp?LANG=ES without the "&" any idea? tks a lot!!! Daniel A: Maybe using replace with that kind of RegEx : https://regex101.com/r/MRmZ00/3 (.*[?&]lang=)[A-Z]{2}(.*) Output : '$1' + newlang + '$2' Working if it's your only parameter or your first one ?lang=ES or anywhere else in the url &lang=ES. A: URI.js is a javascript library for working with URLs. It offers a "jQuery-style" API (Fluent Interface, Method Chaining) to read and write all regular components and a number of convenience methods like .directory() and .authority(). Here is link Here is example : URI(location.href).addQuery("lang", languageName);
{ "language": "en", "url": "https://stackoverflow.com/questions/49397655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CheckBox Gridview Enable and Disable I have a gridview where the checkboxes start off disabled. I want to enable them when I click the edit button that's also in the gridview. Here's the markup <asp:GridView ID="grd_Bookcode" runat="server" DataSourceID="sqldatasource1" autogeneratecolumns="False" onrowcommand="grd_Bookcode_RowCommand1" onrowdatabound="grd_Bookcode_RowDataBound"> <Columns> <asp:BoundField DataField="BookCode" HeaderText="Book Code"/> <asp:BoundField DataField="mag_name" HeaderText="Name"/> <asp:BoundField DataField="display_date" HeaderText="Display Date"/> <asp:TemplateField HeaderText = "PC"> <ItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("82_PC").ToString() == "1" ? true:false %>' Enabled="false" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="eReader"> <ItemTemplate> <asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Eval("83_eReader").ToString() == "1" ? true:false %>' Enabled="false" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Tablet"> <ItemTemplate> <asp:CheckBox ID="CheckBox3" runat="server" Checked='<%# Eval("84_Tablet").ToString() == "1" ? true:false %>' Enabled="false"/> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Mobile"> <ItemTemplate> <asp:CheckBox ID="CheckBox4" runat="server" Checked='<%# Eval("85_Mobile").ToString() == "1" ? true:false %>' Enabled="false" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="None"> <ItemTemplate> <asp:CheckBox ID="CheckBox5" runat="server" Checked='<%# Eval("86_None").ToString() == "1" ? true:false %>' Enabled="false" /> </ItemTemplate> </asp:TemplateField> <asp:CommandField ShowEditButton="True" /> </Columns> And then here's the code that I'm trying to use. Basically, when I hit the edit button, I want the checkboxes themselves to be enabled. For whatever reason, the checkbox isn't enabled at all when the page loads back up. I just started off trying to enable "Checkbox1" after the edit button is clicked but eventually want to enable all 5 checkboxes. protected void grd_Bookcode_RowCommand1(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Edit") { int index = Convert.ToInt32(e.CommandArgument); GridViewRow row = grd_Bookcode.Rows[index]; CheckBox chk = (CheckBox)row.FindControl("CheckBox1"); chk.Enabled = true; } } A: If you want the Edit control to be different than the standard control, you should use the "EditItemTemplate". This will allow the edit row to have different controls, values, etc... when the row's mode changes. Example: <Columns> <asp:TemplateField HeaderText="PC"> <ItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("82_PC").ToString() == "1" ? true:false %>' Enabled="false" /> </ItemTemplate> <EditItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" Checked="true" Enabled="false" /> </EditItemTemplate> </asp:TemplateField> </Columns> A: I guess you could loop through all the rows of the GridView and enable the checkboxes something like below: protected void grd_Bookcode_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Edit") { for (int index = 0; index < GridView1.Rows.Count; index++) { CheckBox chk = grd_Bookcode.Rows[index].FindControl("CheckBox" + index + 1) as CheckBox; chk.Enabled = true; } } } Hope this helps!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7364201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ListView delete line with matching field i have a listview like the following: Name | Gender | Age --------------------- Name1 | XX | 23 Name2 | XY | 21 Name3 | XY | 25 Name4 | XX | 30 When the listview gets filled, it creates entries of a combobox like this: If Not ComboBox4.Items.Contains(gender) Then ComboBox4.Items.Add(gender) End If So I end up with a combobox with 2 entries (XX, XY). Now i want to delete all lines matching to the gender selected in the combobox. The seleted entry then gets removed from the combobox. Example: I select gender 'XX' to be removed, then the program removes the whole line with 'name1, XX , age 23' and 'name4, XX, 30' from the listview. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click for i = 1 to viewlist.items.count 'Need help here to select the right column/viewlist-field next ComboBox4.Items.Remove(ComboBox4.Text) End Sub Thanks in advance A: First of all, your loop should start at viewlist.Items.Count - 1 and end at 0. This is because the right side of To is only evaluated prior to the first iteration. Due to this the loop will go to whatever viewlist.Items.Count - 1 was before the loop was run, instead of what it actually is after removing items (hence why you got the ArgumentOutOfRangeException from my previous code). By starting from the end and going towards 0 i will always represent a valid index as long as you remove at most one item per iteration. This can be illustrated by the following: First iteration Second iteration Third iteration (and so on) Item 0 Item 0 Item 0 Item 1 Item 1 (i) Item 1 Item 2 (i) Item 2 [Removed] (i) Item 3 [Removed] [Removed] Now, to get a sub-column of an item you can use the ListViewItem.SubItems property. Your Gender column is currently at index 1 - the first sub-item (index 0) is apparently the owner of all sub-items, that is, the original ListViewItem. For i = viewlist.Items.Count - 1 To 0 Step -1 Dim CurrentSubItems As ListViewItem.ListViewSubItemCollection = viewlist.Items(i).SubItems If CurrentSubItems.Count >= 2 AndAlso CurrentSubItems(1).Text = ComboBox4.Text Then viewlist.Items.RemoveAt(i) End If Next ComboBox4.Items.Remove(ComboBox4.Text) If you want to use case-insensitive string comparison you can change the If-statement in the loop to: If CurrentSubItems.Count >= 2 AndAlso String.Equals(CurrentSubItems(1).Text, ComboBox4.Text, StringComparison.OrdinalIgnoreCase) Then
{ "language": "en", "url": "https://stackoverflow.com/questions/41825728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make Telegram Instant View wait for page to render javascript? I want to create a template for my blog, which is written in React and is rendered on the client-side. I wonder, is there a way to hint the Telegram Instant View that I want it to fetch and execute client-side javascript and wait until it renders dynamic page content, before starting to process my Instant View template and extracting elements from it with XPath? As a workaround I had to implement isomorphic server-side rendering so far. A: There is no "Telegram IV bot" available in API or something like that. Instead you should got InstantView documentation and create a template yourself. Unfortunately, there is currently no way to add "native" support for IV on your site, after you make a template, you can extract an rhash parameter while using "Check in Telegram" feature in IV editor. After you finish your template, using links "https://t.me/iv?url=YOUR_URL&rhash=YOUR_RHASH" will show people an Instant View article from YOUR_URL.
{ "language": "en", "url": "https://stackoverflow.com/questions/48951864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how can i get the parent elements id, that surrounds the php code, wtih php I'd like to check if the executed php code is within the div called "parent2". I am working on a joomla html override and i have to put one module on 2 different positions. If the module is inside of parent2 some different code should be executed inside of the html override. The only Problem I have right now is, that I don't know how to check the parent id's that surround the php code. <div id="parent2"> <div id="parent1"> <?php echo ; /*id of the second parent. Here would be the php code of the html override*/ ?> </div> </div> I want the echo function to print "parent2". Parent1 and Parent2 are part of the joomla template and inside of parent1 there is a jdoc:include module position. I really tried to find a solution via google but all i could find was something with DOMDocument and html parsers, which i believe wont help me. A: This is not possible with PHP as far as I know. You should consider this particular snippet of PHP will ALWAYS be executed inside parent2 as parent2 is hardcoded in the PHP file.
{ "language": "en", "url": "https://stackoverflow.com/questions/30053163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Angular page can't open I'm beginner to Angular I'm try to make sample web site, I have some issue , I'm crated 2 pages , about.component.html and Contact.component.html But I can't open those pages. I want to know how to correctly set of link to that, and what is best to use for the develop web site Angular or Angular-js? app-navbar.component.html <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation" (click)="toggleCollapsed()"> <span class="navbar-toggler-icon"></span> </button> <div id="navbarSupportedContent" [ngClass]="{'collapse': collapsed, 'navbar-collapse': true}"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" >DASHBOARD<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="about.component.html">About</a> </li> </div> </nav> app-navbar.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-navbar', templateUrl: './app-navbar.component.html', styleUrls: ['./app-navbar.component.css'] }) export class AppNavbarComponent implements OnInit { constructor() { } date = new Date(); ngOnInit() { } } app-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import {IndexComponent} from './index/index.component'; @NgModule({ exports: [ RouterModule ] }) export class AppRoutingModule {} const routes: Routes = [ { path: 'inde', component: IndexComponent, }, // map '/' to '/persons' as our default route { path: '', redirectTo: '/index', pathMatch: 'full' }, ]; export const appRouterModule = RouterModule.forRoot(routes); A: You should use routerLink. not href. You can routerLink. after import RouterModule. If you want to route to about component, you should write route info for about component in app-routing.module.ts. Official document is here =>> https://angular.io/api/router/RouterLink example code is (only required code) app-navbar.component.html <a class="nav-link" [routerLink]="['/about']">About</a> app-navbar.module.ts @NgModule({ imports: [RouterModule] }) app-routing.module.ts const routes: Routes = [{path: 'about', component: AboutComponent}]; A: You Should Use routerLink <a routerLink="/about.component"> and Make Sure that u added that component in Routes{ path: 'about.component', component: AboutComponent },
{ "language": "en", "url": "https://stackoverflow.com/questions/47880638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cloudant Lucene boost factor during indexing During indexing time it is possible to set a boost factor value which then changes the position of specific record in the array of returned documents. Example: index("default", doc.my_field, {"index": "analyzed", "boost": doc.boostFactor}); When applying this boost factor I can see that the sorting changes. However, it appears to be rather random. I would expect a number greater than 1 would sort the document higher. Did anybody managed to get the boost factor with Cloudant to work correctly? A: Yes, Cloudant boost factor should work correctly. Setting boost to a field of a specific doc, will modify the score of this doc: Score = OriginalScore * boost while searching on this field. Do you search on the same field you boost? How does your query look like? Does the field my_field consists of multiple tokens? This may also influence scoring (e.g. longer fields get scored less). You can observe scores of docs in the order fields in the results, and then by modifying boost observe how the scores are changing.
{ "language": "en", "url": "https://stackoverflow.com/questions/41838322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server (running/stopped) Status in SSMS In the attached image below, I show my SQL Server as seen from SSMS on my PC (left) compared to the same as seen from the server (right) ... could someone advise why the view from my PC does not show the status indicator (running/stopped) for the server and for the SQL Server Agent items? Also, when you right-click on either of the options, the selection for START|STOP|RESTART are all greyed out....? For these screenshots, I am connected from my PC with a user account that should have maximum access; under the security settings for this account EVERYTHING is checked. A: Access to a remote Service Control Manager (SCM) is subject to OS privileges. W/o SCM privileges you cannot know what services are running, nor can you start or stop any. The required privileges are listed at Access Rights for the Service Control Manager. None of the above is in any way at all related to SQL Server security. Services are controlled by SCM, not SQL Server.
{ "language": "en", "url": "https://stackoverflow.com/questions/24037449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Save XML from Url and read it I'm making android App and I need to download a xml file from an URL and open it, How I can do this? public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); File dir1 = getDir("xmls",Context.MODE_PRIVATE);//Creating an internal dir; System.out.println("dir1: " + dir1); //Saving The File try { URL url = new URL("http://www. the url of my xml .xml"); // The server thinks this request is from an Opera browser! String userAgent = "Opera/9.63 (Windows NT 5.1; U; en) Presto/2.1.1"; System.out.println("Downloading ..."); downloadFromUrl(url, dir1+"news.xml", userAgent); System.out.println("OK"); } catch (Exception e) { System.err.println(e); System.out.println("Entri pure nel catch"); } //This is the path of the xml file that i have saved URL = dir1+"/news.xml" ; ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(URL); // getting XML from UR Document doc = parser.getDomElement(xml); // getting DOM element //And then i do all the parsing NodeList nl = doc.getElementsByTagName(KEY_CATEGORIA); And the XMlParser Class is like this: public class XMLParser_Categorie { // constructor public XMLParser_Categorie() { } /** * Getting XML from URL making HTTP request * @param url string * */ public String getXmlFromUrl(String url) { String xml = null; try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // return XML return xml; } I need to change this instruction: DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity); It a request from a local directory and non an http request. A: Here is code snippet for you , try { URL url = new URL("your url goes here"); //create the new connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); //set the path where we want to save the file //in this case, going to save it on the root directory of the //sd card. File SDCardRoot = Environment.getExternalStorageDirectory(); //create a new file, specifying the path, and the filename //which we want to save the file as. File file = new File(SDCardRoot,"Demo.xml"); //this will be used to write the downloaded data into the file we created FileOutputStream fileOutput = new FileOutputStream(file); //this will be used in reading the data from the internet InputStream inputStream = urlConnection.getInputStream(); //this is the total size of the file int totalSize = urlConnection.getContentLength(); progressDialog.setMax(totalSize); //variable to store total downloaded bytes int downloadedSize = 0; //create a buffer... byte[] buffer = new byte[1024]; int bufferLength = 0; //used to store a temporary size of the buffer //now, read through the input buffer and write the contents to the file while ( (bufferLength = inputStream.read(buffer)) > 0 ) { //add the data in the buffer to the file in the file output stream (the file on the sd card fileOutput.write(buffer, 0, bufferLength); //add up the size so we know how much is downloaded downloadedSize += bufferLength; } //close the output stream when done fileOutput.close(); //catch some possible errors... } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Else these link can help you, 1)Read remote XML in android 2)Download remote XML and store it in android
{ "language": "en", "url": "https://stackoverflow.com/questions/16333145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MergeMap from Array of Observables TLDR: Working example is in the last codeblock of this question. Check out @bryan60 answer for a working example using concat rather than mergeMap. I'm trying to run a number of remote requests sequentially, but only the first observable is executed. The number of request vary, so I can't do a dodgy solution where I nest observables within each other. I'm using the following code: const observables = [ observable1, observable2, ... ]; from(observables).pipe( mergeMap(ob=> { return ob.pipe(map(res => res)); }, undefined, 1) ).subscribe(res => { console.log('Huzzah!'); }) In the past (rxjs 5.5) Ive used the following: let o = Observable.from(observables).mergeMap((ob) => { return ob; }, null, 1); o.subscribe(res => { console.log('Huzzah!'); }) I'm not sure what I'm doing wrong, can anybody shed some light? An additional request would be to only print 'Huzzah!' once on completion of all requests rather than for each individual Observable. EDIT: Removing undefined from my original code will make it work, however there was another issue causing only the first observable to be executed. I'm using Angular's HttpClient for remote requests. My observable code looked like this: const observables = []; // Only the first observable would be executed observables.push(this.http.get(urla)); observables.push(this.http.get(urlb)); observables.push(this.http.get(urlc)); Adding .pipe(take(1)) to each observable results in each observable being executed: const observables = []; // All observables will now be executed observables.push(this.http.get(urla).pipe(take(1)); observables.push(this.http.get(urlb).pipe(take(1)); observables.push(this.http.get(urlc).pipe(take(1)); The code I ended up using, which executes all observables in sequential order and only triggers Huzzah! once is: const observables = []; observables.push(this.http.get(urla).pipe(take(1)); observables.push(this.http.get(urlb).pipe(take(1)); observables.push(this.http.get(urlc).pipe(take(1)); from(observables).pipe( mergeMap(ob=> { return ob.pipe(map(res => res)); }, 1), reduce((all: any, res: any) => all.concat(res), []) ).subscribe(res => { console.log('Huzzah!'); }) Thanks to @bryan60 for helping me wit this issue. A: if these are http requests that complete, I think your bug is caused by a change to the mergeMap signature that removed the result selector. it's hard to be sure without knowing exactly which version you're on as it was there, then removed, then added again, and they're removing it once more for good in v7. if you want to run them sequentially... this is all you need... // concat runs input observables sequentially concat(...observables).subscribe(res => console.log(res)) if you want to wait till they're all done to emit, do this: concat(...observables).pipe( // this will gather all responses and emit them all when they're done reduce((all, res) => all.concat([res]), []) // if you don't care about the responses, just use last() ).subscribe(allRes => console.log(allRes)) In my personal utility rxjs lib, I always include a concatJoin operator that combines concat and reduce like this. the only trick is that concat requires observables to complete till it moves on to the next one, but the same is true for mergeMap with concurrent subscriptions set to 1.. so that should be fine. things like http requests are fine, as they complete naturally after one emission.. websockets or subjects or event emitters will behave a bit differently and have to be manually completed, either with operators like first or take or at the source. A: If you are not concerned about the sequence of execution and just want 'Huzzah!' to be printed once all the observable has been executed forkJoin can also be used.Try this. forkJoin(...observables).subscribe(res => console.log('Huzzah');
{ "language": "en", "url": "https://stackoverflow.com/questions/61896257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Localization works in iOS 7 but not in iOS 8 I have localized versions of a file hello.txt in folders en.lproj and fr.lproj. When I run the following code on iOS 7 simulator with language set to French, the French version is loaded. But with iOS 8 in French, I only get English... Why? println (NSLocale.preferredLanguages().first!) println (NSBundle.mainBundle().preferredLocalizations.first!) let path = NSBundle.mainBundle().pathForResource ("hello", ofType: "txt") let text = NSString (contentsOfURL: NSURL (fileURLWithPath: path!)!, encoding: NSUTF8StringEncoding, error: nil) println (text!) A: Known issues in Xcode 6.1: Localization and Keyboard settings (including 3rd party keyboards) are not correctly honored by Safari, Maps, and developer apps in the iOS 8.1 Simulator. [NSLocale currentLocale] returns en_US and only the English and Emoji keyboards are available. (18418630, 18512161) Problem exists since Xcode 6 GM
{ "language": "en", "url": "https://stackoverflow.com/questions/27212336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding a column to a Dataframe containing the Symbol of the parent node I am using bulk data (List of CPC Valid symbols) from the CPC website. I've read the csv into a pandas df, and the first 30 rows (of over 260K) are: SYMBOL level not-allocatable additional-only 1 A 2 True False 2 A01 4 True False 3 A01B 5 True False 4 A01B 1/00 7 False False 5 A01B 1/02 8 False False 6 A01B 1/022 9 False False 7 A01B 1/024 9 False False 8 A01B 1/026 9 False False 9 A01B 1/028 9 False False 10 A01B 1/04 9 False False 11 A01B 1/06 8 False False 12 A01B 1/065 9 False False 13 A01B 1/08 9 False False 14 A01B 1/10 9 False False 15 A01B 1/12 9 False False 16 A01B 1/14 9 False False 17 A01B 1/16 8 False False 18 A01B 1/165 9 False False 19 A01B 1/18 9 False False 20 A01B 1/20 8 False False 21 A01B 1/22 8 False False 22 A01B 1/222 9 False False 23 A01B 1/225 10 False False 24 A01B 1/227 9 False False 25 A01B 1/24 8 False False 26 A01B 1/243 9 False False 27 A01B 1/246 9 False False 28 A01B 3/00 7 False False 29 A01B 3/02 8 False False The level value creates a hierarchy. So node A01B 1/00 is level 7 and a child of A01B. A01B 1/02 is level 8 and the child of A01B 1/00 & A01b 3/00 is a child of A01B. What I would like is a way to create a new column called PARENT that contains the SYMBOL of the node's direct parent. For example, I edited the csv in Excel to show the desired result of the first few rows: Note: there are no level 1, 3, or 6 symbols. There are multiple level 2 symbols. There is no parent for level 2 symbols, the parent of level 4 symbols can be assigned the first level 2 symbol above it, and the parent of level 7 symbols likewise can be assigned the first level 5 symbol above it. EDIT: I need to better explain how to determine a node's parent. The level value and the row position are all that is needed to determine a parent. I would like to use pandas to do the work, but I am not sure how to get started. Any takers? Thank you A: In this answer I assume that your direct parent is always in a row above your own as it is what your expected output and your diagramm suggests. With this hypothesis, we can, for each row, take the closest row with a level below the row : import pandas as pd data={"Symbol":["A", "A01", "A01B", "A01B 1/00", "A01B 1/02", "A01B 1/022", "B"], "level":[2,4,5,7,8,9,2]} df=pd.DataFrame(data=data) df['Parent'] = '' for index, row in df.iterrows(): # We look at the potential parents potential_parents = df.loc[df.index.isin([x for x in range(index)]) & (df['level'] < row['level']), 'Symbol'] # And we take the last one as our parent if len(potential_parents) == 0: df.loc[index, 'Parent'] = '' else: df.loc[index, 'Parent'] = potential_parents.iloc[-1] Output : Symbol level Parent 0 A 2 1 A01 4 A 2 A01B 5 A01 3 A01B 1/00 7 A01B 4 A01B 1/02 8 A01B 1/00 5 A01B 1/022 9 A01B 1/02 6 B 2 A: Here's another method. GetParent() returns a function that keeps track of the most recent symbol for each level and returns the parent of the current level. Using it in pandas.apply() creates a column with the parent symbols. def GetParent(): # 0 1 2 3 4 5 6 7 8 9 10 hierarchy = [0, 0, 0, 0, 2, 4, 0, 5, 7, 8, 9] parent = [' ']*11 def func(row): #print(row) symbol,level = row[['SYMBOL', 'level']] parent_level = hierarchy[level] parent_symbol = parent[parent_level] parent[level] = symbol return pd.Series([parent_symbol], index=['parent']) return func # create a column with the parents parents = df.apply(GetParent(), axis=1) df = pd.concat([df, parents], axis=1) df Output: SYMBOL level na ao parent 0 A 2 True False 1 A01 4 True False A 2 A01B 5 True False A01 3 A01B 1/00 7 False False A01B 4 A01B 1/02 8 False False A01B 1/00 5 A01B 1/022 9 False False A01B 1/02 6 A01B 1/024 9 False False A01B 1/02 7 A01B 1/026 9 False False A01B 1/02 8 A01B 1/028 9 False False A01B 1/02 9 A01B 1/04 9 False False A01B 1/02 10 A01B 1/06 8 False False A01B 1/00 11 A01B 1/065 9 False False A01B 1/06 12 A01B 1/08 9 False False A01B 1/06 ...
{ "language": "en", "url": "https://stackoverflow.com/questions/56368124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to loop + 7 days and display the data based on that loop I have a problem with my code, I want to show Tadarus, Kajian, Edukasi and Umum. example I have variable $startdate = '2019-09-20'. If $startdate + 7day, I want to echo Tadarus If $startdate + 14day, I want to echo Kajian If $startdate + 21day, I want to echo Edukasi If $startdate + 28day, I want to echo Umum and then if last echo is Umum, I want to show data from Tadarus again. This is my code: date_default_timezone_set("Asia/Jakarta"); $getdate = date("Y-m-d"); if (strtotime("+7 day", $getdate)) { echo "Tadarus"; }elseif(strtotime("+14 day", $getdate)){ echo "Kajian"; }elseif(strtotime("+21 day", $getdate)){ echo "Edukasi"; }elseif(strtotime("+28 day", $getdate)){ echo "Umum"; } A: Why don't you do something like that: function echoBasedOnDay($date) { if ($date === date('Y-m-d', strtotime("+7 days"))) { echo "Tadarus"; } elseif($date === date('Y-m-d', strtotime("+14 days"))){ echo "Kajian"; } elseif($date === date('Y-m-d', strtotime("+7 days"))){ echo "Edukasi"; } elseif($date === date('Y-m-d', strtotime("+7 days"))){ echo "Umum"; } } echoBasedOnDay(date('2019-09-27')); // You can pass any date you want in here as the function's parameter
{ "language": "en", "url": "https://stackoverflow.com/questions/58029875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to setup path to jupyter lab of activated environment I need to configure several pieces of software to access various executables that might change with conda environments. I know that this is broad so lets stick to jupyter lab, I want to add an item to Windows' context menu. I have all of keys in my registy setup except for Default of command and this entry needs to path to jupyter lab. As I understand all anaconda's executables will be found in Users\my.name\AppData\Local\Continuum\anaconda3 This is the part where I'm lost directory above contains "Scripts" and "env" after examining each it looks to me like "Scripts" contains executables for base(root) environment and env contains files specific to each environment. Is there another directory that I missed, that contains files/links to currently activated environment? Maybe my approach is to0 direct so is there a programmatic way to figure out where is the executable I'm looking for? I should point out that I'm working on Win 10 machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/50991629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Firebase-auth Error with Facebook Firebase auth with Facebook just stopped working on all our Polymer websites. One of them where updated 19th of march and has been working until yesterday/this afternoon (2017-03-27). I get the following error message in chrome: firebase-auth.js:32 "{"error":{"errors":[{"domain":"global","reason":"invalid","message":"A system error has occurred"}],"code":400,"message":"A system error has occurred"}} A: Firebase Authentication is having problems right now. Look at the Firebase Status Dashboard here: https://status.firebase.google.com/ A: Graph API v2.2 has reached the end of its 2-year lifetime on 27 March, 2017, so this might be connected. You should check your library and possible updates. See this chart of deprecation dates, which lists v2.2 as available until March 25, 2017.
{ "language": "en", "url": "https://stackoverflow.com/questions/43054813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to replace forward slashes with backslashes in a string in Emacs Lisp? I would like to replace forward slaches to backslashes in emacs lisp. If I use this : (replace-regexp-in-string "\/" "\\" path)) I get an error. (error "Invalid use of `\\' in replacement text") So how to represent the backslash in the second regexp? A: Does it need to be double-escaped? i.e. (replace-regexp-in-string "\/" "\\\\" path) A: Try using the regexp-quote function, like so: (replace-regexp-in-string "/" (regexp-quote "\\") "this/is//a/test") regexp-quote's documentation reads (regexp-quote string) Return a regexp string which matches exactly string and nothing else. A: What you are seeing in "C:\\foo\\bar" is the textual representation of the string "C:\foo\bar", with escaped backslashes for further processing. For example, if you make a string of length 1 with the backslash character: (make-string 1 ?\\) you get the following response (e.g. in the minibuffer, when you evaluate the above with C-x C-e): "\\" Another way to get what you want is to switch the "literal" flag on: (replace-regexp-in-string "/" "\\" path t t) By the way, you don't need to escape the slash. A: Don't use emacs but I guess it supports some form of specifying unicode via \x e.g. maybe this works (replace-regexp-in-string "\x005c" "\x005f" path)) or (replace-regexp-in-string "\u005c" "\u005f" path))
{ "language": "en", "url": "https://stackoverflow.com/questions/1037545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Shows only one added record, cant view more in CMS admin panel I'm doing PHP course where need to build a CMS system. Problem: In Admin panel shows only one row of added post information: example. If i add more posts it must show more rows like this. Help me i can't find mistake? Source code: view_all_posts.php <?php $query = "SELECT * FROM posts"; $select_posts = mysqli_query($connection, $query); /* check there are records in recordset */ if( mysqli_num_rows( $select_posts ) > 0 ) { while ($row = mysqli_fetch_assoc($select_posts)) { $post_id = $row['post_id']; $post_author = $row['post_author']; $post_title = $row['post_title']; $post_category_id = $row['post_category_id']; $post_status = $row['post_status']; $post_image = $row['post_image']; $post_tags = $row['post_tags']; $post_comment_count = $row['post_comment_count']; $post_date = $row['post_date']; } echo "<tr>"; echo "<td>$post_id</td>"; echo "<td>$post_author</td>"; echo "<td>$post_title</td>"; $query = "SELECT * FROM categories WHERE cat_id = {$post_category_id} "; $select_categories_id = mysqli_query($connection, $query); while ($row = mysqli_fetch_assoc($select_categories_id)) { $cat_id = $row['cat_id']; $cat_title = $row['cat_title']; echo "<td>{$cat_title}</td>"; } echo "<td>$post_status</td>"; echo "<td><img src='../images/$post_image' width='150' height='50'></td>"; echo "<td>$post_tags</td>"; echo "<td>$post_comment_count</td>"; echo "<td>$post_date</td>"; echo "<td><a href='posts.php?source=edit_post&p_id={$post_id}'>Edit</a></td>"; echo "<td><a href='posts.php?delete={$post_id}'>Delete</a></td>"; echo "</tr>"; } ?> add_post.php <?php if(isset($_POST['create_post'])){ $post_title = $_POST['title']; $post_author = $_POST['author']; $post_category_id = $_POST['post_category']; $post_status = $_POST['post_status']; $post_image = $_FILES['image']['name']; $post_image_temp = $_FILES['image']['tmp_name']; $post_tags = $_POST['post_tags']; $post_content = $_POST['post_content']; $post_date = date('y-m-d'); move_uploaded_file($post_image_temp, "../images/$post_image" ); $query = "INSERT INTO posts (post_category_id, post_title, post_author, post_date, post_image, post_content, post_tags, post_status) "; $query .= "VALUES({$post_category_id}, '{$post_title}', '{$post_author}', now(), '{$post_image}', '{$post_content}', '{$post_tags}', '{$post_status}' ) "; $create_post_query = mysqli_query($connection, $query); confirmQuery($create_post_query); } ?> <form action="" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="post_title">Post Title <input type="text" class="form-control" name="title"> </label> </div> <div class="form-group"> <label for=""></label> <select name="post_category" id=""> <?php $query = "SELECT * FROM categories"; $select_categories = mysqli_query($connection, $query); confirmQuery($select_categories); while($row = mysqli_fetch_assoc($select_categories )) { $cat_id = $row['cat_id']; $cat_title = $row['cat_title']; echo "<option value='$cat_id'>{$cat_title}</option>"; } ?> </select> </div> <div class="form-group"> <label for="title">Post Author <input type="text" class="form-control" name="author"> </label> </div> <div class="form-group"> <label for="post_status">Post Status <input type="text" class="form-control" name="post_status"> </label> </div> <div class="form-group"> <label for="post_image">Post Image <input type="file" name="image"> </label> </div> <div class="form-group"> <label for="post_tags">Post Tags <input type="text" class="form-control" name="post_tags"> </label> </div> <div class="form-group"> <label for="post_content">Post Content <textarea class="form-control" name="post_content" id="" cols="30" rows="10"></textarea> </label> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" name="create_post" value="Publish Post"> </div> </form> A: It seems that its just a minor mistake that you have to move your SELECT query of categories within the while loop of $select_posts. Since, in given code, only last record will be passed to next while loop to fetch categories and eventually printed to browser. So, correct code should look like this. { while ($row = mysqli_fetch_assoc($select_posts)) { $post_id = $row['post_id']; $post_author = $row['post_author']; $post_title = $row['post_title']; $post_category_id = $row['post_category_id']; $post_status = $row['post_status']; $post_image = $row['post_image']; $post_tags = $row['post_tags']; $post_comment_count = $row['post_comment_count']; $post_date = $row['post_date']; echo ""; echo "$post_id"; echo "$post_author"; echo "$post_title"; $query = "SELECT * FROM categories WHERE cat_id = {$post_category_id} "; $select_categories_id = mysqli_query($connection, $query); while ($row = mysqli_fetch_assoc($select_categories_id)) { $cat_id = $row['cat_id']; $cat_title = $row['cat_title']; echo "{$cat_title}"; } echo "$post_status"; echo ""; echo "$post_tags"; echo "$post_comment_count"; echo "$post_date"; echo "Edit"; echo "Delete"; echo ""; } } A: Use it like this: Print data inside while loop <?php $query = "SELECT * FROM posts"; $select_posts = mysqli_query($connection, $query); /* check there are records in recordset */ if( mysqli_num_rows( $select_posts ) > 0 ) { while ($row = mysqli_fetch_array($select_posts)) { $post_id = $row['post_id']; $post_author = $row['post_author']; $post_title = $row['post_title']; $post_category_id = $row['post_category_id']; $post_status = $row['post_status']; $post_image = $row['post_image']; $post_tags = $row['post_tags']; $post_comment_count = $row['post_comment_count']; $post_date = $row['post_date']; echo "<tr>"; echo "<td>$post_id</td>"; echo "<td>$post_author</td>"; echo "<td>$post_title</td>"; $query = "SELECT * FROM categories WHERE cat_id = {$post_category_id} "; $select_categories_id = mysqli_query($connection, $query); while ($row = mysqli_fetch_array($select_categories_id)) { $cat_id = $row['cat_id']; $cat_title = $row['cat_title']; echo "<td>{$cat_title}</td>"; } // End of Category Loop echo "<td>$post_status</td>"; echo "<td><img src='../images/$post_image' width='150' height='50'></td>"; echo "<td>$post_tags</td>"; echo "<td>$post_comment_count</td>"; echo "<td>$post_date</td>"; echo "<td><a href='posts.php?source=edit_post&p_id={$post_id}'>Edit</a></td>"; echo "<td><a href='posts.php?delete={$post_id}'>Delete</a></td>"; echo "</tr>"; } // End of Posts Loop } // End of IF ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/35601732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handling json error messages in blob http calls We have http calls like: this.http.get(`${environment.baseUrl}/api/v.1/reports/...`, { responseType: ResponseContentType.Blob }) which returns blob pdfs which we further on save through FileSaver. Problem is if server returns 4XX response with some application/json and message in body. In that case, we cannot find a way how to access it as responseType has to be set prior to request and cannot be altered later. Is there any elegant solution for it? A: I did a few tests and this is what i did so far. It works, all as expected. But i will not accept it as answer yet but leave for some time for a community to review. If someone sees problems with this approach, please point them out in comments. ErrorMessage is of simple format: { message:string } Service: getPDF() { return this.http.get(`${environment.baseUrl}/api/v.1/reports/...`, { responseType: ResponseContentType.Blob }) .map((res) => { return { blob: new Blob([res.blob()], { type: 'application/pdf' }), filename: this.parseFilename(res) } }) .catch((res) => { let fileAsTextObservable = new Observable<string>(observer => { const reader = new FileReader(); reader.onload = (e) => { let responseText = (<any>e.target).result; observer.next(responseText); observer.complete(); } const errMsg = reader.readAsText(res.blob(), 'utf-8'); }); return fileAsTextObservable .switchMap(errMsgJsonAsText => { return Observable.throw(JSON.parse(errMsgJsonAsText)); }) }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/45477757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to change convert different csv files into standard format? I have 2-3 .csv files with fields like Date, Amount, Transaction Description etc and all the csv files contains these fields but in shuffled order. I want a output file to with a standard order (like if I input the sample .csv file, then I can get the things in order in output file). I tried to do it for one file by taking substrings from the .csv file (at that time I didn't know that other files have shuffled order fields). I am kind of new, tell me if I am asking question in a good format! Can I put a link for the sample input and output .csv file for the reference? --> https://drive.google.com/drive/folders/1-NZi5OTMTbOWXAfCTsc-ahNYm1N5DG2g (just because it would be very hard to explain that how file looks like) What I have done? I have just tried to extract data from the fields using the BufferReader using split but it can only work for one type of file, I cant have a standard format using this! Sorry for posting such a long code but what I have done is selected field from the file and copied them into output file corresponding to the standard fields in the output file. Suggest me if there is any other method with which I can proceed. File file = new File("C:\\Users\\R\\Desktop\\CSVDemo.csv"); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); CSVWriter writer = new CSVWriter(outputfile, ',', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); // create a List which contains String array String[] header = { "Date", "Transaction Description", "Debit","Credit","Currency","CardName","Transaction","Location" }; writer.writeNext(header); String splitBy = ","; BufferedReader br = new BufferedReader(new FileReader("G:\\US\\HDFC-Input-Case1.csv")); String line; String transaction = "",name = ""; while ((line = br.readLine()) != null) { // use comma as separator String[] cols = line.split(splitBy); if(cols.length == 2 && cols[1].equals("Domestic Transactions")) { transaction = "Domestic"; continue; } else if(cols.length == 2 && cols[1].equals("International Transactions")) { transaction = "International"; continue; } else if(cols.length == 2) { name = cols[1]; continue; } else if(cols.length<1){ continue; } else if(cols.length>2) { if(cols[0].contains("Date")){ continue; } String[] data1 = new String[header.length]; data1[0] = cols[0]; String curr ; if(cols[1].substring(cols[1].length()-3).equals("USD") || cols[1].substring(cols[1].length()-3).equals("EUR")) { data1[4] = cols[1].substring(cols[1].length()-3); curr = cols[1].substring(0,cols[1].length()-4); data1[1] = curr; } else { data1[4] = "INR"; data1[1] = cols[1]; } if(cols[2].contains("cr")){ data1[3] = cols[2].substring(0,cols[2].length()-2); data1[2] = "0"; } else { data1[2] = cols[2]; data1[3] = "0"; } data1[5] = name; data1[6] = transaction; writer.writeNext(data1); } System.out.println(); } // closing writer connection writer.close(); } A: You can read the header of your input csv files first and find the indexes of required field in this given csv file. Once you have required indexes for every header, read those fields using indexes in the standard order you want for your output csv file. sample codes: `CSVReader reader = new CSVReader(new FileReader(fileName )); String[] header = reader.readNext(); List<String> list= Arrays.asList(header); int indexOfFieldTransaction=list.indexOf("transaction");` Now make a List and insert the field in order you want to write in output file.you will get -1 if the field you are trying to get index of is not present in the input file.
{ "language": "en", "url": "https://stackoverflow.com/questions/63089690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Printing items selected from Knapsack Unbounded algorithm? I know how standard knapsack works, and i can afford to print the items selected in the 2D matrix, but from what i figured, unbounded knapsack is a 1D array. How do you print items selected by unbounded knapsack algorithm? A: Unbounded Knapsack can be solved using 2D matrix, which will make printing the included items easy. The items included in the knapsack can be backtracked from the matrix in the same way as in 0/1 Knapsack. After the dp[][] matrix is populated, this will print the included items: // dp[val.length+1][sackWeight+1] is the matrix for caching. // val[] is the array that stores the values of the objects // and wt[] is the array that stores the weight of the corresponding objects. int x = val.length, y = sackWeight; while (x > 0 && y > 0) { if (dp[x][y] == dp[x - 1][y]) x--; else if (dp[x - 1][y] >= dp[x][y - wt[x - 1]] + val[x - 1]) x--; else { System.out.println("including wt " + wt[x - 1] + " with value " + val[x - 1]); y -= wt[x - 1]; } } A: Assuming dp[][] is a matrix that is populated correctly. We can backtrack to find selected weights def print_selected_items(dp, weights, capacity): idxes_list = [] print("Selected weights are: ", end='') n = len(weights) i = n - 1 while i >= 0 and capacity >= 0: if i > 0 and dp[i][capacity] != dp[i - 1][capacity]: # include this item idxes_list.append(i) capacity -= weights[i] elif i == 0 and capacity >= weights[i]: # include this item idxes_list.append(i) capacity -= weights[i] else: i -= 1 weights = [weights[idx] for idx in idxes_list] print(weights) return weights For details on how to generate this DP array from bottom up DP. def solve_knapsack_unbounded_bottomup(profits, weights, capacity): """ :param profits: :param weights: :param capacity: :return: """ n = len(profits) # base checks if capacity <= 0 or n == 0 or len(weights) != n: return 0 dp = [[-1 for _ in range(capacity + 1)] for _ in range(n)] # populate the capacity=0 columns for i in range(n): dp[i][0] = 0 # process all sub-arrays for all capacities for i in range(n): for c in range(1, capacity + 1): profit1, profit2 = 0, 0 if weights[i] <= c: profit1 = profits[i] + dp[i][c - weights[i]] if i > 0: profit2 = dp[i - 1][c] dp[i][c] = max(profit1, profit2) # maximum profit will be in the bottom-right corner. print_selected_items(dp, weights, capacity) return dp[n - 1][capacity]
{ "language": "en", "url": "https://stackoverflow.com/questions/57903012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: printing float, preserving precision I am writing a program that prints floating point literals to be used inside another program. How many digits do I need to print in order to preserve the precision of the original float? Since a float has 24 * (log(2) / log(10)) = 7.2247199 decimal digits of precision, my initial thought was that printing 8 digits should be enough. But if I'm unlucky, those 0.2247199 get distributed to the left and to the right of the 7 significant digits, so I should probably print 9 decimal digits. Is my analysis correct? Is 9 decimal digits enough for all cases? Like printf("%.9g", x);? Is there a standard function that converts a float to a string with the minimum number of decimal digits required for that value, in the cases where 7 or 8 are enough, so I don't print unnecessary digits? Note: I cannot use hexadecimal floating point literals, because standard C++ does not support them. A: 24 * (log(2) / log(10)) = 7.2247199 That's pretty representative for the problem. It makes no sense whatsoever to express the number of significant digits with an accuracy of 0.0000001 digits. You are converting numbers to text for the benefit of a human, not a machine. A human couldn't care less, and would much prefer, if you wrote 24 * (log(2) / log(10)) = 7 Trying to display 8 significant digits just generates random noise digits. With non-zero odds that 7 is already too much because floating point error accumulates in calculations. Above all, print numbers using a reasonable unit of measure. People are interested in millimeters, grams, pounds, inches, etcetera. No architect will care about the size of a window expressed more accurately than 1 mm. No window manufacturing plant will promise a window sized as accurate as that. Last but not least, you cannot ignore the accuracy of the numbers you feed into your program. Measuring the speed of an unladen European swallow down to 7 digits is not possible. It is roughly 11 meters per second, 2 digits at best. So performing calculations on that speed and printing a result that has more significant digits produces nonsensical results that promise accuracy that isn't there. A: If you have a C library that is conforming to C99 (and if your float types have a base that is a power of 2 :) the printf format character %a can print floating point values without lack of precision in hexadecimal form, and utilities as scanf and strod will be able to read them. A: If the program is meant to be read by a computer, I would do the simple trick of using char* aliasing. * *alias float* to char* *copy into an unsigned (or whatever unsigned type is sufficiently large) via char* aliasing *print the unsigned value Decoding is just reversing the process (and on most platform a direct reinterpret_cast can be used). A: In order to guarantee that a binary->decimal->binary roundtrip recovers the original binary value, IEEE 754 requires The original binary value will be preserved by converting to decimal and back again using:[10] 5 decimal digits for binary16 9 decimal digits for binary32 17 decimal digits for binary64 36 decimal digits for binary128 For other binary formats the required number of decimal digits is 1 + ceiling(p*log10(2)) where p is the number of significant bits in the binary format, e.g. 24 bits for binary32. In C, the functions you can use for these conversions are snprintf() and strtof/strtod/strtold(). Of course, in some cases even more digits can be useful (no, they are not always "noise", depending on the implementation of the decimal conversion routines such as snprintf() ). Consider e.g. printing dyadic fractions. A: The floating-point-to-decimal conversion used in Java is guaranteed to be produce the least number of decimal digits beyond the decimal point needed to distinguish the number from its neighbors (more or less). You can copy the algorithm from here: http://www.docjar.com/html/api/sun/misc/FloatingDecimal.java.html Pay attention to the FloatingDecimal(float) constructor and the toJavaFormatString() method. A: If you read these papers (see below), you'll find that there are some algorithm that print the minimum number of decimal digits such that the number can be re-interpreted unchanged (i.e. by scanf). Since there might be several such numbers, the algorithm also pick the nearest decimal fraction to the original binary fraction (I named float value). A pity that there's no such standard library in C. * *http://www.cs.indiana.edu/~burger/FP-Printing-PLDI96.pdf *http://grouper.ieee.org/groups/754/email/pdfq3pavhBfih.pdf A: You can use sprintf. I am not sure whether this answers your question exactly though, but anyways, here is the sample code #include <stdio.h> int main( void ) { float d_n = 123.45; char s_cp[13] = { '\0' }; char s_cnp[4] = { '\0' }; /* * with sprintf you need to make sure there's enough space * declared in the array */ sprintf( s_cp, "%.2f", d_n ); printf( "%s\n", s_cp ); /* * snprinft allows to control how much is read into array. * it might have portable issues if you are not using C99 */ snprintf( s_cnp, sizeof s_cnp - 1 , "%f", d_n ); printf( "%s\n", s_cnp ); getchar(); return 0; } /* output : * 123.45 * 123 */ A: With something like def f(a): b=0 while a != int(a): a*=2; b+=1 return a, b (which is Python) you should be able to get mantissa and exponent in a loss-free way. In C, this would probably be struct float_decomp { float mantissa; int exponent; } struct float_decomp decomp(float x) { struct float_decomp ret = { .mantissa = x, .exponent = 0}; while x != floor(x) { ret.mantissa *= 2; ret.exponent += 1; } return ret; } But be aware that still not all values can be represented in that way, it is just a quick shot which should give the idea, but probably needs improvement.
{ "language": "en", "url": "https://stackoverflow.com/questions/10895243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How to redirect .htaccess My old website has 3 url's that lead to same place. http://hemodialysis-krk.com/ http://www.hemodialysis-krk.com/ http://hemodialysis-krk.com/index.php?l=HR I plan delete old website and put new one with totally different url's. Including index.html. So what would be solution for that situation? Should I 301 redirect some off them to index.html? Will first two automaticly link to new index.html file in public_html without redirecting? Thanks. A: Use this to redirect all traffic to new site using .htaccess of old sites. <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTP_HOST} .*hemodialysis-krk.com RewriteRule (.*) http://www.newsite.com/ [R=301,L] </IfModule> Or create more rules, if you can map sections of pages from old to new site. If you use: RewriteRule (.*) http://www.newsite.com/$1 [R=301,QSA,L] original path and get query will be used in redirection too. This is always handy working on unique url to reach better position in search engines results. EDIT: If you need to redirect only urls, which don't exists anymore, then use (not tested): <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.*) / [R=301,L] </IfModule>
{ "language": "en", "url": "https://stackoverflow.com/questions/24088511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scipy maximizing linear programming doesn't work I have the following: ball = scipy.optimize.linprog(array([0,0,1]), A, b) where A = array([[-1.0, 0.0, 1.0], [ 1.0, 0.0, 1.0], [ 0.0, -1.0, 1.0], [ 0.0, 1.0, 1.0]], dtype=float128) b = array([ 0.0, 1.0, 0.0, 1.0], dtype=float128) We can maximize this by hand to get the answer x = [0.5, 0.5, 0.5]. Yet scipy gives me status: 0 slack: array([ 0., 1., 0., 1.]) success: True fun: -0.0 x: array([ 0., 0., 0.]) message: 'Optimization terminated successfully.' nit: 0 Which is simply the wrong answer! Is my code wrong, or did I find a bug? EDIT: To verify that the solution given by scipy is not optimal, do np.all(np.dot(A, np.array([0.5,0.5,0.5])) <= b) to see that my solution satisfies the constraints. Then note that np.dot(np.array([0,0,1]), np.array([0.5,0.5,0.5])) > np.dot(np.array([0,0,1]), np.array([0,0,0])) to see it is at least a better solution. In fact, it is the optimal solution. EDIT 2: scipy.__version__ = 0.16.0 A: According to the docs, linprog finds the minimum, while your proposed solution is the maximum.
{ "language": "en", "url": "https://stackoverflow.com/questions/32109668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to kill an android app from another app? i wanna know how to kill an android app from another, i'm developing a tasker, and i wanna to be able to kill an app selected by the user when an event occurs, i readed about Process.killProcess() but only allows me to kill apps in the same package, and that's not the idea! So, in my case, my kill section will request root rights, calling su before accept a kill request, but i don't know how to kill an app using a script! Anyones knows some script to do that?? EDIT: The solution is in this thread: ANDROID: How to gain root access in an Android application? Please close.
{ "language": "en", "url": "https://stackoverflow.com/questions/9727729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Reading an XML from a JavaFX application I would like to import an XML file via a pop-up window in my JavaFX application. After the importing, I would like to read it. For example I want to store, for every <testbus> the <index> and the <tb_name> in a List or something similar, where the <index> is the index of the List and the <tb_name> is the elementof the List. I also would like that for every <testbus> I can access the bitfields and their name. So I was thinking about List of List. I have found a java Library called JAXB that can parse XML files, but I do not know how to achieve what I want. This is the XML file <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <testbuses> <testbus> <index>00</index> <tb_name>buffermngr00</tb_name> <bitfield0> <bitf_name>aaa_00</bitf_name> </bitfield0> <bitfield1> <bitf_name>aaa_01</bitf_name> </bitfield1> <bitfield2> <bitf_name>aaa_02</bitf_name> </bitfield2> <bitfield3> <bitf_name>aaa_03</bitf_name> </bitfield3> <bitfield4> <bitf_name>aaa_03</bitf_name> </bitfield4> <bitfield5> <bitf_name>aaa_04</bitf_name> </bitfield5> <bitfield6> <bitf_name>aaa_04</bitf_name> </bitfield6> <bitfield7> <bitf_name>aaa_05</bitf_name> </bitfield7> </testbus> <testbus> <index>01</index> <tb_name>buffermngr01</tb_name> <bitfield0> <bitf_name>bbb_00</bitf_name> </bitfield0> <bitfield1> <bitf_name>bbb_00</bitf_name> </bitfield1> <bitfield2> <bitf_name>bbb_00</bitf_name> </bitfield2> <bitfield3> <bitf_name>bbb_00</bitf_name> </bitfield3> <bitfield4> <bitf_name>bbb_01</bitf_name> </bitfield4> <bitfield5> <bitf_name>bbb_01</bitf_name> </bitfield5> <bitfield6> <bitf_name>bbb_02</bitf_name> </bitfield6> <bitfield7> <bitf_name>bbb_03</bitf_name> </bitfield7> </testbus> </testbuses> Anyway the structure of this XML is not strict, so if you have a suggestion for a better structure in order to make the reading easily, I will be happy to hear your solution. A: For your xml provided in the XML. First create a java POJO class with fields as: String index; String tb_name; List<String> bitf_names; Use the class below for that: import java.util.List; class TestBus { private String index; private String tb_name; private List<String> bitf_names; public String getIndex() { return index; } public void setIndex(String index) { this.index = index; } public String getTb_name() { return tb_name; } public void setTb_name(String tb_name) { this.tb_name = tb_name; } public List<String> getBitf_names() { return bitf_names; } public void setBitf_names(List<String> bitf_name) { this.bitf_names = bitf_name; } @Override public String toString() { return "TestBus [index=" + index + ", tb_name=" + tb_name + ", bitf_name=" + bitf_names + "]"; } } After that, use the code below to create a list of TestBus classes: i.e List<TestBus> testBusList = new ArrayList<>(); Use this class for the complete code and logic: import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class ReadXMLFile { public static List<TestBus> testBuses = new ArrayList<>(); public static void main(String argv[]) { try { File fXmlFile = new File("D:\\ECLIPSE-WORKSPACE\\demo-xml-project\\src\\main\\resources\\testbus.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); NodeList testBusNodeList = doc.getElementsByTagName("testbus"); for (int parameter = 0; parameter < testBusNodeList.getLength(); parameter++) { TestBus testBus = new TestBus(); Node node = testBusNodeList.item(parameter); if (node.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) node; String index = eElement.getElementsByTagName("index").item(0).getTextContent(); String tb_name = eElement.getElementsByTagName("tb_name").item(0).getTextContent(); NodeList bitf_name = eElement.getElementsByTagName("bitf_name"); List<String> bitf_namesList = new ArrayList<>(); IntStream.range(0, bitf_name.getLength()).forEach(bName -> { bitf_namesList.add(bitf_name.item(bName).getTextContent()); }); testBus.setIndex(index); testBus.setTb_name(tb_name); testBus.setBitf_names(bitf_namesList); testBuses.add(testBus); } } } catch (Exception e) { System.out.println("!!!!!!!! Exception while reading xml file :" + e.getMessage()); } testBuses.forEach(bus -> System.out.println(bus)); // in single line System.out.println("###################################################"); // using getters testBuses.forEach(bus -> { System.out.println("index = " + bus.getIndex()); System.out.println("tb_name = " + bus.getTb_name()); System.out.println("bitf_names = " + bus.getBitf_names()); System.out.println("#####################################################"); }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/51536150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL substatements with more than one column Given a fake example where there are contacts and for each contact there can be one or zero Sms records; I can do this SELECT Contact.id, Contact.name, Sms.provider, Sms.number FROM Contact, Sms WHERE Sms.contactId = Contact.id. But I it needs to show a row even if there is no SMS number for that contact. I know of two ways to accomplish this. One is with a UNION of two selects (SELECT Contact.id, Contact.name, Sms.provider, Sms.number FROM Contact, Sms WHERE Sms.contactId = Contact.id) UNION (SELECT id, name, null provider, null number FROM Contact WHERE (SELECT 1 FROM Sms WHERE contactId = Contact.id) IS NULL). and another is two substatements SELECT id, name, (SELECT provider FROM Sms WHERE contactId = Contact.id) provider, (SELECT number FROM Sms WHERE contactId = Contact.id) number FROM Contact The UNION method requires going through the database twice and the substatements method requires two lookups on the same table. I run into this often and I prefer to have all the code in MySQL and not to work with the software code to accomplish this. Working with MySQL usually turns out to be more efficient as well as simpler. Many of the real situations I work with involve large databases. Is there a way to get two fields from a related table with one query? A: But I it needs to show a row even if there is no SMS number for that contact. Then use a LEFT OUTER JOIN, which returns a row from the left table even if there is no corresponding row in the right table. It's a good idea to learn to always use JOIN syntax instead of the pseudo-inner-join when you just list tables with commas. SELECT Contact.id, Contact.name, Sms.provider, Sms.number FROM Contact LEFT OUTER JOIN Sms ON Sms.contactId = Contact.id
{ "language": "en", "url": "https://stackoverflow.com/questions/4909409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript: prevent internal element "scrolling" in an element I have a script that has a div with a width larger than its' parent, with the parent being set to overflow: hidden;. I have javascript that is setting the left positioning of the big div to create "pages". You can click a link to move between pages. All of that works great, but the problem is if you tab from one "page" element to another, it completely messes up all the left positioning to move between the pages. You can recreate this bug in the fiddle I set up by setting your focus to one of the input boxes on page ONE and tabbing until it takes you to page two. I've set up a demo here. The code that is important is as follows: HTML: <div class="form"> <div class="pagesContainer"> <div class="page" class="active"> <h2>Page One</h2> [... Page 1 Content here...] </div> <div class="page"> <h2>Page Two</h2> [... Page Content here...] </div> </div> CSS: .form { width: 400px; position: relative; overflow: hidden; border: 1px solid #000; float: left; } .pagesContainer { position: relative; /*Width set to 10,000 px in js } .form .page { width: 400px; float: left; } JS: slidePage: function(page, direction, currentPage) { if (direction == 'next') { var animationDirection = '-='; if (page.index() >= this.numPages) { return false; } } else if (direction == 'previous') { var animationDirection = '+='; if (page.index() < 0) { return false; } } //Get page height var height = page.height(); this.heightElement.animate({ height: height }, 600); //Clear active page this.page.removeClass('active'); this.page.eq(page.index()).addClass('active'); //Locate the exact page to skip to var slideWidth = page.outerWidth(true) * this.difference(this.currentPage.index(), page.index()); this.container.animate({ left: animationDirection + slideWidth }, 600); this.currentPage = page; } The primary problem is that whatever happens when you tab from say, an input box on page one to something on page 2, it takes you there, but css still considers you to be at left: 0px;. I've been looking all over for a solution but so far all google has revealed to me is how to stop scrollbar scrolling. Any help or suggestions would be appreciated, thanks! P.S. The html was set up like this so that if javascript is disabled it will still show up all on one page and still function properly. A: I updated your fiddle with a fix for the first tab with the form: http://jsfiddle.net/E7u9X/1/ . Basically, what you can do is to focus on the first "tabbable" element in a tab after the last one gets blurred, like so: $('.form input').last().blur(function(){ $('.form input').first().focus(); }); (This is just an example, the first active element could be any other element) A: Elements with overflow: hidden still have scrolling, just no scroll bars. This can be useful at times and annoying at others. This is why your position left is at zero, but your view of the element has changed. Set scrollLeft to zero when you change "pages", should do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/13147833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }