text:
Q: How to create a form search in dynamic ways Yii2? I have a form like this :
<?php $form = ActiveForm::begin([
    'layout' => 'horizontal'
]); ?>

<?= $form->field($model, 'tanggal_cek')->widget(DatePicker::className(), [
    'options' => [
        'class' => 'form-control'
    ]
]) ?>

<?= $form->field($model, 'lokasi')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'created_by')->widget(Select2::className(), [
    'data' => $mapDataUser,
    'options' => [
        'placeholder' => 'Choose .. '
    ]
]) ?>

Now, I have to manipulate the result that came from this form to find data in my database.
SO far I've created like this :
if ($model->load($request->post())) {
  $tanggalCek = $model->tanggal_cek ? Yii::$app->formatter->asDate($model->tanggal_cek, "php:Y-m-d") : "";
  $lokasi = $model->lokasi;
  $created_by = $model->created_by;

  $model = StockTakingTli::find()
           ->where(['tanggal_cek' => $tanggalCek])
           ->andWhere(['LIKE', 'lokasi', $lokasi])
           ->andWhere(['created_by' => $created_by])
           ->all();

You know, the AR working in sequence.
My question is, is it possible AR to find dynamically ?
Because, sometimes tanggal_cek is null, and lokasi is set, vice versa, and on...and on..
Please advise.

A: Use filterWhere(), it automatically ignores empty values:
$query->filterWhere([
    'username' => $username,
    'email' => $email,
]);

A: You can build dinamic query filter using   filterWhere() and andFilterWhere()   functions  instead of where() and andWhere()  ...
The filterWhere  functions ignore condition with empty values
 $model = StockTakingTli::find()
           ->filterWhere(['tanggal_cek' => $tanggalCek])
           ->andFilterWhere(['LIKE', 'lokasi', $lokasi])
           ->andFilterWhere(['created_by' => $created_by])
           ->all();

http://www.yiiframework.com/doc-2.0/yii-db-querytrait.html#filterWhere()-detail
http://www.yiiframework.com/doc-2.0/yii-db-querytrait.html#andFilterWhere()-detail


text:
Q: Why can't you have a static and non-static method with the same method signature in Java? Doesn't really seem to make sense to me. Maybe someone can help me understand. It seems kind of silly that I have to switch around the order of my parameters to have this feature.

A: Because:
class Example {

   void method () { }

   static void method () { }

   void example () {
      method();   // <- ambiguous
   }

}

So you either introduce a constraint that differentiates static and nonstatic calls in that context, e.g. require Example. before static calls, or you disallow identical signatures. The latter was chosen.
Note that in most cases if you find yourself wanting both a static and nonstatic method with the same signature, this could be a red flag of a possible design issue, or at least a suggestion that better names for your methods could be chosen.
If you're thinking of "switching around the order of your parameters" as a kludge, definitely reconsider. There is definitely room for general improvement if you are in that situation. I would raise some serious eyebrows if I ever saw code like that.

A: Because Java allows to invoke a static method in a non-static manner, i.e. on an object of the class. So, if a class has static and non-static methods - method() of same signature, an invocation like this: obj.method() would be ambiguous.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I change class static variables? I wish to define a dictionary which instances of the class can add entries to, and the class can add entries to. The example generates a 'TypeError: 'property' object does not support item assignment', when the class modifies the variable. How can I change myClass such that it passes the test below?
class myClass(object):
    _d = {}

    @property
    def d(self):
        return self._d
    @d.setter
    def d(self,key,val):
        self._d[key] = val

    def printMyClass(self):
        print self._d

A = myClass()
B = myClass()

A.d['a'] = 1
B.d['b'] = 2
A.printMyClass()
B.printMyClass()     # returns {'a': 1, 'b': 2}
myClass.d['c'] = 3   # fails, expect {'a': 1, 'b': 2, 'c': 3}
B.printMyClass()


text:
Q: Apple Watch app does not localize I have set up interface.storyboard strings for German, French, Spanish, and Simplified Chinese.  I download the iOS app and it loads to the watch. I then set the watch language to German, for example.  But the UI is still in English.
Here are the interface.storyboard strings:
    /* Class = "WKInterfaceButton"; title = "Start Timer"; ObjectID = "1oP-Ed-sIA"; */
"1oP-Ed-sIA.title" = "Timer starten";

/* Class = "WKInterfaceButton"; title = "0:30"; ObjectID = "Kti-O4-Ky6"; */
"Kti-O4-Ky6.title" = "0:30";

/* Class = "WKInterfaceDate"; format = " h:mm:ss a"; ObjectID = "P50-YW-9sa"; */
"P50-YW-9sa.format" = " h:mm:ss a";

/* Class = "WKInterfaceButton"; title = "0:15"; ObjectID = "QLq-vX-zHG"; */
"QLq-vX-zHG.title" = "0:15";

/* Class = "WKInterfaceButton"; title = "Do Not Disturb"; ObjectID = "Zku-u8-rhy"; */
"Zku-u8-rhy.title" = "Bitte nicht stören";

/* Class = "WKInterfaceButton"; title = "Stop Timer"; ObjectID = "afW-nF-dFL"; */
"afW-nF-dFL.title" = "Stoppuhr";

/* Class = "WKInterfaceButton"; title = "0:60"; ObjectID = "tDV-Bi-XDn"; */
"tDV-Bi-XDn.title" = "0:60";

Here is the watch screenshot:

A: I found out that BOTH the watch target AND the watch extension target have to be selected under the localized strings setting "Target Membership."  I do not know why, since supposedly the extension only needs to be localized if there is code that affects the UI, not just the storyboard. But doing this does localize the watch UI.


text:
Q: Is there C/C++ equivalent of eval("function(arg1, arg2)")? it need a way to call function whose name is stored in a string similar to eval. Can you help?

A: #include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

double eval( string expression );

int main( int argc, char *argv[] )
{
    string expression = "";
    for ( int i = 1; i < argc; i++ )
    {
       expression = expression + argv[i];
    }
    cout << "Expression [ " << expression << " ] = " << endl;

    eval( expression );
}

double eval( string expression )
{
    string program = "";
    program = program + "#include <cmath>\n";
    program = program + "#include <iostream>\n";
    program = program + "using namespace std;\n";
    program = program + "int main()\n";
    program = program + "{\n";
    program = program + "   cout << ";
    program = program + expression;
    program = program + " << endl;\n";
    program = program + "}";

    ofstream out( "abc.cpp" );
    out << program;
    out.close();

    system( "g++ -o abc.exe abc.cpp" );
    system( "abc" );
}

A: You could try to adopt an existing scripting engine, expose the functions you like to this and then use this to evaluate your statements. One such enging could be the V8 engine: https://developers.google.com/v8/intro but there are many alternatives and different languages to choose from.
Here are some examples:

*

*Boost Python

*V8

*LUA

*AngelScript

A: C++ doesn't have reflection so you must hack it, i. e.:
#include <iostream>
#include <map>
#include <string>
#include <functional>

void foo() { std::cout << "foo()"; }
void boo() { std::cout << "boo()"; }
void too() { std::cout << "too()"; }
void goo() { std::cout << "goo()"; }

int main() {
  std::map<std::string, std::function<void()>> functions;
  functions["foo"] = foo;
  functions["boo"] = boo;
  functions["too"] = too;
  functions["goo"] = goo;

  std::string func;
  std::cin >> func;
  if (functions.find(func) != functions.end()) {
    functions[func]();
  }
  return 0;
}

A: Except using the function map in the program and hack it on the Makefile, you can access it through ELF.
I think this method is better as it did not need to write duplicate code and compile it every time on different machine.
Here is my demo C/C++ equivalent of eval("function(arg1, arg2)")
#include<stdio.h>
#include<stdlib.h>
#include<elf.h>
#include<libelf.h>
#include<unistd.h>
#include<fcntl.h>
#include<gelf.h>
#include<string.h>

void my_fun()
{
    int a = 19;
    printf("my_fun is excute, a is %d \n", a);
}

void my_fun2()
{
    printf("my_fun2 is excute\n");
    return;
}

void my_fun3()
{
    return;
}

void excute_fun(char *program_name, char *function_name)
{
    int i, count;
    Elf32_Ehdr *ehdr;
    GElf_Shdr   shdr;
    Elf *elf;
    Elf_Scn *scn = NULL;
    Elf_Data *data;
    int flag = 0;
    int fd = open(program_name, O_RDONLY);
    if(fd < 0) {
        perror("open\n");
        exit(1);
    }
    if(elf_version(EV_CURRENT) == EV_NONE) {
        perror("elf_version == EV_NONE");
        exit(1);
    }
    elf = elf_begin(fd, ELF_C_READ, (Elf *) NULL);
    if(!elf) {
        perror("elf error\n");
        exit(1);
    }
    /* Elf32_Off e_shoff; */
    /* if ((ehdr = elf32_getehdr(elf)) != 0) { */
    /*     e_shoff = ehdr->e_shoff; */
    /* } */
    /* scn = elf_getscn(elf, 0); */
    /* printf("e_shoff is %u\n", e_shoff); */
    /* scn += e_shoff; */
    while ((scn = elf_nextscn(elf, scn)) != NULL) {
        gelf_getshdr(scn, &shdr);
        if (shdr.sh_type == SHT_SYMTAB) {
            /* found a symbol table. */
            break;
        }
    }
    data = elf_getdata(scn, NULL);
    if(!shdr.sh_entsize)
        count = 0;
    else
        count = shdr.sh_size / shdr.sh_entsize;
    for (i = 0; i < count; ++i) {
        GElf_Sym sym;
        gelf_getsym(data, i, &sym);
        char *sym_name = elf_strptr(elf, shdr.sh_link, sym.st_name);
        if(sym_name != NULL && sym_name[0] != '_' && sym_name[0] != '\0' && sym_name[0] != ' ' && sym.st_value != 0)
        {
            /* printf("sym_name is %s\n", sym_name); */
            /* printf("%s = %X\n", elf_strptr(elf, shdr.sh_link, sym.st_name), sym.st_value); */
            if(!strcmp(sym_name, function_name)) {
                void (*fun)(void) = (void*)sym.st_value;
                (*fun)();
                flag = 1;
            }
        }
    }
    if(!flag)
        printf("can not find this function\n");

    elf_end(elf);
    close(fd);
}

int main(int argc, char *argv[])
{
    char *input = (char*)malloc(100);
    for(;;) {
        printf("input function_name to excute: ");
        scanf("%s", input);
        excute_fun(argv[0], input);
        memset(input, 0, sizeof(input));
        printf("\n");
    }
    free(input);
    return 0;
}

This implementation is based on Example of Printing the ELF Symbol Table

A: There are at least 2 alternatives:

*

*The command pattern.

*On windows, you can use GetProcAddress to get a callback by name, and dlopen + dlsym on *nix.


text:
Q: Is there a way to play fragmented mp4 at random chunk? Say there is a video rendered into fragmented mp4 consisting of a number of chunks/fragments. The question is: after the init was loaded to MediaSource buffer, is there a way to play a random fragment?
A small research of the thing's specifications gave little understanding of the problem. Fragments seem to have a kind of an order IDs hardcoded in them. It's a fairly reasonable idea to include it in a file in case of unreliable connection and asynchronous fetching while streaming content, but is there a way to parse a chunk and change its ID using JavaScript?
The code below is just playing 2 minute video split into 12 fragments based on user's time and is supposed to be able to start at any chunk (not only the first) and then to repeat.
let mediaSource = new MediaSource
document.getElementById('video').src = URL.createObjectURL(mediaSource)

mediaSource.addEventListener('sourceopen', () => {
    let buffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')
    let loadToBuffer = url => {
        let xhr = new XMLHttpRequest
        xhr.responseType = 'arraybuffer'
        xhr.open('GET', url, true)
        xhr.addEventListener('loadend', () => buffer.appendBuffer(new Uint8Array(xhr.response)))
        xhr.send()
    }
    loadToBuffer('video/init.mp4')
    setInterval(() => loadToBuffer('video/video' + (Math.floor(new Date().getTime() / 1000 / 10) % 12) + '.m4s'), 10 * 1000)
})

A: When you load fragments in a sourceBuffer, those fragments include presentation time stamps (PTS), which put them in the correct playback order in the buffer.
You can either modify the fragments themselves, for which you have to parse the atoms and change the PTS (and possibly other) values, or change the video element currentTime property, so you can play the video at that was correctly buffered.
You can inspect the buffered property on the video element object to check the range of time that has been loaded.


text:
Q: how to make twitter bootstrap navbar fixed width? How can I make twitter bootstrap navbar fixed width, while keeping it centered?
I've tried adding a width parameter in .navbar, but then the navbar is misaligned.
.navbar {
overflow: visible;
margin-bottom: 20px;
color: #956362;
*position: relative;
*z-index: 2;
width: 650px;
}

I also tried

but this also makes it misaligned.

A: Surround it with a div.
Give that div a fixed width.
Something like:

CSS:
.navbar-outer {
  width:500px;
}


text:
Q: iOS Objective C ScrollView I am trying to implement a UIScrollView and load it with images from an array of images in Xcode using objective-C, each image in the UIScrollView must be full screen both  in portrait and in the landscape mode.I have been able to  make it work in portrait mode  but not in landscape mode. It should be fullscreen in all iOS device sizes. Below is the code I have written so far. I have UIScrollView in my storyboard, a button and a label. Any answer or pointing to a tutorial that implements this will be appreciated. Thanks in advance.
CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat widthInPixel = screen.size.width;
CGFloat heightInPixel = screen.size.height;
float increaseAmount = widthInPixel;
self.imageScrollView.contentMode = UIViewContentModeScaleAspectFit;
self.imageScrollView.pagingEnabled = YES;
[self.imageScrollView setAlwaysBounceVertical:NO];
[self.imageScrollView setAlwaysBounceHorizontal:NO];
imageViews = [[NSMutableArray alloc] init];
self.imageScrollView.clipsToBounds = YES;
NSInteger imageNumbers  = [self.images count];
UIImageView *image;
for(NSInteger i = 0; i < imageNumbers; i++) {
    CGFloat xOrigin = i * self.view.frame.size.width;
    image = [[UIImageView alloc] initWithFrame:
                          CGRectMake(xOrigin, 0,
                                     widthInPixel,

    self.imageScrollView.frame.size.height)];

    image.contentMode = UIViewContentModeScaleAspectFit;
    image.clipsToBounds = YES;
    image.image = self.images[i];

    [image setAutoresizingMask:
     UIViewAutoresizingFlexibleWidth |
     UIViewAutoresizingFlexibleHeight];

    [self.imageScrollView addSubview:image];
}

self.imageScrollView.contentSize = CGSizeMake(image.frame.size.width *
                                         imageNumbers,

self.imageScrollView.frame.size.height);

A: You really should learn how to use auto-layout and constraints. Use your favorite search engine and search for ios auto layout tutorial ... you'll find plenty of material.

Edit:
Scroll offset is an inherent issue when rotating a scroll view with paging enabled. See the edit below for an implementation of viewWillTransitionToSize.

But, to give you an idea, this will do what you want, including auto-resizing on device rotation:
//
//  ViewController.m
//  ScrollingImages
//
//  Created by Don Mag on 7/19/18.
//

#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UIScrollView *theScrollView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSArray *images = @[@"a", @"b", @"c", @"d", @"e"];

    [_theScrollView setPagingEnabled:YES];
    [_theScrollView setAlwaysBounceVertical:NO];
    [_theScrollView setAlwaysBounceHorizontal:NO];

    // we'll use this to hold the most recently added view
    UIImageView *prevImageView = nil;

    for (int i = 0; i < images.count; i++) {

        // create an image view with named image from array
        UIImageView *v = [[UIImageView alloc] initWithImage:[UIImage imageNamed:images[i]]];

        // we want to use auto-layout
        v.translatesAutoresizingMaskIntoConstraints = NO;

        // we want aspect-fit
        v.contentMode = UIViewContentModeScaleAspectFit;

        // add it to the scroll view
        [_theScrollView addSubview:v];

        // set width and height constraints equal to the scroll view
        [[NSLayoutConstraint
          constraintWithItem:v
          attribute:NSLayoutAttributeWidth
          relatedBy:NSLayoutRelationEqual
          toItem:_theScrollView
          attribute:NSLayoutAttributeWidth
          multiplier:1.0
          constant:0.0] setActive:YES];

        [[NSLayoutConstraint
          constraintWithItem:v
          attribute:NSLayoutAttributeHeight
          relatedBy:NSLayoutRelationEqual
          toItem:_theScrollView
          attribute:NSLayoutAttributeHeight
          multiplier:1.0
          constant:0.0] setActive:YES];

        if (i == 0) {  // if it's the first image

            // add top constraint
            [[NSLayoutConstraint
              constraintWithItem:v
              attribute:NSLayoutAttributeTop
              relatedBy:NSLayoutRelationEqual
              toItem:_theScrollView
              attribute:NSLayoutAttributeTop
              multiplier:1.0
              constant:0.0] setActive:YES];

            // and leading constraint
            [[NSLayoutConstraint
              constraintWithItem:v
              attribute:NSLayoutAttributeLeading
              relatedBy:NSLayoutRelationEqual
              toItem:_theScrollView
              attribute:NSLayoutAttributeLeading
              multiplier:1.0
              constant:0.0] setActive:YES];

        } else {

            // constrain leading to previous image view trailing
            [[NSLayoutConstraint
              constraintWithItem:v
              attribute:NSLayoutAttributeLeading
              relatedBy:NSLayoutRelationEqual
              toItem:prevImageView
              attribute:NSLayoutAttributeTrailing
              multiplier:1.0
              constant:0.0] setActive:YES];

            // and top to previous image view top
            [[NSLayoutConstraint
              constraintWithItem:v
              attribute:NSLayoutAttributeTop
              relatedBy:NSLayoutRelationEqual
              toItem:prevImageView
              attribute:NSLayoutAttributeTop
              multiplier:1.0
              constant:0.0] setActive:YES];

        }

        if (i == images.count - 1) {  // if it's the last image

            // add trailing constraint
            [[NSLayoutConstraint
              constraintWithItem:v
              attribute:NSLayoutAttributeTrailing
              relatedBy:NSLayoutRelationEqual
              toItem:_theScrollView
              attribute:NSLayoutAttributeTrailing
              multiplier:1.0
              constant:0.0] setActive:YES];

            // and bottom constraint
            [[NSLayoutConstraint
              constraintWithItem:v
              attribute:NSLayoutAttributeBottom
              relatedBy:NSLayoutRelationEqual
              toItem:_theScrollView
              attribute:NSLayoutAttributeBottom
              multiplier:1.0
              constant:0.0] setActive:YES];

        }

        // reference to most recently added view
        prevImageView = v;

    }

}

- (void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {

    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    // execute before rotation

    // get the "index" of the current image in the scroll view
    NSUInteger idx = (unsigned)(_theScrollView.contentOffset.x / _theScrollView.frame.size.width);

    [coordinator animateAlongsideTransition:^(id  _Nonnull context) {
        // execute during rotation

        // update the scroll view's contentOffset, based on the "index"
        self.theScrollView.contentOffset = CGPointMake(idx * self.theScrollView.frame.size.width, 0);

    } completion:^(id  _Nonnull context) {
        // execute after rotation (if additional code wanted)
    }];

}
@end

You can download a working example project here: https://github.com/DonMag/ScrollingImages


text:
Q: How to Reference Template of Control within ControlTemplate I want to style the DateTimePicker from the Extended WPF Toolkit a bit differntly, especially the Calendar control.
<ControlTemplate  x:Key="DatePickerTemplate" TargetType="{x:Type xctk:DateTimePicker}">
           ...
    <Calendar x:Name="PART_Calendar" Template="{StaticResource CalendarTemplate}" BorderThickness="0" DisplayDate="2014-05-14"/>"
           ...
</ControlTemplate>

What is necessary so that I am allowed to reference the Control template below in the code above (both are in the same file)?
<ControlTemplate x:Key="CalendarTemplate" TargetType="Calendar">
    <StackPanel x:Name="Root" HorizontalAlignment="Center">
        <CalendarItem x:Name="CalendarItem" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Template="{StaticResource CalendarItemTemplate}"/>
    </StackPanel>
</ControlTemplate>

At present VS complains: The ressource "CalendarTemplate" could not be resolved.
Update:
After changing the order of definitions, so first define   <ControlTemplate x:Key="CalendarTemplate" TargetType="Calendar">...
then the ControlTemplate that uses CalendarTemplate it works, remembers me of c++, but now I get the following Exception if I try to open the calendarcontrol:
Add value to dictionary of type 'System.Windows.ResourceDictionary' threw an exception.

A: You are referring to a StaticResource so you should be declaring your CalendarTemplate as it's x:Key not it's x:Name i.e.
<ControlTemplate x:Key="CalendarTemplate" TargetType="Calendar">
...
</ControlTemplate>

Update to show something similar working (note that these are defined at the same level in my Xaml file i.e. both directly under my main Views Resources)
<ControlTemplate x:Key="ABC123" TargetType="Button">

</ControlTemplate>

<!-- creating a control template for TextBox -->
<ControlTemplate x:Key="PasswordBoxTemplateBase" TargetType="{x:Type PasswordBox}">
    <Grid x:Name="root" Height="{TemplateBinding Height}" Width="{TemplateBinding Width}">
        <Border x:Name="normalBorder"
                Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}"/>
            <Button Template="{StaticResource ABC123}"/>
        </Border>
    </Grid>
</ControlTemplate>

A: The issue is the use of the x:Name on a StaticResource rather than an x:Key. It should be like this (x:Key="CalendarTemplate"):
<ControlTemplate x:Key="CalendarTemplate" TargetType="Calendar">
</ControlTemplate>

<ControlTemplate  x:Key="DatePickerTemplate" TargetType="DatePicker">
   <Calendar x:Name="PART_Calendar" Template="{StaticResource CalendarTemplate}" BorderThickness="0"/>
</ControlTemplate>


text:
Q: How to put multithreading with boto3 S3 paginator? I have logs sized around 200GB each day in s3. I wrote a script to read from s3 with boto3 paginator and writing it to opensearch. The problem I am facing is the script is too slow to index all data. Its taking around 4 days to index 1 day of logs in s3. My script currently looks like below. I am not sure how to put multithreading with paginators and also make it thread safe. Any suggestion for faster alternative for this would also be appreciated.
import sys
import json
import logging
import boto3
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth

globalVars = {}
globalVars['Environment'] = ""
globalVars['awsRegion'] = ""
globalVars['Bucket'] = ""
globalVars['osIndexPrefix'] = ""
index_name = ''
globalVars['osHosts'] = ""

# Initialize Logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def indexDocElement(obj_list):
    try:
        credentials = boto3.Session().get_credentials()
        auth = AWSV4SignerAuth(credentials, globalVars['awsRegion'])

        client = OpenSearch(
            hosts=[{'host': globalVars['osHosts'], 'port': 443}],
            http_auth=auth,
            use_ssl=True,
            verify_certs=True,
            connection_class=RequestsHttpConnection
        )

        client.bulk(body=obj_list, index=index_name)

    except Exception as e:
        logger.error('ERROR: {0}'.format(str(e)))
        logger.error('ERROR: Unable to index line')

def get_s3_object(s3, log_date):
    try:
        paginator = s3.get_paginator('list_objects_v2')
        operation_parameters = {'Bucket': globalVars['Bucket'],
                                'Prefix': 'eks/'+log_date,
                                'PaginationConfig': {'PageSize': 100}}
        page_iterator = paginator.paginate(**operation_parameters)

        for page in page_iterator:
            if page['KeyCount'] > 0:
                for item in page['Contents']:
                    yield item

    except Exception as e:
        logger.error('ERROR: {0}'.format(str(e)))
        logger.error(
            'ERROR: Unable able to GET object:{0} from S3 Bucket:{1}. Verify object exists.'.format('eks/'+log_date, globalVars['Bucket']))

if __name__ == '__main__':

    s3 = boto3.client('s3')

    log_date = sys.argv[1]
    print("\nDate:", log_date)

    index_string = '{"index": {}}'

    for i in get_s3_object(s3, log_date):
        if i['Key'].split('/')[-1]== '':
            print(len(i['Key'].split('/')))
            continue
        obj = s3.get_object(Bucket=globalVars['Bucket'], Key=i['Key'])
        j = obj['Body'].read().decode('utf-8')
        obj_list = j.split('\n')
        intermediate_item_list = []
        for obj in obj_list:
            if obj == '':
                continue
            obj = json.loads(obj)
            obj['@timestamp'] = obj['date']
            del obj['kubernetes']['labels']
            obj = json.dumps(obj)
            intermediate_item_list.append(obj)

        item_list = []
        for item in intermediate_item_list:
            item_list.append(index_string)
            item_list.append(item)

        item_list = '\n'.join(item_list)
        indexDocElement(item_list)

A: I found a reference on GitHub from here. He is first creating a list of keys and then applies multithreading to download the keys from the list. I tried this in my script and was able to reduce the time taken from 4 days to ~6 hours.


text:
Q: Need advice on authentication for android client connecting to the WCF Rest setup Basically I would like to connect to the WCF windows service from android with authentication. I am an android developer. I have tinkered with the WCF Rest service from this article and also configured the https.
Now I need to think about the authentication process (to the username and password in the database) to the WCF service from android. Should I encode username and password in the url and do http post, while returning a token for authorization, for login process and use the token and username for subsequent operation(and also save encrypted username and token in a pref file to avoid logging in next time, thus avoiding password)? Any advice and pointer to any project and document is welcomed.

A: There is a similar question at the programmers https://softwareengineering.stackexchange.com/questions/93005/designing-authentication-for-rest-api but I want to keep this question open since I would like to add useful code and links here.
Instead of encoding the username and password in url, they should be in the request body. The reason is that even though https encrypt the url, it is not a good practice because if the url is called from browser, the browser will remember it and username/password will be visible there in the browser history. Thus, here is an article to handle http Post http://www.codeproject.com/Tips/150313/Simple-WCF-web-service-to-receive-parameter-from-H
If https is achieved with self-signed certificate, you will need do some extra works
http://blog.antoine.li/2010/10/22/android-trusting-ssl-certificates/
More article on WCF rest and android http://fszlin.dymetis.com/post/2010/05/10/Comsuming-WCF-Services-With-Android.aspx
Creating a custom token in C#
http://msdn.microsoft.com/en-us/library/ms731872.aspx


text:
Q: Why is x==x false if the value of x is NaN? http://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html
This specifies that x==x is false if x is NaN.
What would be the underlying reason? If the compiler detects stuff like 1.0/0.0 (NaN) wouldn't it automatically set the value to 0x7F800000 (IEEE754 Single Precision Floating Point representation for NaN/Inf). Then when the x==x comparison occurs, should it be true as it would be a comparison of the same hex value?


text:
Q: get handler return null in LooperThread public class LooperThread extends Thread {

private Handler handler = null;

public Handler getHandler() {
    return handler;
}

@Override
public void run() {
    Looper.prepare();
    handler = new Handler();
    Looper.loop();
}

}

class Helper {
    private static LooperThread databaseThread = null;

static {
    databaseThread = new LooperThread();
    databaseThread.start();
}

public void postRunable(Runnable r) {
    databaseThread.getHandler().post(r);
    databaseThread.getHandler().sendMessage(new Message());
}
}

//ui thread.

 class UIActivity extends Activity {

     private Helper helper = new Helper();

     public void onCreate(Bundle savedInstanceState) {
         helper.postRunnable(new Runnable() {
              public void run() {
                  //work asyn,like query from db.
              }
         });
     }
 }

sometimes call databaseThread.getHandler().post(r); ,it return null,sometime are not,why this?as usual,handler should be initial by static block.

A: You are some times getting a null Handler because calling databaseThread.start(); in the the static initializer only ensures that the thread will be started at some point in the future this means thats creating a race condition between the handler getting created inside the new thread and getHandler() being called in the old one. Having a thread with a background looper is a very common pattern in Android so there is a class to help us with this.
First get rid of your LooperThread class and use the SDK's HandlerThread instead.
Your Helper class should now look like
class Helper {
    private static final HandlerThread databaseThread;
    private static final Handler dbHandler;
    static {
        databaseThread = new HandlerThread("database thread");
        databaseThread.start();
        // If you have called HandelerThread#start()
        // HandlerThread#getLooper() will block until the looper is initialized and Looping
        dbHandler = new Handler(databaseThread.getLooper());
    }

    public void postRunable(Runnable r) {
        dbHandler.post(r);
    }
}

A: The getHandler method returns null because the view is not attached:
public Handler getHandler() {
    if (mAttachInfo != null) {
        return mAttachInfo.mHandler;
    }
    return null;
}

mAttachInfo is set in dispatchAttachedToWindow and nulled in dispatchDetachedFromWindow.
Instead of mapView.getHandler().post() you can use directly mapView.post() (which seems to use getHandler().post() or ViewRootImpl.getRunQueue().post()).


text:
Q: jQuery Ajax get json returned result I want to get the return result of a php function in an Ajax request in order to make some verification in onSucces. How can I get the JSON result from the php function into the ajax request?
public function verifyEmailAction()
{
    $is_valid = true;
    $is_duplicate = false;
    $email_reset = false;

    $register = $this->getRegisterHelper();
    $register->addEmailCheck();
    $register->setData($this->getAllParams());
    $validationErr = $register->getValidationResult();

    if (!empty($validationErr['badWords']['email']) || $validationErr['banned']['email'] == true
        || empty($validationErr['isEmailValid'])
    ) {
        $is_valid = false;
    } elseif (!empty($validationErr['duplicates']['email'])) {
        $is_duplicate = true;
        $email_reset = $this->sendResetEmail();
    }
    $result = [
      'duplicate' => $is_duplicate,
      'valid' => $is_valid,
      'reset' => $email_reset
    ];

    $this->getResponse()->setBody(json_encode($result));
}

jQuery.validator.addMethod("checkDuplicate", function (value, element) {
        jQuery.ajax({
            type: 'GET',
            url: '/user/register/verify-email.ajax',
            data: {
                'email': value
            }
        });
    });

A:  jQuery.ajax({
            type: 'GET',
            url: '/user/register/verify-email.ajax',
            data: {
                'email': value
            },
            dataType:'json',
            success:function(response){
               console.log(response);
               var duplicate=response.duplicate;
               var valid=response.valid;
               var reset=response.reset;
            },
            error:function(err){
               console.log('Error '+err);
            }
        });

A: You need to use the success and error functions like below,
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
        jQuery.ajax({
            type: 'GET',
            url: '/user/register/verify-email.ajax',
            data: {
                'email': value
            },
            success : function(data, status, xhr) {
                console.log(JSON.stringify(data));
            },
            error: function(jqXhr, textStatus, errorMessage){
                  console.log("ERROR " + errorMessage);
            }
        });
    });

A: $.ajax({
  type: 'GET',
  url: url,
  data: {
   'email': value
  },
  dataType:'json',
  }).success(function(response){
        //YOUR Json KEY
        if(response.success){
        }
});

A: I hope this article will help you.
http://api.jquery.com/jquery.ajax/
Specially you can use this
jQuery.ajax({
  url: "YOURURL",
  type: "YOURTYPE",
  dataType:"json",
}).done(function(data) {
  console.log(data) // to see the reqested data
  // manipulate data here
});

A: Add dataType:'json':
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
        jQuery.ajax({
            type: 'GET',
            url: '/user/register/verify-email.ajax',
            data: {
                'email': value
            },
            dataType:'json'
        });
    });

You can use this to convert JSON string to a JavaScript object:
var txtReturned = JSON.parse(data);

Reference:

*

*jQuery AJAX Call to PHP Script with JSON Return


text:
Q: Fetch only the document ids for documents that match a query in Firebase Cloud Functions I know I can retrieve the documents themselves with a query such as:
    const querySnapshot = await db.collection("records")
      .where("color", "==", 'blue')
      .get();

However this would presumably get expensive, and all I really need is the document Ids so that I can write to the documents. I don't really need to read their data.
So, how can I fetch only the document ids for documents that match my query?
Thanks


text:
Q: How do I turn this SQL into an ActiveRecord query? Ok, so I have this Concern which contains a method top for retrieving records order by the number of times someone has listened to them (directly if the record is a song, or via songs if it's something else, like a genre or artist). In case of a tie, it orders records by the popularity on other sites.
The following code works almost perfectly. It returns an array of the objects, in the correct order. My main issue is that I get an array and not a relation. So the caller cannot further add stuff like Song.top.limit 3 or Genre.top.offset(10).limit(5).
Here's my method:

def top(options = {})
    tname = self.name.tableize

    inner_select = self.select("#{tname}.*,COUNT(DISTINCT(listens.id)) AS listens_count")
    inner_select = inner_select.joins(:songs) unless self.name == 'Song'
    inner_select = inner_select.joins("LEFT JOIN listens ON listens.song_id = songs.id")
    inner_select = inner_select.where("listens.user_id = ?", options[:for].id) if options[:for].is_a? User
    inner_select = inner_select.group("#{tname}.id").to_sql

    # this is the part that needs fixin'
    find_by_sql("
        SELECT
            #{tname}.*,
            #{tname}.listens_count,
            SUM(sources.popularity) AS popularity_count
        FROM (#{inner_select}) AS #{tname}
        LEFT JOIN sources ON
            sources.resource_id = #{tname}.id
            AND
            sources.resource_type = '#{self.name}
        GROUP BY #{tname}.id
        ORDER BY listens_count DESC, popularity_count DESC
    ")
end

Here are the SQL queries that are generated, as requested. This is from Song.top:
SELECT
    songs.*,
    songs.listens_count,
    SUM(sources.popularity) AS popularity_count
FROM (SELECT songs.*,COUNT(DISTINCT(listens.id)) AS listens_count FROM "songs" LEFT JOIN listens ON listens.song_id = songs.id GROUP BY songs.id) AS songs
LEFT JOIN sources ON
    sources.resource_id = songs.id
    AND
    sources.resource_type = 'Song'
GROUP BY songs.id
ORDER BY listens_count DESC, popularity_count DESC

This is from Artist.top:
SELECT
    artists.*,
    artists.listens_count,
    SUM(sources.popularity) AS popularity_count
FROM (SELECT artists.*,COUNT(DISTINCT(listens.id)) AS listens_count FROM "artists" INNER JOIN "artists_songs" ON "artists_songs"."artist_id" = "artists"."id" INNER JOIN "songs" ON "songs"."id" = "artists_songs"."song_id" LEFT JOIN listens ON listens.song_id = songs.id GROUP BY artists.id) AS artists
LEFT JOIN sources ON
    sources.resource_id = artists.id
    AND
    sources.resource_type = 'Artist'
GROUP BY artists.id
ORDER BY listens_count DESC, popularity_count DESC

A: So I found the answer, turns out I had completely missed the from method. I'll post the final method here just in case anyone else is as blind as me:
def top(options = {})
    tname = self.name.tableize

    inner_select = self.select("#{tname}.*,COUNT(DISTINCT(listens.id)) AS listens_count").
        joins("LEFT JOIN listens ON listens.song_id = songs.id").
        group("#{tname}.id")

    inner_select = inner_select.joins(:songs) unless self.name == 'Song'
    inner_select = inner_select.where("listens.user_id = ?", options[:for].id) if options[:for].is_a? User

    inner_select = "(#{inner_select.to_sql}) as #{tname}"

    select("#{tname}.*,#{tname}.listens_count,SUM(sources.popularity) AS popularity_count").
        from(inner_select).
        joins("LEFT JOIN sources ON sources.resource_id = #{tname}.id AND sources.resource_type = '#{self.name}'").
        group("#{tname}.id").
        order("listens_count DESC, popularity_count DESC")
end


text:
Q: return updated innerHTML after updating record In a php file I return some records of a table in a grid like stack of divs (var divid in the funcion below) each one corresponding in a record indexed by id (tdid in the funcion below). The database is in SQLserver.
To edit a particular record I invoke as innerHTML the contents of an orderedit.php file which contains a form (var formid in the function below).
Then with the function below I execute the update and replace the innerHTML of the div with the contents of an orderselect.php which returns a select of this particular record.
It executes all well except that some times the select returns the record updated but other times it returns the updated record as it was before the update. (It is updated, checked)
How can I ensure that the orderselect.php is returned as innerHTML  AFTER the update of the record?
function kataxorisi(tdid){
    var formid = 'form'+tdid;
    document.getElementById(formid).submit();
    // Here some intervention needed
    var divid = 'div'+tdid;
    cdiv = document.getElementById(divid);
    cdiv.innerHTML="<img src='loaderIcon.gif'>";
    if(XMLHttpRequest) var x = new XMLHttpRequest();
    else var x = new ActiveXObject("Microsoft.XMLHTTP");
    x.open("GET", "orderselect.php?gid="+tdid, true);
    x.send();
    x.onreadystatechange = function(){
        if(x.readyState == 4){
            if(x.status == 200) cdiv.innerHTML = x.responseText;
            else cdiv.innerHTML = "Error loading document";
        }
    }
}

A: I have inserted a small delay in the orderselect.php before the execution of the select query.
usleep(50000);

This is independent and does not ensure that the form submission and the record updating has occurred before the select but in a practical way it works.
Still open for better ideas.


text:
Q: demo.html inside a Component Is there a best practice for setting up a demo.html for a component? My component uses bootstrap for styling. Should I use the CDN in demo.html? That way I can ensure that the right styles are available if someone downloads the component via github and wants to take a look at it.

A: Most of the elements I've seen follow the element-boilerplate idea, which is include an index.html for demo purpose and host your project in the gh-pages branch on GitHub (that way you get a live demo right away).
See: https://github.com/webcomponents/element-boilerplate/blob/gh-pages/index.html


text:
Q: Looking for a startswith equivalent for integers in panda I have an integer column. all rows have 9 digits, the first either starts with 5 or 7. i am trying to filter for ones that only start with 7. is there a .str.startswith equivalent for integer dtypes? or do i need to convert to string and back to integer?
df["Case #"].str.startswith(7)

A: If they're all 9 digits, you can just use numeric comparisons:
(df["Case #"].between(700000000, 799999999)
 |  df["Case #"].between(500000000, 599999999))

A: Many ways to skin a cat here:
# fake
np.random.seed([3, 14])
s = pd.Series((np.random.choice(8, 10) + 1) * 1e8, name='Case', dtype='int')
s

0    100000000
1    800000000
2    500000000
3    200000000
4    800000000
5    500000000
6    400000000
7    500000000
8    600000000
9    700000000
Name: Case, dtype: int64

Using arithmetic with isin check, since all numbers have the same digits:
# (df['case'] // 1e8).astype(int).isin([5, 7])
(s // 1e8).astype(int).isin([5, 7])

0    False
1    False
2     True
3    False
4    False
5     True
6    False
7     True
8    False
9     True
Name: Case, dtype: bool

This is much slower. Convert to string and check the first digit.
# Here, comparison is with strings, not integers.
s.astype(str).str[0].isin(['5', '7'])

0    False
1    False
2     True
3    False
4    False
5     True
6    False
7     True
8    False
9     True
Name: Case, dtype: bool

Reminder: much, much, slower.

A: Just do this:
df = df[(df["Case #"].astype(str).str.startswith('7')) | (df["Case #"].astype(str).str.startswith('5'))]

or
df = df[df["Case #"].astype(str).str.contains(r'^7|^5')]


text:
Q: ajax not sending request to php for processing I am new to programming and after a zillion hours working on this I am not getting any closer to a solution. Any help would be greatly appreciated.
I have a form that I am sending to php via ajax(although I don't see /process.php in the address bar after the domain name, or does that even matter?). The confirmation from php does load on the page but the email with the form values does not get sent. I work very hard at this, and I really do believe I'll get this stuff, but right now I am in need a little help. A live version can be viewed at http://www.hydrodyneh2o.com.
Thanks in advance.
   $(document).ready(function(){

//Script for "Submit" button to submit and load 'submission confirmation'

    $('#hydrodyne-form input[type="submit"]').click(function(e){
        e.preventDefault();

        //alert("never!");
        $('#hydrodyne-form .warn').remove();
        var fields = $('#hydrodyne-form').serializeArray();

        $.ajax({
            type : 'POST',
            url : 'processForm.php',
            data : fields,
            dataType : 'json',
            success: function(data) {
                if (data.error) {
                    $.each(data.fields, function(k, v) {
                        $('.' + k).append('' + v + '');
                        $('.warn').fadeIn(700);
                    });
                } else {
                    $('#form-content').fadeOut(700, function() {
                        $(this).hide();

                        $('#form-content').addClass('processing').html('Processing...').fadeIn(400);
                        $('#form-content').delay(1300).fadeOut(700).hide(function(){
                            $(this).removeClass('processing').html(data.confirm).fadeIn(400);
                        });
                    });
                }
            },
            error: function(data) {
                $('#form-content').hide().html('
*Error occurred
').fadeIn(700);
                }
        });

            return false;

    });

});

PHP (processForm.php):
<?php

    $service = $_POST['service'];
    $service_type = implode(",\r\n• ",$service);

    if ($_POST) {

        $expected_inputs = array('company', 'contact_name', 'phone_number', 'email');
        $validation = array(
            'company' => 'Company Name Required',
            'contact_name'  => 'Contact Name Required',
            'phone_number' => 'Phone Number Required',
            'email' => 'Email Address Required'
        );

        $company = stripslashes($_POST['company']);
        $contact_name = stripslashes($_POST['contact_name']);
        $phone_number = stripslashes($_POST['phone_number']);
        $email = stripslashes($_POST['email']);
        $project_summary = stripslashes($_POST['project_summary']);

        $to = 'brian@bseifert.com';
        $subject = 'You\'ve got a Website Inquiry!';
        $message = "\r\n Contact Name:  " . $contact_name .
        $message = "\r\n\r\n Company:  " . $company .
        $message = "\r\n\r\n Phone Number:  " . $phone_number .
        $message = "\r\n\r\n Email Address:  " . $email .
        $message = "\r\n\r\n\r\n Type of Anticipated Service: \r\n\r\n " . $service_type .
        $message = "\r\n\r\n\r\n Message: \r\n\r\n" . $project_summary;
        $message = wordwrap($message, 80);

        $errors = array();
        $output = array();

        foreach($expected_inputs as $key) {

            if (array_key_exists($key, $_POST)) {
                if (empty($_POST[$key])) {
                    $errors[$key] = $validation[$key];
                } else {
                    $output[$key] = $_POST[$key];
                }
            } else {
                $errors[$key] = $validation[$key];
            }

        }

        if (!empty($errors)) {
            $array = array('error' => true, 'fields' => $errors);
        } else {

            // PROCESS FORM
            mail($to, $subject, $message) or die('not working!!!');

            $confirm =
                '

Your message has been sent.
 A representative from Hydrodyne will contact you
 as soon as possible.

';
            $array = array('error' => false, 'confirm' => $confirm);
        }

        echo json_encode($array);

    }

?>

HTML:

ydrodyne thanks you for stopping by, and asks that you use the form below
to ask any questions or place a request. We look forward to hearing from you!

                        <form id="hydrodyne-form" action="processForm.php" method="post">

Fields marked with an asterisk (*) are required.

* Company

                                        <input type="text" name="company"

* Contact Name

                                        <input type="text" name="contact_name"

* Phone Number

                                        <input type="text" name="phone_number"

* Email Address

                                        <input type="text" name="email"

Please check anticipated service(s)

                                        <input type="checkbox" name="service[]" value="Wastewater Flushing / Laundry">   Wastewater Flushing / Laundry

                                        <input type="checkbox" name="service[]" value="Irrigation">   Irrigation

                                        <input type="checkbox" name="service[]" value="Vehicle Washing">   Vehicle Washing

                                        <input type="checkbox" name="service[]" value="Animal Feeding">   Animal Feeding

                                        <input type="checkbox" name="service[]" value="Commercial / Industrial Cooling">   Commercial / Industrial Cooling

                                        <input type="checkbox" name="service[]" value="Commercial / Industrial Processing">   Commercial / Industrial Processing

                                        <input type="checkbox" name="service[]" value="Fire Suppression">   Fire Suppression

Provide Hydrodyne with more information by typing a brief message in the box below.

                                <textarea name="project_summary"></textarea>
                                <input type="submit" value="">

                        </form>

A: According to the pHp documentation: http://php.net/manual/en/function.mail.php#example-3381
you can add a header to the mail();
$headers = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

// PROCESS FORM
mail($to, $subject, $message, $headers) or die('not working!!!');

Also you should check the following line as I guess there is a invalid character which can create any unwanted pHp Warnings/errors;
$service_type = implode(",\r\n• ",$service);

it should be:
$service_type = implode(",\r\n",$service);

A: Thank you Nouphal.M! Man, I spent a lot of time searching for a solution when all I needed to do was check my spam. I really appreciate your time and efforts everyone!


text:
Q: Get the SAML Assertion from Identity Provider for other Service Provider My front-end application "App1", acts as a SAML Service Provider (SP). ADFS is my Identity Provider (IdP).
App1 internally uses a "backend connection" to third party system say "App2".
Note that this "App2" is another SP to the same ADFS IdP.
When user logs on to App1 from the browser (via ADFS), the "backend" connection to the App2 should work seamlessly (in SSO manner).
My plan is to pass the SAML assertion to App2 through the backend call. I am expecting App2 will decrypt/verify this assertion and returns the connection.
My Question is - Is there any way I can get SAML Assertion in App1 for App2 from the common IdP they are using?


text:
Q: How can I replace "true" and "false" in java? I need change the values for boolean variables, for example:
Change this:
boolean x = true;
System.out.print(x); //console: true

For this:
boolean x = true;
System.out.print(x); //console: 1

This is my code:
final boolean[] BOOLEAN_VALUES = new boolean [] {true,false};
for (boolean a : BOOLEAN_VALUES) {
                boolean x = negation(a);
                String chain = a+"\t"+x;
                chain.replaceAll("true", "1").replaceAll("false","0");
                System.out.println(chain);
        }

negation is a method:

    public static boolean negation(boolean a){
            return !a;
        }

As you can see, I try using .replaceAll, but its not working, when I executed, this is the output:

    a ¬a
----------------
true  false
false true

I really don't see my error.

A: System.out.println(x ? 1 : 0); should do the trick , basically 1 if true, and 0 otherwise

A: There are 2 ways:
The if-else one, which checks if x is true or false.
if (x) {
    System.out.println(1);
} else {
    System.out.println(0);
}

Note: if (x) is the same as if (x == true).
The ternary one:
System.out.println(x ? 1 : 0);

Which checks if x is true if so, it prints 1 else it prints 0. I recommend the ternary one as it's shorter and helps for code clarity.

A: Now i found the solution, i just missed matching the variable:
chain = chain.replaceAll("true", "1").replaceAll("false","0");

Now this is solved, thanks for your answers.


text:
Q: Alter a trigger is it a DDL statement The following query:
Alter trigger myTrigger disable

is it a DDL statement?
I found in oracle documentation: http://docs.oracle.com/cd/B12037_01/server.101/b10759/statements_1001.htm
The DDL statements are:
ALTER ... (All statements beginning with ALTER)
...

A: SQL has formed by two branches:

*

*Branch DDL: Data Definition Language.

*Branch DML: Data Manipulating Language.

The first branch works on creation of all structures about a database, the second works on contents in the structure.
I find this article of MSDN about Sql Server where you'll find all DDL operations.
And this for Oracle
And this for MySql
There are other branches as DCL, TCL but the traditionals are DDL and DML.
I hope this accomplish your question.


text:
Q: How can I get rid of the scientific notation when selecting big number on Oracle Database? I need to import a big number to another table using queries, but it always shows with scientific notation. It has to be a number because sorting is necessary and it does not work with char.
I tried all kinds of casting, it changes the number of decimal places but still shows as scientific notation.
SELECT
    CAST(PO_SID AS decimal(38,0)) AS PO_SID,
FROM CMS.PO_V'

When using

  to_number(replace(PO_V.PO_SID,' ',''),
    '9.99999999999999999999EEEE'),

it outputs:
Erro de SQL: ORA-01722: invalid number
01722. 00000 -  "invalid number"


text:
Q: Search (big) file via regex in C++ I am searching a lot of files for a number of strings and some files are too big to put in memory. I tried loading chunks of 10kB or so and it worked, but what if the string I am looking for has been split - half of it in this chunk, the other half in the other? My pattern would never match. Is there any way to fix this?

A: If programming the solution in C++ is not a hard constraint, try find and grep
find . -type f -name "*.txt" -size +4096k -exec grep "whale" {} +

*

*type f only search files

*name only files ending with extension txt

*size only files greater than 4096kb

*replace "whale" with the desired regular expression.

A: Don't just run your regex on chunks. You don't say which library you're using, but you want a library that you can stream the data to. The standard C++11 regex library apparently requires a bidirectional iterator as mentioned on C++ regular expression over a stream
However libsregex claims to offer a non-backtracking implementation, and has an API that you can call with each chunk, keeping the state from the previous chunk, allowing matches that span many chunks.

A: Not portable, but load your file as a memory-mapped file. The target sequence for C++ regex'es can be an iterator pair, so you don't need to copy that file to a std::string. You therefore don't need to load the whole file in RAM at once.
Of course, if you have a really bad input, the backtracking might be horrible, but that is pretty much unavoidable. If your pattern is ab*c and you have 4GB worth of b followed by a d, then yes you'll have to backtrack all the way back to that first a. And your regex implementation might not be smart enough to notice that b* doesn't contain a.


text:
Q: Good all character combinations using a given length Is there a program/tool/utility that would allow me to generate all possible character combinations (lowercase, uppercase, symbols, numbers) over a given length of characters (min-max)?

A: This is essentially the same field as brute-force password cracking, which might be what you are trying to achieve.  Wikipedia has a reasonable article on password cracking, and lists the most popular software for the task.

A: If you don't need a code, just strong passwords you can try to use some services:
http://onlinepasswordgenerator.net
http://h4sher.net
techzoom.net/tools/password-generator.en

A: Online:

*

*Javascript Permutation Generator

*Permutation of strings
Desktop:

*

*Free Password Generator. It's a password generator tool but you are able to

*

*fix the length

*choose to include letters/digits/catpital letters
alt text http://free-random-password-generator.free-random-password-generator-com.qarchive.org/mainscreen350.png


text:
Q: Isolated positive derivative
Is it possible that a function $f:\mathbb R\to\mathbb R$ satisfies $f'(p)>0$ for some $p$ but for all $x\in\mathbb R\setminus\{p\}$, $f'(x)\le0$?

I made this question up myself, knowing basic calculus, and thought about it for a while, but couldn't come up with anything. Nevertheless I think it's an interesting problem.

A: If there is such a function, by the mean-value theorem, $f'(p)=\lim_{x\rightarrow p}\frac{f(x)-f(p)}{x-p}\leq 0$. This contradicts $f'(p)>0$.

A: Let $x \ne p$. By the mean value theorem there is $t_x$ between $x$ and $p$ such that $t_x \ne x , t_x \ne p$ and
$$\frac{f(x)-f(p)}{x-p}= f'(t_x).$$
Since $t \ne x $ we get
$$\frac{f(x)-f(p)}{x-p} \le 0.$$
hence
$$\lim_{x\rightarrow p}\frac{f(x)-f(p)}{x-p}\leq 0,$$
It follows that $f'(p) \le 0.$ A contradiction.

A: If $f'$ is continuous, then obviously not, that's basic calculus.
If you are willing to use distributions, you'll have to work on what $f'(p)>0$ means, but then you can indeed provide an example, use the Heaviside function and $p=0$.


text:
Q: How to set backgroud color to BoxLayout in kivy? I have BoxLayout in kivy
root = BoxLayout(
 orientation = "horizontal",
 padding = 1,
 background_color = [0, 1, 0, 1]
)

Unfortunately, the BoxLayout has a horrible background (default)
How can I set a custom background color for the BoxLayout?

A: Doing this you will get a TypeError as the class BoxLayout has no background_color property.
In kivy you are reasonably free to create your own widget graphical representation. For that you have to create a subclass inheriting from BoxLayout with the desired property.
Below is a sample example implemented with kivy lang, but you can do that in python also with some binding (that will be a little bit verbose).
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ColorProperty
from kivy.uix.boxlayout import BoxLayout

Builder.load_string(
"""

<CustomRoot>:
    canvas:
        Color:
            rgba: root.background_color
        Rectangle:
            pos: self.pos
            size: self.size

""")

class CustomRoot(BoxLayout):
    background_color = ColorProperty() # The ListProperty will also work.

class MyApp(App):

    def build(self):
        return CustomRoot(background_color = (1, 0, 1, 1))

MyApp().run()

For more have a look at kivy documentation.


text:
Q: optimising problem - least mean square error I've got to solve an optimisation problem and don't know how to approach this (I'm thinking of writing a script to solve the problem recursively but wonder if there's another approach).
The target is given by $n$ real numbers, e. g. $a_{1t} = 10$, $a_{2t} = 20$, $a_{3t}=30$.
I've got the current value of the $n$ numbers, e. g. $a_{11}=1$, $a_{21}=1$, $a_{31}=5$.
I can change these numbers as follows:
$a_{12} = a_{11} + \eta · \mu_1 $
$a_{22} = a_{21} + \eta · \mu_2 $
$a_{32} = a_{31} + \eta · \mu_3 $
I need to find $\eta$ so that the mean square root between the two sequences is minimal when changing the $n$ numbers according to this rules where $\mu_1$, $\mu_2$ and $\mu_3$ are fixed factors (e. g. $1$, $2$ and $3$).

A: You are given a vector $a \in \mathbb R^n$, a direction $v \in \mathbb R_n \backslash \{ 0 \}$, and a point $p \in \mathbb R^n$. Write
$$
(p-a) = \left( \frac{(p-a) \cdot v}{v \cdot v} \right) v  + \left( (p-a) - \left( \frac{(p-a) \cdot v}{v \cdot v} \right) v \right).
$$
The two vectors in the sum are orthogonal, the factor $\eta$ you are looking for is $\left( \frac{(p-a) \cdot v }{v \cdot v} \right)$ and the norm of the vector on the right of the sum is the minimal distance you can acheive.
All of this is elementary linear algebra : I projected the vector $p-a$ along the line passing through $a$ in the direction of $v \neq 0$, and the scaling factor of the length of $v$ versus the length of the projection is the factor $\eta$. If you compute $p-a$ minus the projection vector you get the vector that starts at the minimal point on the line and goes to the point, so computing its norm gives you the minimal distance.
Hope that helps,


text:
Q: How to override inline-Style Background-Images (PHP) with a class to get them to load lazy I wonder if it's possible to get my background-images to load lazy. I used the Intersection Observer to set the background-image to: none, but because they have to be inline style (because of the PHP) the style is not overwritten. Any ideas?
<div style="background-image: url(images/<?php echo $dsatz["Vorname_Vorname_Nachname"]; ?>1.jpg);
  background-image: -webkit-image-set(
    url(images/<?php echo $dsatz["Vorname_Vorname_Nachname"]; ?>1_small.jpg) 1x,
    url(images/<?php echo $dsatz["Vorname_Vorname_Nachname"]; ?>1_medium.jpg) 2x);

    background-image: -moz-image-set(
    url(images/<?php echo $dsatz["Vorname_Vorname_Nachname"]; ?>1_small.jpg) 1x,
    url(images/<?php echo $dsatz["Vorname_Vorname_Nachname"]; ?>1_medium.jpg) 2x);
    background-image: -o-image-set(
    url(images/<?php echo $dsatz["Vorname_Vorname_Nachname"]; ?>1_small.jpg) 1x,
    url(images/<?php echo $dsatz["Vorname_Vorname_Nachname"]; ?>1_medium.jpg) 2x);
    background-image: -ms-image-set(
    url(images/<?php echo $dsatz["Vorname_Vorname_Nachname"]; ?>1_small.jpg) 1x,
    url(images/<?php echo $dsatz["Vorname_Vorname_Nachname"]; ?>1_medium.jpg) 2x);

  background-image: image-set(
    url(images/<?php echo $dsatz["Vorname_Vorname_Nachname"]; ?>1_small.jpg) 1x,
    url(images/<?php echo $dsatz["Vorname_Vorname_Nachname"]; ?>1_medium.jpg) 2x);" class="bg lazy" >

Intersection observer script is working (class is toggling) but the inline style is not overwritten by the lazy class
 <script type="text/javascript">
     let lazyloadImages = document.querySelectorAll(".lazy");
  if ("IntersectionObserver" in window) {
    let imageObserver = new IntersectionObserver (function (entries, observer) {
      entries.forEach (function (entry) {
        if (entry.isIntersecting) {
          const image = entry.target;
          image.classList.remove ("lazy");
          imageObserver.unobserve (image);
        }
      });
    });
   lazyloadImages.forEach (function (image) {
    imageObserver.observe (image);
  });
}
 </script>


text:
Q: show the map using mapview include multibyte character in data.frame I want to show the data using mapview  package.
but include multibyte character, sometime cannot show the map.
What would be the best thing to show the map?
library(mapview)
data(atlStorms2005)
test1 <- test2 <- atlStorms2005

test1@data$test <- as.factor(c("日本語", "てすと"))
test2@data$test <- as.factor(c("日本語", "五十嵐"))

mapview(test1)   # can show the map
mapview(test2)    # cannot show

re.data.frame <- function(data, encoding = "UTF-8", fileEncoding="UTF-8"){
  write.csv(data, file("tmp.csv", encoding = encoding), row.names = F, fileEncoding=fileEncoding)
  tmp <- readr::read_csv("tmp.csv",  col_types = cols())
  return(tmp)
}

test2@data <- re.data.frame(test2@data)
mapview(test2) # can show

but,the  popup in test colum character is corrupted text.

data is correct.
head(test2@data)

# A tibble: 6 × 4
Name MaxWind MinPress   test
<chr>   <int>    <int>  <chr>
  1  ALPHA      45      998 日本語
2 ARLENE      60      989 五十嵐
3   BRET      35     1002 日本語
4  CINDY      65      991 五十嵐
5  DELTA      60      980 日本語
6 DENNIS     130      930 五十嵐

A: As of commit bc2c57f, this should have been fixed. Until the next CRAN release of mapview, simply use the development version (devtools::install_github("environmentalinformatics-marburg/mapview", ref = "develop")) to solve this issue.
In brief, this behavior was related to our Rcpp routines which run under the hood in order to ensure a computationally efficient creation of popup tables. Here, the user's native encoding was used instead of UTF-8 to create JSON output files, resulting in corrupted text output on some machines where UTF-8 was not the default.


text:
Q: Why dataframe looping is not working with columns I have a dataframe named as df_tag. To preprocess the data, I go through the dataframe column wise in a for loop. In the else case, I have a String column, that first transforms the strings to lower case (#lower) and second applies a lambda function with regex (#punctuation). Problem is that in a for-loop the punctuation-part does not work:
for col in df_tag.columns:
    if df_tag[col].dtypes == "int64":
        new_data[col]=df_tag[col]
    else:
        #lower
        new_data[col] = df_tag[col].str.lower()
        #punctuation
        new_data[col] = df_tag[col].apply(lambda x : " ".join(re.findall('[\w]+',x)))

But when I apply the punctuation-part without the for-loop it works fine. Here is an example where I apply this on the explicitly called column 'Name':
new_data['Name'] = df_tag['Name'].apply(lambda x : " ".join(re.findall('[\w]+',x)))

Can anyone give me the good way for looping with columns.

A: In your for-loop solution you are replacing your lower-part with punctuation-part in new_data[col]
Will give you an example how to make your code work:
import pandas as pd
import re

data = {'Col1':list(range(1,5)),'Col2': list(range(6,10)),'Col3': ['a=b~c','B-C-D','c?d?e','D.E,F'] }
df_tag = pd.DataFrame(data, columns=data.keys())
print(df_tag)
#   Col1  Col2   Col3
#0     1     6  a=b~c
#1     2     7  B-C-D
#2     3     8  c?d?e
#3     4     9  D.E,F

new_data = pd.DataFrame().reindex_like(df_tag)
for col in df_tag.columns:
    if df_tag[col].dtypes == "int64":
        new_data[col]=df_tag[col]
    else:
        #lower & punctuation
        new_data[col] = df_tag[col].str.lower().apply(lambda x : " ".join(re.findall('[\w]+',x)))

and print of result will look like this
print(new_data)
#   Col1  Col2   Col3
#0     1     6  a b c
#1     2     7  b c d
#2     3     8  c d e
#3     4     9  d e f


text:
Q: Executing a hover function based on the class of the body in jQuery I have a hover function that shows text on hover over certain links and it works fine. However, I am trying to execute this function only if the body does not have the class user-is-touching. Is this possible at all and if so how do I go about it?

$(".o-c").hover(function() {
  $('.home-o-c').show();
  $('.home-i-t').hide();
}, function() {
  $('.home-o-c').hide();
  $('.home-i-t').show();
});

$(".c-f").hover(function() {
  $('.home-c-f').show();
  $('.home-i-t').hide();
}, function() {
  $('.home-c-f').hide();
  $('.home-i-t').show();
});

$(".i-c").hover(function() {
  $('.home-i-c').show();
  $('.home-i-t').hide();
}, function() {
  $('.home-i-c').hide();
  $('.home-i-t').show();
});

$(".c-u").hover(function() {
  $('.home-c-u').show();
  $('.home-i-t').hide();
}, function() {
  $('.home-c-u').hide();
  $('.home-i-t').show();
});

window.addEventListener('touchstart', function onFirstTouch() {
  // we could use a class
  document.body.classList.add('user-is-touching');

  // or set some global variable
  window.USER_IS_TOUCHING = true;

  // or set your app's state however you normally would

  // we only need to know once that a human touched the screen, so we can stop listening now
  window.removeEventListener('touchstart', onFirstTouch, false);
}, false);

$(".o-c").click(function() {
  if ($('body').hasClass('user-is-touching')) {
    $('.home-o-c').show();

  } else {
    $('html, body').animate({
      scrollTop: $(".our-company").offset().top
    }, 2000);

  }
});

$(".c-f").click(function() {
  if ($('body').hasClass('user-is-touching')) {
    $('.home-c-f').show();
    $('.home-o-c').hide();
    $('.home-i-c').hide();
    $('.home-c-u').hide();
    $('.home-i-t').hide();

  } else {
    $('html, body').animate({
      scrollTop: $(".cf2").offset().top
    }, 2000);

  }
});
.left-fill {
  background: #0000006b;
  height: 100vh;
}

.right-fill {
  background: pink;
  height: 100vh;
}

.vc_col-sm-6 {
  width: 50%;
  float: left;
}

.pivot-nav {
  list-style: none;
  font-family: 'Montserrat';
  text-align: left;
}

.pivot-nav li a {
  font-size: 1.6rem;
  font-weight: 700;
  text-transform: uppercase;
  display: inline-block;
  position: relative;
  color: #fff;
  text-decoration: none;
  line-height: 40px;
}

.pivot-nav li a.default-underline::after,
.pivot-nav li a:hover::after {
  width: 100%;
}

.pivot-nav:hover a.default-underline:not(:hover)::after {
  width: 0;
}

.pivot-nav li a::after {
  bottom: 0;
  content: "";
  display: block;
  height: 4px;
  position: absolute;
  background: #fff;
  transition: width 0.3s ease 0s;
  width: 0;
}

.home-o-c,
.home-c-f,
.home-i-c,
.home-c-u {
  display: none;
}

.our-company {
  clear: both;
  display: block;
  height: 50vh;
}

.cf2 {
  clear: both;
  display: block;
  height: 50vh;
}

TEXT One

TEXT One

TExt for C f.

Some more text fo i c.

Get in touch

O C

C F

I C

C U

    Our Company Scroll Down

    cf2 Scroll Down

A: You can use more complex selectors
$('body:not(.user-is-touching) .c-u')

Or you could add "IF" statement inside handlers
etc:
if(!$('body').hasClass('user-is-touching')) { /* do stuff */ }

A: You can unbind events when you are adding user-is-touching class to body.
example
$(".c-f").unbind('mouseenter').unbind('mouseleave')

OR
$(".c-f").off('mouseenter').off('mouseleave')

Update
Refer this snippet
// Replace this event listener with your hover listeners

window.addEventListener('touchstart', function onFirstTouch() {
  // we could use a class
  document.body.classList.add('user-is-touching');

  // or set some global variable
  window.USER_IS_TOUCHING = true;

  // or set your app's state however you normally would

  // Remove mouse-related events here

   $(".o-c, .c-f, .i-c, .c-u").unbind('mouseenter').unbind('mouseleave')

  // we only need to know once that a human touched the screen, so we can stop listening now
  window.removeEventListener('touchstart', onFirstTouch, false);
}, false);

You need to update your html code to have data-attr property update code below

O C

C F

I C

C U


text:
Q: JavaFx: fxmlLoader.load returns Parent? I have ScrollPane at root level in fxml file and I have the following code:
import javafx.scene.Parent;
...
parent = (Parent)fxmlLoader.load(getFxmlStream("my.fxml"));
if (parent.getClass().isAssignableFrom(Parent.class)){
    System.out.println("THIS IS PARENT");
}else{
    System.out.println("THIS IS NOT PARENT");//THIS WILL BE PRINTEED
}

Why what load function returns is not assignable from Parent class?

A: From the Javadocs for isAssignableFrom:

Determines if the class or interface represented by this Class object
  is either the same as, or is a superclass or superinterface of, the
  class or interface represented by the specified Class parameter.

So you are testing if the runtime type of the object you got from the FXML loader is equal to, or a superclass of, Parent. If it is a strict subclass of Parent (VBox, BorderPane etc), then this will be false.
If you want to test if the value you have is some kind of Parent, the usual way to do that is with instanceof:
if (parent instanceof Parent)){
    System.out.println("THIS IS PARENT");
}else{
    System.out.println("THIS IS NOT PARENT");//THIS WILL BE PRINTEED
}

If you want to use getClass() and isAssignableFrom(), then you have things the wrong way around:
if (Parent.class.isAssignableFrom(parent.getClass())){
    System.out.println("THIS IS PARENT");
}else{
    System.out.println("THIS IS NOT PARENT");//THIS WILL BE PRINTEED
}

though I recommend the standard instanceof approach anyway.
Also note that you can use FXML to pretty much load any object, so there is certainly no guarantee that what you get is a subclass of Parent.


text:
Q: Using a list to make a contour plot of multiple values I'm trying to make a contour plot for multiple values of the same function.
To accomplish that, I'm doing the following:

lst = Table[x^2 - y^2 == i, {i, -100, 100, 10} ]

ContourPlot[lst, {x,-10,10}, {y,-10,10}]

But it produces an empty plot (it's blank).
However, if I paste the contents of the list into the command, i.e.,
ContourPlot[
 {x^2 - y^2 == -100, x^2 - y^2 == -90, x^2 - y^2 == -80,
 x^2 - y^2 == -70, x^2 - y^2 == -60, x^2 - y^2 == -50,
 x^2 - y^2 == -40, x^2 - y^2 == -30, x^2 - y^2 == -20,
 x^2 - y^2 == -10, x^2 - y^2 == 0, x^2 - y^2 == 10, x^2 - y^2 == 20,
 x^2 - y^2 == 30, x^2 - y^2 == 40, x^2 - y^2 == 50, x^2 - y^2 == 60,
 x^2 - y^2 == 70, x^2 - y^2 == 80, x^2 - y^2 == 90, x^2 - y^2 == 100},
 {x, -10, 10}, {y, -10, 10}]

it works.
What's is the difference between using  lst, instead of the whole list within ContourPlot[].

A: You need to Evaluate the expression.
ContourPlot[Evaluate@lst, {x, -10, 10}, {y, -10, 10}]

A: We can use x^2 - y^2 as the first argument of ContourPlot with the option ContourShading -> None (as suggested by JM in comments) and get colored contours using the form  $\{\{level_1, style_1\},\ldots\}$ for setting the option Contours:
levels = Range[-100, 100, 10];
colors = ColorData[97] /@ Range[21];

contours = Transpose[{levels, colors}]

ContourPlot[x^2 - y^2, {x, -10, 10}, {y, -10, 10},
 Contours -> contours, BaseStyle -> Thick, ContourShading -> None]


text:
Q: How can i get index from map using hooks? i am using routers and hooks in my code,
So i have 2 components
"AddRoom"
"Homescreen"
Inside app i have addroom() arrow function, and hook called "rooms" that is sent to "AddRoom" component like so:
      <Router>
      <Switch>
       <Route exact path='/' component={() => { returnn <HomeScreen rooms={rooms} /> }} />
      <Route exact path='/AddRoom' component={() => { return <AddRoom add={addRoom} rooms={rooms} /> }} /
       </Switch>
      </Router>

The "addRoom" function:
      const [rooms, setRooms] = useState([]);

      const addRoom = (room, name, color) => {
    //I have tried to use here map to add index for array "rooms" it is not working//
        setRooms([...rooms, { room: room, name: name, color: color ,index:{index}}])}

I am trying to get index everytime i add a room to "rooms" array but it wont add it to my array i dont understand why, how can i do it?
And that is "AddRoom" component:
    import React, { Component, useState } from
    'react'
    import context from 'react-
    bootstrappp/esm/AccordionContext';
    import { render } from 'react-dom';
    import { useHistory } from "react-router-
    dom";

    export default function AddRoom(props) {

    const [room, setRoom] = useState()
    const [name, setName] = useState()
    const [color, setColor] = useState('black')
    const [showError, setShowError] = useState(false)
    const [index, setIndex] = useState([]);
    const history = useHistory();

    const validInput = () => {//input validation
        if ((name == null) || ((room == 'Choose') || (room == null))) {//no name typed and no room chosen
            debugger
            window.alert('Please choose a room and enter at least one character in room name');
            return true;//if alert pops up
        }
        else {
            if (name.length > 5) {
                return false;//name is too long
            }
        }

    }

    const AddClick = () => {
        let result = validInput();
        let path = '/';
        if (result == true)//no name was typed and room was not selected
        {
            debugger
            history.push(path);
        }
        else {
            if (name.length > 5) {//name is too long
                setShowError(true)
            }
            else//all fields are correct, go back to home screen with ner room
            {
                setShowError(false)
                /*  {props.rooms.map((element, i) => { */
                props.add(room , name , color /*(setIndex(...index, { index: i })) */);
            }
            )}
            history.push(path);
        }
    }

    return (

                    <select onChange={(element) => { setRoom(element.target.value) }} name="room" id="room">
                        <option value="Choose">Choose your room</option>
                        <option value="Livingroom">Livingroom</option>
                        <option value="Kitchen">Kitchen</option>
                        <option value="Bedroom">Bedroom</option>
                        <option value="Bathroom">Bathroom</option>
                    </select>

                    <input onChange={(element) => { setName(element.target.value) }} id="name" type="text" placeholder="Room Name"></input>

Room Name Is More Then 5 Character

                    <input onChange={(element) => { setColor(element.target.value) }} id="color" type="color" placeholder="Room Color"></input>

                    <button onClick={AddClick}>Create Room</button>

    )
}

before calling addRoom function:
rooms=[{}]

after calling function addRoom:
rooms=[{room:"Kitchen",name:"Kit",color:"red",index:0},{room:"Bathroom",name:"Bat",color:"green",index:1}...]

A: If I'm understanding your question correctly, you're trying to map your array of rooms and you'd like the index of each room in the array.
If all you want is to get the index of the room while you are map-ing the array, you can provide a second argument to the map function which will have the index passed to it.
rooms.map((room, index) => {
    // Do stuff...
});

Actually storing the index within the object is an anti-pattern since you have no way of guaranteeing that the stored index actually matches its index in the array. Any time you add or remove a room not at the end, you'd have to update all the rooms with their new indices. Plus, unless you're storing references to all of these rooms outside of the array, you have to have the index before you can access a room anyway.
But if that's still what you want to do, you can either:

*

*Store the index as you add the room

// Room is being added at the end, so its index must be rooms.length
setRooms([...rooms, { ...room, index: rooms.length }]);

*Update the indices after each addition

// This is basically the first part of my answer with extra steps
setRooms([...rooms, room].map((room, index) => ({ ...room, index: index })));


text:
Q: Invoking dotnet assembly method from C++ returns error COR_E_SAFEARRAYTYPEMISMATCH I am trying to load and execute a dotnet executable from a memory buffer inside my C++ program.
In order do this, I am trying to invoke the Main function of a dotnet assembly I have loaded inside my C++ project.
First I load the CRL runtime, gets loaded ok.
Then I load the dotnet.exe from a memory buffer, it gets loaded ok.
Then I would like to start it, by Invoking its Main function.
At that point, the Invoke_3 function returns COR_E_SAFEARRAYTYPEMISMATCH.
Which I don't understand why, since I retrieved the parameters using the GetParameters function, which fills the SAFEARRAY to pass to the Invoke function.
Anybody knows what is wrong in that parameters?
Thank you in advance!
// Up here we correctly load the CRL runtime

// Load up our dotnet file inside a std::string
string sFileData = FileToString("C:\\dotnet.exe");

// Copy our file data inside a SAFEARRAY
SAFEARRAYBOUND bounds = { sFileData.size(), 0 };
SAFEARRAY *pSA = SafeArrayCreate(VT_UI1, 1, &bounds);
void* data;
HRESULT hr = SafeArrayAccessData(pSA, &data);
CopyMemory(data, sFileData.c_str(), sFileData.size());
hr = SafeArrayUnaccessData(pSA);

if (pSA)
{
    // Load our managed assembly:
    _AssemblyPtr spAssembly = nullptr;
    hr = spAppDomain->Load_3(pSA, &spAssembly);

    // Get the entrypoint of the assembly, which should be the "Main" function
    _MethodInfoPtr entryp;
    hr = spAssembly->get_EntryPoint(&entryp);

    // Get the parameters of the entrypoint function and save them in a SAFEARRAY
    SAFEARRAY *pArrParams;
    hr = entryp->GetParameters(&pArrParams);

    // Call the entrypoint passing parameters in the SAFEARRAY.
    // Returns error COR_E_SAFEARRAYTYPEMISMATCH
    VARIANT retval;
    hr = entryp->Invoke_3(_variant_t(), pArrParams, &retval);
}

A: According to the framework source for SafeArrayTypeMismatchException (which maps to COR_E_SAFEARRAYTYPEMISMATCH):

This exception is thrown when the runtime type of an array is different than the safe array sub type specified in the metadata.

Hence I'm pretty sure this is the problem:
SafeArrayCreate(VT_UI1, 1, &bounds);

VT_UI1 is a 1-byte unsigned integer. But the standard Main() method in C# applications takes an array of 4-byte signed integers. These are different types, hence the error. So you'll need to change your code to this:
SafeArrayCreate(VT_I4, 1, &bounds);

A: VARIANT ret;
VARIANT obj;
SAFEARRAY *args = SafeArrayCreateVector(VT_VARIANT, 0, 1);

ZeroMemory(&ret, sizeof(VARIANT));
ZeroMemory(&obj, sizeof(VARIANT));
obj.vt = VT_NULL;

hr = entryp->Invoke_3(obj, args, &ret);

change the type from VT_UI1 to VT_VARIANT.


text:
Q: Recall book series with a young girl who can talk to animals (English with at least 4 books) I read this series about 9 years ago (2009-2010). I don't know when it was published. The series has at least 4 books. The only things I remember are:
1) The young girl (about 8-9 years old) is approached by a small rabbit(?) in a library to help it.
2) She crawls through a really small under-ground tunnel to get to the other side of a wall(?) into a forest where she finds she can talk to all animals.
They chose her because she was small enough to crawl through it. For some reason the "magic" which enables these animals to talk to certain humans is going away slowly.
3) She later finds out that her father is not really her father, but her Uncle.
I really do not recall anything else about it, so can't write any more here. The first two points I mentioned are all from the first book. The third one is from a later book.

A: This is likely The Land of Elyon series by Patrick Carman. There are four books and a prequel. As you remember, she is initially approached by a rabbit in the library in the first book, and in the third book, she learns who her real parents are.
Summary excerpt of the first book, The Dark Hills Divide:

12-year-old Alexa Daley is spending another summer in Bridewell with her father, the Mayor of Lathbury. The book starts by Alexa going on a walk through the streets of Bridewell with her adventurer friend Thomas Warvold. During the stroll, Warvold tells Alexa a fable that he heard on one of his far-off journeys. When the fable is finished, Alexa finds that Warvold is dead.

....

Later on, Alexa uses the silver key to open a passageway hidden behind her favorite nook. At the end of the passageway, outside the wall, Alexa is greeted by a short man named Yipes, who seems to have been waiting for her. Alexa follows Yipes up Mount Norwood and comes to a glowing pond. Inside the pond, she finds a green stone. Once she puts it in her leather pouch, Yipes takes her to his house. Waking up from her sleep, Alexa finds that she has the ability to talk to animals. Darius, a wolf separated from his family, leads her to a tunnel under the walled road between Lathbury and Bridewell. At the end of the tunnel, Alexa discovers that the convicts of Ainsworth inhabit The Dark Hills. Once she is back outside, a rabbit named Malcolm takes her to the forest king Ander, a grizzly bear. Ander tells Alexa that she can talk to animals as long as she has the green stone with her and is outside the walls. He also tells her that the convicts living in The Dark Hills are planning to attack and take over Bridewell. The leader of the convicts is someone the convicts call Sebastian, an escaped convict posing as a citizen of Bridewell. At the meeting, Alexa meets Murphy (Squirrel), Beaker (Raccoon), Henry (Badger), Picardy (Female Black Bear), Boone (Bobcat), Odessa (Darius's wife) and Sherwin (Darius's son).

Summary of the third book, The Tenth City:

Alexa goes back to Bridewell to rescue her friend Yipes with Warvold, Armon, and the rest of the animals. After the death of Thomas Warvold, the brother of Roland Warvold, Alexa learns that Catherine and Thomas were her parents and her foster parents are Catherine's sister Laura and her husband James Daley.

For the sake of further reference, my search terms were book series young girl can talk to animals.


text:
Q: No performance gain after using openMP on a program optimize for sequential running I have optimized as much as I could my function for sequential running.
When I use openMP I see no gain in performance.
I tried my program on a machine with 1 cores and on a machine with 8 cores, and the performance is the same.
With year set to 20, I have
1 core: 1 sec.
8 core: 1 sec.
With year set to 25 I have
1 core: 40 sec.
8 core: 40 sec.
1 core machine: my laptop's intel core 2 duo 1.8 GHz, ubuntu linux
8 core machine: 3.25 GHz, ubuntu linux
My program enumerate all the possible path of a binomial tree and do some work on each path. So my loop size increase exponentially and I would expect the footprint of openMP thread to be zero. In my loop, I only do a reduction of one variable. All other variable are read-only. I only use function I wrote, and I think they are thread safe.
I also run Valgrind cachegrind on my program. I don't fully understand the output but there seems to be no cache miss or false sharing.
I compile with
gcc -O3 -g3 -Wall -c -fmessage-length=0 -lm -fopenmp -ffast-math

My complete program is as below. Sorry for posting a lot of code. I'm not familiar with openMP nor C, and I couldn't resume my code more without loosing the main task.
How can I improve performance when I use openMP?
Are they some compiler flags or C tricks that will make the program run faster?
test.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#include "test.h"

int main(){

    printf("starting\n");
    int year=20;
    int tradingdate0=1;

    globalinit(year,tradingdate0);

    int i;
    float v=0;
    long n=pow(tradingdate0+1,year);
    #pragma omp parallel for reduction(+:v)
    for(i=0;i<n;i++)
        v+=pathvalue(i);

    globaldel();
    printf("finished\n");
    return 0;
}

//***function on which openMP is applied
float pathvalue(long pathindex) {
    float value = -ctx.firstpremium;
    float personalaccount = ctx.personalaccountat0;
    float account = ctx.firstpremium;
    int i;
    for (i = 0; i < ctx.year-1; i++) {
        value *= ctx.accumulationfactor;
        double index = getindex(i,pathindex);
        account = account * index;
        double death = fmaxf(account,ctx.guarantee[i]);
        value += qx(i) * death;
        if (haswithdraw(i)){
            double withdraw = personalaccount*ctx.allowed;
            value += px(i) * withdraw;
            personalaccount = fmaxf(personalaccount-withdraw,0);
            account = fmaxf(account-withdraw,0);
        }
    }

    //last year
    double index = getindex(ctx.year-1,pathindex);
    account = account * index;
    value+=fmaxf(account,ctx.guarantee[ctx.year-1]);

    return value * ctx.discountfactor;
}

int haswithdraw(int period){
    return 1;
}

float getindex(int period, long pathindex){
    int ndx = (pathindex/ctx.chunksize[period])%ctx.tradingdate;
    return ctx.stock[ndx];
}

float qx(int period){
    return 0;
}

float px(int period){
    return 1;
}

//****global
struct context ctx;

void globalinit(int year, int tradingdate0){
    ctx.year = year;
    ctx.tradingdate0 = tradingdate0;
    ctx.firstpremium = 1;
    ctx.riskfreerate = 0.06;
    ctx.volatility=0.25;
    ctx.personalaccountat0 = 1;
    ctx.allowed = 0.07;
    ctx.guaranteerate = 0.03;
    ctx.alpha=1;
    ctx.beta = 1;
    ctx.tradingdate=tradingdate0+1;
    ctx.discountfactor = exp(-ctx.riskfreerate * ctx.year);
    ctx.accumulationfactor = exp(ctx.riskfreerate);
    ctx.guaranteefactor = 1+ctx.guaranteerate;
    ctx.upmove=exp(ctx.volatility/sqrt(ctx.tradingdate0));
    ctx.downmove=1/ctx.upmove;

    ctx.stock=(float*)malloc(sizeof(float)*ctx.tradingdate);
    int i;
    for(i=0;i<ctx.tradingdate;i++)
        ctx.stock[i]=pow(ctx.upmove,ctx.tradingdate0-i)*pow(ctx.downmove,i);

    ctx.chunksize=(long*)malloc(sizeof(long)*ctx.year);
    for(i=0;i<year;i++)
        ctx.chunksize[i]=pow(ctx.tradingdate,ctx.year-i-1);

    ctx.guarantee=(float*)malloc(sizeof(float)*ctx.year);
    for(i=0;i<ctx.year;i++)
        ctx.guarantee[i]=ctx.beta*pow(ctx.guaranteefactor,i+1);
}

void globaldel(){
    free(ctx.stock);
    free(ctx.chunksize);
    free(ctx.guarantee);
}

test.h
float pathvalue(long pathindex);
int haswithdraw(int period);
float getindex(int period, long pathindex);
float qx(int period);
float px(int period);
//***global
struct context{
    int year;
    int tradingdate0;
    float firstpremium;
    float riskfreerate;
    float volatility;
    float personalaccountat0;
    float allowed;
    float guaranteerate;
    float alpha;
    float beta;
    int tradingdate;
    float discountfactor;
    float accumulationfactor;
    float guaranteefactor;
    float upmove;
    float downmove;
    float* stock;
    long* chunksize;
    float* guarantee;
};
struct context ctx;
void globalinit();
void globaldel();

EDIT I simplify all global variables as constant. For 20 year, the program run two time faster (great!). I tried to set the number of thread with OMP_NUM_THREADS=4 ./test for example. But it didn't give me any performance gain.
Can my gcc have some problem?
test.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <omp.h>
#include "test.h"

int main(){

    starttimer();
    printf("starting\n");
    int i;
    float v=0;

    #pragma omp parallel for reduction(+:v)
    for(i=0;i<numberofpath;i++)
        v+=pathvalue(i);

    printf("v:%f\nfinished\n",v);
    endtimer();
    return 0;
}

//function on which openMP is applied
float pathvalue(long pathindex) {
    float value = -firstpremium;
    float personalaccount = personalaccountat0;
    float account = firstpremium;
    int i;
    for (i = 0; i < year-1; i++) {
        value *= accumulationfactor;
        double index = getindex(i,pathindex);
        account = account * index;
        double death = fmaxf(account,guarantee[i]);
        value += death;
        double withdraw = personalaccount*allowed;
        value += withdraw;
        personalaccount = fmaxf(personalaccount-withdraw,0);
        account = fmaxf(account-withdraw,0);
    }

    //last year
    double index = getindex(year-1,pathindex);
    account = account * index;
    value+=fmaxf(account,guarantee[year-1]);

    return value * discountfactor;
}

float getindex(int period, long pathindex){
    int ndx = (pathindex/chunksize[period])%tradingdate;
    return stock[ndx];
}

//timing
clock_t begin;

void starttimer(){
    begin = clock();
}

void endtimer(){
    clock_t end = clock();
    double elapsed = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("\nelapsed: %f\n",elapsed);
}

test.h
float pathvalue(long pathindex);
int haswithdraw(int period);
float getindex(int period, long pathindex);
float qx(int period);
float px(int period);
//timing
void starttimer();
void endtimer();
//***constant
const int year= 20 ;
const int tradingdate0= 1 ;
const float firstpremium= 1 ;
const float riskfreerate= 0.06 ;
const float volatility= 0.25 ;
const float personalaccountat0= 1 ;
const float allowed= 0.07 ;
const float guaranteerate= 0.03 ;
const float alpha= 1 ;
const float beta= 1 ;
const int tradingdate= 2 ;
const int numberofpath= 1048576 ;
const float discountfactor= 0.301194211912 ;
const float accumulationfactor= 1.06183654655 ;
const float guaranteefactor= 1.03 ;
const float upmove= 1.28402541669 ;
const float downmove= 0.778800783071 ;
const float stock[2]={1.2840254166877414, 0.7788007830714049};
const long chunksize[20]={524288, 262144, 131072, 65536, 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1};
const float guarantee[20]={1.03, 1.0609, 1.092727, 1.1255088100000001, 1.1592740743, 1.1940522965290001, 1.2298738654248702, 1.2667700813876164, 1.304773183829245, 1.3439163793441222, 1.384233870724446, 1.4257608868461793, 1.4685337134515648, 1.512589724855112, 1.557967416600765, 1.6047064390987882, 1.6528476322717518, 1.7024330612399046, 1.7535060530771016, 1.8061112346694148};

A: Even if your program benefits from using OpenMP, you won't see it because you are measuring the wrong time.
clock() returns the total CPU time spent in all threads. If you run with four threads and each runs for 1/4 of the time, clock() will still return the same value since 4*(1/4) = 1. You should be measuring the wall-clock time instead.
Replace calls to clock() with omp_get_wtime() or gettimeofday(). They both provide high precision wall-clock timing.
P.S. Why are there so many people around SO using clock() for timing?

A: I don't see any section in which you're specifying the number of cores OpenMP will use.  It's supposed to, by default, use the number of CPUs it sees, but for my purposes, I've always forced it to use as many as I specified.
Add this line before your parallel for construct:
#pragma omp parallel num_threads(num_threads)
{
   // Your parallel for follows here
}

...where num_threads is an integer between 1 and the number of cores on your machine.
EDIT:  Here's the makefile used to build the code.  Place this in a text file named Makefile in the same directory.
test: test.c test.h
    cc -o $@ $< -O3 -g3 -fmessage-length=0 -lm -fopenmp -ffast-math

A: It seems as if it should work. Probably you need to specify the number of threads to use. You can do so by setting the OMP_NUM_THREADS variable. For instance, for using 4 threads:
OMP_NUM_THREADS=4 ./test

EDIT: I just compiled the code and I observe significant speedups when changing the number of threads.


text:
Q: Restoring Navicat backup files I have made the backup from Navicat files in following formats:
*.backup
*.nppb
*.ncx
How can I restore the tables?

A: If you created the backup under public/backups, This should work.
a. navigate to the DC/public and click the Backups button
b. Click the + add button
c. Under the Advanced tab to name the backup click user specified file checkbox name and write name
d. Then hit play looking button "Start"
e. Now this will show up in Backups
f. To Restore backup click the backup you want then the open button with folder picture.
Then hit start and everything will be reloaded.
Note: For some reason, to see data changes, you must right click in each to table to have them reload correctly.

A: *

*Create new DB

*Open it

*Then backup (see image)

*

*So you can pick up your tables (copy them to desired DB)


text:
Q: AWS, Shared subscription behaviour capability of AWS MQTT broker I'm exploring AWS IoT MQTT broker capabilities for my future use and I'm trying to figure out if AWS MQTT broker supports "shared subscriptions" functionality.
Shared subscriptions, relatively new functionality, introduced by IBM MessageSight. Represents "queue" or "p2p" behavior when multiple subscribers with same clientID can be connected/subscribed to the same topic and only one subscriber instance (load is balancing automatically) receives particular message. Against of pub/sub topic model, when all subscribers receive copies, this is very convenient to use in software architecture as we don't need to use one more "player" message queue to distribute load between parallel application instances.
In case if IoT, messages published by devices can be consumed by several application instances, working in parallel, to distribute load between them.

A: AWS IoT does not support Shared subscriptions but there is feature request. So we could expect it (soon).
https://forums.aws.amazon.com/thread.jspa?messageID=757689

A: Spent time on documentation and yes, unfortunately, AWS IoT MQTT does not support shared subscriptions at this point of time.


text:
Q: Raspberry Pi as a I²S slave I am using a raspberry pi 3B+ as a I²S signal generator (simple sine wave via python script). The plan is to receive the signal with a STM32L476RGT6 board. In my used configuration the raspberry has to be the slave.
Is there a way to configure the raspberry in I²S slave mode, so that:
Raspberry = Transmitter --> sending via SD
STM32L476RGT6 = Receiver --> receiving via SD and providing SCK and WS
?


text:
Q: Getting a struct from PostGres DB I followed a thread in here and came up with this
var b Button

queryErr := connection.QueryRow("SELECT id_printer, name, has_children FROM button WHERE id_parent IS NULL;").Scan(&b.ID, &b.Name, &b.Children)
if queryErr != nil {
    response, err := json.MarshalIndent(b, "", "  ")
    fmt.Fprint(w, string(response))
    if err != nil {
        log.Println("Error on jsonmarshalindent Starter")
    }
} else {
    log.Println("Error on queryErr  starter")
    log.Println(queryErr)

    fmt.Fprint(w, "Error getting starter button")
}

it has 2 problems:

*

*It breaks on b.Children

*I don't know how to make it dynamically. for instance, the query returns 3 rows, but it depends on the company's client, it can be 3 or any number.

the struct is
type Starter struct {
    Buttons []Button `json:buttons`
}

type Button struct {
    ID       int    `json:id`
    Name     string `json:name`
    Children bool   `json:children`
}

Can someone shed some light in this please?

A: For the bool, it depends on the type of the actual column.  If it isn't boolean, it won't map directly.
You may need to store in a temporary variable first and then translate and assign to the field in Button to match.
As for reading all rows, here's an example adapted from the docs.
You use Query instead of QueryRow to get all rows.
rows, err := db.Query("SELECT id_printer, name, has_children FROM button WHERE id_parent IS NULL;")
if err != nil {
        log.Fatal(err)
}
defer rows.Close()
var buttons []Button
for rows.Next() {
        var b Button
        if err := rows.Scan(&b.ID, &b.Name, &b.Children); err != nil {
                log.Fatal(err)
        }
        buttons = append(buttons,b)
}
// At this point, you have all your rows in the "buttons" variable