text
stringlengths
15
59.8k
meta
dict
Q: How to deactivate redirect for non-logged in users on specific pages? I created a website wide (wordpress) redirect for non-logged in users by adding the following code to my function.php file: function admin_redirect() { if ( !is_user_logged_in()) { wp_redirect( home_url('/login') ); exit; } } add_action('get_header', 'admin_redirect'); However there are a few pages, which should be accessible for non-logged in users. Any ideas how to solve the problem? Thanks for your help! A: Check conditionally tags in your funciton https://codex.wordpress.org/Conditional_Tags function admin_redirect() { if( is_page('about_us') ) return; if ( !is_user_logged_in()) { wp_redirect( home_url('/login') ); exit; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/36636252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Opensource Webcam Library Is there any opensource library which can be used to decrease frame rate or resolution of webcam on windows platform? I need to limit bandwidth utilized by high resolution webcam connected to USB port. Thanks. A: I think OpenCV fullfills your requirements. See the thread here about decreasing the resolution and read the OpenCV documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/10574203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Objective C Visual Autolayout NSTextField dynamic height I am trying to create a dynamic size NSView using visual auto layout. I am trying to achieve something like the following diagram. I added following constraints to achieve this. [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-15-[_iconImageView(39)]-12-[_textView(239)]-15-|" options:NSLayoutFormatAlignAllTop metrics:nil views:views]]; [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-15-[_textView]-4-[_mainButton]-5-|" options: NSLayoutFormatAlignAllLeft metrics:nil views:views]]; [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_mainButton]-15-[_secondaryButton]" options:NSLayoutFormatAlignAllTop metrics:nil views:views]]; But this creates the following layout. As per my understanding, the following VFL will layout _textView 15px from top and then layout _mainButton after 4px from _textView bottom. But in actual _mainbottom is layout after 4px from top of _textView. Am i missing something here? @"V:|-15-[_textView]-4-[_mainButton]-5-|" Update I replaced NSTextView with NSTextField. But now the problem is, NSTextField does not grow more than a single line height, but NSTextField is multi-line. Complete code for layouting and setting up views is as follow. -(void)setupView { _textField = [[NSTextField alloc] initWithFrame:NSZeroRect]; [[_textField cell] setWraps:YES]; [_textField setLineBreakMode:NSLineBreakByWordWrapping]; [[_textField cell] setTitle:@"This is a _textView, This will contain dynamic resizing text."]; [_textField setSelectable:NO]; [_textField setEditable:NO]; [_textField setDelegate:self]; [_textField setBordered:NO]; [_textField sizeToFit]; [_textField setTranslatesAutoresizingMaskIntoConstraints:NO]; [self addSubview:_textField]; _iconImageView = [[NSImageView alloc] initWithFrame:NSZeroRect]; [_iconImageView setImage:[NSImage imageNamed:@"notify-warning-icon"]]; [_iconImageView setTranslatesAutoresizingMaskIntoConstraints:NO]; [self addSubview:_iconImageView]; _mainButton = [[NSButton alloc] init]; _mainButton.translatesAutoresizingMaskIntoConstraints = NO; [_mainButton setTitle:@"_mainButton"]; [self addSubview:_mainButton]; _secondaryButton = [[NSButton alloc] init]; _secondaryButton.translatesAutoresizingMaskIntoConstraints = NO; [_secondaryButton setTitle:@"_secondaryButton"]; [self addSubview:_secondaryButton]; NSDictionary *views = NSDictionaryOfVariableBindings(_textField,_iconImageView,_mainButton,_secondaryButton); [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-15-[_iconImageView(39)]-12-[_textField(239)]-15-|" options:NSLayoutFormatAlignAllTop metrics:nil views:views]]; [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-15-[_textField]-4-[_mainButton]-5-|" options: NSLayoutFormatAlignAllLeft metrics:nil views:views]]; [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_mainButton]-15-[_secondaryButton]" options:NSLayoutFormatAlignAllTop metrics:nil views:views]]; [self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:0.f constant:320.f]]; } But if it changed this @"V:|-15-[_textField]-4-[_mainButton]-5-|" with this @"V:|-15-[_textField(>=40)]-4-[_mainButton]-5-|" I get the following output But the problem is textfield content is dynamic and could change at runtime, it could be 2 lines, 3 lines etc. So how could i add some height constraint to NSTextField that will change NSTextField height depending on its content. A: You can use a text field rather than a text view and set its preferredMaxLayoutWidth property. By default, if preferredMaxLayoutWidth is 0, a text field will compute its intrinsic size as though its content were laid out in one long line (or, at least, without any maximum width). Even if you apply a constraint that limits its actual width, that doesn't change its intrinsic height and therefore it typically won't be tall enough to contain the text as wrapped. If you set preferredMaxLayoutWidth, then the text field will compute its intrinsic size based on the text as wrapped to that width. That includes making its intrinsic height tall enough to fit.
{ "language": "en", "url": "https://stackoverflow.com/questions/29527082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set password on cronjob So i searched a bit and didn't find answers I'm trying a cronjob for the first time and i'm trying to push to my Gitlab repository on a determined daily time I'm trying something like: 10 10 * * * cd/repofolder && git push && login && password The thing is it works only until the git push command, then login and password are not being typed on the cron job How do i make the cronjob also type the login and password when the Gitlab asks for it? A: I'm having some (permission denied) problem with SSH ( which i didn't have yesterday), Check with which account your root command is executed: root or your own? Because the cron job will look for ~/.ssh/id_rsa(.pub) keys in the HOME folder. Make sure the provate key is not passphrase protected. so for now i kinda want to do this with HTTP, Then make sure the credentials are cached, through a credential helper. That way, you don't have to enter any credentials. (Again, beware of the account used).
{ "language": "en", "url": "https://stackoverflow.com/questions/53659829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does cat-ing this small file cause the Mac terminal emulator to minimize? In hex, the file is 1b 5b 32 74 ie. [ESC] then [2t. Printing this file's contents to the terminal on mac sends the window to the tray. I can't get the same behaviour anywhere else or find any documentation on this particular escape sequence. Any ideas? A: It is the Xterm control sequence for iconify window. An excerpt: CSI Ps ; Ps ; Ps t Window manipulation (from dtterm, as well as extensions). These controls may be disabled using the allowWindowOps resource. Valid values for the first (and any additional parameters) are: Ps = 1 -> De-iconify window. Ps = 2 -> Iconify window. Ps = 3 ; x ; y -> Move window to [x, y]. [...] CSI is the control sequence initiator (ESC [). t is the "command", which allows for several types of window manipulation, the exact manipulation determined by parameters (indicated by Ps) that precede the t. The parameter 2 indicates the window should be iconified, which on Mac OS means to send it to the doc.
{ "language": "en", "url": "https://stackoverflow.com/questions/44021272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: git diff origin/master@{1} origin/master --name-status throws fatal: Log for 'origin/master' only has 1 entries error I am using git diff origin/master@{1} origin/master --name-status command to print the previous push details. But it is throwing fatal: Log for 'origin/master' only has 1 entries error. I got to know that diff with the reflog syntax @{n} here will only work if there are more than 1 entry for the branch in the reflog. from the answer Get list of files to recently pushed to remote Git branch if i run this command in local it will work.But i have a CI/CD server which clones this repo and executes this.There am getting this reflog entry error. Is there any way to restore atleast last two three entries in remote repo? otherwise i need to execute the equivalent of it diff origin/master@{1} origin/master --name-status in a cloned repository
{ "language": "en", "url": "https://stackoverflow.com/questions/58023630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unwanted new-line when plugging a string variable into a RichTextBox Im generating a string variable from other string variables that themselves are generated in a button press and take their values from textboxes / user input. Simultaneously, the mass string variable is being loaded into a RichTextBox. While I do purposely use one VbLf in my mass string variable, I am encountering an additional point where a new line begins in my string where it is not supposed too. How can I avoid this? Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click numb = numbtxt.Text year = yeartxt.Text author = authortxt.Text pages = pagestxt.Text pgnum = pgnumtxt.Text item1 = item1txt.Text item2 = item2txt.Text format = numb + ") """ + item1 + """" + vbLf + item2 + _ " - " + author + " (" + year + ") " + pages + " " + pgnum rtf.Text = format End Sub I am expecting this: https://i.imgur.com/5q5MME2.png but I am getting this: https://i.imgur.com/dCMAIqA.png Any help would be very much so appreciated. A: Please check your content of cour variable item2 containing the url. I guess, that this variable contains a line break at the end. Try to just print this variable with a leading and trailing char. If so, you can either replace the new line character in item2 or try to substring the content. A: To remove any unwanted characters from the input strings, you can trim them, or do a character replacement. For example, to remove CR/LF from the end of strings (untested, from memory); numb = numbtxt.Text.TrimEnd( {vbCr, vbLf, vbCrLf, Environment.Newline} ) or to remove all occurrences; year = yeartxt.Text.Replace(vbCrLf, String.Empty) or; year = yeartxt.Text.Replace(vbCr, String.Empty).Replace(vbLf, String.Empty) etc. YMMV depending on the actual CR/LF character arrangments and language settings!
{ "language": "en", "url": "https://stackoverflow.com/questions/55739746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Downloading an entire webpage with C: recv() Good evening. I'm trying to obtain the full contents of webpages (images excepted) through a C application. After connecting to the desired URL, I use recv(), like so: char *reply; reply==malloc(10000*sizeof(char)); recv(socketname, reply, 10000, 0); This gives me a part of the page (958-972 bytes, according to recv()'s return value). So, I tried modifying it to: ssize_t received=0; char *reply, *buffer; reply=malloc(10000*sizeof(char)); buffer=malloc(255*sizeof(char)); while(received<10000) { received+=recv(socketname, buffer, 10000, 0); strcat(reply, buffer); } But this gives me a segmentation fault on large pages (before exceeding the size allocated to the reply) and, on small pages, results in the reply containing several times the contents of the page. How do I do this properly? A: buffer=malloc(255*sizeof(char)); gives you only 255 bytes. recv(socketname, buffer, 10000, 0); tries to read much more. That's why you get a segfault. Also, you do not know what you actualy download, so you'd be better off with memcpy to copy. An untested example: ssize_t received=0, current_received=0; char *reply, *buffer; reply=malloc(10000*sizeof(char)); buffer=malloc(255*sizeof(char)); while(received<10000) { current_received = recv(socketname, buffer, 255, 0); if(current_received <= 0) { //if we're done or we have an error. Think about some error handling. break; } //I have switched the following lines to make it a bit easier. //As an exercise try to avoid overflow if received=9999 and current_received=255 :) memcpy(reply + received, buffer, current_received); received += current_received; } If you're looking for a library that will do it for you, check this link. Keep in mind that using a library might be actually quite difficult if you want just a very simple example. A: But to jxh's point, you want to be using memcpy instead of strcat, and keeping any advancing pointer into your consolidated reply, incrementing by received each time.
{ "language": "en", "url": "https://stackoverflow.com/questions/29991605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to generate datasets dynamically based on schema? I have multiple schema like below with different column names and data types. I want to generate test/simulated data using DataFrame with Scala for each schema and save it to parquet file. Below is the example schema (from a sample json) to generate data dynamically with dummy values in it. val schema1 = StructType( List( StructField("a", DoubleType, true), StructField("aa", StringType, true) StructField("p", LongType, true), StructField("pp", StringType, true) ) ) I need rdd/dataframe like this with 1000 rows each based on number of columns in the above schema. val data = Seq( Row(1d, "happy", 1L, "Iam"), Row(2d, "sad", 2L, "Iam"), Row(3d, "glad", 3L, "Iam") ) Basically.. like this 200 datasets are there for which I need to generate data dynamically, writing separate programs for each scheme is merely impossible for me. Pls. help me with your ideas or impl. as I am new to spark. Is it possible to generate dynamic data based on schema of different types? A: ScalaCheck is a framework to generate data, you generate a raw data based on the schema using you custom generators. Visit ScalaCheck Documentation. A: Using @JacekLaskowski's advice, you could generate dynamic data using generators with ScalaCheck (Gen) based on field/types you are expecting. It could look like this: import org.apache.spark.sql.types._ import org.apache.spark.sql.{Row, SaveMode} import org.scalacheck._ import scala.collection.JavaConverters._ val dynamicValues: Map[(String, DataType), Gen[Any]] = Map( ("a", DoubleType) -> Gen.choose(0.0, 100.0), ("aa", StringType) -> Gen.oneOf("happy", "sad", "glad"), ("p", LongType) -> Gen.choose(0L, 10L), ("pp", StringType) -> Gen.oneOf("Iam", "You're") ) val schemas = Map( "schema1" -> StructType( List( StructField("a", DoubleType, true), StructField("aa", StringType, true), StructField("p", LongType, true), StructField("pp", StringType, true) )), "schema2" -> StructType( List( StructField("a", DoubleType, true), StructField("pp", StringType, true), StructField("p", LongType, true) ) ) ) val numRecords = 1000 schemas.foreach { case (name, schema) => // create a data frame spark.createDataFrame( // of #numRecords records (0 until numRecords).map { _ => // each of them a row Row.fromSeq(schema.fields.map(field => { // with fields based on the schema's fieldname & type else null dynamicValues.get((field.name, field.dataType)).flatMap(_.sample).orNull })) }.asJava, schema) // store to parquet .write.mode(SaveMode.Overwrite).parquet(name) } A: You could do something like this import org.apache.spark.SparkConf import org.apache.spark.sql.types._ import org.apache.spark.sql.{DataFrame, SparkSession} import org.json4s import org.json4s.JsonAST._ import org.json4s.jackson.JsonMethods._ import scala.util.Random object Test extends App { val structType: StructType = StructType( List( StructField("a", DoubleType, true), StructField("aa", StringType, true), StructField("p", LongType, true), StructField("pp", StringType, true) ) ) val spark = SparkSession .builder() .master("local[*]") .config(new SparkConf()) .getOrCreate() import spark.implicits._ val df = createRandomDF(structType, 1000) def createRandomDF(structType: StructType, size: Int, rnd: Random = new Random()): DataFrame ={ spark.read.schema(structType).json((0 to size).map { _ => compact(randomJson(rnd, structType))}.toDS()) } def randomJson(rnd: Random, dataType: DataType): JValue = { dataType match { case v: DoubleType => json4s.JDouble(rnd.nextDouble()) case v: StringType => JString(rnd.nextString(10)) case v: IntegerType => JInt(rnd.nextInt()) case v: LongType => JInt(rnd.nextLong()) case v: FloatType => JDouble(rnd.nextFloat()) case v: BooleanType => JBool(rnd.nextBoolean()) case v: ArrayType => val size = rnd.nextInt(10) JArray( (0 to size).map(_ => randomJson(rnd, v.elementType)).toList ) case v: StructType => JObject( v.fields.flatMap { f => if (f.nullable && rnd.nextBoolean()) None else Some(JField(f.name, randomJson(rnd, f.dataType))) }.toList ) } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/53552983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: how to display CFStringType? Like kABHomeLabel I know that NSString and CFString are toll-bridge, they can convert in such a way. CFStringRef cfStr; NSString* anStr=(NSString*)cfStr; however,when I convert string in such a case when dealing addressbook NSString* homeLabel=(NSString*)kABWorkLabel; then homeLabel is "_$!<Work>!$_"; the other pre-defined CFStringRef in the addressbook property is the same. in my program, I want to get both the label and the label item's info. NSString* label=ABMultiValueCopyLabelAtIndex(multi,i); so how to correctly get the string of the label? A: Try this: + (NSString *) displayPropertyName:(NSString *) propConst{ if ([propConst isEqualToString:@"_$!<Anniversary>!$_"]) return @"anniversary"; if ([propConst isEqualToString:@"_$!<Assistant>!$_"]) return @"assistant"; if ([propConst isEqualToString:@"_$!<AssistantPhone>!$_"]) return @"assistant"; if ([propConst isEqualToString:@"_$!<Brother>!$_"]) return @"brother"; if ([propConst isEqualToString:@"_$!<Car>!$_"]) return @"car"; if ([propConst isEqualToString:@"_$!<Child>!$_"]) return @"child"; if ([propConst isEqualToString:@"_$!<CompanyMain>!$_"]) return @"company main"; if ([propConst isEqualToString:@"_$!<Father>!$_"]) return @"father"; if ([propConst isEqualToString:@"_$!<Friend>!$_"]) return @"friend"; if ([propConst isEqualToString:@"_$!<Home>!$_"]) return @"home"; if ([propConst isEqualToString:@"_$!<HomeFAX>!$_"]) return @"home fax"; if ([propConst isEqualToString:@"_$!<HomePage>!$_"]) return @"home page"; if ([propConst isEqualToString:@"_$!<Main>!$_"]) return @"main"; if ([propConst isEqualToString:@"_$!<Manager>!$_"]) return @"manager"; if ([propConst isEqualToString:@"_$!<Mobile>!$_"]) return @"mobile"; if ([propConst isEqualToString:@"_$!<Mother>!$_"]) return @"mother"; if ([propConst isEqualToString:@"_$!<Other>!$_"]) return @"other"; if ([propConst isEqualToString:@"_$!<Pager>!$_"]) return @"pager"; if ([propConst isEqualToString:@"_$!<Parent>!$_"]) return @"parent"; if ([propConst isEqualToString:@"_$!<Partner>!$_"]) return @"partner"; if ([propConst isEqualToString:@"_$!<Radio>!$_"]) return @"radio"; if ([propConst isEqualToString:@"_$!<Sister>!$_"]) return @"sister"; if ([propConst isEqualToString:@"_$!<Spouse>!$_"]) return @"spouse"; if ([propConst isEqualToString:@"_$!<Work>!$_"]) return @"work"; if ([propConst isEqualToString:@"_$!<WorkFAX>!$_"]) return @"work fax"; return @""; } A: Tried using ABAddressBookCopyLocalizedLabel? Something like: ABAddressBookRef ab = ABAddressBookCreate(); ABRecordID personID = <someid>; CFIndex phoneNumberIndex = <anIndexFromSomewhere>; ABRecordRef person = ABAddressBookGetPersonWithRecordID(ab, personID); CFStringRef name = ABRecordCopyCompositeName(person); ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty); CFStringRef number = ABMultiValueCopyValueAtIndex(phoneNumbers, phoneNumberIndex); CFStringRef label = ABMultiValueCopyLabelAtIndex(phoneNumbers, phoneNumberIndex); CFStringRef localizedLabel = ABAddressBookCopyLocalizedLabel(label); NSLog(@"Person: %@", name); NSLog(@"%@ : %@", localizedLabel, number); CFRelease(label); CFRelease(localizedLabel); CFRelease(number); CFRelease(phoneNumbers); CFRelease(name); CFRelease(ab); A: You'll have to detect labels with the suffix and prefix. Then do a substring to get the label. The values you're getting are the correct label of the strings in the address book database. They're just polished up a bit before presentation to the user. That's all. A: In the newer Contacts framework, you have a class function Here is the example in swift 4 let emailValue: CNLabeledValue<NSString> = ... let label = emailValue.label ?? "" let prettyLabel = type(of: emailValue).localizedString(forLabel: label) This changes "_$!<Work>!$_" to "work" Even better you can make an extension extension CNLabeledValue { @objc func prettyLabel() -> String? { if let label = label { return type(of: self).localizedString(forLabel: label) } return nil } } And now you have even more simple call let emailValue: CNLabeledValue<NSString> = ... let prettyLabel = emailValue.prettyLabel()
{ "language": "en", "url": "https://stackoverflow.com/questions/2570962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Issue with digital signature generated using Podofo library I'm using OpenSSL to generate digital signature for a PDF by PoDoFo library. Here is the logic for signature handler OpenSSLSignatureHandler.h #import <Foundation/Foundation.h> // OpenSSL includes #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/pkcs12.h> #include <openssl/pkcs7.h> #include <openssl/rsa.h> #include <openssl/sha.h> @interface OpenSSLSignatureHandler : NSObject { SHA_CTX m_sha_ctx; EVP_PKEY* mp_pkey; // private key X509* mp_x509; // signing certificate STACK_OF(X509)* mp_ca; // certificate chain up to the CA } - (id) initWithCert:(NSString*) p12file password: (NSString*) password; - (void) AppendData: (NSData*)data; - (NSData*) getSignature; @end OpenSSLSignatureHandler.m #import "OpenSSLSignatureHandler.h" #include <string> @implementation OpenSSLSignatureHandler - (id) initWithCert:(NSString*) p12file password: (NSString*) password{ if (self = [super init]) { // Initialize OpenSSL library CRYPTO_malloc_init(); ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); FILE* fp = fopen([p12file cStringUsingEncoding: NSASCIIStringEncoding], "rb"); if (fp == NULL) @throw ([NSException exceptionWithName: @"PDFNet Exception" reason: @"Cannot open private key." userInfo: nil]); PKCS12* p12 = d2i_PKCS12_fp(fp, NULL); fclose(fp); if (p12 == NULL) @throw ([NSException exceptionWithName: @"PDFNet Exception" reason: @"Cannot parse private key." userInfo: nil]); mp_pkey = NULL; mp_x509 = NULL; mp_ca = NULL; int parseResult = PKCS12_parse(p12, [password cStringUsingEncoding: NSASCIIStringEncoding], &mp_pkey, &mp_x509, &mp_ca); PKCS12_free(p12); if (parseResult == 0) @throw ([NSException exceptionWithName: @"PDFNet Exception" reason: @"Cannot parse private key." userInfo: nil]); //initialize sha context SHA1_Init(&m_sha_ctx); } return self; } - (void) AppendData: (NSData*)data { SHA1_Update(&m_sha_ctx, [data bytes], [data length]); return; } - (BOOL) Reset { SHA1_Init(&m_sha_ctx); return (YES); } - (NSData*) getSignature { unsigned char sha_buffer[SHA_DIGEST_LENGTH]; memset((void*) sha_buffer, 0, SHA_DIGEST_LENGTH); SHA1_Final(sha_buffer, &m_sha_ctx); PKCS7* p7 = PKCS7_new(); PKCS7_set_type(p7, NID_pkcs7_signed); PKCS7_SIGNER_INFO* p7Si = PKCS7_add_signature(p7, mp_x509, mp_pkey, EVP_sha1()); PKCS7_add_attrib_content_type(p7Si, OBJ_nid2obj(NID_pkcs7_data)); PKCS7_add0_attrib_signing_time(p7Si, NULL); PKCS7_add1_attrib_digest(p7Si, (const unsigned char*) sha_buffer, SHA_DIGEST_LENGTH); PKCS7_add_certificate(p7, mp_x509); int c = 0; for ( ; c < sk_X509_num(mp_ca); c++) { X509* cert = sk_X509_value(mp_ca, c); PKCS7_add_certificate(p7, cert); } PKCS7_set_detached(p7, 1); PKCS7_content_new(p7, NID_pkcs7_data); PKCS7_SIGNER_INFO_sign(p7Si); int p7Len = i2d_PKCS7(p7, NULL); NSMutableData* signature = [NSMutableData data]; unsigned char* p7Buf = (unsigned char*) malloc(p7Len); if (p7Buf != NULL) { unsigned char* pP7Buf = p7Buf; i2d_PKCS7(p7, &pP7Buf); [signature appendBytes: (const void*) p7Buf length: p7Len]; free(p7Buf); } PKCS7_free(p7); return (signature); } - (void) dealloc { sk_X509_free(mp_ca); X509_free(mp_x509); EVP_PKEY_free(mp_pkey); // Release OpenSSL resource usage ERR_free_strings(); EVP_cleanup(); [super dealloc]; } @end Using podofo to embed signature void CreateSimpleForm( PoDoFo::PdfPage* pPage, PoDoFo::PdfStreamedDocument* pDoc, const PoDoFo::PdfData &signatureData ) { PoDoFo::PdfPainter painter; PoDoFo::PdfFont* pFont = pDoc->CreateFont( "Courier" ); painter.SetPage( pPage ); painter.SetFont( pFont ); painter.DrawText( 10000 * CONVERSION_CONSTANT, 280000 * CONVERSION_CONSTANT, "PoDoFo Sign Test" ); painter.FinishPage(); PoDoFo::PdfSignatureField signField( pPage, PoDoFo::PdfRect( 0, 0, 0, 0 ), pDoc ); signField.SetFieldName("SignatureFieldName"); signField.SetSignature(signatureData); signField.SetSignatureReason("Document verification"); // Set time of signing signField.SetSignatureDate( PoDoFo::PdfDate() ); } +(void)addDigitalSignatureOnPage:(NSInteger)pageIndex outpath:(NSString*)path/*doc:(PoDoFo::PdfMemDocument*)aDoc*/{ PoDoFo::PdfPage* pPage; PoDoFo::PdfSignOutputDevice signer([path UTF8String]); // Reserve space for signature signer.SetSignatureSize(1024); if([[NSFileManager defaultManager] fileExistsAtPath:path]){ PoDoFo::PdfStreamedDocument writer( &signer, PoDoFo::ePdfVersion_1_5 ); // Disable default appearance writer.GetAcroForm(PoDoFo::ePdfCreateObject, PoDoFo::PdfAcroForm::ePdfAcroFormDefaultAppearance_None); pPage = writer.CreatePage(PoDoFo::PdfPage::CreateStandardPageSize(PoDoFo::ePdfPageSize_A4 ) ); TEST_SAFE_OP( CreateSimpleForm( pPage, &writer, *signer.GetSignatureBeacon() ) ); TEST_SAFE_OP( writer.Close() ); } // Check if position of signature was found if(signer.HasSignaturePosition()) { // Adjust ByteRange for signature signer.AdjustByteRange(); // Read data for signature and count it // We have to seek at the beginning of the file signer.Seek(0); //OpenSSLSignatureHandler NSString * p12certpath = [[NSBundle mainBundle] pathForResource:@"iphone-cert" ofType:@"p12"]; OpenSSLSignatureHandler*signatureHandler = [[OpenSSLSignatureHandler alloc] initWithCert:p12certpath password:@"test123$"]; char buff[65536]; size_t len; while( (len = signer.ReadForSignature(buff, 65536))>0 ) { NSData* data = [NSData dataWithBytes:(const void *)buff length:len]; [signatureHandler AppendData:data]; } const PoDoFo::PdfData *pSignature = NULL; // NSString *pkcsMessage = [[signatureHandler getSignature] base64EncodedString]; // NSLog(@"OpenSSLSignatureHandler signature message = %@",pkcsMessage); // const char * cstr = [pkcsMessage UTF8String]; // if(pSignature==NULL)pSignature = new PoDoFo::PdfData(cstr, sizeof(cstr)); unsigned char *bytePtr = (unsigned char *)[[signatureHandler getSignature] bytes]; std::string str; str.append(reinterpret_cast<const char*>(bytePtr)); // Paste signature to the file if(pSignature==NULL)pSignature = new PoDoFo::PdfData(str.c_str(), sizeof(str)); NSLog(@"str = %s",str.c_str()); NSLog(@"sizeof(str) = %lu",sizeof(str)); signer.SetSignature(*pSignature); } signer.Flush(); } But the signature that's embeded in the PDF is always empty can some help with this issue ?
{ "language": "en", "url": "https://stackoverflow.com/questions/24751957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php pdo search code with multiple parameters Below is my code... I am trying to create search with multiple parameters in php pdo....with Multiple if else condition...in singlw query... plz help ...to make this...how can i do this with php pdo... <?php $db=new PDO('mysql:host=localhost;dbname=circulation_scheme_prepaid','root',''); if(isset($_POST['Submit'])) { $result=$db->prepare('SELECT * FROM receipt_entry WHERE'); if($_POST['book']!='') { $result->bindParam(':book',$_POST['book']); } $result->execute(); $data = $result->fetchAll(); } ?> I nned to make above code like this.. <?php require_once("includes/config.php"); if(isset($_POST['search'])) { $sql = "SELECT * FROM properties WHERE"; if($_POST['location']!='') { $location = $_POST['location']; $sql .= " location = '$location' AND"; } if($_POST['purpose']!='') { $purpose = $_POST['purpose']; $sql .= " purpose = '$purpose' AND"; } $sql = substr($sql, 0 ,-3); $query = mysql_query($sql); while($row = mysql_fetch_array($query,MYSQL_ASSOC)) { $rows[] = $row; } } ?> A: You can try something like this : if (isset($_POST['search'])) { $sql = 'SELECT * FROM properties'; $where = array(); $params = array(); if (!empty($_POST['location'])) { $where[] = "location = :location"; $params[':location'] = $_POST['location']; } if (!empty($_POST['purpose'])) { $where[] = "purpose = :purpose"; $params[':purpose'] = $_POST['purpose']; } if(count($where) > 0) $sql .= ' WHERE ' . implode(' AND ', $where); $stmt = $db->prepare($sql); foreach($params as $param => $value) { $stmt->bindParam($param, $value); } $stmt->execute(); $data = $stmt->fetchAll(); print_r($data); }
{ "language": "en", "url": "https://stackoverflow.com/questions/28991012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: decompiling a .class for struts So initially my goal is to modify MY copy of a network monitoring tool to add to its html an EXTRA option in the navigation menu so I can relocate to html.net for example when someone clicks that menu item. The tool is written in Java using struts and it took me 1 week fo searching throguh the files and folder to finally find the .class for one of the menu items named Dashboard From the struts.config.xml I found that Dashboard.jsp is one of the menu's files....I am probably confusing you so please ignore anything that DOES confuse you... Long story short its all in something called servlet which I am not familiar with... So to modify the html thats in the .jsp file I have to change the .class because in the files or folders the source code isnt there so its all precompiled...I decompiled the class for Dashboard_jsp.class and got this: http://pastebin.com/UkspReDu Now I just need help figuring out what this is because I have never worked with this before...I need to add an extra menu item or make it so when a user clicks on the Dashboard tab it relocates to html.net I dont know what line to modify here...I need help with that. Then I can recompile and replace old .class with new.
{ "language": "en", "url": "https://stackoverflow.com/questions/6985391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WPF - Hide Selected Item / Text Box portion from Combobox Control I'm looking for a way to hide the Selected Item / Textbox portion of the wpf combobox, leaving only the drop down button so users can still interact with the list. I cannot find a property to toggle this behaviour, I was curious to know if there is a way to change visibility of certain portions of this control? If anyone has any suggestions, It'd be greatly appreciated. A: The easiest way to hide the text part is probably to set the Width of the ComboBox: <ComboBox Width="20" /> Otherwise, you could always define your own custom ControlTemplate and set the Template property to this one but this requires some more effort. A: EDIT - To use the below code you will need to use ComboBoxStyleWithoutText as a style on your combobox To achieve this I had to re-create a combo-box and edit the template itself whilst tweaking the individual styles to suit the colour scheme of our app. This is the result In the application Please feel free to use the code below, it likely has some custom colours I've used from other dictionaries (Change these to whatever suits your app) <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Shared.xaml" /> <ResourceDictionary Source="Colours.xaml" /> <ResourceDictionary Source="Brushes.xaml" /> </ResourceDictionary.MergedDictionaries> <!-- SimpleStyles: ComboBox --> <ControlTemplate x:Key="ComboBoxToggleButton" TargetType="ToggleButton"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition Width="20" /> </Grid.ColumnDefinitions> <Border x:Name="Border" Grid.ColumnSpan="2" CornerRadius="2" Background="{StaticResource ScreenBackgroundBrush}" BorderBrush="{StaticResource GridBorderBrush}" BorderThickness="2" /> <Border Grid.Column="0" CornerRadius="2,0,0,2" Margin="1" Background="{StaticResource ScreenBackgroundBrush}" BorderBrush="{StaticResource GridBorderBrush}" BorderThickness="1,1,1,1" /> <Path x:Name="Arrow" Grid.Column="1" Fill="{StaticResource SecondaryControlBrush}" HorizontalAlignment="Center" VerticalAlignment="Center" Data="M 0 0 L 4 4 L 8 0 Z" /> </Grid> <ControlTemplate.Triggers> <Trigger Property="ToggleButton.IsMouseOver" Value="true"> <Setter TargetName="Border" Property="Background" Value="{StaticResource DataGridHeaderRowBackgroundBrush}" /> </Trigger> <Trigger Property="ToggleButton.IsChecked" Value="true"> <Setter TargetName="Border" Property="Background" Value="{StaticResource DataGridHeaderRowBackgroundBrush}" /> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Opacity" Value="0.25" /> <Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}" /> <Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource DisabledBorderBrush}" /> <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}" /> <Setter TargetName="Arrow" Property="Fill" Value="{StaticResource DisabledForegroundBrush}" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> <ControlTemplate x:Key="ComboBoxTextBox" TargetType="TextBox"> <Border x:Name="PART_ContentHost" Focusable="False" Background="{TemplateBinding Background}" /> </ControlTemplate> <Style x:Key="ComboBoxStyleWithoutText" TargetType="{x:Type ComboBox}"> <Setter Property="SnapsToDevicePixels" Value="true" /> <Setter Property="OverridesDefaultStyle" Value="true" /> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" /> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" /> <Setter Property="ScrollViewer.CanContentScroll" Value="true" /> <Setter Property="MinWidth" Value="0" /> <Setter Property="MinHeight" Value="20" /> <Setter Property="Background" Value="Green" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ComboBox"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="0"></ColumnDefinition> <ColumnDefinition MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Width="0"/> </Grid.ColumnDefinitions> <ToggleButton Name="ToggleButton" Template="{StaticResource ComboBoxToggleButton}" Grid.Column="2" Focusable="false" IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press"> </ToggleButton> <ContentPresenter Name="ContentSite" IsHitTestVisible="False" Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" Margin="3,3,3,3" VerticalAlignment="Center" HorizontalAlignment="Left" /> <TextBox x:Name="PART_EditableTextBox" Style="{x:Null}" Template="{StaticResource ComboBoxTextBox}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="3,3,3,3" Focusable="True" Visibility="Hidden" IsReadOnly="{TemplateBinding IsReadOnly}" /> <Popup Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True" Focusable="False" PopupAnimation="Slide"> <Grid Name="DropDown" SnapsToDevicePixels="True" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}"> <Border x:Name="DropDownBorder" Background="{StaticResource TextBoxBrush}" BorderThickness="2" BorderBrush="{StaticResource SolidBorderBrush}" /> <ScrollViewer Margin="4,6,2,2" SnapsToDevicePixels="True"> <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" /> </ScrollViewer> </Grid> </Popup> </Grid> <ControlTemplate.Triggers> <Trigger Property="HasItems" Value="false"> <Setter TargetName="DropDownBorder" Property="MinHeight" Value="95" /> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}" /> </Trigger> <Trigger Property="IsGrouping" Value="true"> <Setter Property="ScrollViewer.CanContentScroll" Value="false" /> </Trigger> <Trigger SourceName="Popup" Property="Popup.AllowsTransparency" Value="true"> <Setter TargetName="DropDownBorder" Property="CornerRadius" Value="4" /> <Setter TargetName="DropDownBorder" Property="Margin" Value="0,2,0,0" /> </Trigger> <Trigger Property="IsEditable" Value="true"> <Setter Property="IsTabStop" Value="false" /> <Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible" /> <Setter TargetName="ContentSite" Property="Visibility" Value="Hidden" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Style.Triggers> </Style.Triggers> </Style> <Style x:Key="{x:Type ComboBox}" TargetType="ComboBox"> <Setter Property="SnapsToDevicePixels" Value="true" /> <Setter Property="OverridesDefaultStyle" Value="true" /> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" /> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" /> <Setter Property="ScrollViewer.CanContentScroll" Value="true" /> <Setter Property="MinWidth" Value="120" /> <Setter Property="MinHeight" Value="20" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ComboBox"> <Grid> <ToggleButton Name="ToggleButton" Template="{StaticResource ComboBoxToggleButton}" Grid.Column="2" Focusable="false" IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press"> </ToggleButton> <ContentPresenter Name="ContentSite" IsHitTestVisible="False" Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" Margin="3,3,23,3" VerticalAlignment="Center" HorizontalAlignment="Left" /> <TextBox x:Name="PART_EditableTextBox" Style="{x:Null}" Template="{StaticResource ComboBoxTextBox}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="3,3,23,3" Focusable="True" Visibility="Hidden" IsReadOnly="{TemplateBinding IsReadOnly}" /> <Popup Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True" Focusable="False" PopupAnimation="Slide"> <Grid Name="DropDown" SnapsToDevicePixels="True" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}"> <Border x:Name="DropDownBorder" Background="{StaticResource TextBoxBrush}" BorderThickness="2" BorderBrush="{StaticResource SolidBorderBrush}" /> <ScrollViewer Margin="4,6,4,6" SnapsToDevicePixels="True"> <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" /> </ScrollViewer> </Grid> </Popup> </Grid> <ControlTemplate.Triggers> <Trigger Property="HasItems" Value="false"> <Setter TargetName="DropDownBorder" Property="MinHeight" Value="95" /> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}" /> </Trigger> <Trigger Property="IsGrouping" Value="true"> <Setter Property="ScrollViewer.CanContentScroll" Value="false" /> </Trigger> <Trigger SourceName="Popup" Property="Popup.AllowsTransparency" Value="true"> <Setter TargetName="DropDownBorder" Property="CornerRadius" Value="4" /> <Setter TargetName="DropDownBorder" Property="Margin" Value="0,2,0,0" /> </Trigger> <Trigger Property="IsEditable" Value="true"> <Setter Property="IsTabStop" Value="false" /> <Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible" /> <Setter TargetName="ContentSite" Property="Visibility" Value="Hidden" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Style.Triggers> </Style.Triggers> </Style> <!-- SimpleStyles: ComboBoxItem --> <Style x:Key="{x:Type ComboBoxItem}" TargetType="ComboBoxItem"> <Setter Property="SnapsToDevicePixels" Value="true" /> <Setter Property="OverridesDefaultStyle" Value="true" /> <Setter Property="Background" Value="{StaticResource ScreenBackgroundBrush}"/> <Setter Property="Foreground" Value="{StaticResource PrimaryTextBrush}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ComboBoxItem"> <Border Name="Border" Padding="2" SnapsToDevicePixels="true"> <ContentPresenter /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsHighlighted" Value="true"> <Setter TargetName="Border" Property="Background" Value="{StaticResource DataGridRowSelectedBrush}" /> <Setter TargetName="Border" Property="CornerRadius" Value="2" /> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>
{ "language": "en", "url": "https://stackoverflow.com/questions/70420224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: using IDataErrorInfo in asp.net mvc I've got a simple address entry app that I'm trying to use the IDataErrorInfo interface as explained on the asp.net site. It works great for items that can be validated independently, but not so well when some items depend on others. For example, validating the postal code depends on the country: private string _PostalCode; public string PostalCode { get { return _PostalCode; } set { switch (_Country) { case Countries.USA: if (!Regex.IsMatch(value, @"^[0-9]{5}$")) _errors.Add("PostalCode", "Invalid Zip Code"); break; case Countries.Canada: if (!Regex.IsMatch(value, @"^([a-z][0-9][a-z]) ?([0-9][a-z][0-9])$", RegexOptions.IgnoreCase)) _errors.Add("PostalCode", "Invalid postal Code"); break; default: throw new ArgumentException("Unknown Country"); } _PostalCode = value; } } So you can only validate the postal code after the country has been set, but there seems to be no way of controlling that order. I could use the Error string from IDataErrorInfo, but that doesn't show up in the Html.ValidationMessage next to the field. A: For more complex business rule validation, rather than type validation it is maybe better to implement design patterns such as a service layer. You can check the ModelState and add errors based on your logic. You can view Rob Conroys example of patterns here http://www.asp.net/learn/mvc/tutorial-29-cs.aspx This article on Data Annotations ay also be useful. http://www.asp.net/learn/mvc/tutorial-39-cs.aspx Hope this helps. A: Here's the best solution I've found for more complex validation beyond the simple data annotations model. I'm sure I'm not alone in trying to implement IDataErrorInfo and seeing that it has only created for me two methods to implement. I'm thinking wait a minute - do i have to go in there and write my own custom routines for everything now from scratch? And also - what if I have model level things to validate. It seems like you're on your own when you decide to use it unless you want to do something like this or this from within your IDataErrorInfo implementation. I happened to have the exact same problem as the questioner. I wanted to validate US Zip but only if country was selected as US. Obviously a model-level data annotation wouldn't be any good because that wouldn't cause zipcode to be highlighted in red as an error. [good example of a class level data annotation can be found in the MVC 2 sample project in the PropertiesMustMatchAttribute class]. The solution is quite simple : First you need to register a modelbinder in global.asax. You can do this as an class level [attribute] if you want but I find registering in global.asax to be more flexible. private void RegisterModelBinders() { ModelBinders.Binders[typeof(UI.Address)] = new AddressModelBinder(); } Then create the modelbinder class, and write your complex validation. You have full access to all properties on the object. This will run after any data annotations have run so you can always clear model state if you want to reverse the default behavior of any validation attributes. public class AddressModelBinder : DefaultModelBinder { protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) { base.OnModelUpdated(controllerContext, bindingContext); // get the address to validate var address = (Address)bindingContext.Model; // validate US zipcode if (address.CountryCode == "US") { if (new Regex(@"^\d{5}([\-]\d{4})?$", RegexOptions.Compiled). Match(address.ZipOrPostal ?? "").Success == false) { // not a valid zipcode so highlight the zipcode field var ms = bindingContext.ModelState; ms.AddModelError(bindingContext.ModelName + ".ZipOrPostal", "The value " + address.ZipOrPostal + " is not a valid zipcode"); } } else { // we don't care about the rest of the world right now // so just rely on a [Required] attribute on ZipOrPostal } // all other modelbinding attributes such as [Required] // will be processed as normal } } The beauty of this is that all your existing validation attributes will still work - [Required], [EmailValidator], [MyCustomValidator] - whatever you have. You can just add in any extra code into the model binder and set field, or model level ModelState errors as you wish. Please note that for me an Address is a child of the main model - in this case CheckoutModel which looks like this : public class CheckoutModel { // uses AddressModelBinder public Address BillingAddress { get; set; } public Address ShippingAddress { get; set; } // etc. } That's why I have to do bindingContext.ModelName+ ".ZipOrPostal" so that the model error will be set for 'BillingAddress.ZipOrPostal' and 'ShippingAddress.ZipOrPostal'. PS. Any comments from 'unit testing types' appreciated. I'm not sure about the impact of this for unit testing. A: Regarding the comment on Error string, IDataErrorInfo and the Html.ValidationMessage, you can display object level vs. field level error messages using: Html.ValidationMessage("address", "Error") Html.ValidationMessage("address.PostalCode", "Error") In your controller decorate the post method handler parameter for the object with [Bind(Prefix = "address")]. In the HTML, name the input fields as such... <input id="address_PostalCode" name="address.PostalCode" ... /> I don't generally use the Html helpers. Note the naming convention between id and name.
{ "language": "en", "url": "https://stackoverflow.com/questions/1511495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: why do I get the error: pygame.error: video system not initialized Like the title says I am confused why I get the error: pygame.error: video system not initialized As far as i understand this error is raised if you forget to initialize your code with pygame.init() but I did, here's my code and thanks in advance: import pygame from pygame.locals import * pygame.init() screen_height = 700 screen_width = 1000 screen = pygame.display.set_mode((screen_width,screen_height)) pygame.display.set_caption("platformer") # load images sun_img = pygame.image.load("img/sun.png") backround_img = pygame.image.load("img/sky.png") run = True while run: screen.blit (backround_img,(0,0)) screen.blit(sun_img, (100, 50)) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() pygame.display.update() the error does not crash the window or anything and it works as intended its just somewhat annoying. A: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() pygame.display.update() When the event loop happens, if you close the window, you call pygame.quit(), which quits pygame. Then it tries to do: pygame.display.update() But pygame has quit, which is why you are getting the message. separate the logic out. Events in one function or method, updating in another, and drawing and updating the display in another to avoid this.
{ "language": "en", "url": "https://stackoverflow.com/questions/67448637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Routing rails url contains multiple parameters I am doing a sharing application like facebook ,where user can share a url on their posts I have a user posts form and I populate the form from url params the problem I want to route /sharer?urlparams to the sharer action on my controller without removing the url params in the url somthing like localhost:3000/sharer?params[:url]="http://stackoverflow.com/questions/ask"&params[:title]=""&params[:description]="" N.B update I found these method match'/sharer/:url'=>"manys#sharer",:constraints => {:url => /.*/} A: If the url and controller name are not equal best way is the following method. match "/sharer/:id/share" => redirect{ |params, request| "/posts/#{params[:id]}/share?#{request.query_string}" } If the url name and the action name is same you can use something like this. resources :sharer do member do get :share end end You can use collection instead of member routing according to your url. I used member because my example is taking id in the url path. Therefore it becomes a member route.
{ "language": "en", "url": "https://stackoverflow.com/questions/19236977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a dynamic root in Rails 3? I have admins and normal users in my webapp. I want to make their root (/) different depending on who they are. The root is accessed from many different pages, so it would be much easier if I could make this happen in the routes.rb file. Here is my current file. ProjectManager::Application.routes.draw do root :to => "projects#index" end Can someone please link me to an example that can show me the direction to go in? Is there any way to put logic into the routes file? Thanks for all the help. A: You can just create controller for root route. class RoutesController < ActionController::Base before_filter :authenticate_user! def root root_p = case current_user.role when 'admin' SOME_ADMIN_PATH when 'manager' SOME_MANAGER_PATH else SOME_DEFAULT_PATH end redirect_to root_p end end In your routes.rb: root 'routes#root' P.S. example expects using Devise, but you can customize it for your needs. A: There are a few different options: 1. lambda in the routes file(not very railsy) previously explained 2. redirection in application controller based on a before filter(this is optimal but your admin route will not be at the root) source rails guides - routing you would have two routes, and two controllers. for example you might have a HomeController and then an AdminController. Each of those would have an index action. your config/routes.rb file would have namespace :admin do root to: "admin#index" end root to: "home#index" The namespace method gives you a route at /admin and the regular root would be accessible at '/' Then to be safe; in your admin controller add a before_filter to redirect any non admins, and in your home controller you could redirect any admin users. 3. dynamically changing the layout based on user role. In the same controller that your root is going to, add a helper method that changes the layout. layout :admin_layout_filter private def admin_layout_filter if admin_user? "admin" else "application" end end def admin_user? current_user.present? && current_user.admin? end Then in your layouts folder, add a file called admin.html.erb source: rails guides - layouts and routing A: You can't truly change the root dynamically, but there's a couple of ways you can fake it. The solution you want needs to take place in either your application controller or the "default" root controller. The cleanest/easiest solution is simply to have your application controller redirect to the appropriate action in a before filter that only runs for that page. This will cause the users' url to change, however, and they won't really be at the root anymore. Your second option is to have the method you've specified as root render a different view under whatever conditions you're looking for. If this requires any major changes in logic beyond simply loading a separate view, however, you're better off redirecting.
{ "language": "en", "url": "https://stackoverflow.com/questions/11960977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: I want to return response to download CSV file from data frame contains Arabic letters I have encountered a problem while coding using Flask for my website I have a CSV file that I converted to Dataframe then I want to return it as CSV to the user so they can download it. however, when I do that the Arabic letters do not show clearly only symbols :( I tried different possible ways but unfortunately, all doesn't work @flask_app.route('/getPlotCSV') def download_file(): path ="marked_test_df.csv" #path.encode('utf-8-sig') try: df = pd.read_csv(path, encoding='utf-8-sig') df_ob= df.to_csv(encoding='utf-8-sig') resp = make_response(df_ob) resp.headers["Content-Disposition"] = "attachment; filename=marked_test_df.csv " #resp.charset='utf-8-sig' #resp.iter_encoded='utf-8-sig' resp.headers["Content-Type"] = "text/csv ; charset = utf-16" resp.content_encoding = 'utf-16' os.remove(path) except Exception as error: flask_app.logger.error("Error removing or closing downloaded file handle", error) return resp sample of the CSV before the user can download it: However, when the user downloads it through the download button it shows like that:
{ "language": "en", "url": "https://stackoverflow.com/questions/71931702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Designing a label with images and text GWT I am current trying to create tab that has a check mark when the I click done and then shows an an "X" when I click cancel. Currently I have my tab written in XML. I am wondering how I would go about implementing this. I am thinking about using two labels and combining them together. One will be in XML the other one will be in java only. I am also wondering how i would space these two so they over lap and act as one tab together. public class buttonclickers extends Composite { private static buttonclickersUiBinder uiBinder = GWT .create(buttonclickersUiBinder.class); @UiField PushButton button_1; @UiField PushButton button_2; interface buttonclickersUiBinder extends UiBinder<Widget, buttonclickers> { } public buttonclickers() { initWidget(uiBinder.createAndBindUi(this)); } @UiHandler("button_1") void onButton_1Click(ClickEvent event) { AppUtils.EVENT_BUS.fireEvent(new ButtonEvent()); } @UiHandler("button_2") void onButton_2Click(ClickEvent event) { } } This is what I have so far. Is there anyway to change the image on these xml buttons when I press it? Any idea will help thank you! Edit: So I ran into this website http://www.javacodegeeks.com/2012/03/gwt-custom-button-using-uibinder.html and it shows how to add an image to a button. I would like to do the same thing but instead of having a static image I want the image to change every time I clicked done or cancel. Edit: current I have a label and image. I want to be able to change that image every time I press a button. private static buttonclickersUiBinder uiBinder = GWT .create(buttonclickersUiBinder.class); @UiField PushButton button_1; @UiField PushButton button_2; @UiField Image checkimage; @UiField Label label_one; interface buttonclickersUiBinder extends UiBinder<Widget, buttonclickers> { } public buttonclickers() { initWidget(uiBinder.createAndBindUi(this)); } @UiHandler("button_1") void onButton_1Click(ClickEvent event) { AppUtils.EVENT_BUS.fireEvent(new ButtonEvent()); } @UiHandler("button_2") void onButton_2Click(ClickEvent event) { } @UiHandler("checkimage") void onCheckimageClick(ClickEvent event) { Window.alert("hit"); AppUtils.EVENT_BUS.fireEvent(new ButtonEvent()); } @UiHandler("label_one") void onLabel_oneClick(ClickEvent event) { AppUtils.EVENT_BUS.fireEvent(new ButtonEvent()); } } I understand we have checkimage as the id. is it possible that I just add other images into the xml and call it whenever something is pressed? A: actually I figured it out. you add " checkimage.setUrl("mvpwebapp/gwt/clean/images/xmark.png"); " to change the images.
{ "language": "en", "url": "https://stackoverflow.com/questions/17733539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ARKit – Save scene as USDZ? Right now I can save what I created in ARKit as a scene file, and load it back later. sceneView.scene.write(to: path, options: nil, delegate: nil, progressHandler: nil) But is it possible to save the scene as USDZ file and load it back? A: First of all, read the following SO post that is very helpful. Creating USDZ from SCN programmatically In SceneKit, there's the write(to:options:delegate:progressHandler:) instance method that does the trick (the only thing you have to do is to assign a file format for URL). let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] .appendingPathComponent("model.usdz") sceneView.scene.write(to: path) Converting OBJ to USDZ using SceneKit.ModelIO However, if you need to convert OBJ model into USDZ, you have to import SceneKit.ModelIO module at first. Then use the following code: let objAsset = MDLAsset(url: objFileUrl) let destinationFileUrl = URL(fileURLWithPath: "path/Scene.usdz") objAsset.exportToUSDZ(destinationFileUrl: destinationFileUrl) Terminal approach In Xcode 11/12/13/14, you can convert several popular input formats into USDZ via command line: obj, gltf, fbx, abc, usd(x). usdzconvert file.gltf In Xcode 10, only OBJ-to-USDZ, single-frame ABC-to-USDZ and USD(x)-to-USDZ conversion is available via command line: xcrun usdz_converter file.obj file.usdz Preparing files for RealityKit In Xcode 12+ you can use a Reality Composer software for converting any RC scene into usdz file format (right from UI). Also, there's a Reality Converter standalone app. And, of course, you can use Autodesk Maya 2020 | 2022 | 2023 with Maya USD plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/51059875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ImageList pictures not showing up in ImageIndex or ImageKey I've encountered an annoying problem while creating a new application today. I was trying to add an image to a TabControl in Windows Forms (vb.net) using an ImageList but for some reason they no longer show up in the ImageIndex or ImageKey properties of controls. It keeps showing (none) only. Never had this before and haven't done anything unusual. Anyone else had this problem? Can't find anything on the web. I'm using Visual Studio 2015.
{ "language": "en", "url": "https://stackoverflow.com/questions/40638948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get the time a file was last editted in python I've looked around on SO and various other websites and thought I figured this out, but apparently I didn't or I'm doing something wrong. Here is what I have tried: pre = datetime.fromtimestamp(f) pre = os.path.getmtime(f) pre = fromtimestamp(f) All three return the error: TypeError: an integer is required I did some digging and found this for what a lot of people have suggested: os.path.getmtime(path)¶ Return the time of last modification of path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, the result is a floating point number. So now I am faced with the problem, how do I get it to be an integer value so I can compare this time with another after reading a file to determine if the file changed while parsing. A: os.path.getmtime takes a file path, not a file object: >>> os.path.getmtime('/') 1359405072.0 If f is an open file, try passing in f.name.
{ "language": "en", "url": "https://stackoverflow.com/questions/14572927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Binding member function to a member variable Precondition: Here is a function: typedef std::function<void (int)> Handler; void g(const Handler& h) { h(100); } , and a class(original version): class A { public: A(int arg) : m(arg) {} void f0(int n) { std::cout << m + n << std::endl; } void f() { ::g(std::bind(&A::f0, this, std::placeholders::_1)); } private: const int m; }; And this will print two lines, '101' and '102': int main() { A a1(1); a1.f(); A a2(2); a2.f(); return 0; } Now I realized A::f() will be called very frequently, so I modified it like this(new version): class A { public: A(int arg) : m(arg), handler(std::bind(&A::f0, this, std::placeholders::_1)) {} void f0(int n) { std::cout << m + n << std::endl; } void f() { ::g(handler); } private: const int m; const Handler handler; }; My Questions: Is it safe to bind this pointer to a member variable? Is there no functional difference between two versions? Can I expect the new version will really gain some performance benefit? (I suspect my compiler(MSVC) will optimize it by itself, so I may not need to optimize it by myself). PS.: This question corrects and replaces the previous one: Binding member function to a local static variable A: As Igor Tandetnik mentioned in comments: Is it safe to bind this pointer to a member variable? Beware the compiler-generated copy constructor and assignment operator. Consider: A a(42); A b = a; Here, b.handler still refers to &a, not &b. This may or may not be what you want. I also don't think the performance benefit deserves dev-time effort to maintain member variables. (*)
{ "language": "en", "url": "https://stackoverflow.com/questions/26541667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a tab control with bootstrap in asp.net Here I am implementing bootstrap tab control in asp.net application. 1) On click on next i want to go to next tab. I want to make tab control working by clicking on tabs of tab control to go to next tab or by clicking on next button. <form id="form1" runat="server"> <div class="container"> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#personal">Personal Information</a></li> <li><a data-toggle="tab" href="#professional">Professional Information</a></li> <li><a data-toggle="tab" href="#accountinformation">User Account Infromation</a></li> </ul> <div class="tab-content"> <div id="personal" class="tab-pane fade in active"> <div class="form-group"> <div class="row"> <div class="col-sm-12 col-md-12 col-lg-12"> <div class="col-sm-4"> <span class="Star-clr">*</span>First Name : </div> <div class="col-sm-8"> <asp:TextBox ID="txtName" runat="server" placeholder="First Name"</asp:TextBox> </div> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-sm-12 col-md-12 col-lg-12"> <div class="col-sm-2"> </div> <div class="col-sm-10" style="float: right"> <asp:Button ID="btnNext" Width="150" runat="server" Text="NEXT" /> </div> </div> </div> </div> </div> <div id="professional" class="tab-pane fade"> </div> <div id="accountinformation" class="tab-pane fade"> </div> </div> </div> </form> Image of Tab control: A: Create a button after your content divs and call function on this button <input type="button" value="Next" onclick="ShowNextTab();" /> function ShowNextTab() { if ($('.nav-tabs > .active').next('li').length == 0) //If you want to select first tab when last tab is reached $('.nav-tabs > li').first().find('a').trigger('click'); else $('.nav-tabs > .active').next('li').find('a').trigger('click'); } Below is a complete solution HTML <form id="form1" runat="server"> <div class="container"> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#personal">Personal Information</a></li> <li><a data-toggle="tab" href="#professional">Professional Information</a></li> <li><a data-toggle="tab" href="#accountinformation">User Account Infromation</a></li> </ul> <div class="tab-content"> <div id="personal" class="tab-pane fade in active"> <div class="form-group"> <div class="row"> <div class="col-sm-12 col-md-12 col-lg-12"> <div class="col-sm-4"> <span class="Star-clr">*</span>First Name : </div> <div class="col-sm-8"> <asp:TextBox ID="txtName" runat="server" placeholder="First Name"></asp:TextBox>//close tag is missing </div> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-sm-12 col-md-12 col-lg-12"> <div class="col-sm-2"> </div> <div class="col-sm-10" style="float: right"> <asp:Button ID="btnNext" Width="150" runat="server" Text="NEXT" /> </div> </div> </div> </div> </div> <div id="professional" class="tab-pane fade"> </div> <div id="accountinformation" class="tab-pane fade"> </div> <input type="button" value="Next" onclick="ShowNextTab();" /> <input type="button" value="Prev" onclick="ShowPrevTab();" /> </div> </div> </form> JavaScript function ShowNextTab() { $('.nav-tabs > .active').next('li').find('a').trigger('click'); } function ShowPrevTab() { $('.nav-tabs > .active').prev('li').find('a').trigger('click'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/37959511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can Amazon S3 bucket permissions be set so every time I save a file read permissions stay public? I'm using the Coda app at add, edit, and save files on my S3 bucket. The bucket has static web hosting enabled. Every time I upload or save a file, the permissions automatically change to restrict the "world" from reading the file. How can Amazon S3 bucket permissions be set so every time I save a file read permissions stay public? A: Add a bucket wide policy rather than on each file: { "Version": "2008-10-17", "Statement": [ { "Sid": "AllowPublicRead", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": [ "s3:GetObject" ], "Resource": [ "arn:aws:s3:::my-brand-new-bucket/*" ] } ] } http://s3browser.com/working-with-amazon-s3-bucket-policies.php A: Instead of adding a new bucket policy, I fixed my problem by aliasing a domain name to my bucket. When I access bucket files through the alias, I'm seeing no permission errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/23413674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Operator overloading adding two objects error I have no idea why this code should work, but tell me what to do if i want to add two objects together. please. while you are trying to answer please be more noob specific sorry for my bad english, I am an Indian, here is my code. #include<iostream> using namespace std; class time { private: int sec; int mint; int hours; public: int Inputsec; int Inputmint; int Inputhours; time(int Inputsec, int Inputmint, int Inputhours):sec(Inputsec), mint(Inputmint), hours(Inputhours){}; time operator+(time Inputobj) { time blah (sec+Inputsec,mint+Inputmint,hours+Inputhours); return blah; } void DisplayCurrentTime() { cout << "The Current Time Is"<<endl<< hours<<" hours"<<endl<<mint<<"minutes"<<endl<<sec<<"seconds"<<endl; } }; int main() { time now(11,13,3); time after(13,31,11); time then(now+after); then.DisplayCurrentTime(); } code is working fine but it is giving me horrible output. Where is my mistake? A: Your addition operator is using unitinitialized member Inputsec, Inputmint and Inputhours variables. It should look like this: time operator+(time Inputobj) { return time(sec+InputObj.sec, mint+InputObj.mint, hours+InputObj.hours); } or time operator+(time Inputobj) { InputObj.sec += sec; InputObj.mint += mint; InputObj.hours += hours; return InputObj; } Or, even better, implement time& operator+=(const time& rhs); and use it in a non-member addition operator: time operator+(time lhs, const time& rhs) { return lhs += rhs; } You have two sets of member variables representing the same thing. You do not need this duplication. One final remark: there is something called std::time in header<ctime>. Having a class called time, and using namespace std is asking for trouble. You should avoid both if possible (avoiding the second is definitely possible). A: You should rewrite your operator+ at least as follows: time operator+(time Inputobj) { time blah time(sec+InputObj.sec, mint+InputObj.mint, hours+InputObj.hours); return blah; } also I think you should use the % operator for getting the correct time results: time operator+(time Inputobj){ int s = (sec+InputObj.sec) % 60; int m = (sec+InputObj.sec) / 60 + (mint+InputObj.mint) % 60; int h = (mint+InputObj.mint) / 60 + (hours+InputObj.hours) % 24; return time(s,m,h); } A: Your operator overloading function is using uninitialized variables. Initialize variables inputsec, inputmint, Inputhours in your constructor. Moreover, try this: time operator+ (time Inputobj) { time blah (sec+Inputobj.sec, mint+Inputobj.mint, hours+Inputobj.hours); return blah; } A: Your error is your publics members with the same name as the parameter constructor, which are unitialized. Try this : #include <iostream> using namespace std; class time { private: int sec; int mint; int hours; public: time(int Inputsec, int Inputmint, int Inputhours):sec(Inputsec), mint(Inputmint), hours(Inputhours) { }; time operator+(time Inputobj) { time blah (sec+Inputobj.sec, mint+Inputobj.mint, hours+Inputobj.hours); return blah; } void DisplayCurrentTime() { cout << "The Current Time Is"<<endl<< hours<<" hours"<<endl<<mint<<"minutes"<<endl<<sec<<"seconds"<<endl; } }; int main() { time now(11,13,3); time after(13,31,11); time then(now+after); then.DisplayCurrentTime(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/17274913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Concatenate backslash on python I'm new to python so forgive me if this sounds simple. I want to join a few variables to produce a path. Like this: AAAABBBBCCCC\2\2014_04\2014_04_01.csv Id + '\' + TypeOfMachine + '\' + year + '_' + month + '\' + year + '_' + month + '_' + day + '.csv' How do I concatenate this? I putted single quotes around underline or backslash, but stackoverflow omits/modifies them. A: Normally, you'd double the backslash: '\\' Use os.path.join() to join directory and filename elements, and use string formatting for the rest: os.path.join(Id, TypeOfMachine, '{}_{}'.format(year, month), '{}_{}_{}.csv'.format(year, month, day)) and let Python take care of using the correct directory separator for your platform for you. This has the advantage that your code becomes portable; it'll work on an OS other than Windows as well. By using string formatting, you also take care of any non-string arguments; if year, month and day are integers, for example. A: You can simply call the character by its ASCII code. (I'm using Python 3.7). Example: In this case, the ASCII code is 92, you can use Python's chr() function to call the character In this website you can find a list of ASCII codes for more printable characters. The code used above: delimiter = chr(92) FileName = 'Id' + delimiter + 'TypeOfMachine' + delimiter + 'year' + '_' + 'month' + delimiter + 'year' + '_' + 'month' + '_' + 'day' + '.csv' print(FileName) Hope it helps. A: A backslash is commonly used to escape special strings. For example: >>> print "hi\nbye" hi bye Telling Python not to count slashes as special is usually as easy as using a "raw" string, which can be written as a string literal by preceding the string with the letter 'r'. >>> print r"hi\nbye" hi\nbye Even a raw string, however, cannot end with an odd number of backslashes. This makes string concatenation tough. >>> print "hi" + r"\" + "bye" File "<stdin>", line 1 print "hi" + r"\" + "bye" ^ SyntaxError: invalid syntax There are several ways to work around this. The easiest is using string formatting: >>> print r'{}\{}'.format('hi', 'bye') hi\bye Another way is to use a double-backslash in a regular string to escape the second backslash with the first: >>> print 'hi' + '\\' + 'bye' hi\bye But all of this assumes you're facing a legitimate need to use backslashes. If all you're trying to do is construct Windows path expressions, just use os.path.join. A: You should use os.path.join to construct the path. e.g: import os path = os.path.join(Id, TypeOfMachine, year + '_' + month, year + '_' + month + '_' + day + '.csv') or if you insist on using backslashes, you need to escape them: as, so '\\' A: Without importing os.path module you could simply do: my_path = '\\'.join([Id,TypeOfMachine, year + '_' + month, year + '_' + month + '_' + day + '.csv']) A: You can also use normal strings like: Id + '/' + TypeOfMachine + '/' + year + '_' + month + '/' + year + '_' + month + '_' + day + '.csv'
{ "language": "en", "url": "https://stackoverflow.com/questions/22792113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Undef values from CSV file giving undesirable result I am having a CSV file Sample.csv like below named Name,Memory,Encoding,Extra 1,Extra 2 ,d,,h,b FUSE_1,36,30,37,15 FUSE_1,36,28,36,31 Name1,1TB,00000001,30,010 Name1,1TB,00000010,52,001 I am parsing this file and want to retrieve some values from the file. What I want is Only those names from the first row for which corresponding value is present in 2nd row. Means I want to get Memory,Extra 1 and Extra 2 as corresponding value is present in 2nd row (d,h and b). For which What I am doing is I am storing the values of both the rows in separate arrays and then I am traversing the array for 2nd row and the indexes corresponding to which value is present in this that corresponding index value I am taking from 1st array and storing it in second array.The code which I am using is- my $iniFilename = "Sample.csv"; open(my $fi,'<',$iniFilename) or die "Can't open $iniFilename"; while(my $row=<$fi>){ if($row_no == 0) { chomp($row); $row=~ s/\A\s+//g; $row=~s/\R//g; if(length($row)) { @fuse_name_initial = split(/,/,$row); } } elsif($row_no == 1) { chomp($row); $row=~ s/\A\s+//g; $row=~s/\R//g; if(length($row)){ @fuse_data_type_initial =split(/,/,$row); } } $row_no++; } my $trace=0; foreach (@fuse_data_type_initial) { if($_) { if($fuse_name_initial[$trace] !~ /Extra Fuse/){ push @column_no_for_fuse_value,($trace+1); push @fuse_names , $fuse_name_initial[$trace]; push @fuse_data_type ,$_ ; $trace++; } else{ push @extra_fuse_data_type ,$_ ; $trace++; } } } Now I am expecting the @fuse_names array to reflect names "Memory" as "Extra Fuse1" and "Extra Fuse2" is filtered out using regex but instead I am getting very bad result. I am getting three elements in the @fuse_names- Name,Memory,Encoding . Can Somebody please tell me What I am doing wrong in the code?? EDIT : When I am changing 2nd row to ",d,,," and following @Dada method then it should only take "Memory" from 1st row but instead it is taking everything after memory i.e Memory,Encoding,Extra Fuse1,Extra Fuse2 And then I printed the length of @filter array.It should ideally be 5 with 1 defined value and 4 other undef value but strangely the length of @filter came out to be 2. It is really Confusing. A: Your code is pretty bad for several reasons. Instead of trying to fix them, which would leave you with a bad-but-working code, I'm going to point them out, and suggest a better way. * *You first while(my $row = <$fi>) iterates over the whole file when you are only interested in the first two rows. You should just use <$fi> twice to read the first two lines: my $headers = <$fi>; my $filters = <$fi>; *You shouldn't duplicate code. In particular, you wrote twice chomp($row); $row=~ s/\A\s+//g; $row=~s/\R//g; Whereas you could have put that only once at the beginning of the while. *Same thing for $trace++: you want it done at every iteration of your foreach loop; there is no reason to put it in at the end of the if and at the end of the else. *always use strict and use warnings. Here is what I suggest instead: use strict; # Always use strict and warnings! use warnings; my $iniFilename = "Sample.csv"; open(my $fi,'<',$iniFilename) or die "Can't open $iniFilename"; my @headers = split ',', <$fi> =~ s/\A\s+|\s+\Z//gr, -1; my @filter = split ',', <$fi> =~ s/\A\s+|\s+\Z//gr, -1; for my $i (0 .. $#filter) { $headers[$i] = undef if !$filter[$i] || $filter[$i] eq "" ; } # @headers now contains (undef, "Memory", undef, "Extra 1", "Extra 2") If you need the index of @headers that are not undef: my @headers_indices = grep { defined $headers[$_] } 0 .. $#headers; If you need just the names of the non-undef headers: my @non_undef_headers = grep { defined $_ } @headers; Finally, since you are parsing CSV files, you might want to use a CSV parser (Text::CSV_XS for example), rather than split /,/. (the latter will misbehave with quoted fields containing commas or newlines (and probably has other issues that I'm not thinking about right now))
{ "language": "en", "url": "https://stackoverflow.com/questions/55420550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Canvas Responsive - Fabricjs I trying let the responsive canvas following this topic1 and topic2 I'm trying to let the responsive canvas for all devices. I know it's possible but I'm having a tough time finding the solution. Following the two topics above I tried to set the width and height for the max canvas size in javascript. And in the css for each device a different size to canvas view, even changing the CSS display size actual size defined in javascript must remain I´m using fabric.js SOLUTION Note: stack Overflow view considering width 360px because of the preview in the post var canvas = this.__canvas = new fabric.StaticCanvas ('c'); canvas.setHeight(600); canvas.setWidth(800); canvas.setBackgroundImage('http://lorempixel.com/500/500/animals', canvas.renderAll.bind(canvas), { width: 800,height: 600 }); var text = new fabric.Text('Hello', { left: 100, top: 100, fill: 'blue', }); canvas.add(text); #c{ border:1px solid red; top:22px; left:0px; height: 100%; width: 99%; } @media screen and (min-width: 360px) { #c { -webkit-transform : scale(0.4); -webkit-transform-origin : 0 0; } } @media screen and (min-width: 768px) { #c { -webkit-transform : scale(0.45); -webkit-transform-origin : 0 0; } } @media screen and (min-width: 992px) { #c { -webkit-transform : scale(0.5); -webkit-transform-origin : 0 0;} } @media screen and (min-width: 1200px) { #c { -webkit-transform : scale(0.5); -webkit-transform-origin : 0 0;} } <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.js"></script> <canvas id="c"></canvas> A: Solution in my question. In topic1 I found it: X4V1 answered Jun 16 '15 at 20:24 I have found a trick to do that without having to copy the canvas. This solution is really close to css zoom property but events are handle correctly. This is an example to display the canvas half its size: -webkit-transform : scale(0.5); -webkit-transform-origin : 0 0;
{ "language": "en", "url": "https://stackoverflow.com/questions/34909243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AngularJS: How to toggle element from controller How can I use the following controller to toggle the content inside li tag? Right now the content is rendered only after that span is clicked, but it won't hide if I click again the span. Here's my code: <span ng-click="get_menu_items(folder)> <i class="fa fa-folder-o"></i> {{ folder.name }} </span> <ul> <li class="item" ng-repeat="file in folder.files"> <label> <input type="checkbox" name="file_map[]" value="{{ file.id }}" ng-model="file_map[file.id]" ng-click="update_selection(file.id)"/> <i class="fa fa-file-o"></i> <span>{{ file.name }}</span> </label> </li> <li menuitem ng-repeat="folder in folder.folders" ng-model="folder"></li> </ul> Controller: scope.get_menu_items = function(folder){ http.get("/api/folders/" + folder.id).success(function(data){ folder.folders = data.data.folders; folder.files= data.data.files; }) } A: You can simply create a boolean for show/hide and toggle it on your click method like. scope.get_menu_items = function(folder){ //if folder.folder exist means we don't need to make $http req again if(folder.folders){ $scope.showFolder = !$scope.showFolder } else{ http.get("/api/folders/" + folder.id).success(function(data){ folder.folders = data.data.folders; folder.files= data.data.files; $scope.showFolder = true; }) } } and add ng-if on your view like. <span ng-click="get_menu_items(folder)> <i class="fa fa-folder-o"></i> {{ folder.name }} </span> <ul ng-if="showFolder"> <li class="item" ng-repeat="file in folder.files"> <label> <input type="checkbox" name="file_map[]" value="{{ file.id }}" ng-model="file_map[file.id]" ng-click="update_selection(file.id)"/> <i class="fa fa-file-o"></i> <span>{{ file.name }}</span> </label> </li> <li menuitem ng-repeat="folder in folder.folders" ng-model="folder"></li> </ul> Hope it helps. A: Add a global variable in controller as scope. Outside controller, add a variable (for example called: toggleVariable) and assign it to false. Inside controller put this: scope.toggleVariable = !scope.toggleVariable; In HTML, add to ul tag: ng-show="toggleVariable". Give it a try
{ "language": "en", "url": "https://stackoverflow.com/questions/36281305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to run tests prerequisite once and clean up in the end in whole unit test run I'm running series of testcases in multiple files, but I want to run the prereq and cleanup only once through out the run, please let me know is there a way to do it? A: py.test -> session scoped fixtures and their finalization should help you You can use conftest.py to code your fixture.
{ "language": "en", "url": "https://stackoverflow.com/questions/31251808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Elasticsearch Geo_point query not returning results I am trying to fetch all the documents within a radius of a particular location (lat,long). Here's the mapping with location as the geo_point: { "mappings": { "_doc": { "properties": { "color": { "type": "long" }, "createdTime": { "type": "date" }, "location": { "properties": { "lat": { "type": "float" }, "lon": { "type": "float" } } } } } } } And here's my query { "aggregations": { "weather_agg": { "geo_distance": { "field": "location", "origin": "41.12,-100.77", "unit": "km", "distance_type": "plane", "ranges": [ { "from": 0, "to": 100 } ] }, "aggregations": { "timerange": { "filter": { "range": { "createdTime": { "gte": "now-40h", "lte": "now" } } }, "aggregations": { "weather_stats": { "stats": { "field": "color" } } } } } } } } I am getting 0 hits for this. My question is whether there's something wrong with the mapping or the query ? We recently migrated to a newer cloud version and there's a possibility that something broke because of that. A: Instead of mapping lat and long as float you should geo-point mapping
{ "language": "en", "url": "https://stackoverflow.com/questions/74236396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deserialize from SqlXml to object I have an int value stored in SQL Server as xml type, which is SqlXml when retrieved in C# The value in database: <int>1234</int> How can I deserialize this value to an int with value 1234? A: Assuming the SqlXml object contains exactly what was mentioned in the question, you might want to use the following helper method. Should work for any type that has been serialized this way, even complex objects. static T GetValue<T>(SqlXml sqlXml) { T value; // using System.Xml; using (XmlReader xmlReader = sqlXml.CreateReader()) { // using System.Xml.Serialization; XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); value = (T) xmlSerializer.Deserialize(xmlReader); } return value; } Example case: using (MemoryStream stream = new MemoryStream()) using (XmlWriter writer = new XmlTextWriter(stream, Encoding.ASCII)) { writer.WriteRaw("<int>123</int>"); writer.Flush(); stream.Seek(0, SeekOrigin.Begin); using (XmlReader reader = new XmlTextReader(stream)) { SqlXml sqlXml = new SqlXml(reader); int value = GetValue<Int32>(sqlXml); Debug.Assert(123 == value); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/26054563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to improve the performance and customize the listview to avoid OMM error in Android I am absolute beginner to Android and now I start using volley HTTP library with Listview. So I created a test project and trying on volley and Android. I am creating a newfeeds viewing app. Example , facebook newfeeds. Data are just dummy for learning purpose. My project is working as I expected. It loads new data when the scoll reach at the bottom of the listview. But after it loads the data for multiple times frequently, my App is throwing out of memory error. My activity class public class VolleyActivity extends Activity{ private int defaultLastLoadedItem=0; private int lastSawFirstListItem; private int itemLoadedOn; private ArrayAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.volley_main); Button getBtn = (Button)findViewById(R.id.btn_get_request); getBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); ListView listView = (ListView)findViewById(R.id.volleyListView); adapter = new CustomAdapter(this,new ArrayList<Entity>()); listView.setAdapter(adapter); updateListView(); listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if(lastSawFirstListItem<firstVisibleItem) { int currentLastItem = firstVisibleItem+visibleItemCount; if(currentLastItem!=itemLoadedOn) { updateListView(); Toast.makeText(getBaseContext(),"More item loaded",Toast.LENGTH_SHORT).show(); itemLoadedOn = currentLastItem; } } lastSawFirstListItem = firstVisibleItem; } }); } public void updatedListView(int lastloadedItem) { defaultLastLoadedItem = lastloadedItem; //"http://api.androidhive.info/feed/feed.json"; String url = "http://192.168.43.82:8888/simple_json/index.json";//"http://api.androidhive.info/feed/feed.json"; JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { List<Entity> items = new ArrayList<Entity>(); try{ JSONArray jsonArray = jsonObject.getJSONArray("feed"); for(int i=0;i<jsonArray.length();i++) { JSONObject item = jsonArray.getJSONObject(i); Entity en = new Entity(); en.setId(item.getInt("id")); en.setName(item.getString("name")); en.setUrl(item.getString("url")); items.add(en); } adapter.addAll(items); } catch (JSONException e) { Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Toast.makeText(getBaseContext(),"Error listener",Toast.LENGTH_SHORT).show(); } }); Volley.newRequestQueue(getBaseContext()).add(jsonRequest); } public void updateListView() { updatedListView(defaultLastLoadedItem); } } What I want to know are: * *Will my application will throws that kind of error(omm) when it reaches to production ? *If it will does, how can I fix that issue ? *How should I customize listview for this kind of newfeeds app for better performance if my current code is not suitable? A: I think your http request getting called all time while you are scrolling you just have to add following code in your onScroll of setOnScrollListener final int lastItem = firstVisibleItem + visibleItemCount; if(lastItem == totalItemCount) { //your http request } I hope this will work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/34948064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: std::chrono::duration passed as a method parameter I have this method: string tpToString(const system_clock::time_point &tp) { string formatStr { "%Y-%m-%d %H:%M:%S" }; return date::format(formatStr, date::floor<microseconds>(tp) ); } This method produces a string such as: 2021-02-09 20:53:10.123456 That's great. It uses Howard Hinnant's date library. I just found myself hitting an instance where an API is returning an error if I offer a time out to microseconds. It wants milliseconds. So I can do that with a second method: string tpToStringInMillis(const system_clock::time_point &tp) { string formatStr { "%Y-%m-%d %H:%M:%S" }; return date::format(formatStr, date::floor<milliseconds>(tp) ); } That works. But what I'd prefer to do is pass (as an optional parameter) the duration, something like this: string tpToString(const system_clock::time_point &tp, chrono::duration dur = milliseconds) { string formatStr { "%Y-%m-%d %H:%M:%S" }; return date::format(formatStr, date::floor<dur>(tp) ); } However, this produces an error "no matching function for call to 'floor'". I'm actually surprised that it doesn't complain about the function definition, as milliseconds is a typedef. Suggestions? I suppose I could pass a lambda, but that's starting to get ugly. A: If you make tpToString a template you can allow the caller to choose the accuracy at compile time. template <typename FloorType = microseconds> string tpToString(const system_clock::time_point& tp) { string formatStr{ "%Y-%m-%d %H:%M:%S" }; return date::format(formatStr, date::floor<FloorType>(tp)); } int main() { std::cout << tpToString(system_clock::now()) << "\n"; std::cout << tpToString<milliseconds>(system_clock::now()) << "\n"; std::cout << tpToString<seconds>(system_clock::now()) << "\n"; std::cout << tpToString<minutes>(system_clock::now()) << "\n"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/66127149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iCal Eventstore - successful function on completion I have the following function to add a dynamic date to Ical - -(void)AddToIcal{ EKEventStore *store = [[EKEventStore alloc] init]; [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (!granted) { return; } EKEvent *event = [EKEvent eventWithEventStore:store]; event.title = self.booked.bookingTitle; event.startDate = self.booked.bookingDate; event.endDate = [event.startDate dateByAddingTimeInterval:60*60]; //set 1 hour meeting [event setCalendar:[store defaultCalendarForNewEvents]]; NSError *err = nil; [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err]; NSString *savedEventId = event.eventIdentifier; //this is so you can access this event later }]; } Does anyone know how I could show a stored / not stored message when the ad event function is complete? A: what about changing [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err]; to if (![store saveEvent:event span:EKSpanThisEvent commit:YES error:&err]) { NSLog([NSString stringWithFormat:@"Error saving event: %@", error.localizedDescription]); } else { NSLog(@"Successfully saved event."); } You could as well do something different than writing to NSLog, like use an UIAlertView or such. Also you may have a look a the Return Value section of the saveEvent:span:commit:error Apple documentation. It says: Return Value If successful, YES; otherwise, NO. Also returns NO if event does not need to be saved because it has not been modified.
{ "language": "en", "url": "https://stackoverflow.com/questions/20053026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual Studio never hits break point in Controller Action In troubleshooting AddTagsCollection Action behavior in a controller, I have a strange scenario which I have not encountered before, its not even a multi threaded section. The Visual Studio Debugger enters the function till the first line string alert = ""; and even stops at the debugger but never goes on to the other lines!! public JsonResult AddTagsCollection(int collectionID, string Name, string Description, string Order, bool IsActive, bool RootUseOnly) { // Yes hits this break point only then bails out - whats going on?? string Alert = ""; // NEVER hits this break point if (ProfileTagCollection.GetByName(Name.Trim()).ProfileTagCollectionID > 0) Alert = "The collection \"" + Name + "\" already exists."; // NEVER hits this break point!!! var testme = "test"; // NEVER hits this break point - you get the idea, it just return back to the HTML view?? if (Name.Trim().ToLower().Length == 0) Alert = "The collection name should not be empty."; if (Alert != "") { RequestResultModel _model = new RequestResultModel(); _model.InfoType = RequestResultInfoType.ErrorOrDanger; _model.Alert = Alert; AuditEvent.AppEventWarning(Profile.Member.Email, Alert); return Json(new { NotifyType = NotifyType.DialogInline, Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model), }, JsonRequestBehavior.AllowGet); } ProfileProfileTagCollection ProfileTagCollection = new ProfileProfileTagCollection(); tagCollection.OrderID = 0; tagCollection.tagCollectionName = Name; tagCollection.tagCollectionDescription = Description; tagCollection.IsActive = IsActive ? 1 : 0; tagCollection.RootUseOnly = RootUseOnly ? 1 : 0; tagCollection.Save(); if (collectionID > 0) AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("The \"{0}\" profile collection has been updated.", Name)); else AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("The \"{0}\" profile collection has been added.",Name)); if (Order != "") { Order = Order.Replace("this", tagCollection.tagCollectionID.ToString()); ProfiletagCollections.UpdateOrder(Order); } // I have tried passing other combinations to reach here, but why does it not get here return Json(new { NotifyType = -1, Html = "", }, JsonRequestBehavior.AllowGet); } I also tried to lookup the debug windows module, in 2013 its not listed, has it moved... In debug mode, select debug->windows->modules (modules is missing for me) Can you help me with why the debugger does not hit the break point and what steps I can take to resolve or investigate this? A: I think you could use this You probably are after something like this: if(System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); Of course that will still get compiled in a Release build. If you want it to behave more like the Debug object where the code simply doesn't exist in a Release build, then you could do something like this: [Conditional("DEBUG")] void DebugBreak() { if(System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); } Then add a call to it in your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/29880375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FOSRestBundle parse headers I am using FOSRestBundle in order to implement an API. I would like to parse HTTP headers that are sent to me from the client. How can I access them ? A: You can get headers from Request object in your controller methods. use Symfony\Component\HttpFoundation\Request; public function someAction(Request $request){ $request->headers //get headers }
{ "language": "en", "url": "https://stackoverflow.com/questions/36007066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are sub-selects in a where-clauses executed multiple times or just once? I have a separate table (with no PK, only one row) to store the row count of a certain result. Now, this count is used in a query, like this (just an example): SELECT * FROM `car` WHERE `car`.`featured` = 1 AND ( SELECT `count` FROM `carfeaturedcounter` ) > 5; Will SELECT count FROM carfeaturedcounter be executed multiple times (once for every row), or only once per query? A: I think it depends on the version of MySQL. You might as well move the condition to the from clause, where it will only be executed once: SELECT c.* FROM car c.CROSS JOIN (SELECT `count` FROM carfeaturedcounter) x WHERE c.featured = 1 AND x.`count` > 5;
{ "language": "en", "url": "https://stackoverflow.com/questions/38350726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can no longer get response from web request when 400 returned I am having trouble making web service calls in an iOS application built with Xamarin. This EXACT same code, that builds a request and uses HTTPWebRequest GetResponse() to get the response, used to work but now it is crashing when trying to get the response. It crashes on ReadToEnd, saying that the argument cannot be null. This code has remained unchanged since it worked. I know that there IS a response with the 400 because PostMan works and I can also see a log from the backend when I'm making the call from my Xamarin app. Searching stackoverflow is revealing that some people have resolved this issue by upgrading Xamarin and that it has something to do with the mono runtime it uses. But the latest version of Xamarin is doing the same thing for me. ... } catch(WebException ex) { try { if(ex.Response == null || ex.Status != WebExceptionStatus.ProtocolError) throw; ... Stream data = ex.Response.GetResponseStream(); if(data==null) return "ERR"; StreamReader reader = new StreamReader(data); if(reader==null) return "ERR"; string responseFromServer = reader.ReadToEnd(); Expected results should be that my GetResponse does generate a WebException in the event of an HTTP 400, however there should still be a response body to read. Here is a stacktrace of the exception: 2019-04-02 09:15:17.367099-0400 ******.iOS[41201:4512789] *****> System.Net.WebException: Value cannot be null. Parameter name: src ---> System.ArgumentNullException: Value cannot be null. Parameter name: src at System.Buffer.BlockCopy (System.Array src, System.Int32 srcOffset, System.Array dst, System.Int32 dstOffset, System.Int32 count) [0x00003] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/corlib/ReferenceSources/Buffer.cs:39 at System.Net.WebResponseStream+<ProcessRead>d__49.MoveNext () [0x00082] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/System/System.Net/WebResponseStream.cs:203 --- End of inner exception stack trace --- at System.Net.HttpWebRequest+<RunWithTimeoutWorker>d__241`1[T].MoveNext () [0x000e8] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/System/System.Net/HttpWebRequest.cs:956 --- End of stack trace from previous location where exception was thrown --- at System.Net.WebConnectionStream.Read (System.Byte[] buffer, System.Int32 offset, System.Int32 count) [0x00070] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/System/System.Net/WebConnectionStream.cs:136 at System.IO.Stream.ReadByte () [0x00007] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/io/stream.cs:758 at *****.API.callService (System.String endpt, System.String parm, System.Boolean isGet) [0x003e9] in /Users/****/Projects/*****/*****/API.cs:80
{ "language": "en", "url": "https://stackoverflow.com/questions/55463460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ion-footer not showing when ion-content contains elements The ion-footer is not showing when my ion-content has elements In this code the footer doesn't appear : <ion-content> <div class="text-center"> <p class="text-gray-800 text-3xl font-bold m-0">{{user.name}}</p> <p class="text-gray-400 mt-2">{{user['custom:role']}}</p> </div> <ion-button expand="block" color="primary">logout</ion-button> </ion-content> <ion-footer> <ion-toolbar> <ion-title>Footer</ion-title> </ion-toolbar> </ion-footer> And that works : <ion-content> <ion-button expand="block" color="primary" (click)="cognito.logout()">logout</ion-button> </ion-content> <ion-footer> <ion-toolbar> <ion-title>Footer</ion-title> </ion-toolbar> </ion-footer> I have tried to remove div and p tags using ion-text or to remove the button and keep only the p / ion-text But I cannot make the footer show up with content (except the ion-button) in my ion-content. I for the moment use some css, without ion-footer. I'd rather find a non-hacky solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/69826899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to improve performance using multithreading in spring Mvc I am using spring MVC model in my project. In which controller get request from some some thired party application. Controller get 20 request per sec. Code look like this @Controller @RequestMapping("/action") public class FrontController{ @AutoWired private CommonService commonService; (First Code) @RequestMappint("/save") public String saveData(@PathParam("id")String did){ List<String, Object> map = commonService.getVmn(did); CallReporting callReporting = new CallReporting(); callReporting.setName(map.get("name")); so---on (have 15 field) commonService.save(callReporting); } return "1"; } This code is working fine but some time if mysql is busy then it takes time to return the value to calling application. So I droped the idea and start Async communication. (Second Code) @RequestMappint("/save") public String saveData(@PathParam("id")String did){ Thread thread = new Thread(new Runnable(){ List<String, Object> map = commonService.getVmn(did); CallReporting callReporting = new CallReporting(); callReporting.setName(map.get("name")); so---on (have 15 field) commonService.save(callReporting); }); } return "1"; } I started using the code something like this. So that calling party can get the response immediately(reduce the response time) and later on my application continue to work. But in First code i test the load with JMeter(20 req/sec ) and found it is working fine with cpu load(3%). But in second code with same load cpu load is going to more than 100%.Than i started using the ThreadPoolTaskExecutor with below configuration. @AutoWired private ThreadPoolTaskExecutor executor; @RequestMappint("/save") public String saveData(@PathParam("id")String did){ //Assume this code is in MyRunnableWorker Class List<String, Object> map = commonService.getVmn(did); CallReporting callReporting = new CallReporting(); callReporting.setName(map.get("name")); so---on (have 15 field) commonService.save(callReporting); MyRunnableWorker worker = new MyRunnableWorker(); executor.execute(worker) return "1"; } <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="50" /> <property name="maxPoolSize" value="100" /> <property name="keep-alive" value="10" /> <property name="queueCapacity" value="200" /> </bean> but found the same result. Whats wrong with code can somebody suggest me. One important thing when i test with Jmeter in stage envorment then load is moving between 30% to 70%.. But in production server it is always around 100%. It is java consuming 100% other process is quite low. Production machine haveing linux OS. hexacore processer having 128 GB RAM. Can some one tell me what to do. A: Your ThreadPoolTaskExecutor has too many threads. CPU spend lot of time to switch context between threds. On test you run just your controller so there are no other threads (calls) that exist on production. Core problem is waiting for DB, because it is blocking thread Solutions * *set pool size smaller (make some experiment) *remove executor and use actor system like Akka for save operation. *Most important use batch to save objects in DB. There will be only one call per e.g. 1000 objects not 1k calls for 1k objects > JPA/Hibernate improve batch insert performance A: It looks like you are turning the wrong knob. In your first version you had up to N threads banging your database. With N being configured somewhere in your servlet container. And also doing the servlet thingy, accepting connections and stuff. Now you created 200 additional threads, which do basically nothing but hitting the database. While the previous threads do their connection handling, request parsing thing. So you increased the load on the database and you added the load do to context switching (except when you have multiple hundred cores). And for some weird reason, your database didn't get any faster. In order to improve, reduce the number of threads in your thread pool which hits the database. Measure how many threads the database can handle before performance degrades. Make the queueCapacity large enough to cover the request spikes you need to handle. Implement something that gets a meaningfull answer to the user when this isn't sufficient. Something like "Sorry ..." And then take care of the real issue: How to make your database handle the requests fast enough. It might be that some db tuning is in place, or you need to switch to a different database system, or maybe the implementation of the save method needs some tuning ... But all this is for a different question. A: the bottle neck in your case are transactions (DB) here's some proposals : * *if it's not necessary that data has to be instantly saved just use an asynchronous job to do it (JMS, In Memory Queue, etc) *You may consider to load DB into RAM
{ "language": "en", "url": "https://stackoverflow.com/questions/27549156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to extend validation of a subitem of my viewmodel? My model class Animal implements INotifyDataErrorInfo to add validation. My view is bound to a viewmodel with a property SelectedAnimal of type Animal like that: View <TextBox Text="{Binding SelectedAnimal.Epc, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" /> ViewModel public Animal SelectedAnimal { get { return _animal; } set { Set(() => Animal, ref _animal, value); } } Error visualization works fine: Question I want to add additional validation, of the field EPC that is done in my viewmodel not in the Animal class. So I want to add another validation rule (e.g. check if EPC is unique), that is visualized with the EPC TextBox. How can I achieve this? Validation errors of that viewmodel rule should also be shown on the EPC TextBox. I tried manipulating the list of validation errors of class Animal without success. Additional info validation based on class ValidatableModel A: This is one way to solve your problem: * *Wrap the property whose validation you want to extend in your viewmodel public string Epc { get { return _epc; } set { Animal.Epc = value; Set(() => Epc, ref _epc, value, false); } } *Add two custom validation rules to that property [CustomValidation(typeof(ViewModel), "AnimalEpcValidate")] [CustomValidation(typeof(ViewModel), "ExtendedEpcValidate")] *Add your extended validation code, that is not done by Animal itself, to ExtendedEpcValidate *Call the Animal.Epc validation and add the results to the Epc validation results in your viewmodel public static ValidationResult AnimalEpcValidate(object obj, ValidationContext context) { var aevm = context.ObjectInstance as ViewModel; // get errors from Animal validation var animalErrors = aevm.Animal.GetErrors("Epc")?.Cast<string>(); // add errors from Animal validation to your Epc validation results var error = animalErrors?.Aggregate(string.Empty, (current, animalError) => current + animalError); // return aggregated errors of Epc property return string.IsNullOrEmpty(error) ? ValidationResult.Success : new ValidationResult(error, new List<string> { "Epc" }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/39659965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sending POJO containing XML Document via Spring MVC i try to post a POJO from one Spring Boot&MVC app to another. This all works fine except for one case, in which the POJO contains a w3c.dom.Document XML attribute. The POJO is quite simple, all getters and setters are managed by project lombok: @Data public class SmartContractFile { private final UUID id; private Document file; private int copies; public SmartContractFile(UUID id, Document scFile, int copies) { this.id = id; this.file = scFile; this.copies = copies; } } The POSTing happens via Spring RestTemplate and contains only the POJO. I expect a simple true or false response. public boolean saveFile(SmartContractFile smartContract) { RestTemplate template = new RestTemplate(); URI methodURI; try { methodURI = new URI(this.address + DNWebConstants.REST_ADDSC); ResponseEntity<Boolean> response = template.postForEntity(methodURI, smartContract, Boolean.class); return (response.hasBody() && response.getBody()); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } The server-side webservice is bound via @RequestMapping and a constant to the target address. I already tried @PostMapping, but the behavior did not change. The POJO should be extracted by Spring via @RequestBody. @RequestMapping(DNWebConstants.REST_ADDSC) public ResponseEntity<Boolean> addSmartContract(@RequestBody SmartContractFile smartContract) { try { smartContractHandler.validateScDocument(smartContract.getFile()); } catch (ContractException | IOException e) { e.printStackTrace(); return ResponseEntity.badRequest().body(false); } if (this.thisNode.saveRequestedScStorage(smartContract)) return ResponseEntity.ok(true); else System.out.println("Wrong storage location."); return ResponseEntity.badRequest().body(false); } In case of any error in my application, i would always expect a 400 bad request with "false" in the response body, as well as an output on the servers console (either via printStackTrace() or System.out.println()). However, all i get is a 400 with empty body: org.springframework.web.client.HttpClientErrorException: 400 null at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:766) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:724) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:698) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:484) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at model.Node.saveFile(Node.java:80) ~[classes/:na] at model.Topology.saveFile(Topology.java:50) ~[classes/:na] at mgmt.web.DNWebservice.saveSmartContract(DNWebservice.java:111) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.32.jar:8.5.32] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_201] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_201] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32] at java.lang.Thread.run(Thread.java:748) [na:1.8.0_201] With this being my application: at model.Node.saveFile(Node.java:80) ~[classes/:na] at model.Topology.saveFile(Topology.java:50) ~[classes/:na] at mgmt.web.DNWebservice.saveSmartContract(DNWebservice.java:111) ~[classes/:na] Where model.Node.saveFile(Node.java:80) is the client method shown above. I basically tried every way i know to pack that request and switched wildly through al Spring Annotations, but nothing worked. So i hope there's somebody here to help me. Thanks in advance! A: I now found my error, it had nothing to do with the resttemplate. The bootstrap had an error which caused the app to send the request to itself. The client denied its' own request and Spring did all the errorhandling automatically, so it did not show in the console output as logged by my application, which is why i overlooked it. After fixing this, the request in the OP worked just fine. Sorry.
{ "language": "en", "url": "https://stackoverflow.com/questions/56292986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use debugger in android or Java? I am trying to create a simple android application. This is the first time I am coding for android and Java. I have installed android sdk on win 7 machine. I have never used a debugger. I want a resource to learn use of debugger in android from basic. If it is same as Java, Kindly provide me a link to learn java debugger from basic. Thanks in advance. A: I hope you are using eclipse to develop an Android app. If not the please do that. Here is a information to debug an Android app. A: Have you tried just playing around with the Eclipse debugger? Try: * *Click on the left-hand margin next to code you want to investigate, setting a "breakpoint" *Click on the bug icon to run your application in Debug mode. *When your application arrives at that line of code, Eclipse will pop up a dialog confirming a change to the debug perspective. *Play with the step-next/step-out buttons in the debugger.
{ "language": "en", "url": "https://stackoverflow.com/questions/5202235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to make first dropdown not render in reactjs and ant design I need to make my current draggable component's dropdown to not render on specific cell (specifically the first Row). However, it will still show the cell just without the dropdown. I tried to search for a way however could not find any. Appreciate any help / directions given. Thanks! I also also attached the screenshot of current and expected. (Just take note of the dropdown being empty) *Current Interface - all dropdown rendered *Expected New Interface - first dropdown not rendered Main code with ant design component Row/Col and Select/Option for the dropdown: render() { return ( <div> <Table scroll={{ x: 300 }} pagination={{ defaultPageSize: 10, showSizeChanger: true, pageSizeOptions: ['10', '25', '50'], }} columns={this.state.columns} dataSource={this.state.datas} ></Table> <Modal destroyOnClose={true} width={'80%'} title='Approval Sequence' visible={this.state.isVisible} onOk={() => { updateFlowType(this.state.currentItem.id, { name: this.state.currentItem.name, sites: this.state.initTags.map((x) => ({ idSite: x.id, returnToStep: x.returnToStep, })), }) .then((r) => { notification['sucess']({ message: 'Success', description: 'Save data success', }); this.setState({ isVisible: false }); this.getData(); }) .catch(() => { notification['failed']({ message: 'Failed', description: 'Failed to save', }); }); }} onCancel={() => { this.setState({ isVisible: false }); }} > <Row gutter={[2, 2]}> <Col style={{ textAlign: 'center' }} span={8}> <Text strong>Role</Text> </Col> <Col style={{ textAlign: 'center' }} span={8}> <Text strong> Return to Department: </Text> </Col> </Row> <div className='list-area'> <div className='drag-list'> <DraggableArea onChange={(initTags) => this.setState({ initTags })} isList tags={this.state.initTags} render={({ tag }) => ( <Row> <Col span={8}> <Button style={{ width: '100%' }}>{tag.name}</Button> </Col> <Col span={16}> <Select onChange={(e) => { //create clone let clone = [...this.state.initTags]; let item = clone.find((x) => x.id === tag.id); let itemReject = clone.find((x) => x.name === e); console.log('itemReject', itemReject); //create returnToStep in item item.returnToStep = itemReject.id; this.setState({ initTags: clone, }); }} //placeholder = 'Select return step' style={{ width: '100%' }} > {this.getReject(tag.name).map((newTag) => ( //getReject function will slice to get only items before the current iteration object (e.g. if current is index 3, only get index 0~2) <Option key={newTag.name} value={newTag.name}> {newTag.name} </Option> ))} </Select> </Col> </Row> )} ></DraggableArea> </div> </div> </Modal> </div> ); } A: You can do "conditional render" using a condition and a component like this: const someBoolean = true; retrun ( { someBoolean && <SomeComponent /> } ) if someBoolean is true, then <SomeComponent/> will show. if someBoolean is false, then <SomeComponent/> will not show. So, just use that to conditionally render your dropdown column or any other component. If, the table rows are based upon content and dynamically rendered, then I would modify the content accordingly. (i.e. don't provide the rows you don't want to render).
{ "language": "en", "url": "https://stackoverflow.com/questions/73396859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't pass array value into Invoke-RestMethod URL String I have the below code snippet that saves a array of ~90 devices to my string $report $report = Get-ADComputer -Filter * -SearchBase 'OU=Boston, DC=someCompany, DC=com' | Select -ExpandProperty name Now my issue is when I try to pass this array to my Invoke-RestMethod command $headers=@{} $headers.Add("Content-Type", "application/json") $headers.Add("Authorization", "Bearer mykeyhere") $response = Invoke-RestMethod -Uri "https://app.ninjarmm.com/v2/devices/search?q=$report[0]" -Method GET -Headers $headers When I run the above code snippet, I would think that $response returns the result of my first array of $report, but what actually happens is that it returns back $response in the attached photo. Help appreciated, thanks yall
{ "language": "en", "url": "https://stackoverflow.com/questions/73130193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which algorithm should be used to find the point? You need to find some unknown, predetermined point in three-dimensional space, in the smallest number of attempts, using only a function that can return the distance from any point you pass to it to the desired unknown point. To solve the problem, first implement a function f that, by taking the coordinates of any point s(x, y, z), return the distance between that point and a conditionally unknown, randomly generated point point you arbitrarily generate r(x, y, z), where x, y, z can be integers between 0 и 100. For example, for an arbitrarily generated point r(0, 0, 10) and a point passed to the function s(0, 0, 0), the result of the function would be as follows: f(s) = 10 // the distance between s(0, 0, 0) and r(0, 0, 10) is 10 Next, implement the algorithm itself for the assignment. The algorithm should find the coordinates of of an arbitrarily generated point with the least number of calls to the function f. I have a randomizer instead of an algorithm, that's all I got. Help. const pointToFound = { x: 12, y: 9, z: 76, }; let attemts = 0; let isXFound = false; let isYFound = false; let isZFound = false; const pointHistory = []; const getRandomPoint = () => { return { x: isXFound ? isXFound : Math.floor(Math.random() * 101), y: isYFound ? isYFound : Math.floor(Math.random() * 101), z: isZFound ? isZFound : Math.floor(Math.random() * 101), }; }; const getDifference = (point, pointToCompare) => { return { x: Math.max(point.x, pointToCompare.x) - Math.min(point.x, pointToCompare.x), y: Math.max(point.y, pointToCompare.y) - Math.min(point.y, pointToCompare.y), z: Math.max(point.z, pointToCompare.z) - Math.min(point.z, pointToCompare.z), }; }; const condition = !isXFound && !isYFound && !isZFound; while (condition) { const point = getRandomPoint(); const difference = getDifference(point, pointToFound); pointHistory.push(point); attemts += 1; if (isXFound && isYFound && isZFound) { console.log("Total attempts: ", attemts); console.log(point); break; } if (difference.x === 0 && !isXFound) { isXFound = point.x; } if (difference.y === 0 && !isYFound) { isYFound = point.y; } if (difference.z === 0 && !isZFound) { isZFound = point.z; } } console.log(pointHistory); I have a randomizer instead of an algorithm, that's all I got. Help. A: One idea is as follows: You pick an initial random point, and for each dimension, find the exact value. How? For the sake of symmetry, suppose that you desire to find x of the target point. Increase by one the x, and compute the distance of the new point from the target point. If it goes further, it means that you should move in the opposite direction. Hence, you can run a binary search and get the distance to find the exact x of the target point. Otherwise, it means that you are going in the right direction along X-axis. So, do a binary search between all points with the same y and z such that their x values can change from x+1 to 100. A more formal solution comes in the following (just a pseudo-code). You should also ask about the complexity of this solution. As the dimension of the point is constant (3) and checking these conditions take a constant time, the complexity of number of calling getDifference function is O(log(n)). What is n here? the length of valid range for coordinates (here is 100). 1. p: (x,y,z) <- Pick a random coordinate 2. dist: (dist_x, dist_y, dist_z) <- getDifference(p, TargetPoint) 3. For each dimension, do the following (i can be 0 (x), 1 (y), 2 (3)): 4. if(dist == 0): 5. isFound[i] <- p[i] 6. continue 7. new_i <- p[i] + 1 8. new_point <- p 9. new_point[i] <- new_i 10. new_dist <- getDifference(new_point, pointToFound) 11. if(new_dist == 0): 12. isFound[i] <- new_point[i]; 13. continue 14. if(new_dist[i] > dist[i]): 15. isFound[i] <- binary_search for range [0, p[i]-1] to find the exact value of the pointToFound in dimension i 15. continue 16. else: 17. isFound[i] <- binary_search for range [p[i] + 1, 100] to find the exact value of the pointToFound in dimension i 18. continue A: Following method will work for coordinates with positive or negative real values as well. Let's say you are searching for the coordinates of point P. As the first query point, use origin O. Let the distance to the origin O be |PO|. At this point, you know that P is on the surface of sphere (P.x)^2 + (P.y)^2 + (P.z)^2 = |PO|^2 (1) As the second query point, use Q = (|PO|, 0, 0). Not likely but if you find the distance |PQ| zero, Q is the point you are looking for. Otherwise, you get another sphere equation, and you know that P is on the surface of this sphere as well: (P.x - |PO|)^2 + (P.y)^2 + (P.z)^2 = |PQ|^2 (2) Now, if you subtract (1) from (2), you get (P.x - |PO|)^2 - (P.x)^2 = |PQ|^2 - |PO|^2 (3) Since the only unknown in this equation is P.x you can get its value: P.x = (((-|PQ|^2 + |PO|^2) / |PO|) + |PO|)/2) Following similar steps, you can get P.y with R = (0, |PO|, 0) and P.z with S = (0, 0, |PO|). So, by using four query points O, Q, R, and S you can get the coordinates of P. A: This can be done with at most 3 guesses and often with 2 guesses: * *Let the first guess be [0, 0, 0], and ask for the distance *Find in the 100x100x100 cube all points that have that distance to [0, 0, 0]. There might be around 100-200 points that have that distance: consider all of these candidates. *Take the first candidate as the second guess and ask for the distance *Find among the other candidates the ones that have exactly that distance to the first candidate. Often there will be only one point that satisfies this condition. In that case we can return that candidate and only 2 guesses were necessary. *Otherwise (when there is more than one candidate remaining) repeat the previous step which will now certainly lead to a single point. Here is an implementation that provides a blackbox function which chooses the secret point in a local variable, and which returns two functions: f for the caller to submit a guess, and report for the caller to verify the result of the algorithm and report on the number of guesses. This is not part of the algorithm itself, which is provided in the findPoint function. const rnd = () => Math.floor(Math.random() * 101); const distance = (a, b) => a.reduce((acc, x, i) => acc + (x - b[i]) ** 2, 0) ** 0.5; function findPoint(f) { // First guess is always the zero-point let guess = [0, 0, 0]; let dist = f(guess); if (dist === 0) return guess; // Extremely lucky! // Find the points in the cube that have this distance to [0,0,0] let candidates = []; const limit = Math.min(100, Math.round(dist)); for (let x = 0; x <= limit; x++) { const p = [x, limit, 0]; // Follow circle in X=x plane while (p[1] >= 0 && p[2] <= limit) { const d = distance(p, guess); const diff = d - dist; if (Math.abs(diff) < 1e-7) candidates.push([...p]); if (diff >= 0) p[1]--; else p[2]++; } } // As long there are multiple candidates, continue with a guess while (candidates.length > 1) { const candidates2 = []; // These guesses are taking the first candidate as guess guess = candidates[0]; dist = f(guess); if (dist === 0) return guess; // lucky! for (const p of candidates) { let d = distance(p, guess); let diff = d - dist; if (Math.abs(diff) < 1e-7) candidates2.push(p); } candidates = candidates2; } return candidates[0]; // Don't call f as we are sure! } function blackbox() { const secret = [rnd(), rnd(), rnd()]; console.log("Secret", JSON.stringify(secret)); let guessCount = 0; const f = guess => { guessCount++; const dist = distance(secret, guess); console.log("Submitted guess " + JSON.stringify(guess) + " is at distance " + dist); return dist; }; const report = (result) => { console.log("Number of guesses: " + guessCount); console.log("The provided result is " + (distance(secret, result) ? "not" : "") + "correct"); } return {f, report}; } // Example run const {f, report} = blackbox(); const result = findPoint(f); console.log("Algorithm says the secret point is: " + JSON.stringify(result)); report(result); Each run will generate a new secret point. When running this thousands of times it turns out that there is 1/9 probability that the algorithm needs a third guess. In the other 8/9 cases, the algorithm needs two guesses.
{ "language": "en", "url": "https://stackoverflow.com/questions/74815070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Search for sentence that may containing different words in Python In python, I have a string sentence as follows: Change setting to value 50. I essentially want to search for the sentence in a list of strings and extract the "setting" and "50" values, as they may be different. I'm not terribly great with regular expressions, so any help would be greatly appreciated. A: Try this: "Change (.*?) to value (.*?)\." https://regex101.com/r/gG5sK3/2 Where the first and the second group are your desired values!
{ "language": "en", "url": "https://stackoverflow.com/questions/33466181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Decimal arithmetic in shell shows as command not found My intention is to reduce or increase brightness levels using code The following is my code BRIGHTNESS=`xrandr --verbose | grep -m 1 -i brightness | cut -f2 -d ' '` z=$($BRIGHTNESS-0.1) echo "$z" I get the error adjust_brightness.sh: line 4: 1.0-0.1: command not found A: $(...) is a command substitution. Command substitution executes the commands inside it. Here it tries to execute 1.0-0.1 as a command. The $((...)) does arithmetic expansion, note the double braces. While the following will trigger arithmetic expansion: z=$(($brightness-0.1)) No, shell does not support floating point arithmetic, only whole numbers. Research other questions on this site how to do floating point arithmetic in shell. Because arithmetic expansion expands also variables, you can remove the $ from inside. For example pipe the string to be calculated to bc (<<< is a here string): z=$(bc <<<"$brightness - 0.1") Notes: * *And while were at it, do not use backticks `...` at all. Use $(...) instead. brightness=$(xrandr --verbose | grep -m 1 -i brightness | cut -f2 -d ' ') *UPPER CASE VARIABLES are by convention reserved for exported variables, like IFS, LINES, COLUMNS etc. Use lower case variables in your scripts.
{ "language": "en", "url": "https://stackoverflow.com/questions/62086496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is there a way to check if the email and password edit text are filled before excecuting the login button intent? I am new to android. i have created a login page with email and password editTexts and a login button. how can i check if the email and password is filled before executing the login button intent? and how is the login button conditional intent declared? here is my xml code <EditText android:id="@+id/emailEt" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:ems="10" android:hint="@string/emailEt" android:inputType="textEmailAddress" android:paddingStart="8dp" android:paddingEnd="8dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.025" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="parent" /> <EditText android:id="@+id/passwordEt" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:ems="10" android:hint="@string/passwordEt" android:inputType="textPassword" android:paddingStart="8dp" android:paddingEnd="8dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="@+id/parent" app:layout_constraintTop_toBottomOf="@+id/parent" /> <Button android:id="@+id/loginBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="24dp" android:text="@string/loginBtn" android:textAllCaps="false" android:textSize="15sp" android:onClick="login" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/passwordEt" /> </androidx.constraintlayout.widget.ConstraintLayout> A: Yes, there are lot of ways that this can be handled. A simple google search could have helped you out. The most simple way is to set OnClickListener() for the Login Button. The listener method will be called when the button is clicked. Inside the method, you can check if the Edittext field is empty using the TextUtils.isEmpty("TEXT INSIDE EDITEXT") method. The text inside the edit text can be read using the getText() method. Please have a look at the below code for reference. public OnClickListener onLoginClick = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText emailField = (EditText)layout.findViewById(R.id. emailEt); String email = emailField.getText().toString() if(TextUtils.isEmpty(email)) { // Show error here } else { // Do the necessary action here. } } }; Similarly, add a check for the password field. In the XML file, set the listener to the Login button like this. android:onClick="onLoginClick" A: yourEditext.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //Here you can store email into variable before clicking button // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); A: Yes you can user myEditText.addTextChangedListener() when user is Typing you will get the the email and password emailEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //Here you can store email into variable before clicking button // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } });
{ "language": "en", "url": "https://stackoverflow.com/questions/60388637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query Builder with join and condition in Many to many relation I have a many to many relation with Employee and MembreFamille. And i want to get all MembreFamilles that have an Employee. This is my query : class MembreFamilleRepository extends EntityRepository { public function getMembres($emp) { $qb = $this->createQueryBuilder('a'); $qb ->leftJoin('a.employees', 'employees'); $qb ->where('employees.id = :id') ->setParameter('id', $emp); return $qb ->getQuery() ->getResult() ; } } When I test this function in the controller , the function return 0 result. The mapping in Employee Entity: /** * @ORM\ManyToMany(targetEntity="PFE\EmployeesBundle\Entity\MembreFamille", cascade={"persist"}) */ private $membreFamilles; The Mapping in MembreFamille Entity : /** * @ORM\ManyToMany(targetEntity="PFE\UserBundle\Entity\Employee", cascade={"persist"}) */ private $employees; The use in the Controller ($employee is an instance of Employee Entity ) : $list = $em->getRepository('PFEEmployeesBundle:MembreFamille')->getMembres($employee->getId()); A: You can use a construction called "MEMBER OF". class MembreFamilleRepository extends EntityRepository { public function getMembres($emp) { return $this->createQueryBuilder('a'); ->where(':employee MEMBER OF a.employees') ->setParameter('employee', $emp) ->getQuery() ->getResult() ; } } You can use a construction called "MEMBER OF" A: You need to add a JoinTable for your ManyToMany association and set the owning and inverse sides: /** * @ORM\ManyToMany(targetEntity="PFE\EmployeesBundle\Entity\MembreFamille", * cascade={"persist"}, mapped="employees") */ private $membreFamilles; ................................. /** * @ORM\ManyToMany(targetEntity="PFE\UserBundle\Entity\Employee", cascade={"persist"}, inversedBy="membreFamilles") * @ORM\JoinTable(name="membre_familles_employees") */ private $employees;
{ "language": "en", "url": "https://stackoverflow.com/questions/30461865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert "Select" in dropdown with LInq I have loaded the drop down box from LINQ, CustomerDataContext customer = new CustomerDataContext(); ddlCust.DataSource = from cust in customerDC.Customers orderby cust.CustId ascending select new {cust.CustId, cust.CustName} ; ddlCust.DataTextField = "CustName"; ddlCust.DataValueField = "CustId"; ddlCust.DataBind(); it is working fine but I want item of drop down list as : Text: Select Value: 0 How can I do that? A: .... .... ddlCust.DataBind(); ddlCust.Items.Insert(0, new ListItem("Select Value:", "0"));
{ "language": "en", "url": "https://stackoverflow.com/questions/4786758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to match dataframe by match column I'm new to pandas. I'm trying to join two datasets as below: df1: df1 = pd.DataFrame({'id': [1121, 1122, 1123, 1124, 1125], 'name': ['F.01', 'F.01', 'F.02', 'F.02', 'F.02'], 'description': ['r1', 'r2', 'l1', 'l2', 'l3']}) Looks like: id name description 1121 F.01 r1 1122 F.01 r2 1123 F.02 l1 1124 F.02 l2 1125 F.02 l3 df2: df2 = pd.DataFrame({'code': ['F.01', 'F.02'], 'r1': [1, 0], 'r2': [2, 0], 'l1': [0, 3], 'l2': [0, 4], 'l3': [0, 5]}) df2 looks like: code r1 r2 l1 l2 l3 F.01 1 2 0 0 0 F.02 0 0 3 4 5 The result I would like them match by df1.name = df2.code df1.description = df2.(column name) The result I prefer is like: id name description value 1121 F.01 r1 1 1122 F.01 r2 2 1123 F.02 l1 3 1124 F.02 l2 4 1125 F.02 l3 5 Thanks! A: The general guidance by Henry is right, but it lacks some necessary details. To get your expected result the following steps are required: * *rename code in df2 to name, *melt df2 on name, setting var_name to description, *merge df1 with the above melt result on name and description. The code to do it is: result = pd.merge(df1, df2.rename(columns={'code': 'name'}).melt( 'name', var_name='description'), on=['name', 'description']) The result is: id name description value 0 1121 F.01 r1 1 1 1122 F.01 r2 2 2 1123 F.02 l1 3 3 1124 F.02 l2 4 4 1125 F.02 l3 5
{ "language": "en", "url": "https://stackoverflow.com/questions/64736389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WordPress permalinks rewrite on iis7 I spend a lot of time in looking for solution, so you are my last hope before giving up :) On my localhost iis7 i set custom permalinks http://sitename/%sample-post%/ with rewrite mode installed. <configuration> <system.webServer> <defaultDocument> <files> <add value="index.php"/> </files> </defaultDocument> <rewrite> <rules> <rule name="WordPress: http://tip4u03" patternSyntax="Wildcard"> <match url="*"/> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/> </conditions> <action type="Rewrite" url="index.php"/> </rule></rules> </rewrite> </system.webServer> </configuration> Its work only in wwwroot directory. Outside of wwwroot directory, its return 404 template page. Same issue on my shared iis7 server (VPS) A: I solved the issue !!! The problem was't with site location, it was because the permalinks are in Hebrew language. I added the following condition to wp-config file if (isset($_SERVER['UNENCODED_URL'])) { $_SERVER['REQUEST_URI'] = $_SERVER['UNENCODED_URL']; } according to this link: Wordpress Hebrew permalinks Finally its work !
{ "language": "en", "url": "https://stackoverflow.com/questions/43580324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mouse Down Event not firing (Bubbling events) I am a novice to WPF. I started learning about RoutedEvents in WPF. I tried a sample and i met up with a problem <Grid Margin="5" Name="Grid" MouseDown="Window_MouseUp"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> </Grid.RowDefinitions> <Label BorderBrush="Black" BorderThickness="1" Grid.Row="0" Margin="5" Name="FancyLabel" MouseDown="Window_MouseUp" > <StackPanel Name="Stack" MouseDown="Window_MouseUp"> <TextBlock Margin="3" Name="txtBlock1"> Click Any Where </TextBlock> <TextBlock Margin="50" Name="txtBlock2" > Click me also </TextBlock> </StackPanel> </Label> <ListBox Grid.Row="1" Margin="5" Name="ListMessages"/> <Button Grid.Row="3" Margin="5" Name="cmd_Clear" MouseDown="Cmd_Clear_MouseDown" >Clear</Button> </Grid> The handler for the mouseDown event of the button is different from others int the tree hierarchy. The event is not firing.. But if i add in the .cs file the following code Grid.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp),true); Stack.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true); FancyLabel.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true); txtBlock1.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true); txtBlock2.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true); Img1.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true); cmd_Clear.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Cmd_Clear_MouseDown), true); the Cmd_Clear_MouseDown event is fired and the event is bubbled up to the grid and the grid fires Window_MouseUp. A: Two points: 1) Is MouseDown="Window_MouseUp" everywhere intended? 2) Why not register to Click event with ClickMode="Press" instead of MouseDown. I don't think Button provides/raises MouseDown unless may be with a custom template. Example: <Button Grid.Row="3" Margin="5" Name="cmd_Clear" ClickMode="Press" Click="Cmd_Clear_MouseDown">Clear</Button>
{ "language": "en", "url": "https://stackoverflow.com/questions/4497105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Vertically bottom align a linear gradient I have made a jsfiddle = https://jsfiddle.net/wLomyf65/ HTML: <div class="skeleton-6euk0cm7tfi"></div> CSS: .skeleton-6euk0cm7tfi:empty {height: 100px; background-color: #ffffff; border-radius: 0px 0px 0px 0px; background-image: linear-gradient( #676b6f 6px, transparent 0 );background-repeat: repeat-y;background-size: 88px 100px;background-position: left 0px bottom 0px;} I wish to vertically bottom align the linear gradient (so that its in the bottom left corner). I have used: background-position: left 0px bottom 0px; but this hasn't done it. A: A slight problem with the way you are setting things up is that the height of the element itself and the height of the background image (before you have sized it) are the same, and its drawing the gray for 6px from the top (the default direction for a linear-gradient) and the rest is transparent. This snippet slightly simplifies what is going on. It 'draws'a background image in the gray color, setting its width to 88% and its height to 6px and its position to bottom left. It sets it to not repeat on either axis. body { background: red; } .skeleton-6euk0cm7tfi:empty { height: 100px; background-color: #ffffff; border-radius: 0px 0px 0px 0px; background-image: linear-gradient( #676b6f, #676b6f); background-repeat: no-repeat; background-size: 88px 6px; background-position: left bottom; } < <div class="skeleton-6euk0cm7tfi"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/75024168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: MYSQL - MAX() returns wrong date I have a mysql table like this +----------+----------+-------------------+ | entrykey | user_key | validfrom | +----------+----------+-------------------+ | 1 | 3 | 2016-4-1 0:0:0.0 | | 2 | 3 | 2016-12-1 0:0:0.0 | | 3 | 2 | 2016-12-1 0:0:0.0 | | 4 | 2 | 2016-3-1 0:0:0.0 | +----------+----------+-------------------+ now I am trying to get only the row for each user where the validfrom is the newest. So I am doing a query like this: SELECT entrykey, user_key, max(validfrom) FROM table Group by user_key; It is working fine for almost all of my data, just this two examples I posted here in the table select the wrong row which is older. So for user_key 3 it selects entrykey 1 and for the user_key 2 it selects entrykey 4. What am I doing wrong? A: I guess the validform should be 2016-03-01 instead of 2016-3-01 because it is not converted into date before compare. A: I am totally agree with the point made in the accepted answer (+1 for that). But, even if op somehow convert validfrom from string to DateTime, his attempt won't give him the desired result. Let's examine the query given in question: SELECT entrykey, user_key, MAX(STR_TO_DATE(validfrom, '%Y-%c-%e')) as date1 FROM table Group by user_key; Now, this query will return user_key with maximum value of validfrom for that particular user_key. But the entrykey won't be the entrykey with max validfrom. (Check the first result in demo link) In order to achieve above task, following query will work just fine! SELECT t1.entrykey, t1.user_key, t2.maxdate as MaxDate FROM t t1 inner join (select user_key,MAX(STR_TO_DATE(validfrom, '%Y-%c-%e')) as maxdate from t Group by user_key ) t2 on t1.user_key = t2.user_key and t1.validfrom = t2.maxdate; Click here for Demo with DateTime as datatype of validfrom Click here for Demo with STR_TO_DATE() function Hope it helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/46971081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: .htaccess Php rewrite url I try to realize a system of rewriting URLs in .htaccess. Then here is my goal: If I have an url of this form: http://localhost/view.php?Id=456 Then I want to transform it to: http://localhost/456 I use this rule in htaccess: RewriteRule ^ ([a-zA-Z0-9] +) $ view.php? Id = $ 1 Now this works very well! But my problem I want to add points to id ie instead of 456 I can put: my.book That is to say: http://localhost/my.book A: Try this: RewriteRule ^([a-zA-Z0-9\.]+)$ view.php?Id=$1 Basically what I did is I added \. with your pattern. This will make sure your regex matches any letter (small/caps), decimal numbers and periods (.). Hope this helps :) A: RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([a-zA-Z0-9\.]+)$ view.php?id=$1 [QSA,L] You need RewriteCond %{REQUEST_FILENAME} !-f before the RewriteRule line to tell the server that the RewriteRule written below to be executed if the input passed in the URL is not an actual file. Because server searches for a file matching the input you pass in the URL and also it won't work in case you pass my.book in the URL since web server recognizes . as prefix for extension like .php or .html or like so and thereby it results in Not Found error if there is no file named my.book exists. So, you also need to escape . in the URL. To allow .'s in the input, you need to add . with escape sequence \ in the character class group like ^([a-zA-Z0-9\.]+)$. Note, allowing this can result in escaping the extension in the URL, that is, passing view.php in the URL won't navigate to the actual file. Rather, it will be considered as a value in the query string.
{ "language": "en", "url": "https://stackoverflow.com/questions/41252108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google code downloading source This might be an extremely stupid question, but for the life of me, I cannot figure out how to download this: http://code.google.com/p/xmppframework/source/browse/#hg%253Fstate%253Dclosed There is nothing under the "downloads" tab. And when I try to "clone" it using my terminal it says "HG command not found". Any ideas?? A: hg is the executable for Mercurial, you're going to need to download and install Mercurial. Once you have it installed you can use it to clone the project: hg clone https://xmppframework.googlecode.com/hg/ xmppframework
{ "language": "en", "url": "https://stackoverflow.com/questions/6132255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How To classify Read and Unread news in Feed Reader? I am working on a RSS Feed module in WPF Application. I am getting news items in xml document from the httpWebResponse. I want to calssify the unread feeds. How can we identify the user read or Unread the news article ? A: It depends on how the web pages linked by RSS feed are opened. If they are opened within your app using a WebBrowser control, then you must track history of read feeds yourself within your app. See WPF WebBrowser Recent Pages. You can use the Navigated event of the WebBrowser control. If they are opened using a particular web browser, then you can eventually read somehow the history of that particular browser. But when the history gets deleted, your read/unread status gets deleted as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/26210308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to invert the green channel of an image in Python? How do I invert one channel of an RGB image? In this case my image is a normal map for a 3D engine, saved in an image format like JPEG or TIFF, and I want to invert the green channel — that is, completely reverse the highs and lows in the green band. A: You can accomplish this by installing and using Pillow, which can work with most image formats (JPEG, PNG, TIFF, etc.). from PIL import Image from PIL.ImageChops import invert image = Image.open('test.tif') red, green, blue = image.split() image_with_inverted_green = Image.merge('RGB', (red, invert(green), blue)) image_with_inverted_green.save('test_inverted_green.tif') After loading the image from your file, split into its channels with Image.split, invert the green channel/image with ImageChops.invert, and then join it together with the original red and blue bands into a new image with Image.merge. If using a format that's encoded in something other than RGB (such as PNG, which has an additional transparency channel), the image-opening line can be amended to: image = Image.open('test.png').convert('RGB') Testing with this image: Produces this: (ImageChops, by the way, looks like a very odd term, but it's short for "image channel operations".) A: I assume you have a numpy (or torch tensor) image - you can index on the green channel (assuming channels are your last dimension) img[:, :, 1] = 255 - img[:, :, 1] I am assuming by invert you want 0 -> 255 and 255 -> 0 A: T(r) = L – 1 – r L=256 L-1=255(Max) r=Each pixel of the image s=255-r s= T(r) =255-r
{ "language": "en", "url": "https://stackoverflow.com/questions/59293800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP is ignoring code like var_dump(), die(), etc This is a very weird situation like I've never seen in my life. For some reason PHP is ignoring a lot of code inside a static function. Here is the example: static function describe($tableName, $columns = '*') { var_dump($tableName); die(); $md5 = ...code... if (!empty($content = Cache::get($md5))) { return unserialize($content); } I keep getting the error Parse error: syntax error, unexpected '=', expecting ')' in if (!empty($content = Cache::get($md5))) { And yes it recognises the class Cache and its function. Can anyone guide me? A: Prior to PHP 5.5, empty() function can only support strings. Any other input provided to it like: a function call e.g. if (empty(myfunction()) { // ... } would result parse error. As per documentation: Note: Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false. Better way, get your $content variable first and then check if it is not empty. Rather than initialising it and checking its emptiness simultaneously. You can separate the if statement in two parts like this: if ($content = Cache::get($md5) && !empty($content)) { return unserialize($content); } A: Try this, if (!empty($content) && $content = Cache::get($md5)) { return unserialize($content); } OR : To get easy readability if (!empty($content){ if($content = Cache::get($md5)){ return unserialize($content); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/55724495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using graphql-codegen adds query to query? I'm trying to use graphql-codegen to add types to my graphql queries I have this in my package.json "@graphql-codegen/add": "^3.1.0", "@graphql-codegen/cli": "^2.3.0", "@graphql-codegen/typescript-operations": "^2.2.1", "@graphql-codegen/typescript-react-apollo": "^3.2.2", I have a codegen.yml overwrite: true schema: http://localhost:3000/api/graphql documents: 'queries/*.ts' generates: generated/index.tsx: config: reactApolloVersion: 3 withHooks: false plugins: - "typescript" - "typescript-operations" - "typescript-react-apollo" I'm using keystonejs which has a graphql api My query is like export const ALL_PRODUCTS_QUERY = gql` query ALL_PRODUCTS_QUERY{ allProducts{ id price description name photo{ id image{ publicUrlTransformed } } } } ` And in my package.json I have "codegen": "graphql-codegen --config codegen.yml" If I run yarn codegen I get the types generated in generated/index.tsx For ALL_PRODUCTS_QUERY I get export type All_Products_QueryQuery = { __typename?: 'Query', allProducts?: Array<{ __typename?: 'Product', id: string, price?: number | null | undefined, description?: string | null | undefined, name?: string | null | undefined, photo?: { __typename?: 'ProductImage', id: string, image?: { __typename?: 'CloudinaryImage_File', publicUrlTransformed?: string | null | undefined } | null | undefined } | null | undefined } | null | undefined> | null | undefined }; Why does the Query get added to the name so its now All_Products_QueryQuery and why is it not an interface I thought it would be an interface to describe the query
{ "language": "en", "url": "https://stackoverflow.com/questions/70460600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Auto Align of button Hi On our website I have a page where there are Buy Now buttons https://www.nutricentre.com/m-300-herbs-hands-healing.aspx The styling that controls this is .item .price { color:#8c9c54; font-size:14px; font-weight: bold; /* position: absolute; bottom: 48px; left: 0px; width: 150px; */ text-align: center; margin-bottom: 45px; } .item a.blue_btn { position: absolute; bottom: 10px; left: 15px; cursor: pointer; } Any idea how I can get this aligned in a straight line regardless of the text above? A: You don't have to change the css of the button, but from the whole item: just add: .item{ height: 380px; } Of course, you have to care about the maximum item-height: your value must not be less, or the price won't be visible anymore. In this case, min-height would be the better alternative. A: I would recommend setting a min-height: 370px; for the easiest solution. You do not want to set a static height for this because if you have an item with a longer description it will not automatically add space but just cram everything in. A: Add a static height to .item height:375px; The height:auto; declaration tells .item to expand as big as it needs to be to fit everything in, so the tops of the divs line up, but since they are different heights, the bottoms are staggered. As some of my co-responders have noted, min-height is also an acceptable option, until you have an item with enough text that item expands past the min-height value, at which point they will begin to expand and stagger again. A: This should point you in the right direction: http://jsfiddle.net/v9grm/ Create a grid and with the help of display: table make the columns the same height. Then place the button at the bottom of the column with position: absolute.
{ "language": "en", "url": "https://stackoverflow.com/questions/21338306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Autorotate not working after reload view controller I'm trying to make an iPhone app, but i found some issue that auto-rotate is not working after I reload the view controller. here is the code for loading the app for first run: //AppDelegate.m:<br /> -(BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { iPhoneScanViewController = [[iPhoneScan alloc] init]; iPhoneScanViewController.ENAD = self; [window addSubview:iPhoneScanViewController.view]; [self.window makeKeyAndVisible]; [[UIApplication sharedApplication] setStatusBarHidden:YES]; } the view controller loads, autorotate is working. then sometimes I need to reload the view controller, this is what I use: -(void) resetIphoneScan { if (iPhoneScanViewController) { [iPhoneScanViewController release]; } iPhoneScanViewController = [[iPhoneScan alloc] init]; iPhoneScanViewController.ENAD = self; for (UIView *view in [window subviews]) { [view removeFromSuperview]; } [window addSubview:iPhoneScanViewController.view]; [self.window makeKeyAndVisible]; } After I reload / resetIphoneScan, the autorotate won't work. I've spend a few days on this problem and I haven't found solution for that. I really appreciate any help. Thanks in advance. A: I would suggest that rather than reload the entire root VC, you have separate data classes which you can reset as necessary - after all, the VC is really for displaying it all.
{ "language": "en", "url": "https://stackoverflow.com/questions/10138412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ExtJS: Ext.Window Prototypal inherited objects cannot be destroy [ExtJS 3.4.0] I have a class with prototypal intheritance to Ext.Window, something like this: function Cls_MyWindow() { ..... var SaveButton = new Ext.Button({...}); var CancelButton= new Ext.Button({...}); ..... Cls_MyWindow.prototype.width = Ext.getBody().getWidth() - 800; Cls_MyWindow.prototype.height = Ext.getBody().getHeight() - 350; Cls_MyWindow.prototype.plain = true; Cls_MyWindow.prototype.buttons = [SaveButton, CancelButton]; ..... } Cls_MyWindow.prototype = new Ext.Window; Cls_MyWindow.prototype.constructor = Ext.Window; When this window is shown, it can be closed by pressing the CancelButton or the built-in "x" button of Ext.Window. When I close it with CancelButton, SaveButton and CancelButton get destroyed normally. But, if is closed by the "x" button, the buttons cannot be destroyed, the loop is taking forever causing my application to crashed. After some investigation I found, in ext-all-debug.js, this: Ext.Panel = Ext.extend(Ext.Container, { ..... if(Ext.isArray(this.buttons)){ while(this.buttons.length) { Ext.destroy(this.buttons[0]); } } ..... } which invoke Ext.destroy, this: Ext.apply(Ext, function(){ ..... destroy : function(){ Ext.each(arguments, function(arg){ if(arg){ if(Ext.isArray(arg)){ this.destroy.apply(this, arg); }else if(typeof arg.destroy == 'function'){ arg.destroy(); }else if(arg.dom){ arg.remove(); } } }, this); }, ..... }()); What appears to be is that, this.buttons -from pressing CancelButton- are Ext.Component thus, it get destroyed normally. While this.buttons -from pressing "x"- are not, which leads to the questions. * *Why this.buttons are not the same objects when it is destroy via different way? *What are the solution/options I have, if I want/need to retain the inheritance? Shedding me some lights is most appreciated. Thank you in advance. A: If we stay within Ext 3.4.0 boundaries, not reaching back to the plain javascript then you haven't done inheritance correctly. Inheritance is already implemented in Ext, so you do not need to go down to prototypes, creating constructors as instances of parent classes, and so on. Let's suppose you want to define MyWindow class inheriting from Ext.Window: Ext.define('MyWindow',{ extend:'Ext.Window' ,method:function(){/* some stuff */} ,closable:false // don't create close box ,closeAction:'hide' // etc }); To create an instance: var win = Ext.create('MyWindow', { width:800 ,height:600 }); win.show(); For more info see Ext.define docs. A: After days, I've found an answered from Inheritance using prototype / “new”. The code around my first code block at the bottom part is where I got it wrong. Cls_MyWindow.prototype = new Ext.Window; Cls_MyWindow.prototype.constructor = Ext.Window; The "new" at "new Ext.Window" operator there is my mistake. * *Why this.buttons are not the same objects when it is destroy via different way? Answer: Because of the new operator, when I created a new instance of Cls_MyWindow total of 2 constructors get called: one of the Cls_MyWindow, another of Ext.Window. Which then cause them to have "their own prototype of buttons" where SaveButton and CancelButton available in Cls_MyWindow as Ext.Button objects and in Ext.Window as a plain Object Closing Cls_MyWindow with CancelButton -> The buttons can be destroyed in Ext.Window.destroy's way. Closing it with "x" -> The buttons cannot be destroyed. Solution: I change my code to //Cls_MyWindow.prototype = new Ext.Window; the old one Cls_MyWindow.prototype = Ext.Window.prototype; Cls_MyWindow.prototype.constructor = Ext.Window; and everything works perfectly
{ "language": "en", "url": "https://stackoverflow.com/questions/23824144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: denormalizing JSON with jq I have JSON that looks like this: [ { "fields": { "versions": [ { "id": "36143", "name": "ST card" }, { "id": "36144", "description": "Acceptance test card", "name": "AT card" } ], "severity": { "value": "B-Serious", "id": "14231" } } }, { "fields": { "versions": [ { "id": "36145", "name": "ST card" } ], "severity": { "value": "C-Limited", "id": "14235" } } } ] I want to convert it with jq to this: [ { "id": "36143", "name": "ST card" "value": "B-Serious" }, { "id": "36144", "name": "AT card" "value": "B-Serious" }, { "id": "36145", "name": "ST card" "value": "C-Limited" } ] Note that the first object has 2 versions, and the same severity. I have tried jq's group_by and map functions but haven't been too successful. Please help :) A: This should work. You wouldn't want to use a group_by here, you would do that if you were trying to go from more to less, we're going the other way. You're combining the different versions with the corresponding severity. Here's how you could do that. map(.fields | (.versions[] | { id, name }) + { value: .severity.value })
{ "language": "en", "url": "https://stackoverflow.com/questions/33148557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to test basic example of async function in useEffect I have a simple component, it fetches async list of posts. export const Posts = () => { const [list, dispatch] = useReducer(listReducer, []); useEffect(() => { fetchList(dispatch); }, []); return ( <ul> {list.map((el) => ( <li key={el.id}>{el.title}</li> ))} </ul> ); }; In other file i keep the logic: export const fetchList = async (dispatch) => { try { const result = await api.get('/list/') /* AXIOS */ dispatch({ type: LIST_SUCCES, payload: result.data.list }) } catch (error) { dispatch({ type: LIST_FAILURE }) } } export const listReducer = (state, action) => { switch (action.type) { case LIST_SUCCES: return action.payload case LIST_FAILURE: return [] default: throw new Error() } } I've tried multiple libraries but i'm just unable to write a test. How can i write Posts.test.js to check if post are fetched and displayed, i'm triggering async fetchList after first mount of the component (so it is not componentDidMount), and after data are fetched i dispatch action from that async function and update the list. A: Here is the unit test solution: index.tsx: import React, { useReducer, useEffect } from 'react'; import { listReducer, fetchList } from './reducer'; export const Posts = () => { const [list, dispatch] = useReducer(listReducer, []); useEffect(() => { fetchList(dispatch); }, []); return ( <ul> {list.map((el) => ( <li key={el.id}>{el.title}</li> ))} </ul> ); }; reducer.ts: import axios from 'axios'; const LIST_SUCCES = 'LIST_SUCCES'; const LIST_FAILURE = 'LIST_FAILURE'; export const fetchList = async (dispatch) => { try { const result = await axios.get('/list/'); /* AXIOS */ dispatch({ type: LIST_SUCCES, payload: result.data.list }); } catch (error) { dispatch({ type: LIST_FAILURE }); } }; export const listReducer = (state, action) => { switch (action.type) { case LIST_SUCCES: return action.payload; case LIST_FAILURE: return []; default: throw new Error(); } }; index.spec.tsx: import React from 'react'; import { Posts } from './'; import { mount } from 'enzyme'; import axios from 'axios'; import { act } from 'react-dom/test-utils'; describe('Posts', () => { afterAll(() => { jest.restoreAllMocks(); }); it('should render list correctly', async () => { const mResponse = { data: { list: [{ id: 1, title: 'jest' }] } }; jest.spyOn(axios, 'get').mockResolvedValueOnce(mResponse); const wrapper = mount(<Posts></Posts>); expect(wrapper.find('ul').children()).toHaveLength(0); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); wrapper.update(); expect(wrapper.find('ul').children()).toHaveLength(1); expect(wrapper).toMatchInlineSnapshot(` <Component> <ul> <li key="1" > jest </li> </ul> </Component> `); }); it('should render empty list when request list data failed', async () => { const mError = new Error('Internal server error'); jest.spyOn(axios, 'get').mockRejectedValueOnce(mError); const wrapper = mount(<Posts></Posts>); expect(wrapper.find('ul').children()).toHaveLength(0); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); wrapper.update(); expect(wrapper.find('ul').children()).toHaveLength(0); expect(wrapper).toMatchInlineSnapshot(` <Component> <ul /> </Component> `); }); }); Unit test result with coverage report: PASS src/stackoverflow/59197574/index.spec.tsx (12.494s) Posts ✓ should render list correctly (105ms) ✓ should render empty list when request list data failed (37ms) › 1 snapshot written. ------------|----------|----------|----------|----------|-------------------| File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s | ------------|----------|----------|----------|----------|-------------------| All files | 95.83 | 66.67 | 100 | 95 | | index.tsx | 100 | 100 | 100 | 100 | | reducer.ts | 92.86 | 66.67 | 100 | 91.67 | 21 | ------------|----------|----------|----------|----------|-------------------| Snapshot Summary › 1 snapshot written from 1 test suite. Test Suites: 1 passed, 1 total Tests: 2 passed, 2 total Snapshots: 1 written, 1 passed, 2 total Time: 14.409s Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59197574
{ "language": "en", "url": "https://stackoverflow.com/questions/59197574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle Performance: Partition Split vs Insert Append I am currently refactoring a data loading process in Oracle 12c and am exploring partitioning as a solution. My data is categorised by date and I have ~500k records per date which seems to fit the "minimum optimal" for partitioning, or so I am told. The original plan was to use a staging table to load the data, then add a dummy partition to the main table and perform a partition exchange. However, my data load contains data from several days rather than from one day. Preliminary research suggests there are two methods to solve this problem: Option 1: Perform the partition exchange, then split the large partition in a loop ALTER TABLE MAIN_TABLE ADD PARTITION DUMMY_PARTITION VALUES LESS THAN (TO_DATE('1-1-9999', 'DD-MM-YYYY')); ALTER TABLE MAIN_TABLE EXCHANGE PARTITION DUMMY_PARTITION WITH TABLE STAGING_TABLE WITHOUT VALIDATION UPDATE GLOBAL INDEXES; BEGIN FOR row IN (select distinct to_char(DATE_FIELD+1, 'YYYYMMDD') DATE_FIELD from PARTITIONED_TABLE order by DATE_FIELD) LOOP EXECUTE IMMEDIATE 'ALTER TABLE MAIN_TABLE SPLIT PARTITION DUMMY_PARTITION AT (TO_DATE('''||row.DATE_FIELD||''', ''YYYYMMDD'')) INTO (PARTITION p'||row.DATE_FIELD||', PARTITION DUMMY_PARTITION) UPDATE GLOBAL INDEXES'; END LOOP; END; / Option 2: Perform an insert append INSERT /*+ append */ INTO MAIN_TABLE SELECT * FROM STAGING_TABLE; Somehow, it seems like splitting the partition is a slower process than doing the insert. Is this expected behaviour or am I missing something? A: There is a fast split optimization, depending on the circumstances. However from your description, I would simply do the INSERT /+* APPEND */ You may want to employ some parallelism too, if you have the resources and you are looking to speed up the inserts.
{ "language": "en", "url": "https://stackoverflow.com/questions/39360982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails and state_machine gem, when before_transition fails, transition to an error state I am using the state_machine gem to track the status of an object. I have a before_transition process to run and if that has any errors, I would like to set the object's state to "errored" so it is no longer an active object and I am notified that something went wrong. Below is a simplified code snippet to demonstrate what I am trying to do: class Status < ActiveRecord::Base state_machine :initial => :pending do state :pending state :processed state :errored event :process do transition :pending => :processed end event :error do transition all => :errored end before_transition :on => :process, :do => :processing_task after_failure :on => :process, :do => :log_error end def processing_task puts "Processing Task Started" ...do some processing... false #to force the before_transition task to fail end def log_error puts "Error detected, logging results" #LogUtility to store error error end end When I run status.process I receive the following: BEGIN Processing Task Started Error detected, logging results UPDATE SQL COMMAND, state = 'errored' ROLLBACK I tried to disable transactions state_machine :initial => :pending, :use_transactions => false' but that didn't make a difference. I feel like I should be able to transition an errored state when detecting an error during a before_transition process?? UPDATE I tried to do something like this: def custom_process begin process! rescue => e puts e #debugging purposes #log error error #transition to error state end end Then i can call object.custom_process and this accomplishes my goal but I'm creating my own transition outside the state machine, which feels a little weird to me. If this is the only way, I can implement it like this but was hoping to keep everything inside the state machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/41877514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating dynamic order basket using php javascript I am creating an ePos system, that adds any item user clicks to the basket and calculate the total in the end all done without total page refresh. I tried using $_SESSION and storing as order ( [item] => [price] ) but failed, as i need to refresh. what I need is: * *to display added Items [id name Qnty price] *calculate total price of added items. please advice me on the best method to do this. thanks this is what I attempter in javascript function addItem(name, price, id) { var table=document.getElementById("basket"); var row=table.insertRow(-1); var cell1=row.insertCell(0); var cell2=row.insertCell(1); var cell3=row.insertCell(2); cell1.innerHTML=name; cell2.innerHTML=1; cell3.innerHTML=price; } but my issue was, i could not find a way to add decimals, parseFloat made alot of bugs for me A: You should not need to refresh the page in order to save information into the PHP Session object. PHP Session information is stored on the server, so you can do an asynchronous HTTP request to the backend, and store information the PHP Session. I would suggest using the jQuery.ajax function (http://api.jquery.com/jQuery.ajax/) to do your async HTTP requests. If you are not familiar with jQuery, I highly suggest you get familiar with it. I also suggest you look into how AJAX works. Also, if you are using the PHP session, if you are not using some kind of framework which does session management, you must make sure to call session_start() before using the $_SESSION variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/15328076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using readAllBytes to read a file's bytes, but output is not changing when I change the file If I have a directory called "files" and I have 2 txt files in there. The files have different names, but have the same exact contents. With this code, I am not getting the same byte[] when I readAllBytes. Should I be getting the same output when I print bytes? If not, what method could I use to compare byte strands in this way? I am trying to do this: if I have 2 files with content in common but not all the same, in this case, should I have commonalities in the two byte strands also? What method would accomplish this? public class Main { public static final File CWD = new File(System.getProperty("user.dir")); public static final File files = new File(CWD, "files"); public static void main(String[] args) { for (File file: files.listFiles()){ try { byte[] bytes = Files.readAllBytes(file.toPath()); System.out.println(bytes); System.out.println(file.toString()); } catch (IOException e){ System.out.println("File is empty"); } } } } A: You are trying to print byte[] as a String which uses String.valueOf(bytes) and appears as something like: [B@23ab930d which is [B followed by the hashcode of the array. Hence different byte arrays have different string values. Compare these: byte[]a=new byte[]{65}; System.out.println(new String(a)); => A System.out.println(a); // Prints something like: [B@6438a396 Change to print the byte array contents converted as a String: System.out.println(new String(bytes)); OR: read the text file as a String directly: String contents = Files.readString(file.toPath()); System.out.println(contents);
{ "language": "en", "url": "https://stackoverflow.com/questions/66990927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error inserting date and time in SQL Server 2005 datetime c#? Problem saving to SQL Server 2005: cmd = new SqlCommand("INSERT into survey_Request1(sur_no,sur_custname,sur_address,sur_emp,sur_date,sur_time,Sur_status)values(" + "'" + textBox9.Text + "'" + "," + "'" + textBox8.Text + "'" + "," + "'" + textBox5.Text + "'" + "," + "'" + textBox1.Text + "'" + "," + "Convert(Datetime,Convert(char(15),"+"'" + dateTimePicker2.Value +"'"+")" + "," + "'" + dateTimePicker1.Value.ToLongTimeString() + "'" + "," + "'" + "Active" + "'" + ")", conn); cmd.ExecuteNonQuery(); A: You should ALWAYS use parametrized queries - this prevents SQL injection attacks, is better for performance, and avoids unnecessary conversions of data to strings just to insert it into the database. Try somethnig like this: // define your INSERT query as string *WITH PARAMETERS* string insertStmt = "INSERT into survey_Request1(sur_no, sur_custname, sur_address, sur_emp, sur_date, sur_time, Sur_status) VALUES(@Surname, @SurCustName, @SurAddress, @SurEmp, @SurDate, @SurTime, @SurStatus)"; // put your connection and command into "using" blocks using(SqlConnection conn = new SqlConnection("-your-connection-string-here-")) using(SqlCommand cmd = new SqlCommand(insertStmt, conn)) { // define parameters and supply values cmd.Parameters.AddWithValue("@Surname", textBox9.Text.Trim()); cmd.Parameters.AddWithValue("@SurCustName", textBox8.Text.Trim()); cmd.Parameters.AddWithValue("@SurAddress", textBox5.Text.Trim()); cmd.Parameters.AddWithValue("@SurEmp", textBox1.Text.Trim()); cmd.Parameters.AddWithValue("@SurDate", dateTimePicker2.Value.Date); cmd.Parameters.AddWithValue("@SurTime", dateTimePicker2.Value.Time); cmd.Parameters.AddWithValue("@SurStatus", "Active"); // open connection, execute query, close connection again conn.Open(); int rowsAffected = cmd.ExecuteNonQuery(); conn.Close(); } It would also be advisable to name your textboxes with more expressive names. textbox9 doesn't really tell me which textbox that is - textboxSurname would be MUCH better!
{ "language": "en", "url": "https://stackoverflow.com/questions/16062696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Spring, Annotation for Creating Current Date in Hibernate? in my Spring Application using JPA Hibernate Annotions. In that mysql Database have table and one column called CreateDate This column value will be added when record is inserted. So is their any annotation for creating current Date and time? other wise in our Hibernate bean writing setter method in that add private Date currrent; public void setCurrent(Date current) { this.current = new Date(); } A: I think you're looking for this:- @Temporal(TemporalType.TIMESTAMP) @Column(name = "curr", length = 10) public Date getCurrrent() { return this.currrent; } A: What Jelies mentioned is the correct approach. You simply instantiate the date object with private Date currrent = new Date(); during object creation and then persist it. To add on to that, its not safe to use @Temporal(TemporalType.TIMESTAMP) for storing the date and time, if there is a chance of you comparing the field current with any java.util.Date objects as the saved field will be loaded as java.sql.Timestamp. The reason is mentioned here. Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds - the nanos - are separate. The Timestamp.equals(Object) method never returns true when passed a value of type java.util.Date because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method. Also, the hashcode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation. Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance. The work around is to use TypeDef. This post discusses about the issue and the workaround. The code used there will be good enough for you. A: I think the easiest way to achieve that is to initialize your field with the new Date(): private Date currrent = new Date(); IMHO, I don't recommend changing the behavior of the setter method, other developers will not expect that. If you want this field to be filled immediately before the entity is persisted/updated, you can define a method with @PrePersist or @PreUpdate JPA annotations to populate current property then.
{ "language": "en", "url": "https://stackoverflow.com/questions/16230753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I make my custom class compatible with For Each? Is it possible to make a custom container class implemented purely in VBScript (no COM objects) work with the For Each statement? If so, what methods must I expose? A: In short, no Why? To create an enumerable collection class to get something like Class CTest .... End Class Dim oTest, mElement Set oTest = New CTest .... For Each mElement In oTest .... Next the class MUST follow some rules. We will need the class to expose * *A public readonly property called Count *A public default method called Item *A public readonly property called _NewEnum, that should return an IUnknown interface to an object which implements the IEnumVARIANT interface and that must have the hidden attribute and a dispatch ID of -4 And from this list or requirements, VBScript does not include any way to indicate the dispatch ID or hidden attribute of a property. So, this can not be done The only way to enumerate over the elements stored in a container class is to have a property (or method) that returns * *an object that supports all the indicated requirements, usually the same object used to hold the elements (fast, but it will expose too much information) *an array (in VBScript arrays can be enumerated) holding references to each of the elements in the container (slow if the array needs to be generated on call, but does not return any non required information)
{ "language": "en", "url": "https://stackoverflow.com/questions/30175464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Contact us form: Mail not received I'm trying to create a contact us form with PHP. The problem is that, I'm not receiving the email in my account. When the submit button is clicked it takes me to the mail.php page where a "thank you" message is shown. The code is as shown below: <div class="container"> <div class="col-xs-offset-2 col-xs-10 col-sm-8"> <h2>Contact Us</h2> <form action="mail.php" method="POST" class="form-horizontal"> <div class="form-group"> <label class="control-label col-sm-2 col-xs-6" for="email">First Name:</label> <div class="col-sm-6 col-xs-6"> <input type="text" class="form-control" id="fname" placeholder="First Name*" name="fname" required="required"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">Last Name:</label> <div class="col-sm-6"> <input type="text" class="form-control" id="lname" placeholder="last Name" name="lname" > </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="email">Email ID:</label> <div class="col-sm-6"> <input type="text" class="form-control" id="email" placeholder="Email Address*" name="email" required="required"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="message">Message:</label> <div class="col-sm-6"> <textarea id="form_message" name="message" class="form-control" placeholder="Message*" rows="4" required="required" data-error="Please, leave us a message."></textarea> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> </div> The code for mail.php: <?php $firstname = $_POST['fname']; $lastname = $_POST['lname']; $email = $_POST['email']; $message = $_POST['message']; $formcontent="From: $fname $lname \n Message: $message"; $recipient = "[email protected]"; $subject = "Contact Form"; $mailheader = "From: $email \r\n"; mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); echo "Thank You!"; ?> A: Please try using SMTP ? PHPmailler.class Download : https://github.com/PHPMailer/PHPMailer
{ "language": "en", "url": "https://stackoverflow.com/questions/52135400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R: Removing Non-Corresponding Rows in Data Frames I have two data frames - germany_yields and italy_yields. If a specific date that appears in one of germany_yields's rows is not present in any of italy_yields's rows, then I would like to remove this row from germany_yields (and vice versa). For example, here are five rows taken from either of the frames: germany_yields: italy_yields: Date Yield Date Yield 642 Jan 06, 2008 4.087 642 Jan 06, 2008 4.461 643 Dec 30, 2007 4.193 643 Dec 30, 2007 4.522 644 Dec 23, 2007 4.368 644 Dec 16, 2007 4.563 645 Dec 16, 2007 4.268 645 Dec 09, 2007 4.601 646 Dec 09, 2007 4.304 646 Dec 02, 2007 4.420 647 Dec 02, 2007 4.105 647 Nov 25, 2007 4.439 The date Dec 23, 2007 is present within germany_yields (row 644), but not within italy_yields. I would therefore like to remove row 644 from germany_yields. How can I do this? For reference, here is the code I have so far: germany_yields <- read.csv(file = "Germany 10-Year Yield Weekly (2007-2020).csv") italy_yields <- read.csv(file = "Italy 10-Year Yield Weekly (2007-2020).csv") germany_yields <- germany_yields[, -(3:6)] italy_yields <- italy_yields[, -(3:6)] colnames(germany_yields)[1] <- "Date" colnames(germany_yields)[2] <- "Yield" colnames(italy_yields)[1] <- "Date" colnames(italy_yields)[2] <- "Yield" A: The easiest approach is to use %in%: germany_yields[germany_yields$Date %in% italy_yields$Date, ] A: We can also use dplyr library(dplyr) germany_yields %>% filter(Date %in% italy_yields$Date)
{ "language": "en", "url": "https://stackoverflow.com/questions/61429738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Workflow Lookup List view threshold Alert me I have a workflow from a Document Library that copy the file to another Document Library and then "Update Item in" on this other Document Library through lookup. However the workflow won't work because where the file is copied the Document Library has more than 5k files and the List View Threshold is setup for only 5k. I tried to create a specific field on both Document Library that the workflow could do the lookup, but I still get the same error. I was wondering how to make the workflow lookup on a different Document Library with exceeded list view threshold without changing the list view threshold limit. This is the erro that I get from the workflow status: "The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator." A: A better solution would be to parse out your document libraries so they aren't exceeding the list view threshold. Assuming you're running 2013 since you tagged it in your post, you could have the workflow do a REST API call to the destination library and check the item count. If it returns >5000, alert the document library manager to archive some old files - or save the file to an alternate library using an If/Then block. The SPD Workflow to do this: Build {...} Dictionary (Output to Variable: requestHeaders) then Call [site url]/_api/web/Lists/GetByTitle('[Library Name to Query]') HTTP web service with request (ResponseContent to Variable: responseContent|ResponseHeaders to Variable: responseHeaders|ResponseStatusCode to Variable: responseCode) then Get d/ItemCount from Variable: responseContent (Output to Variable: count) If Variable: count is less than 5000 [Proceed as normal] If Variable: count is greater than or equal to 5000 [Save to secondary library and notify admin to do some cleanup] (Here's some background on REST API if you haven't used it before)
{ "language": "en", "url": "https://stackoverflow.com/questions/34696606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Prevent centring on focused input in hidden overflow area It is hard to explain with words so here's a fiddle I made to explain the problem better: http://jsfiddle.net/j2zurbbv/1/. When the first timeout fires the container div is not 'scrolled' which is the behaviour I want. However when the input is outside of the visible part of the div (as it is with the second timeout) the container div centres about this input. Container css: #container { overflow: hidden; height: 200px; position: absolute; width: 200px; } For the record I have only tested this on Chrome 37.0 A: Managed to work it out. Counter the scrolling that the browser does by doing document.getElementById('container').scrollTop = 0; whenever you programatically focus on an element outside of the visible area of an overflow: hidden div AND whenever a user inputs in such an element. Demonstrative JSFiddle (without prevention of input scrolling) http://jsfiddle.net/j2zurbbv/2/.
{ "language": "en", "url": "https://stackoverflow.com/questions/25792441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Index page is not re rendering/refreshing on search in Rails I am making a simple search in rails on the index page. My problem is that on debug I get the correct results but they don't show on the frontend. def index if !params[:category].present? and !params[:title].present? @services = Service.take(4) else if params[:category] != "Find Service" and params[:title].present? @services = Service.where(category: params[:category], title: params[:title]).take(4) elsif params[:category] == "Find Service" and params[:title].present? @services = Service.where(title: params[:title]).take(4) elsif params[:category] != "Find Service" and !params[:title].present? @services = Service.where(category: params[:category]).take(4) else @services = Service.take(4) end end end My view index.html.erb <%= form_with(url: "services", method: "get") do |form| %> <div class="banner-input" style="margin-top"> <div class="listing-sort listing-sort--main-listing" style="width: 50%;float: left; border-radius: 6px; border: 2px solid white; background: transparent; padding: 0px;"> <input type="submit" value="" class="main-listing__form-field agent-submit" style="width: 10% ;float:right"> <%= form.text_field "title", id: "search_agent", class: "main-listing__form-field ", placeholder: "Search by Name or Location...", style: "width: 75% ;float:right; background: transparent; color: white!;" %> <div class="listing-sort__inner" style="float:left;margin: 0px; width: 25%; padding: 0px;"> <p class="listing-sort__sort"> <%= form.select("category",options_for_select(["Find Service", "Assembly", "Carpet Cleaning", "Electrical", "House Cleaning", "HVAC", "Handyman", "IT", "Junk Removal", "Lawn Care","Moving", "Painting", "Plumbing", "Staging", "Photography", "Videography", "Inspectors"], :selected => "Find Service"), {include_blank: false}, { :class => 'ht-field listing-sort__field' }) %> </p><!-- .listing-sort__sort --> </div><!-- .listing-sort__inner --> </div><!-- .listing-sort --> </div> <% end %> <section style="margin-top: 50px"> <h2 style="margin-left: 15px; padding-bottom: 30px; font-size: 24px;">Recently viewed & more</h2> <% @services.each do |service| %> <%= render 'services/service_card', :f => service %> <% end %> </section> <section class="jumbotron"style="margin-top: 50px"> <h2 style="margin-left: 15px; padding-bottom: 30px; font-size: 24px;">Pro SEM services </h2> <% @services.each do |service| %> <%= render 'services/service_card', :f => service %> <% end %> </section> This is _service_card <div class="col-xs-12 col-sm-6 col-md-6 col-lg-3" style="padding-bottom: 10px"> <div class="boxes"> <div class="box-img"> <img src="assets/MobileApps.png"> </div> <div class="user-detail-main"> <div class="user-detail-img"> <img src="assets/MobileApps.png"> </div> <div class="user-detail"> <a><h3><%= f.user.profile.first.first_name %></h3></a> <p>Level 1 Seller</p> </div> <div class="user-detail-para"> <% byebug %> <p><%= f.description %></p> </div> <div style="padding-top: 50px;"> <i class="fas fa-star" style="color: #ffbf00"></i> (5) </div> </div> <div class="user-detail-footer"> <div class="heart-icon"> <i class="fas fa-heart" style="color: #c6c6c6"></i> <i class="fas fa-bars" style="color: #c6c6c6"></i> </div> <div class="user-value"> <p>Starting At $ <%= f.packages.first.price%></p> </div> </div> </div> Please help me regarding this. Looking forward. It is working fine without search, but with search it doesn't update the results and show same results.
{ "language": "en", "url": "https://stackoverflow.com/questions/58852964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select statement over multiple columns I have an SQLite database with a table help with columns i_id, issue, url, steps, kw1, kw2, [...], kw12. kw1 - kw12 contain one word and can be null. When I do: sqlite> select issue,url,steps from help where kw1='adobe'; I get: blank popup|blankpopup.html|S missing pdfs|missingpdfs.html|S printall not populating|printall.html|A this is right. When I move to another keyword like 'ie' that is in multiple fields across kw1 - kw12, how do I do a select statement where instead of searching just kw1, it searches kw1 through to kw12? I know what fields 'ie' is in. I have an Excel sheet of how the database is built but the people using the database don't. A: If I understand right, you just need to use Or keyword and search thru all the kw-fields sqlite> select issue,url,steps from help where kw1='ie' or kw2='ie' or kw3='ie' or kw4='ie' or kw5='ie' or kw6='ie' or kw7='ie' or kw8='ie' or kw9='ie' or kw10='ie' or kw11='ie' or kw12='ie';
{ "language": "en", "url": "https://stackoverflow.com/questions/11743120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TortoiseHg - infinite cloning of repository I've encountered a quite troubling problem. I've tried to clone repository from the server and I was able to start cloning, but it never ends, and no files are being downloaded on my hard drive. I'm using pagaent with my private key. I've tried it on 3 different PC, and it didn't helped, but I know it is working because some people were able to clone this repository.
{ "language": "en", "url": "https://stackoverflow.com/questions/24292431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running a program in eclipse Each time I try to run a new program, an old program 'client.java' is run by eclipse. How do I change this setting? How do we tell eclipse which program to run? I tried using the arrow beside run button but it dosen't list out my new program. A: Right Click To the class -> Run As-> JAVA Application A: You can change the default behavior by going to Window > Preferences > Run/Debug > Launching and in the 'Launch Operation' section, select the radio button for Launch the selected resource or active editor and then select Launch the associated project underneath. A: Firs of all make sure that your program has a main class. Then click in the black button next to the run button -> Run As-> JAVA Application. If this doesn work make sure you have all this properly set up. Run Configurations
{ "language": "en", "url": "https://stackoverflow.com/questions/33266295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Matplotlib ticks sans-serif for all plots I'm trying to achieve sans-serif axes labels and ticks in matplotlib with pgf. I want to control that by rcParams so I have it working for all subsequent plots. Currently, I'm using "pgf.rcfonts":False, "pgf.texsystem": "pdflatex", "text.usetex": True, "font.family": "sans-serif", which I adapted from the mpl docs. It does set all my text in the figure to sans-serif. However, the numbers are kept with a serif font. I want them to be sans-serif. As soon as i force the formatter, its sans-serif. Any way to get it to do that automatically? MinEx follows... import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import FormatStrFormatter #define style style = { "pgf.rcfonts":False, "pgf.texsystem": "pdflatex", "text.usetex": True, "font.family": "sans-serif" } #set mpl.rcParams.update(style) #get data data = np.random.random(100) #set up plot f,ax = plt.subplots() ax.plot(data) #label something ax.set_xlabel('Runner') The label is sans now. The ticks are not! But when calling ax.xaxis.set_major_formatter(FormatStrFormatter('%d')) they are. A: According to the pgf texsystem example, you need to use the "pfg" backend (mpl.use("pgf")) and choose the font you want to use: style = { "pgf.texsystem": "pdflatex", "text.usetex": True, "pgf.preamble": [ r"\usepackage[utf8x]{inputenc}", r"\usepackage[T1]{fontenc}", r"\usepackage{cmbright}", ] } Alternatively you may use a formatter, which does not format the ticklabels as latex math (i.e. does not put them into dollar signs). One may adapt the default ScalarFormatter not to use latex math by setting ax.xaxis.get_major_formatter()._usetex = False ax.yaxis.get_major_formatter()._usetex = False A: The problem is LateX related. You just need to load the extra cmbright package that enable sans-serif math fonts. On Debian-like systems: sudo apt install texlive-fonts-extra On Fedora: sudo dnf install texlive-cmbright Then try your code with this style: style = { "text.usetex": True, "font.family": "sans-serif" "text.latex.preamble" : r"\usepackage{cmbright}" }
{ "language": "en", "url": "https://stackoverflow.com/questions/51405646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Creating network visualization dashboards I'm a Network Engineer, I want to create a custom data network visualization dashboard that includes interactive charts and graphs with drill down options and such. I'm a bit overwhelmed by the proliferation of languages and different ways of accomplishing this. What are some languages/libraries I should learn to accomplish this task, as well as good tutorials for your recommendations. I have intermediate coding experience. Thanks! A: I recommend using D3js, force directed graph is perfect for creating a network visualization, there are some examples here: D3 force directed graph
{ "language": "en", "url": "https://stackoverflow.com/questions/28174388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error using Reactive Maps with Google maps Javascript Api I am trying to build and app with ReactiveSearch and ReactiveMaps using some indexed files in Elasticsearch. The indexed files in Elasticsearch have a field "location", for example: "location": { "Lat": 56.746423, "Lon": 37.189268 } And other fields like "Title" or "Authors". I got a Google maps API key and in my App.js file I have these components: <DataSearch componentId="mainSearch" dataField={["Title", "Title.search", "Abstract", "Abstract.search"]} queryFormat="and" placeholder="Search for HEP" autosuggest={true} className="datasearch" innerClass={{ input: "searchbox", list: "suggestionlist" }} /> <ReactiveMap componentId="map" dataField="location" size={100} defaultZoom={13} defaultCenter={{ lat: 37.74, lng: -122.45 }} showMapStyles={true} defaultMapStyle="Standard" showMarkerClusters={true} showSearchAsMove={true} searchAsMove={true} react={{ and: "mainSearch" }} onData={result => ({ label: result.Title })} /> in the same file ("App.js") I have this lines : <ReactiveBase app="title" url=here_the_elasticsearch_cluster mapKey="here_my_googlemapsAPI_key" > Also in the file Public/index.html I have <script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3.34&key=MY_GOOGLE_MAPS_API_KEY&libraries=places" ></script> However, When I search for any documents in the mainBar I found it, but, when I click on it it doesnt appear in the map. What am I doing wrong? A: Finally I have solved it. ReactiveMaps does not allow the location field in uppercase, so I had to change the indexed documents in elasticsearch taking in account this. "location": { "lat": 56.746423, "lon": 37.189268 }
{ "language": "en", "url": "https://stackoverflow.com/questions/55445547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Creating an array from two data-* and one select array codeigniter I have a table with products where i can add rows dynamically and on each row i add it will be a select and an edit button. If i press this button,it will display a modal where i can modify 2 data-* of the select.The dependence(dep) and the category. After editing one select, i will have something like this: <select data-dep="1" data-category="3"></select> After submitting,in the model,i will get the products like this: $products = $this->input->post('products[]'); In this way, i will have an array with all the products i wanted to add to database.The question is, can i make an array with the id of the product(what i have now), the value from data-dep and the value from data-category?And if i can,how?Something like this: [1]--->product_id = 1,dep = 3, category = 2; [2]--->product_id = 2,dep = 1, category = 3; My HTML is this: <div class="form-group" id="container-div"> <table id="dynamic"> <tr id="row1"> <td> <select class="form-control select-table" name="products[]" id="select-1" data-dep="" data-category=""> <?php foreach($products as $product):?> <option value="<?php echo $product['products_id'];?>"><?php echo $product['product_name'];?></option> <?php endforeach;?> </select> <i id="1" data-toggle="modal" data-target="#editModal" class="fas fa-edit fa-lg edit-div"></i> <div id="plus-div"><span><i class="fas fa-plus fa-lg"></i></span></div> </td> </tr> </table> </div> <label>Pret:</label> <input type="number" name="price" class="form-control"/> <input type="submit" class="btn btn-primary" name="submit" value="Creaza meniul" style="margin-top: 5px;"/> </div> </div> <div class="modal" id="editModal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <select class="form-control dep-select" id="dep-test" name="dep-select"> <option class="form-group" value="1">Fara garnitura&salata</option> <option class="form-group" value="2">Fara salata</option> <option class="form-group" value="3">Fara garnitura</option> <option class="form-group" value="4">Cu de toate</option> </select> <select class="form-control category-select" name="category-select"> <option class="form-group" value="1">Fel Principal</option> <option class="form-group" value="2">Garnitura</option> <option class="form-group" value="3">Salata</option> <option class="form-group" value="4">Supa</option> <option class="form-group" value="5">Desert</option> </select> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" id="save" data-dismiss="modal">Salveaza</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Inchide</button> </div> </div> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/49778886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I get a Google Admin to Fix my Project Console? Short of paying $150/month so I can actually submit a ticket, what can I do to get Google's attention? I've seen other people get help for what appears to be the exact same issue. I uploaded a new (small) app to Google App Engine (GAE), and the Applications Settings page shows an error under Cloud Integration ("An error occurred when creating the project. Please retry"). I've retried over a period of days, but it tries for a while, then reports another failure. I've asked questions of StackOverflow, and in the GAE issues forum, to no response. A: Try to get hold of the people from Google Developer relations here, in the relevant Google+ communities or on Google groups. If it can bring you any comfort: paying the $150 does not help you much - we have the subscription. A: If you have a second Google Apps domain, replicate the issue by switching domains and recreating the project from scratch. Then if the error occurs again, post that it occurs in 2 or more cloud.google.com accounts with separate domains. This should help show this is not a one off error and requires investigation. If it does not occur in the second domain, save your data, delete your project and recreate with a different project name and number. -ExGenius
{ "language": "en", "url": "https://stackoverflow.com/questions/23392122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiply columns of different sheets in power BI I need to multiply the no.of grants into the expected attrition rate based on dates. In image 3 i have the rates and now for image 2, i need to multiply the rates in image based on the date. Im new to power bi and i'm not able to work it out.
{ "language": "en", "url": "https://stackoverflow.com/questions/69791684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: React Router: props aren't passed down when directly accessing the URL of child component. Will I need to use the same state in both parent and child? I'm pretty new to React and React Router so apologies if this is a silly question or answered elsewhere - I did a search but couldn't find a similar question. I'm using React Router v6 and React Hooks. My very basic full-stack app is focused on keeping track of musical artists and their released projects (albums, mixtapes, EPs, etc.). My App component will render the ProjectList component at the '/' route, and the ArtistList component at the '/artists' route. Relevant portions of App.js: import React, { useState, useEffect } from 'react'; import { Routes, Route, Link } from 'react-router-dom'; import axios from 'axios'; import ProjectList from './ProjectList'; import ArtistList from './ArtistList'; import { Button } from './styles.js'; const App = () => { const [ projects, setProjects ] = useState([]); const getProjects = () => axios('projects').then(({ data }) => setProjects(data)); useEffect(getProjects, []); return (<> <Link to="/"> <Button>Projects</Button> // Button is using styled-components </Link> <Link to="/artists"> <Button>Artists</Button> </Link> <Routes> <Route path="/" element={<ProjectList projects={projects} />} /> <Route path="/artists" element={<ArtistList projects={projects} />} /> </Routes> </>); }; This all works as expected when I click the Projects and Artists buttons. However, when I attempt to access the '/artists' route directly through the URL bar of my browser, nothing renders and I get an error about how the projects prop is undefined. My assumption is that because I'm trying to access the ArtistList component before rendering the App component itself, getProjects doesn't run and so no projects props are passed down to ArtistList. I need the list of projects to render my ArtistList component. Each element of projects is an object that includes an artist property that I use to create my list of artist names and a dateAdded property that I use to sort the artist list by recency. I also keep track of how many projects each artist has. Relevant portions of ArtistList.jsx (the return block contains some styled-components - Options, Header, TextWrapper, and Artist): const ArtistList = ({ projects }) => { const [ artists, setArtists ] = useState([]); const [ sortBy, setSortBy ] = useState('name'); const getArtists = () => { const artists = []; let curArtist = projects[0].artist; let projectCount = 0; const now = new Date(); let firstAdded = now; for (const { artist, dateAdded } of projects) { if (artist !== curArtist) { artists.push({ name: curArtist, projectCount, firstAdded }); curArtist = artist; projectCount = 0; firstAdded = now; } projectCount++; const projectDate = new Date(dateAdded); if (projectDate < firstAdded) firstAdded = projectDate; } setArtists(artists); }; useEffect(getArtists, [ projects, sortBy ]); if (sortBy === 'number') artists.sort((a, b) => b.projectCount - a.projectCount); else if (sortBy === 'recency') artists.sort((a, b) => b.firstAdded - a.firstAdded); return (<> <Options> <label htmlFor="sortBy">Sort by: </label> <select id="sortBy" value={sortBy} onChange={e => setSortBy(e.target.value)}> <option value="artist">Name</option> <option value="number"># of Projects</option> <option value="recency">Recently Added</option> </select> </Options> <Header> <TextWrapper>Name</TextWrapper> <TextWrapper># of Projects</TextWrapper> </Header> {artists.map(({ name, projectCount }, idx) => ( <Artist key={idx}> <TextWrapper>{name}</TextWrapper> <TextWrapper>{projectCount}</TextWrapper> </Artist> ))} </>); }; I currently see 2 solutions to this issue (I'm sure I'm missing more): * *Create a projects state and a getProjects in the ArtistList component, pretty much exactly as they are in the parent App component. Whenever I render ArtistList, I will make a request to my back end to retrieve a list of projects and then invoke setProjects. I'd then derive the artists state from projects, as before. Of course, I'd no longer need to pass the projects props from App to ArtistList. However, I would then have the exact same state values/functionality in both parent and child components, and this feels to me like a violation of fundamental React principles. *Put a collection of Artists into my Mongo database, in addition to the Projects collection I currently have. I would have to implement something similar to the getArtists function, but in the back end this time, then put the list of artist data into my database. Then, every time I try to render ArtistList, I will make a request to my back end to retrieve the list of artists and go from there. The third option is doing nothing, but then I'm unable to access the '/artists' page directly through the URL. What would be best practice and the best approach in this instance? Any help is appreciated! A: The projects state is actually defined on the initial render cycle: const [ projects, setProjects ] = useState([]); So it's a defined prop when passed to ArtistList: <Route path="/artists" element={<ArtistList projects={projects} />} /> The issue starts when in ArtistList in the useEffect hook calling getArtists where it is incorrectly attempting to access a property of the first element of the projects array which is currently an undefined object. const getArtists = () => { const artists = []; let curArtist = projects[0].artist; // <-- error, access artist of undefined! let projectCount = 0; const now = new Date(); let firstAdded = now; for (const { artist, dateAdded } of projects) { if (artist !== curArtist) { artists.push({ name: curArtist, projectCount, firstAdded }); curArtist = artist; projectCount = 0; firstAdded = now; } projectCount++; const projectDate = new Date(dateAdded); if (projectDate < firstAdded) firstAdded = projectDate; } setArtists(artists); }; useEffect(getArtists, [projects, sortBy]); What you can do is to only run the logic in getArtists is the array is populated. const getArtists = () => { const artists = []; let curArtist = projects[0].artist; let projectCount = 0; const now = new Date(); let firstAdded = now; for (const { artist, dateAdded } of projects) { if (artist !== curArtist) { artists.push({ name: curArtist, projectCount, firstAdded }); curArtist = artist; projectCount = 0; firstAdded = now; } projectCount++; const projectDate = new Date(dateAdded); if (projectDate < firstAdded) firstAdded = projectDate; } setArtists(artists); }; useEffect(() => { if (projects.length) { getArtists(); } }, [projects, sortBy]); And to ensure that projects is at least always a defined value, provide an initial value when destructuring the prop. const ArtistList = ({ projects = [] }) => { ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/71137413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find largest count using table in a matrix in R Suppose I had the following matrix m = matrix(c(1, 0, 0, 0, 0, 0, 1, 1, 0), ncol = 3) > m [,1] [,2] [,3] [1,] 1 0 1 [2,] 0 0 1 [3,] 0 0 0 I want to have a count of the values for each of the columns, so table(m[,1]) table(m[,2]) table(m[,3]) And I want to figure out what's the value (either 0, or 1) that has the largest counts (appears more than the other). So for column 1 I would want R to return 0 (because there are more 0's than 1's), for column 2, R should return 0, and for column 3 return 1. I've tried which.max() but that only gives me the index. Not the value with the largest count. A: If you are working with a binary matrix, you can use colMeans as.numeric(colMeans(m) > 0.5) # [1] 0 0 1 since colMeans(m) gives you the percentage of 1's in each column A: A simple solution is to use indexation and which.max, as you had proposed. To make things simpler, it can be done using apply and a function indexing which.max Thus, following your example matrix: apply(m,2,function (X) as.numeric(names(table(X)[which.max(table(X))])))
{ "language": "en", "url": "https://stackoverflow.com/questions/27096506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does size of a VARCHAR column matter when used in queries Possible Duplicate: is there an advantage to varchar(500) over varchar(8000)? I understand that a VARCHAR(200) column containing 10 characters takes same amount of space as a VARCHAR(20) column containing same data. I want to know if changing a dozen VARCHAR(200) columns of a specific table to VARCHAR(20) would make the queries run faster, especially when: * *These columns will never contain more than 20 characters *These columns are often used in ORDER BY clause *These columns are often used in WHERE clause * *Some of these columns are indexed so that they can be used in WHERE clause PS: I am using SQL Server 2000 but will upgrade to later versions of SQL anytime soon. A: Here's a blog post that explains under what circumstances and why there are performance differences when using different column sizes (with tests and technical details): Advanced TSQL Tuning: Why Internals Knowledge Matters A: It does matter for the query optimiser when it will evaluate the best query path to perform your query. When more than one path will be available, it will calculate an I/O cost and other various parameters based on your query and from these, chose the one that will appears to him as the least costly. This is not an absolute calculation, it's only an approximation process. Therefore, it can easily be thrown off if the apparent mean size required to manipulate the records from one table in memory is much bigger then what will be really necessary and the optimiser might chose a less performing path based on what it thinks would have be necessary for the others paths. Having a realistic max size is also usefull to any other programmer that will come along looking at your code. If I have a variable that I want to display in a GUI, I might allocate much more space than neededd if I see that is backed by something like nvarchar(200) or nvarchar(2000) instead of nvarchar(20) if its size is never greater than that. A: Yes, the length of varchar affects estimation of the query, memory that will be allocated for internal operation (for example for sorting) and as consequence resources of CPU. You can reproduce it with the following simple example. 1.Create two tables: create table varLenTest1 ( a varchar(100) ) create table varLenTest2 ( a varchar(8000) ) 2. Fill both of them with some data: declare @i int set @i = 20000 while (@i > 0) begin insert into varLenTest1 (a) values (cast(NEWID() as varchar(36))) set @i = @i - 1 end 3. Execute the following queries with "include actual execution plan": select a from varLenTest1 order by a OPTION (MAXDOP 1) ; select a from varLenTest2 order by a OPTION (MAXDOP 1) ; If you inspect execution plans of these queries, you can see that estimated IO cost and estimated CPU cost is very different: A: Size matters Always use the smallest data size that will accommodate the largest possible value. If a column is going to store values between 1 and 5, use tinyint instead of int. This rule also applies to character columns. The smaller the data size, the less there is to read, so performance, over all, benefits. In addition, smaller size reduces network traffic. With newer technology, this tip seems less relevant, but don’t dismiss it out of hand. You’ll won’t regret being efficient from the get-go. For more info visit http://www.techrepublic.com/blog/10-things/10-plus-tips-for-getting-the-best-performance-out-of-your-sql-server-data-types/
{ "language": "en", "url": "https://stackoverflow.com/questions/13894528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Spring MVC not loading static resources from webapp Issue Unable to get Spring to add a resource handler for static resources. Background Information I have a Spring MVC webapp running in a standalone Jetty instance. My webapp structure is webapp root/ resources/ css/ images/ js/ WEB-INF/ layouts/ tiles.xml page.jsp lib/ views/ home/ home.jsp tiles.xml web.xml I've extended the WebMvcConfigurerAdaptor to add a resource mapping such that urls like company.com/myservlet/resources/css/main.css will get resolved to the webapp root/resources/css folder. @Configuration @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } } My little controller is this: @Controller public class SpringAppController { public SpringAppController() { } @RequestMapping(value = "/home", method = RequestMethod.GET) public ModelAndView handleRequestHome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { return new ModelAndView("home"); } } My web.xml is simply this: <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- Java-based Spring container definition --> <context-param> <param-name>contextClass</param-name> <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> </context-param> <!-- Location of Java @Configuration classes that configure the components that makeup this application --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>com.company</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Processes application requests --> <servlet> <servlet-name>admin</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value></param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>admin</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- Ensure UTF-8 encoded pages so that certain characters are displayed and submitted correctly --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Enables support for DELETE and PUT request methods with web browser clients --> <filter> <filter-name>hiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>hiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> My JavaConfig for the webapp to instantiate some mvc resolvers is this: @Configuration public class MainConfig { @Bean public ViewResolver viewResolver() { UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); viewResolver.setViewClass(TilesView.class); return viewResolver; } @Bean public TilesConfigurer tilesConfigurer() { TilesConfigurer configurer = new TilesConfigurer(); configurer.setDefinitions(new String[] { "/WEB-INF/layouts/tiles.xml", "/WEB-INF/views/**/tiles.xml" }); configurer.setCheckRefresh(true); return configurer; } @Bean public org.springframework.context.MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("/WEB-INF/messages/messages"); return messageSource; } } When I hit the url company.com/myservlet/home the tiles stuff works and the home.jsp page is displayed but the css and images are not loaded. The servlet logs this warning: [DEBUG] [DispatcherServlet] [DispatcherServlet with name 'admin' processing GET request for [/api/v1/tlb/resources/page.css]] [DEBUG] [RequestMappingHandlerMapping] [Looking up handler method for path /resources/form.css] [DEBUG] [RequestMappingHandlerMapping] [Did not find handler method for [/resources/form.css]] [WARN ] [PageNotFound] [No mapping found for HTTP request with URI [/api/v1/tlb/resources/form.css] in DispatcherServlet with name 'admin'] I've tried debugging the servlet and the WebMvcConfig.addResourceHandlers() method is never called and hence why the static resources cannot be found. What am I missing to get this working? As a note if I add the following to my web.xml the css resource will be loaded but I would like to know why the WebMvcConfig.addResourceHandlers() method is not called so I don't need this servlet mapping. <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/resources/*</url-pattern> </servlet-mapping> A: Well, I've fixed the issue but not exactly sure why/how yet. The project had imported a jar that contained a class that extended WebMvcConfigurationSupport like the following: @Configuration public class EnableUriMatrixVariableSupport extends WebMvcConfigurationSupport { @Override @Bean public RequestMappingHandlerMapping requestMappingHandlerMapping() { RequestMappingHandlerMapping hm = super.requestMappingHandlerMapping(); hm.setRemoveSemicolonContent(false); return hm; } } Additionally I also has @EnableMvc annotation which imports DelegatingWebMvcConfiguration. I think this ends up creating two instances of a WebMvcConfigurationSupport and this causes havoc in the spring container. Unfortunately I upgraded to spring 4.x in the process of fixing this issue so I'm not sure yet if this helped in some way.
{ "language": "en", "url": "https://stackoverflow.com/questions/25440502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Create new database on the fly in Laravel 4 I want dynamically create new database, database user and password with privileges, create some tables in new database on the fly in Laravel 4 for every new user. This is for a multi tenant website. Whats the best solution? thanks. A: This is not your first database connection it's easy, but you'll have to execute raw statements because database creation is no available as connection methods: DB::statement(DB::raw('CREATE DATABASE <name>')); To do that you can use a secondary connection: <?php return array( 'default' => 'mysql', 'connections' => array( 'mysql' => array( 'driver' => 'mysql', 'host' => 'host1', 'database' => 'database1', 'username' => 'user1', 'password' => 'pass1' ), 'store' => array( 'driver' => 'mysql', 'host' => 'host2', 'database' => 'database2', 'username' => 'user2', 'password' => 'pass2' ), ), ); Then you can, during application bootstrap, change the database of the secondary connection: DB::connection('store')->setDatabaseName($store); or Config::set('database.connections.store', $store); And use the secondary connection in your queries: $user = User::on('store')->find(1); or DB::connection('store')->select(...);
{ "language": "en", "url": "https://stackoverflow.com/questions/25821291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show in Action bar, only if it can fit with text? I am having the following buttons, with some ic_menu icons: Register, Clear. I want them, in whatever device(smartphone or tablet), to be shown if they can fit, including their text. If i use on both them: withText|ifRoom, on smartphone they appear both, without their text on portrait, and landscape with text. On tablet they appear both with text. I want them, on smartphone, NOT to appear if they cant fix with their text too. Are any other combinations ? Also what is collapseActionView for?
{ "language": "en", "url": "https://stackoverflow.com/questions/11536869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is meant by indexing in MongoDB? To be true, After typing the Question title only, i had a look about DB indexing in Wiki. Now i know something about Indexing in general. But, still i have some questions on MongoDB indexing. What is indexing in MongoDB? What it will exactly do, If i index a collection? What i can do with indexing in MongoDB? Will i able to use it for searching specific data? Can anyone explain it with the below set of documents in a Collection in some MongoDB? { "_id":"das23j..", "x": "1", "y":[ {"RAM":"2 GB"}, {"Processor":"Intel i7"}, {"Graphics Card": "NVIDIA.."}]} Thanks!!! A: An index speeds up searching, at the expense of storage space. Think of the index as an additional copy of an attribute's (or column's) data, but in order. If you have an ordered collection you can perform something like a binary search, which is much faster than a sequential search (which you'd need if the data wasn't ordered). Once you find the data you need using the index, you can refer to the corresponding record. The tradeoff is that you need the additional space to store the "ordered" copy of that column's data, and there's a slight speed tradeoff because new records have to be inserted in the correct order, a requisite for the quick search algorithms to work. For details on mongodb indexing see http://www.mongodb.org/display/DOCS/Indexes.
{ "language": "en", "url": "https://stackoverflow.com/questions/4290079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unable to display username from another table I currently am able to view a list of contacts with no issues and would like to be able to view the mentors / tutors for the clients. The username is stored in another table to the contact information and the mentor ID is stored in the contacts table. I have followed a tutorial on how to do this but can't get it to work. I have tried to join the accounts and contacts table together and has stopped the everything from showing. My old code showed everything fine apart from the mentor. (Old code also below) Error reporting says Warning: Undefined array key "id" Code; $stmt = $pdo->prepare('SELECT c.id , c.name , c.last_name , c.mobile_number , c.status , a.username as mentorname FROM contacts c LEFT JOIN accounts a ON c.mentor = a.id WHERE c.id = ?;'); $stmt->execute([$_GET['c.id']]); $fullContactInfo = $stmt->fetchAll(PDO::FETCH_ASSOC); } Display code <?php if($fullContactInfo == null){ echo "<tr><td>No Record Found!</td></tr>"; }else{ foreach($fullContactInfo as $info){ ?> <tr> <td><?php echo $info['name']; ?> <?php echo $info['last_name']; ?></td> <td><?php echo $info['mobile_number']; ?></td> <td><?php echo $info['status']; ?></td> <td><?= $info['mentorname']; ?></td> Table examples Contacts ID: 1 Name: Joe Blogs Mobile: 1889454 Status: Current Mentor: 25 Accounts ID: 25 Username: jbloggs Old Code $stmt = $pdo->prepare('SELECT id,name,last_name,mobile_number,status,dob,mentor,image FROM contacts'); $stmt->execute([$_GET['id']]); $fullContactInfo = $stmt->fetchAll(PDO::FETCH_ASSOC); if($fullContactInfo == true){ $stmt = $pdo->prepare('SELECT username FROM accounts WHERE id = ?'); $stmt->execute([ $fullContactInfo['mentor'] ]); $fullContactInfo1 = $stmt->fetch(PDO::FETCH_ASSOC); A: You can just replace $_GET['c.id'] with $_GET['id'].
{ "language": "en", "url": "https://stackoverflow.com/questions/73363210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I get my WCF Service constructor called? I'm currently trying to get my head around WCF services for an ASP.NET dev environment, and I believe that I'm doing well save for one thing that has me stumped. Basically, I've got a WCF service set up (let's take the default, with an added constructor): public class MyService : IMyService { public MyService() { /* blah */ } public DoWork() { /* blah */ } } The IMyService interface defines the DoWork() method as an [OperationContract], as it should. So I've got this service referenced in another project (let's say a [Unit] Test Project), via Add Service Reference on the VS2010 UI. This creates a reference to a MyServiceClient which exposes my WCF service methods, as it should. However, when I do this in my test project: ServiceReference.IMyService service; service = new ServiceReference.MyServiceClient(); ... the MyService() constructor does not get called, basically because I'm instantiating a MyServiceClient, not a MyService per se. How do I go about getting that constructor called? I'm planning to use that for initialization purposes (perhaps grabbing a layer in a tiered implementation, for example?). A: That constructor will be called on the server when you make your request from the client. Creating a "reference" to a web service (and then using the client classes) is very different to referencing a regular .DLL. All of your service code will run on the server-side, but not until the service is invoked... A: The only way for the server-side constructor to be called for each request is to set the InstanceContextMode to PerCall (in the ServiceBehavior attribute).
{ "language": "en", "url": "https://stackoverflow.com/questions/4079236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }