text:
Q: Understanding Decompiled Assembly Code I'm trying to understand this code from assembly,
int32_t phase_5(char * str) {
    int32_t v1 = 0;
    if (strlen(str) != 4) {
        // 0x8049153
        alert_henchmen(5);
        v1 = 0;
        // branch -> 0x80491a6
    }
    while (true) {
        int32_t * v2 = (int32_t *)(4 * v1 + (int32_t)&g2); // 0x8049192_0
        char * v3 = (char *)(v1 + (int32_t)str);
        int32_t v4 = 0;
        int32_t v5 = 0; // 0x01516
        // branch -> 0x8049175
        int32_t v6; // bp+014
        while (true) {
            char v7 = *(char *)(v4 + (int32_t)"4l6aiqhor20x"); // 0x8049188
            v6 = v5;
            if ((int32_t)*v3 == (int32_t)v7) {
                // 0x804918f
                v6 = *v2 == v4 ? 1 : v5;
                // branch -> 0x80491a2
            }
            int32_t v8 = v4 + 1; // 0x80491a2
            if (v8 >= 12) {
                // break -> 0x80491ac
                break;
            }
            v4 = v8;
            v5 = v6;
            // continue -> 0x8049175
        }
        // 0x80491ac
        if (v6 % 256 != 1) {
            // 0x80491b7
            alert_henchmen(5);
            // branch -> 0x80491c3
        }
        int32_t v9 = v1 + 1; // 0x80491c3
        if (v9 >= 4) {
            // break -> 0x80491cd
            break;
        }
        v1 = v9;
        // continue -> 0x80491a6
    }
    // 0x80491cd
    return confirm_phase(5, str);
}

and I'm just not sure what this line does:
int32_t * v2 = (int32_t *)(4 * v1 + (int32_t)&g2)

and also this line:
char v7 = *(char *)(v4 + (int32_t)"4l6aiqhor20x")

and what does int32_t mean?

A: I'm not exactly sure what your question is, but I will try to help in answer, by explaining that when a programmer writes something, there is a purpose to each line that he or she knows about - for example, if they want to write a message, they may call the variable "myMessage". This information is not included in the final result, though. So, a decompiler won't know to call it "myMessage", and will just assign a memory address (denoted by a & reference), or a random variable name (denoted by v's above). With some detailed examination, you can figure out what that part of the code does specifically, but without hints like "myMessage", you may have to process and map out the entire program before really understanding it.
So for the code line:
int32_t * v2 = (int32_t *)(4 * v1 + (int32_t)&g2)
You can only say that it takes 4, multiplies it by v1, and adds it to the address of variable g2. The result is a 32-bit address that is stored in v2. Because there's no reference here that says what g2 even is, then you may start to see the rationale in my answer. Since it's 32 bits (4 bytes), this could explain the multiplication by 4, and maybe v1 is a counter.

A: int32_t is one of the types defined in <stdint.h>; it is a 32-bit wide signed integer type with 2's complement representation and no padding bits.
The decompiler seems to take the shortest possible path, without actually understanding how to write idiomatic C code. The code itself might not even be valid C as I believe it might not conform to strict aliasing requirements of C.
Here, for example:
int32_t * v2 = (int32_t *)(4 * v1 + (int32_t)&g2); // 0x8049192_0

The value of the address of g2 is converted to an int32_t; then the value 4 * v1 is added to it; and the resulting integer is cast to a pointer to int32_t. This is a contrived way of writing
int32_t *v2 = ((int32_t *)&g2) + v1;

Or; if g2 is already declared as an array of int32_t, it is sufficient to write
int32_t *v2 = g2 + v1;

All in all, the code casts the address of g2 into a pointer to int32_t, and then assigns the pointer to v1th (0-based) int32_t in the array of consecutive int32_ts, first of which is the one at that pointer, into v2.
Again,
char v7 = *(char *)(v4 + (int32_t)"4l6aiqhor20x")

Is the straightforward - but non-portable code (it doesn't work in 64-bit processors!) for the code
char v7 = "4l6aiqhor20x"[v4];

i.e. the value of v4th character from the string "4l6aiqhor20x" is assigned to v7.


text:
Q: Spring Data Mongodb and CrudRepository save(): dropped fields from document if not in POJO model I'm using Spring Data Mongodb; yesterday I realized that, after calling standard Repository method save(...), it dropped some fields that weren't defined in POJO model: is there any annotation or annotation option to tell spring data to ignore fields that aren't specified in method argument object? Obviously I wanted not to use MongoTemplate save().

A: If you want to update a mongoDB Document, all you need to use is the save() method and pass the mongoDB auto-created Document _id with the details.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular 2 Http Error I'm new in Angular 2 and I am very stuck on HTTP.
The application runs but when I try get my InMemoryDbService it fails.
The error is:

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property '0' of undefined

but I'm not trying access to '0' property. The error disappear when I delete function get(this.url) in clientes.service.ts
My Code:
clientes.service.ts
import { Injectable } from '@angular/core';
import { Cliente } from './../models/clientes';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class ClientesService{

    private headers = new Headers({'Content-Type': 'application/json'});
    private url = '/app/components/apis/clientes-data';// URL a la web api.

    constructor(private http: Http) { }

// Método Get para obtener la lista de objetos.
//
    get(): Promise<Cliente[]> {
        console.log(this.http.get(this.url)); // THE ERROR IS HERE
        return this.http.get(this.url)        // AND HERE IN
                   .get(this.url)
                   .toPromise()
                   .then(response => response.json().data as Cliente[])
                   .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('Ha habido un error con la solicitud '+this.url, error);
        return Promise.reject(error.message || error);
    }

}

clientes-data.service.ts
import { InMemoryDbService } from 'angular2-in-memory-web-api';
export class ClientesData implements InMemoryDbService {
    createDb() {
        let clientes = [
           { id: '1', nombre: 'Pepe' },
           { id: '2', nombre: 'Juan' },
           { id: '3', nombre: 'Paco' },
           { id: '4', nombre: 'Chema' }
        ];
        return {clientes};
     }
}

app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { InMemoryWebApiModule } from 'angular2-in-memory-web-api';

// Imports for loading & configuring the in-memory web api
import { XHRBackend } from '@angular/http';

import './rxjs-extensions';
import { AppComponent } from './app.component';
import { routing } from './app.routing';

/** DATAS SERVICE */
import { ClientesData } from './components/apis/clientes-data.service';

/** PIPES */
import { KeyArrayPipe } from './components/pipes/keyArray.pipe';

import { MainComponent } from './main.component';
import { HeaderComponent } from './header.component';
import { FooterComponent } from './footer.component';
import { NavLeftComponent } from './nav-left.component';
import { DashboardComponent } from './components/dashboard.component';
import { ListadoComponent } from './components/listado.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    routing,
    HttpModule,
InMemoryWebApiModule.forRoot(ClientesData),
  ],
  declarations: [
    AppComponent,
    MainComponent,
    HeaderComponent,
    FooterComponent,
    NavLeftComponent,
    DashboardComponent,
    ListadoComponent,
    KeyArrayPipe
  ],
  providers: [
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

package.json
{
 "name": "angular2-tour-of-heroes",
 "version": "0.1.0",
 "scripts": {
   "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
   "lite": "lite-server",
   "postinstall": "typings install",
   "tsc": "tsc",
"tsc:w": "tsc -w",
"typings": "typings"
 },
 "dependencies": {
   "@angular/common": "2.0.0-rc.6",
   "@angular/compiler": "2.0.0-rc.6",
   "@angular/compiler-cli": "0.6.0",
   "@angular/core": "2.0.0-rc.6",
   "@angular/forms": "2.0.0-rc.6",
   "@angular/http": "2.0.0-rc.6",
   "@angular/platform-browser": "2.0.0-rc.6",
   "@angular/platform-browser-dynamic": "2.0.0-rc.6",
   "@angular/router": "3.0.0-rc.2",
   "@angular/upgrade": "2.0.0-rc.6",
   "angular2-in-memory-web-api": "0.0.18",
   "concurrently": "^2.2.0",
   "core-js": "^2.4.1",
   "reflect-metadata": "^0.1.3",
   "rxjs": "5.0.0-beta.11",
   "systemjs": "0.19.27",
   "zone.js": "^0.6.17"
 },
 "devDependencies": {
   "concurrently": "^2.2.0",
   "lite-server": "^2.2.2",
   "typescript": "^1.8.10",
   "typings": "^1.3.2"
 }
}

Thanks!!

A: There might be few issues with the way you try to get the data and the error might be because you don't point to the right endpoint, so there is no data.

*

*If you didn't change the default API base for that collection (check docs here) it means you need to change private url = '/app/components/apis/clientes-data'; into private url = 'app/clientes-data';

*On top of the first change, you need to be very careful to the collection name. Right now you are trying to fetch a collection that does not exist. Your collection is called clientes and not clientesData (this is the service name). I recommend looking at John Papa's example, where you can easily see the differences. Try to follow that way in order to get it work.

Please try to change private url = '/app/components/apis/clientes-data'; into private url = '/app/clientes'; and see if you still have the error.


text:
Q: Find out the biggest odd number from three arguments in a function [Python] I need to write a function that will print biggest odd  number from three input arguments.
Here is my code.
def oddn(x,y,z):
odd_number_keeper = []
for item in x,y,z:
    global odd_number_keeper
    if item % 2==1:
        odd_number_keeper = [item]
        return max(odd_number_keeper)
    else:
        print 'No odd number is found'

My codes seem is not working. Any ideas how i can modify this code?

A: A few changes would be needed:
def oddn(x,y,z):
    odd_number_keeper = []
    for item in [x,y,z]:
        if item % 2==1:
            odd_number_keeper.append(item)
    if not odd_number_keeper:
        print 'No odd number is found'
        return
    return max(odd_number_keeper)

Iterate over the values x, y and z and add the odd numbers to odd_number_keeper. If there are any numbers then you return the max() of the elements in this list of odd numbers. If there are no odd numbers then you print the message and return (without a result, as there is no number to return).

A: You have to first filter all odd-numbers and then call max:
def oddn(x,y,z):
    odd_numbers = [item for item in (x,y,z) if item%2==1]
    return max(odd_numbers)

or in short:
def oddn(*numbers):
    return max(x for x in numbers if x % 2 == 1)

also it is not good practice, if you want to print some message on error:
def oddn(*numbers):
    try:
        return max(x for x in numbers if x % 2 == 1)
    except ValueError:
        print 'No odd number is found'
        return None

A: You are not finding the biggest odd number from the list, instead, you are finding the first odd number and returning that. The issue is in the lines -
odd_number_keeper = [item]
return max(odd_number_keeper)

you first need to be appending item to the list, insteading of making odd_number_keeper the list with only that item.
Secondly, the return statement should be at the end of the function, not inside the for loop.
You need a code something like -
def oddn(x,y,z):
    odd_number_keeper = []
    for item in x,y,z:
        if item % 2==1:
            odd_number_keeper.append(item)
    return max(odd_number_keeper)

A: You are resetting odd_number_keeper each time. You probably meant
odd_number_keeper += [item]

Also the return and print should be at the end of (outside) the for loop.
(please fix indentation to be clearer on your intent).

A: Solving it using filter. Doing it in pythonic way.
def oddn(a, b, c):
    final = []
    final.append(a)
    final.append(b)
    final.append(c)
    result = filter(lambda x: x % 2 != 0, final)
    return max(result)


text:
Q: How to ignore a specific value from numpy column vector, without removing it? I am doing an image segmentation task where I need to ignore a nodata pixel value for a certain function, say for example plotting a histogram of the image. However, I do not want to remove it from the array as this changes the shape of the image. I have tried both of the following methods listed below but it didn't work. The nodata pixel value I'm trying to ignore is 190. My data is of the shape (12350,1)
img=np.ma.masked_array(img, mask=(img == 190))

The second method I tried was:
img=np.ma.masked_values(img, 190).


text:
Q: I can't seem to echo without quotation marks around my string I'm trying the following form in a .sh script:
echo 'string' $var >> print.dat

and it prints the following:
'string' 14.27

Which is almost what I want, but I need the quotation marks to disappear. All I need is:
string 14.27

does anyone know the solution here? I'm sure it's a simple question but I searched around and I couldn't find what I wanted. Maybe I just didn't know what exactly to search for.
EDIT:
I appreciate all your help and hate to admit it, but I was making a really foolish mistake all along. Things were printing the way I wanted all along in print.dat, but I was using sh -x to view the output and thus I saw quotations around my strings.

A: This workaround may do the job (backslashify the backtick ` according to your shell):
echo 'string' $var | tr -d \' >> print.dat

A: echo 'string' $var >print.dat

This would not display anything, but write string followed by the value of $var (possibly undergoing some transformations as it's not quoted) to the file print.dat. The quotes around the string will be removed.
Make sure you don't have echo aliased to anything.  To bypass any alias or shell function with the same name, use
command echo 'string' $var >print.dat

or use /bin/echo in place of echo.
You may also use printf which is usually more portable than echo:
printf 'string %s\n' "$var" >print.dat


text:
Q: Which of the following sentences are grammatically correct? Could you please explain which of the forms of the following pairs are correct? I find it difficult to understand how do they differ.
(I)

*

*I cooked dinner

*I have cooked dinner

(II)

*

*I am cooking dinner

*I have been cooking dinner

(III)

*

*I am studying since 2 AM

*I have been studying since 2 AM

A: (I) - "I cooked dinner" is past tense.  Most commonly it means you just finished cooking dinner, and it is ready to eat.  You could also say "I've cooked dinner" to mean the same thing, but that's a bit more formal and unusual in spoken English in the US.  Another meaning of "I've cooked dinner" is that you have cooked dinner at least once in your life.
"I cooked dinner" is also past tense for telling stories ("Last night, I cooked dinner, then I ate it, and then I went to bed.")  But you CANNOT use "I've cooked dinner" this way.
(II) - "I'm cooking dinner" is usually present tense and means you are cooking dinner but haven't finished.  "I've been cooking dinner" is similar but it emphasizes that you have been cooking for some amount of time.  If someone asks "Did you see what happened outside an hour ago?" you could answer: "No, I've been cooking dinner!"
"I'm cooking dinner" is also used conversationally as future tense to tell someone that you are going to cook dinner tonight.  For example, "Come to my house at 7 p.m.  I'm cooking dinner."
(III) "I am studying since..." is incorrect.  "I've been studying since 2 AM" means you started studying at 2 AM and you are still studying.

A: The difference in (I) is mostly about style and natural speech rhythm.
The difference in (ii) involves two time periods, the first is current and the second is past (though the latter can involve the current as long as you are currently continuing cooking that started in the past).
The difference in (iii) is the first one is grammatically incorrect because that grammatical construction can only be used on the present tense, whereas the latter implied that you can started studying earlier and are continuing it currently.


text:
Q: Which Data Mining task to retrieve a unique instance I'm working with data mining, and I'm familiar with classification, clustering and regression tasks. In classification, one can have a lot of instances (e.g. animals), their features (e.g. number of legs) and a class (e.g. mammal, reptile).
But what I need to accomplish is, given some attributes, including the class attribute, to determine which unique instance I'm referring to (e.g. giraffe). I can supply all known attributes that I have, and if the model can't figure out the answer, it can ask for another attribute – just analogous to a 20 questions style of game.
So, my question is: does this specific task have a name? It seems to be similar to classification, where the class is unique to each instance, but this wouldn't fit on the current training models, except perhaps for a decision tree model.

A: Your inputs, denoted features in machine learning, are tuples of species (what I think you mean by "instance"), and physical attributes. Your outputs are broader taxonomic ranks. Thus, assigning one to each input is a classification problem. Since your features are incomplete, you want to perform ... classification with incomplete data, or impute missing features. Searching for these terms will give you enough leads.
(And the other task is properly called clustering.)

A: IMHO you are looking for simply a decision tree.
Except, that you don't train it on your categorial attribute (your "class"), but on the individual instance label.
You need to carefully choose the splitting measure though, as many measures go for class sizes - and all your classes have size 1 now. Finding a good split for the decision tree may involve planning some splits ahead to get an optimal balanced tree. A random forest like approach may be of use to improve the chance of finding a good tree.


text:
Q: The argument type 'HWFamily' can't be assigned to the parameter type 'ProviderListenable' I'm following the example in https://carltonaikins.me/how-to-use-riverpod-2-generator-in-your-flutter-project and I now have ...
@riverpod
class HW extends _$HW {
 @override
 dynamic build(foo) => 'HelloWorld'; // without foo, I get build dynamic Function() is not a valid override of build (dynamic Function(dynamic)
}

return Consumer(builder: (context, ref, child) {
   var s1 = ref.watch(hWProvider);   // gives The argument type 'HWFamily' can't be assigned to the parameter type 'ProviderListenable<dynamic>'.
   var s2 = ref.watch(hWProvider.notifier);   // gives The getter 'notifier' isn't defined for the type 'HWFamily'.
   var s3 = ref.watch(hWProvider.call('foo');   // seems to work
...

I don't understand if I'm doing something wrong, or the example I'm following is somehow out of date? If the latter, is there a better example to follow?
What is the significance of foo?
Versions:-

*

*flutter_riverpod: 2.1.3

*riverpod_annotation: 1.1.1

*riverpod_generator: 1.1.1

EDIT
I suspect this might be a problem with the build process. I killed the watch process, deleted main.g.dart, removed "foo", restarted the watch, and now everything works as it should. Somehow the "foo" (which I added to get past the override error) was creating a Family.

A: The build method of your provider has parameters. As such, when listening to your provider you need to pass those providers:
ref.watch(hWProvider(foo));

If you don't need that parameter, remove it from your build method. Then you will be able to listen to the provider without passing any value.


text:
Q: Cannot open server requested by the login I'm trying to connect to my Azure SQL database using pyodbc. The azure account that I am using is under the username xxxxxx@student.bham.ac.uk (my university account). When I try to connect to the database, I get the error
Cannot open server "student.bham.ac.uk" requested by the login.  The login failed. (40532).
The credentials that I am using are correct. The error makes me think that it might be confusing my login for the database server? What does this error mean and how can I fix the issue?

A: I recently suffered this same problem and I fixed it this way:

*

*Go to your SQL Server resource on Azure

*Go to "Firewalls and virtual networks"

*Verify "allow Azure's service and resources accessing this server" is set as YES

Save changes and let up to 5 minutes to apply this changes.

A: This seems to work for me:
If your SQL Database server is called myazureserver and your login is user@example.com, then you must supply your login as user@example.com@myazureserver.

A: What Hdot said works also for me

If your SQL Database server is called myazureserver and your login is user@example.com, then you must supply your login as user@example.com@myazureserver.

but, worth to mention that if you use DBeaver, you must update USER and PASSWORD in 'Driver Properties' tab (instead of 'Main'). This can be really confusing.


text:
Q: View in frame XAML innitialization I have XAML code to create program output in frame. I can change content of frame in case I used "MyFrame.Navigate(typeof(Setup))". Is there any way to initialize content of frame in XAML code?
XAML code fragment:
        </SplitView.Pane>
        <SplitView.Content>
            <Frame Name="MyFrame" ?any reference to view to first time intiilaization? />
        </SplitView.Content>

Thanks for help

A: You can use SourcePageType
It can set in xaml ,the code is
    <Frame Name="MyFrame" SourcePageType="Setup"></Frame>

The frame will navigate to Setup
I think you can use the control above in the Frame when you enter the page ,you can set it Visibility and you can set is hidden when load complete.


text:
Q: Tiles inside a html windows store app I want to port a web app (sorry, german, but you will unterstand what I mean: http://www.jalfm.de/games/Nerdquiz) to Windows store. If you go on the web page, you will see 4 different tiles at the beginning. I'd like to create something like that in my app. I looked through the whole list of controls (http://msdn.microsoft.com/en-us/library/windows/apps/hh465453.aspx#t_section), but I didn't find anything what was named "tile" or similar.
I know I could use the same CSS-class (Metro bootstrap) I used for the web app, but I'd like to know if there is a way to do that natively.


text:
Q: How to find difference between two column in excel pivot I have a column in power pivot named "member_status" which contains the status of a member as "Joiner"and "Leaver". I have another column called Date which has join date and leave date. I wan't to see how many left how many joined and the difference between two in a pivot table. Can any one please guide to what i wants to achieve please.
Table structure.
Status       Date
Joiner     2017-11-31 00:00:00.000
Leaver     2017-09-30 00:00:00.000
Joiner     2017-02-11 00:00:00.000
Joiner     2017-03-26 00:00:00.000
Leaver     2017-10-31 00:00:00.000


text:
Q: SQL Agent Powershell step not using specified proxy I'm trying to execute a powershell script, and use a proxy to do. The job runs correctly, but using whoami within the script to log the executing user indicates that the script is not being run by the user I (think I) specified in the proxy.
I have a credential, with the correct username and password for the windows server:

I have a proxy set up to use that credential:

The user [Domain]\MSSQLService02:

*

*Is specified as a principle for this proxy

*Has its own login

*Is the job owner
I'm using the proxy to Run As in the job step:

However, as mentioned, logging within the script indicates that [Domain]\MSSQLService02 is the user executing the script.
I don't know if I'm misunderstanding the use of proxies, I'm missing a step, or something is misconfigured.


text:
Q: Textarea won't display values after hitting Reset The reset button only appears once a conversion from Fahrenheit to Celsius is successfully done. It works fine. However, after hitting Reset, I cannot see values in the textarea when perform more conversions. I think the problem is most likely caused the two arrays in my codes. What do you think?
I have recreated the problem here: http://jsfiddle.net/wnna3646/
<!DOCTYPE html>

<meta charset="UTF-8" />
<title>Temperature Conversion</title>

<form id="myForm" onsubmit="return this.ftemp.value!=''">

   Fahrenheit:<input id="ftemp" onkeypress="return fNumericCharactersOnly(event)" onkeyup="this.form.Convertbtn.disabled = this.value==''; this.form.Avgbtn.disabled = this.value==''; if(!validnum(this.value)) this.value=''">

   Celsius:<input id="ctemp" readonly>

Fahrenheit Celsius

   <textarea rows="5" id="txtArea" readonly></textarea>

   <input type="button" id="Convertbtn" value="Convert" accesskey="c" onclick="convertTemp(); counter++" disabled="disabled"/>
   <input type="button" id="Avgbtn" value="Average" accesskey="a" onclick="averageTemp(); AddResetbutton()" disabled="disabled"/>

</form>

Also, I have attempted to make the script automatically display all values after the 10th one is entered, but can't seem to make it work. Any suggestions?

A: Hey Your code is fixed.
<!DOCTYPE html>

<meta charset="UTF-8" />
<title>Temperature Conversion</title>

<form id="myForm" onsubmit="return this.ftemp.value!=''">

   Fahrenheit:<input id="ftemp" onkeypress="return fNumericCharactersOnly(event)" onkeyup="this.form.Convertbtn.disabled = this.value==''; this.form.Avgbtn.disabled = this.value==''; if(!validnum(this.value)) this.value=''">

   Celsius:<input id="ctemp" readonly>

Fahrenheit Celsius

   <textarea rows="5" id="txtArea" name="textarea-name" readonly></textarea>

   <input type="button" id="Convertbtn" value="Convert" accesskey="c" onclick="convertTemp(); counter++" disabled="disabled"/>
   <input type="button" id="Avgbtn" value="Average" accesskey="a" onclick="averageTemp(); AddResetbutton()" disabled="disabled"/>

</form>


text:
Q: Error: Required parameter: part I am working with Youtube data API with node after following the sample steps form documentation. I ran into this Error The API returned an error.
 Error: Required parameter: part

A: Quick-fix is to revert to googleapis version 24.0.0:
npm uninstall googleapis --save
npm install googleapis@24.0.0 --save

Found here.


text:
Q: Much faster interpolation in Python? I am looking for a very fast interpolation in Python. Here is my code:
from scipy.integrate import quad
import numpy as np
from scipy import interpolate
import time
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

input="-0.5 0.0 \
-0.4 0.6 \
-0.3 0.9    \
-0.2 0.85 \
-0.1 0.82 \
0.0 0.8 \
0.1 0.7 \
0.2 0.6 \
0.3 0.4 \
0.4 0.3 \
0.5 0.02"

start_time = time.time()

input_coordinates = np.genfromtxt(input.splitlines()).reshape(-1,2) # shape to 2 columns, any number of rows
x_coordinates = input_coordinates[:,0]
H_values = input_coordinates[:,1]
H_interpolation = interpolate.InterpolatedUnivariateSpline(x_coordinates, H_values)
# H_interpolation = interp1d(x_coordinates, H_values)
# H_interpolation = interp1d(x_coordinates, H_values, kind='cubic')

def function(x):
    return H_interpolation(x)*np.exp(2/np.sqrt(1+x))

complex_integral = quad(function, -0.5, 0.5)

print("Quad",complex_integral)

print("--- %s seconds ---" % (time.time() - start_time))

xnew = np.arange(-0.5, 0.5, 0.01)
ynew = H_interpolation(xnew)   # use interpolation function returned by `interp1d`
plt.plot(x_coordinates, H_values, '.', label='original data')
plt.plot(xnew, ynew, '-', label='interpolation')
plt.legend()
plt.show()

Where for:
interpolate.InterpolatedUnivariateSpline

time is 0.011002779006958008 seconds
and for:
interp1d type linear

time is 0.05301189422607422 seconds
and for:
interp1d type cubic

time is 0.03500699996948242 seconds.
But I am looking for something really much faster due to multiple calculations in huge loops. Is there any much faster function approximation in Python? It should be accurate too.
I observed that if I reduce number of input points in
input

the time of calculation also drops, but I don't have much possibilities for reducing the number of points in input data.

A: The speed of your interpolation depends almost entirely upon the complexity of your approximation function.  What mathematical properties can you guarantee about the your input points and the desired output?  You need to take full advantage of those to improve over the general-purpose methods you're using.
Most important, remember that virtually all CPUs now implement on-chip transcendental functions: basic trig functions, exp, sqrt, log, etc.  These are micro-coded for blinding speed, such that sin(x) or exp(x) is faster than a fifth-degree polynomial in x (five multiplications, five additions).
You should also explore using vectorized operations, to handle a set of interpolations in parallel.

A: Don't use interp1d if you care about performance. Use interpolators directly:

*

*for linear interpolation, use np.interp (yes, numpy)

*for cubic use either CubicSpline or make_interp_spline

Note that the latter objects allow vectorized evaluations, so you might avoid python looping altogether.
Also note that scipy interpolators have e.g. .integrate method, so you might avoid using quad, too.


text:
Q: Open Cart - Admin panel trouble I have a problem with the admin panel of Open Cart.
I moved from localhost to online an opencart website.
Everything went fine except that the login page and admin panel add some Prefix text to the navigation menu and tabs title.
Check this image to see what it looks like:

If you have any ideas about this problem.
I did recheck all CONFIG.PHP files and they are filled with right information.
I dont know what to do actually....
Thanks in advance.

A: It looks like text is not being translated from language files.
Try to copy all files again , also make sure you have current language set in database. I also suggest to open "System -> Settings" in menu and check if language is selected menu and save those settings.
ALso check for any errors in OC error logs, apache error logs, or maybe in VQmod logs if you use it.

A: Ok so i found the soluition.
I did use a fres config.php file filed with my DIR and Database information and all came back to normal on the Admin cPanel.
Thanks


text:
Q: Apex Replace String Is it possible to implement this function in apex?
where_str Value should be
'(Mobile__c = null OR Store__r.Name = null) AND Name != null'
String filter_str = '(1 OR 2) AND 3';
String json_str = '[{"keyVal":1,"field":"Mobile__c","condition":"=","value":"null"},{"keyVal":2,"field":"Store__r.Name","condition":"=","value":"null"},{"keyVal":3,"field":"Name","condition":"!=","value":"null"}]';

List<optWrapper> opts = (List<optWrapper>)JSON.deserialize(json_str, List<optWrapper>.class);
for (Integer i = 0; i < opts.size(); i++) {
    System.debug(LoggingLevel.INFO, 'i = ' + i);
    if (opts[i].keyVal == i+1) {
        filter_str = filter_str.replace(String.valueOf(i+1), opts[i].field + opts[i].condition + opts[i].value);
    }
}
System.debug(LoggingLevel.INFO, 'filter_str = ' + filter_str);

public class optWrapper{
    public Integer keyVal;
    public String field;
    public String condition;
    public String value;
}

A: I suggest you to run through the pattern string and extract full numeric values on run, then replace them with suitable condition and move further (I have stored condition parts in Map, so there will be no misconception, if any keyVal may be omitted):
private static Map<String, Integer> getKeyValMap(List<Integer> patternChars, Integer startingPos) {
    String keyVal = String.fromCharArray(new List<Integer>{patternChars[startingPos]});
    Integer lastPos = startingPos;
    for (Integer i = startingPos + 1, n = patternChars.size(); i < n; i++) {
        String currentChar = String.fromCharArray(new List<Integer>{patternChars[i]});
        if (currentChar.isNumeric()) {
            keyVal += currentChar;
            lastPos = i;
        } else {
            break;
        }
    }
    return new Map<String, Integer>{
            'keyVal' => Integer.valueOf(keyVal),
            'lastPos' => lastPos
    };
}

public static String getCondition(String pattern, Map<Integer, String> conditionParts) {
    String condition = '';

    List<Integer> patternChars = pattern.getChars();
    for (Integer i = 0, n = patternChars.size(); i < n; i++) {
        String currentChar = String.fromCharArray(new List<Integer>{patternChars[i]});
        if (currentChar.isNumeric()) {
            Map<String, Integer> keyValMap = getKeyValMap(patternChars, i);
            condition += conditionParts.get(keyValMap.get('keyVal'));
            i = keyValMap.get('lastPos');
        } else {
            condition += currentChar;
        }
    }

    return condition;
}

You may get conditionParts map with this method:
public static Map<Integer, String> getConditionParts(String jsonString) {
    Map<Integer, String> conditionParts = new Map<Integer, String>();
    for (Object tmp : (List<Object>) JSON.deserializeUntyped(jsonString)) {
        Map<String, Object> conditionPart = (Map<String, Object>) tmp;
        conditionParts.put(
                (Integer) conditionPart.get('keyVal'),
                (String) conditionPart.get('field') + (String) conditionPart.get('condition') + (String) conditionPart.get('value')
        );
    }
    return conditionParts;
}

I have tested it on several examples and it looks fine:
@IsTest
static void test_getCondition() {
    String jsonString = '[{"keyVal":1,"field":"Mobile__c","condition":"=","value":"null"},{"keyVal":2,"field":"Store__r.Name","condition":"=","value":"null"},{"keyVal":3,"field":"Name","condition":"!=","value":"null"}]';
    Map<Integer, String> conditionParts = ConditionBuilder.getConditionParts(jsonString);
    String pattern = '(1 OR 2) AND 3';
    String condition = ConditionBuilder.getCondition(pattern, conditionParts);
    System.assertEquals('(Mobile__c=null OR Store__r.Name=null) AND Name!=null', condition);

    jsonString = '[{"keyVal":10,"field":"A","condition":"=","value":"2"},{"keyVal":2,"field":"B","condition":"=","value":"\'x\'"}]';
    conditionParts = ConditionBuilder.getConditionParts(jsonString);
    pattern = '10 AND 2';
    condition = ConditionBuilder.getCondition(pattern, conditionParts);
    System.assertEquals('A=2 AND B=\'x\'', condition);
}

Also, if you may know any better way to operate with chars in Apex Stings, please, tell me, I'm wondering if it is one though.


text:
Q: awk compare consecutive rows This is quite simple maybe, but I am stacked.Thanks for any help.
I have an input file with two two columns. In one column I have an ID and in the second a value associated to it.  I need an output where the first column will be the ID (no repetitions are allowed) and in the second column the average is printed. The ids are not always repeated, and if repeated it could only be consecutively and at a max repetition value of two.
Input
10;10
10;20
20;30
20;40
30;15
40;10
40;12

Desired output
10;15
20;35
30;15
40;11

A: This one-liner does it:
awk -F';' -v OFS=";" '{a[$1]+=$2+0;b[$1]++}END{for(x in a)print x,a[x]/b[x]}' file

Test with your data:
kent$  cat f
10;10
10;20
20;30
20;40
30;15
40;10
40;12

kent$  awk -F';' -v OFS=";" '{a[$1]+=$2+0;b[$1]++}END{for(x in a)print x,a[x]/b[x]}' f
10;15
20;35
30;15
40;11

A: $ cat tst.awk
BEGIN { FS=OFS=";" }
($1 != prev) && (NR>1) { print prev, sum/cnt; sum=cnt=0 }
{ prev=$1; sum+=$2; cnt++ }
END { if (cnt) print prev, sum/cnt }

$ awk -f tst.awk file
10;15
20;35
30;15
40;11

A: (written live, I did not try it; assume GNU awk; assume sorted input)
awk -F';' '
    BEGIN {
        id=""
    }
    $1 != id {
        if (id != "") {
            printf("%s;%d\n", id, sum/n);
            n = sum = 0;
            id = str($1);
        }
        sum += $2;
        n++;
    }
    END {
        if (n > 0) printf("%s;%s\n", id, sum/n);
    }
'


text:
Q: How to make vuex getter from data from google api docs? I'm trying to make getter in vuex store with flat data from google dosc api. All what I need is to take textRun content and keep this in array (because there will be few messages). Now I hardcoded this response in state like:
 state: {
    googleResponse: [
      {
        "body": {
          "content": [
            {
              "endIndex": 75,
              "paragraph": {
                "elements": [
                  {
                    "endIndex": 75,
                    "startIndex": 1,
                    "textRun": {
                      "content": "This is an ordinary paragraph. It is the first paragraph of the document",
                      "textStyle": {}
                    }
                  }
                ],
                "paragraphStyle": {
                  "direction": "LEFT_TO_RIGHT",
                  "namedStyleType": "NORMAL_TEXT"
                }
              },
              "startIndex": 1
            },
            {
              "endIndex": 102,
              "paragraph": {
                "elements": [
                  {
                    "endIndex": 102,
                    "startIndex": 75,
                    "textRun": {
                      "content": "Here's a level one heading",
                      "textStyle": {}
                    }
                  }
                ],
                "paragraphStyle": {
                  "direction": "LEFT_TO_RIGHT",
                  "headingId": "h.o1fkftgl5zwf",
                  "namedStyleType": "HEADING_1"
                }
              },
              "startIndex": 75
            },
          ]
        }
      }
    ],
}

and after that I make a getter message and used map from lodash:
message: (state) => {
  let message = '';
  map(state.googleResponse, (element) => ({
    content: map(element.body.content, (content) => {
      map(content.paragraph.elements, (obj) => {
        message += get(obj, 'textRun', '')
      })
    })
  }))
}

But when I'm checking message in vuex it says is undefined... I want to have array with textRun objects. Where might be the problem ?

A: i am wondering whether you can get the message keep in Array by this way?
 you can write like this may your want

   let messageArray = state.googleResponse.map(
        item => item.body.content.map(
            itemCotent => itemCotent.paragraph.elements.map(
                itemElements => itemElements.textRun.content)))

A: You need to return themessage variable in your getter.


text:
Q: Чем могут быть опасны внешние ключи в БД? Наткнулся на проект, в котором главный разработчик запретил использование внешних ключей в БД (MySql, таблицы InnoDb).
Но не смог понятно объяснить, почему так сделали.
Кроме недостатков, описанных в документации, может кто-нибудь назвать другие адекватные причины отказа от внешних ключей?
A:
Администраторы баз данных часто
создают такую сложную топологию
связей, при которой затруднительно, а
зачастую и вовсе невозможно получить
резервную копию или восстановить
единичные таблицы.

Думаю из-за этого, плюс каскадное удаление может потереть здоровенный кусок базы, если "правильно" прописано.


text:
Q: How can change my Delphi Android App to "Dark mode"? I have my app in Delphi 10.3 for Android and I'm trying to convert it to "dark mode" but many controls are missing a color attribute so some are still bright white. I have no idea how to handle the "Styles" that seem to be around.
Are there any hints you can give me on how to implement this?

A: I put a test program in a github repository but without any explanations.
Not tested with 10.3 but should work I think.
Light_Dark_Side
Goal was first to detect Dark/Light mode and then check how to use TStyleManager

A: by putting a stylebook on my form and loading a PRESET TEMPLATE (dark in my case) I was able to change my app to dark mode without any design changes myself.


text:
Q: Creating an xml file from .net I have next code and I have 2 problems after try execute:
1. System.Xml.XmlException: The ':' character, hexadecimal value 0x3A, cannot be included in a name.
2. base {System.SystemException} = {Can not re-define the prefix'' from'' to 'urn = schemas-microsoft-com: office: excel' within the same start element tag.} {"No se puede volver a definir el prefijo '' de '' a 'urn=schemas-microsoft-com:office:excel' dentro de la misma etiqueta de elemento inicial."}
My code is:
XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
   new XElement("Document",
          new XElement("Worbook",
               new XElement("DocumentProperties", new XElement("Author", "YO"),
                                                       new XElement("Created",DateTime.Today),
                                                       new XElement("Company","CIA")),
                                   new XElement("ExcelWorkBook", new XElement("WindowHeight","6795"),
                                                            new XElement("WindowWidth","8460"),
                                                            new XElement("WindowTopX","120"),
                                                            new XElement("WindowTopY","15"),
                                                            new XElement("ProtectStructure","False"),
                                                            new XElement("ProtectWindows","False")
                                                ),
                                    new XElement("Styles", new XElement("Style", new XAttribute("ss:ID", "Default"), new XAttribute("ss:Name", "Normal"),
                                                                                new XElement("Alignment", "", new XAttribute("ss:Vertical","Bottom")),
                                                                                new XElement("Borders", ""),
                                                                                new XElement("Font", ""),
                                                                                new XElement("Interior", ""),
                                                                                new XElement("NumberFormat", ""),
                                                                                new XElement("Protection", "")
                                                                        ),
                                                        new XElement("Style",new XAttribute("ss:ID","s21"), new XElement("Font", "", new XAttribute("x:Family", "Swiss"), new XAttribute("ss:Bold", "1")))
                                                ),
                                    new XElement("Worksheet",new XAttribute ("ss:Name","Sheet1"),
                                                                   new XElement("Table", new XAttribute("ss:ExpandedColumnCount", "2"),
                                        new XAttribute("ss:ExpandedRowCount", "5"),
                                        new XAttribute("x:FullColumns","1"),
                                        new XAttribute("x:FullRows","1"),
                                                                                new XElement("Row", new XElement("Cell", new XElement("Data",
                                                    new XAttribute("ss:Type","String"), "Text in cell A1"))),
                                                                                new XElement("Row", new XElement("Cell", new XElement("Data", new XAttribute("ss:Type", "String"), "Bold text in cell A2"))),
                                                                                new XElement("Row", new XAttribute("ss:Index", "4"), new XElement("Cell", new XAttribute("ss:Index", "2"),
                                                            new XElement("Data", new XAttribute("ss:Type", "Number"), "43"))),
                                                                                new XElement("Row", new XElement("Cell", new XAttribute("ss:Index", "2"),
                                                    new XAttribute("ss:Formula", "=R[-1]C/2"),
                                                    new XElement("Data", new XAttribute("ss:Type", "Number"), "21.5")))),
                                                                new XElement("WorksheetOptions",
                                                                        new XAttribute("xmlns","urn=schemas-microsoft-com:office:excel"),
                                                                        new XElement("Print", new XElement("ValidPrinterInfo", ""),
                                                                                new XElement("HorizontalResolution", "600"),
                                                                                new XElement("VerticalResolution", "600")),
                                                                                new XElement("Selected",""),
                                                                                new XElement("Panes", new XElement("Pane", new XElement("Number","3"),
                                                                                new XElement("ActiveRow", "5"),
                                                                                new XElement("ActiveCol","1"))),
                                                                                new XElement("ProtectObjects",""), new XElement("ProtectScenarios","False"))
                    )
    )
));

Regards,
María


text:
Q: Loading Google map blank with console errors Hi am trying to get a google map to show up on a page in a ruby on rails app but I'm getting the following errors. I'm struggling to understand how the whole process works. I think it has to do with the script tag but can't figure it out.
gmaps.js file in javascript folder:
/* Options for Google maps */

map = new google.maps.Map(document.getElementById('map-canvas'), {
  center: {lat: -34.397, lng: 150.644},
  zoom: 8
});

html.erb:
<%# Google map %>

Script in application html:
<%-# Google map script tag-%>

Console errors:
Uncaught ReferenceError: google is not defined

Uncaught InvalidValueError: initMap is not a function

A: Uncaught ReferenceError: google is not defined is referring to this line:
map = new google.maps.Map(document.getElementById('map-canvas')

This error means that Ruby doesn't know what google is because you have not defined it.
Uncaught InvalidValueError: initMap is not a function  is referring to this line:
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD6jUOjpSNBqs3jVSCyZiXU6On1NqPIS6I&callback=initMap">

so the callback is being called but your application hasn't defined what the initMap function is.
Are you using a gem to do this?  If so which one?


text:
Q: How do I connect to a database I created in HostGator? Edit: I have googled and searched, read what I could find of their documentation. Even chatted with them. The chatter could help me. This is why I reach to you.
I am a complete beginner and I am having some troubles getting started with databases on hostgator. I guess my question also is valid using other hosts.
I created a db through the cpanel in hostgator and added a user to it.
I copied this script into a test.php in my /public_html/ folder and ran it on my site.
In the script I used the name, user and password from the database and user I previously created in cpanel. This database I can see using phpMyAdmin.
<?php
  try
  {
    //open the database
    $db = new PDO('sqlite:localhost;dbname=user_db', 'user_username', 'password');

    //create the database
    $db->exec("CREATE TABLE Dogs (Id INTEGER PRIMARY KEY, Breed TEXT, Name TEXT, Age INTEGER)");

    //insert some data...
    $db->exec("INSERT INTO Dogs (Breed, Name, Age) VALUES ('Labrador', 'Tank', 2);".
               "INSERT INTO Dogs (Breed, Name, Age) VALUES ('Husky', 'Glacier', 7); " .
               "INSERT INTO Dogs (Breed, Name, Age) VALUES ('Golden-Doodle', 'Ellie', 4);");

    //now output the data to a simple html table...
    print "
";
    print "
Id	Breed	Name	Age
";
    $result = $db->query('SELECT * FROM Dogs');
    foreach($result as $row)
    {
      print "
".$row['Id']."	";
      print "".$row['Breed']."	";
      print "".$row['Name']."	";
      print "".$row['Age']."
";
    }
    print "
";

    // close the database connection
    $db = NULL;
  }
  catch(PDOException $e)
  {
    print 'Exception : '.$e->getMessage();
  }
?>

This worked, which is nice, but it created a file in my /public_html/ folder called 'localhost;dbname=user_db'
My issue is that I thought I was connecting to the database I created using cpanel, but when I open phpMyAdmin, that database is empty.
How do I change that script to talk to the database I created using cpanel so that I can reach it using phpMyAdmin?
Edit 2:
So I learned that I need to use mysql, not sqlite because phpMyAdmin is based on MySQL.
Also, using the script from http://www.w3schools.com/php/php_mysql_create_table.asp I was able to connect! So, success! Thank you @mituw16 and @Fred -ii-  for helping me! :D

A:
I am assuming you created a MySQL database if you used PHPMyAdmin even thought the tags say SQL Lite.

It looks like you're trying to create an SQL Lite database instead of opening a  connection to your MySQL database.
Change this line to the following
//open the database
$db = new PDO('mysql:localhost;dbname=user_db', 'user_username', 'password');


text:
Q: auto increment list index in python Watch index n ( and y)
n = 0
while(0 < y):
  result[ n += 1] = items[y -= 1]

So the above is accepted syntax. Is there an elegant way to do this, in the order of Java's
result[ n++] = items[--y]

A: No, this is not accepted syntax.
If I understand correctly what you are trying to do, the pythonic way would be
result = items[::-1]

or
result = list(reversed(items))

(the reversed function itself returns an iterator, not a list).


text:
Q: Change Voice Memos microphone to the non-system setting one How can I change the Voice Memos microphone?
Even though Voice Memos User Guide says

To create a recording, use the built-in microphone, a supported headset or an external mic

I can't see how can I choose which one to use.
QuickTime Player lets me choose the microphone to make new recordings with. I am not forced to use the system setting.
Can I customise Voice Memos to also use an input device of my choosing, that won't necessarily be the system setting?


text:
Q: exposing .Net to COM I have some .Net functionality I am trying to use in VB6.  I have followed several tutorials.  I wrote a test program with success using the formula here: http://www.codeproject.com/Articles/3511/Exposing-NET-Components-to-COM
However, when I try to do it with my actual project, my ProgId doesn't show in the registry like my test file. I made sure property ComVisible == true
using System.Runtime.InteropServices;

namespace Controls.Graph.Web
{
    [Guid("5F9F6C6F-016A-4CFF-BD7A-3463761807E1")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface _GraphScript
    {
        [DispId(1)]
        string getGraphXml();
    }

[Guid("35901BC6-EFF1-490C-84FA-786E8462C553")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId(ProgIds.GraphScript)]
public class GraphScript : _GraphScript
{
    protected GraphScript()
    {
    }

    /// <summary>
    ///
    /// </summary>
    /// <returns>The graphs xml and javascript</returns>
    public string getGraphXml()
    {
        DisplayDefaults tempDefaults;
        tempDefaults = new DisplayDefaults();

        GraphConstructor graph = new GraphConstructor();
        graph.constructGraph();
        GraphModel completedGraph = graph.Graph;

        return GraphControl.RenderGraph(completedGraph, tempDefaults, 1) + GraphControl.RenderGraphScript();
    }
}
}

and my progid...
using System;

namespace Controls.Graph.Web
{
    /// <summary>
    /// ProgID Constant
    /// </summary>
    public static class ProgIds
    {
        public const string GraphScript = "GraphData";
    }
}

I'm not sure which piece of the puzzle I'm missing here
EDIT: actually the Guid shows up in the registry however the Progid still is not.  Any ideas/suggestions?
also made sure to do this:

A: I have figured out what was wrong.  I needed to change some access modifiers to PUBLIC -- including my GraphScript() constructor.


text:
Q: How to mock AWS S3 getObject with sinon I'm trying to unit test a restify route that returns an S3 object from a bucket
my route is:

module.exports = function(server) {
  server.get('/configs/:version', (req, res, next) => {
    const s3 = new AWS.S3();

    const params = {
      Bucket: 'testBucket',
      Key: 'testKey'
    };

    function send(data, next) {
      res.setHeader('Content-Type', 'text/plain');
      res.setHeader('Cache-Control', 'no-cache');
      res.status(200);
      res.send(data.Body);
      next();
    }

    s3.getObject(params, (err, data) => (err) ? next(err) : send(data, next));
  });
};

For my unit test I've been trying to mock the S3 constructor so I can stub getObject and failing miserably.

describe('#configs', () => {
  let req;
  let res;
  let next;
  let server;
  let config;
  let AWS;
  let S3;
  let route;

  beforeEach(() => {
    req = {
      params: {
        version: 'testVersion'
      }
    };

    res = {
      send: sinon.spy(),
    };

    next = sinon.spy();

    server = {
      get: sinon.stub(),
    };

    config = {
      get: sinon.stub(),
    }

    AWS = () => {
      return {
        S3: () => {
          return {
            getObject: sinon.stub()
          }
        }
      }
    }

    route = proxyquire(process.cwd() + '/lib/routes/configs/get', {
      'configs.js': config,
      'aws-sdk': AWS,
    });

    route(server);
  });

  describe('#GET', () => {
    it('Should register configs get route', () => {
      let s3 = sinon.createStubInstance(AWS.S3, {
        getObject: sinon.stub(),
      });

      server.get.callArgWith(1, req, res, next);
      expect(server.get).calledOnce.calledWith('/configs/:version');
      expect(s3.getObject).calledOnce.calledWith({
        Bucket: 'testBucket',
        Key: 'testKey'
      });
    });
  });
});

But I getting this error:
TypeError: undefined is not a spy or a call to a spy! on the getObject method.
After reading sinon docs over and over again I can't understand how to mock the constructor, how can I stub the getObject method so I can make sure it's being called correctly and it's returns so I know it's responses are being treated correctly Can someone help me with this?

A: Finally made my mocks work, the issue was that I was mocking AWS as a function not has an object, it's S3 that needs to be mocked as a function, because it's S3 that needs to be instantiated. This is how the mock should look like:
function S3() {
  return s3;
}

s3 = {
  getObject: sinon.stub(),
  putObject: sinon.stub()
};

AWS = {
  config: {
    update: sinon.stub()
  },
  S3: S3
};

Like this if one needs to mock putObject, he just needs for example do this:
s3.putObject.callsArgWith(1, err, data);

A: const getObjectStub = AWS.S3.prototype.getObject = Sinon.stub();
    getObjectStub.yields(null, {
    AcceptRanges: "bytes",
    ContentLength: 3191,
    ContentType: "image/jpeg",
    Metadata: {
    },
    TagCount: 2,
    VersionId: "null"
   }
);


text:
Q: For-loop running more iterations than expected? Disclaimer
Im sorry for that question might be inapropriate on stack, and I probably miss something. There is just something that I totally do not understand.
Id be very happy if you could give more insights to whats happening there, or, if this question is inapropriate on stack to give me a hint where such debugging questions might be apropriate.
Question
I recently created a unit test looping x iterations, calling a class to calculate averages.
Minimal reproducible example:
public void StaticPositiveValues()
{
    for (int b = 0 ; b < max; b+= stepSize)
    {
        progressingAverage.AddValue(4.0);
    }
}

To my understanding, progressingAverage.AddValue(result); is beeing called int.MaxValue/20 (20) times.
progressingAverage.AddValue(result); contains a counter iterating by one each time.
Once int.max is reached in the counter, an exception is thrown.
For some unknown reason to me, this exception is beeing hit. Eventhough the amount of times it should end up at most ~20 to my understanding.
public class Progressing_Average_Double
{
    // init class with 0
    public Progressing_Average_Double()
    {
        _Count = 0;
        Value = 0;
    }
    // the currently calculated average
    public double Value { get; private set; }
    // the amount of values added already. Serves calculation
    private int _Count { get; set; }
    // adds a new input value to average value.
    public void AddValue(double input)
    {
        //  at this point this class is not suitable to calculate
        if (_Count == int.MaxValue)
        {
            throw new IndexOutOfRangeException("max amount has been reached! use preciseaverage or moving avg instead!");
        }
        // Increments counter by one.
        _Count++;
        // calculate the new average
        Value += (input - Value) / _Count;
    }
}

I could imagine that in my main loop, Progressing_Average_Double progressingAverage = new Progressing_Average_Double(); does not properly reset the class but thats mostly a shot into thin air from my part.


text:
Q: Elasticsearch: Could not parse date from the value I am getting this error, some times, while I scan documents for an export:
elasticsearch_dsl.exceptions:ValidationException:
Could not parse date from the value (u'2016-11-03T21:46:09.278914+00:00')

Traceback:
File "/usr/local/lib/python2.7/dist-packages/elasticsearch_dsl/search.py", line 666, in scan
File "/usr/local/lib/python2.7/dist-packages/elasticsearch_dsl/document.py", line 216, in from_es
File "/usr/local/lib/python2.7/dist-packages/elasticsearch_dsl/document.py", line 108, in __init__
File "/usr/local/lib/python2.7/dist-packages/elasticsearch_dsl/utils.py", line 339, in __init__
File "/usr/local/lib/python2.7/dist-packages/elasticsearch_dsl/field.py", line 76, in deserialize
File "/usr/local/lib/python2.7/dist-packages/elasticsearch_dsl/field.py", line 224, in _deserialize

Using:

*

*Elasticsearch 2.4.0

*elasticsearch==2.4.0

*elasticsearch-dsl==2.1.0

Any ideas why and how to fix it?
Edit: Parsing the date works, as can be seen in the example below taken from official elasticsearch_dls repo https://github.com/elastic/elasticsearch-dsl-py/blob/master/elasticsearch_dsl/field.py#L222:
from dateutil import parser

x = '2016-11-03T21:46:09.278914+00:00'
print parser.parse(x) # will output 2016-11-03 21:46:09.278914+00:00


text:
Q: Bootstrap 4 using Flexbox with responsive columns but column unresponsive content I need to create the following layout:
Initial:

After resizing:

So, Group 1 and Group 2 don't wrap.
But what I get is this:

Here is my code:

    <input type="button" value="Group 1"/>
    <input type="button" value="Group 1"/>

    <input type="button" value="Group 2"/>
    <input type="button" value="Group 2"/>

Codeply
Thanks for the help.
Update.
If I add flex-column to the top div I kinda get what I need but then when I resize Group 2 goes into the new row way too early. There is still plenty of space between Groups there is no need for two rows.

A: Add flex-wrap to

so it becomes

Fiddle demo


text:
Q: Debian: How to set an empty password for user "sync"? The Debian documentation at https://wiki.debian.org/SystemGroups says:

sync: The shell of user sync is /bin/sync. Thus, if its password is
  set to something easy to guess (such as ""), anyone can sync the
  system at the console even if they have don't have an account.

I want to follow that advice. But it is not easy to allow an empty-password login for a particular user.
I guess I would have to re-configure PAM somehow to allow this.
What is the least intrusive way to do this?
I do not want to allow empty passwords for all users, just for this particular user.
I also would prefer to add an additional "plug-in" configuration files to /etc/pam.d/ rather than modifying an existing file there (which might create trouble for future updates).
Is this possible? And if, how?

A: the easiest way is probably to directly edit your password-file:
# vipw -s

(this will open the shadow file (-s) with the "password editor" (vipw).

*

*locate the "sync" entry (it will look like sync:*:12345:0:99999:7:::

*the second entry (*) in the line is the actual password (* being an illegal password, so the account is actually locked; if you have set a real password, you will see some hash value)

*remove the password, so you get something like sync::12345:0:99999:7:::
(so there is nothing between the 1st and the 2nd : colon); keep the rest of the line intact)

*save the file and exit the editor

now you are done. test by logging in as user sync.
# login -f sync

otoh, I'm not really sure whether this is really what you want (as it requires physicial access to the computer to login as the sync user. ssh will prohibit empty passwords,...)


text:
Q: Change videos frame rate (fps) in python I would like to know if it is possible to change the fps of a video.
I have videos of 24, 25 and 30 fps and I would like to change them all to 30 fps.
Thank you

A: With moviepy one can simply try this:
from moviepy.editor import *
clip = VideoFileClip(video_input_path)
clip.write_videofile(video_output_path, fps=30)
#clip.reader.close()

A: I finally solved the problem:
import subprocess

c = 'ffmpeg -y -i ' + video_input_path + ' -r 30 -s 112x112 -c:v libx264 -b:v 3M -strict -2 -movflags faststart '+video_output_path

subprocess.call(c, shell=True)


text:
Q: What does "Message Catalog Not Found" mean? I have a MDB running in WebSphere, when it tries to pull a message off an MQ Queue
the following exception is thrown:
com.ibm.mq.MQException: Message catalog not found
Any idea how to resolve this?

A: Add the directory containing the mqji.properties file to the CLASSPATH

A: Google says it's a missed entry in the classpath:
http://www.mqseries.net/phpBB2/viewtopic.php?t=5979&highlight=mqji

A: The mqji.properties files is already included in the mq jar file.
The Message Catalog not found exception is thrown as part of a "MQJMS2002: failed to get message from MQ queue".

A: It turns out that this error was thrown because I had the Queue Connection Factory defined
at server level (on the WebSphere v6 server) and the wrong classloader was being used to
load the above mentioned properties file.
I solved the issue by redefining factory at cell level.

A: Since the error message you'll be getting with the message catalog is pretty useless, too, here is a little patch for the mq.jar:

*

*Get jad

*Disassemble MQException and MQInternalException (the latter is only necessary because it inherits from MQException; we won't change it).

*Add this code to MQException:
    // PATCH New fields
    private final static IntHashMap completionCodes = new IntHashMap ();
    private final static IntHashMap reasonCodes = new IntHashMap ();
    static
    {
        addCodes (completionCodes, "MQCC_");
        addCodes (reasonCodes, "MQRC_");
    }

    /**
     * PATCH Create a map of names for the MQ error codes
     *
     * @param map
     * @param prefix
     */
    private static void addCodes(IntHashMap map, String prefix)
    {
        Field[] field = MQException.class.getFields();

        try
        {
            for (int i = 0; i < field.length; i++)
            {
                String name = field[i].getName();
                if (name.startsWith(prefix))
                {
                    name = name.substring(prefix.length());
                    int value = field[i].getInt(null);
                    map.put (value, name);
                }
            }
        }
        catch (IllegalArgumentException e) {
            throw new RuntimeException (e);
        }
        catch (IllegalAccessException e) {
            throw new RuntimeException (e);
        }
    }

*Replace getMessage() with this code:
    // PATCH Complete rewrite
    public String getMessage()
    {
        if(ostrMessage == null) {
            String rc = (String)reasonCodes.get(reasonCode);
            if (rc == null)
                rc = "ReasonCode "+reasonCode;
            String cc = (String)completionCodes.get(completionCode);
            if (cc == null)
                cc = "CompletionCode "+completionCode;

            String message = "MQJE001: "+cc+" "+rc;

            if(msgId == 0)
                ostrMessage = message;
            else {
                String s = msgId+" {0} {1}";
                if (exceptionMessages != null) {
                    s = exceptionMessages.getString(Integer.toString(msgId));
                }
                if(numInserts > 0) {
                    Object as1[] = new String[numInserts];
                    if(numInserts > 0) as1[0] = insert1;
                    if(numInserts > 1) as1[1] = insert2;
                    s = MessageFormat.format(s, as1);
                }

                ostrMessage = message+"\n"+s;
            }

            if (underlyingException != null)
                ostrMessage = ostrMessage + "\n" + underlyingException.getMessage();
        }

        return ostrMessage;
    }

*Either compile these two classes into a new jar or patch the original mq.jar.
Instead of the MQJE001: RC 2 CC 2035, you'll get "MQJE001: FAILED NOT_AUTHORIZED"


text:
Q: How to use JOIN for my query? I have two tables.
One contains:
id, album name, description, etc...

Another contains:
id, album id, photo

I want to get album details and its photos through album id?
How can I achieve this?
Can I use left join?

A: Assuming your tables are called Albums and Photos:
SELECT Albums.*, Photos.Photo
FROM Albums
LEFT JOIN Photos
ON Albums.id=Photos.album_id
WHERE Albums.id=42

A: select a.id, a.album_name ..., b.photo
from albums a
left join OtherTable b on a.id = b.album_id

A: SELECT *
FROM album a JOIN photo p
ON a.id=p.album_id
WHERE a.id= 11


text:
Q: How to get list of all constraints present in a table in Oracle? I have a table named STUDENT with following attributes:
enroll VARCHAR(20),
name VARCHAR(50),
age INT,
fees FLOAT(6,2)

Now I want to know that which all constraints (like Primary Key, Unique Key, NOT NULL, etc) are present in this table. Kindly let me know how can I get this?

A: You can get it from user_constraints
SELECT *
FROM user_constraints
WHERE table_name = 'STUDENT'

Make sure you pass the STUDENT in caps. table_name is case sensitive
To know the constraint type check this column CONSTRAINT_TYPE
Type of constraint definition:
C (check constraint on a table)
P (primary key)
U (unique key)
R (referential integrity)
V (with check option, on a view)
O (with read only, on a view)

A: You can use the JOIN on two tables USER_CONSTRAINTS and USER_CONS_COLUMNS  to fetch the Column Name, Constraint Type and Table Name.
SELECT ucc.COLUMN_NAME, uc.CONSTRAINT_TYPE ,uc.TABLE_NAME
FROM USER_CONSTRAINTS uc  JOIN  USER_CONS_COLUMNS ucc
ON uc.CONSTRAINT_NAME = ucc.CONSTRAINT_NAME
AND uc.TABLE_NAME=ucc.TABLE_NAME
WHERE uc.TABLE_NAME='mytablename';

Constraint Definition can be referred as:
C (check constraint on a table)
P (primary key)
U (unique key)
R (referential integrity)
V (with check option, on a view)
O (with read only, on a view)

For more information you can view Oracle Documentation here

A: Try this View query and specify your Table name to get all the constrains detail.
SELECT *
  FROM user_cons_columns
  WHERE table_name = '<YOUR_TABLE_NAME>';
Or
SELECT *
  FROM user_constraints
  WHERE table_name = '<your table name>'
  AND constraint_name = '<your constraint name>';

A: just use describe
describe student
but remember you should use Web browser mode for it


text:
Q: Firefox vim mode, can't switch to normal mode in style editor When I use vim mode in firefox dev tools settings, Esc trigger split console in the style editor. So, I can't leave insert mode. In the scratchpad Esc works well tho, but in the style editor there is always split console. Is there a way to redefine split console to another key, or what will be even better to redefine Esc for vim mode?

A: You can use Ctrl-C for this purpose.

A: This is definitely a bug.  Thanks for pointing it out!  CC your email address on the bug to get emails pertaining to resolution and updates.


text:
Q: onchange check password to be similar I have created a small fields for checking password to be similar like while writing confirm password it should verify whether the confirm password is similar or not I have created but it is not working can somebody help me out with this please.
My code:

function ppd() {
  var password = $("#password").val();
  var confirm_password = $("#confirm").val();

  if (password != confirm_password) {
    $("#confirm").css('border-color', "#c80000");
    $("#textboxid").css({
      "background-color": "#fee2e2"
    });
  }
}

  <input type="password" id="password" name="" placeholder="Password" class="form-control" />

  <input type="password" id="confirm" onChange="ppd();" name="" placeholder="Confirm Password" class="form-control" />

jQuery Fiddle Here

A: You need to trigger onkeyup event handler.The event is triggered after the character is typed into the form field.
Here is solution.

document.getElementById('confirm').onkeyup=function(){
    var password = $("#password").val();
 var confirm_password = $("#confirm").val();
 if(password != confirm_password) {
           $("#confirm").css('border-color', "red");
 }
        else{
           $("#confirm").css('border-color', "green");
        }
}

     <input type="password" id="password" name="" placeholder="Password" class="form-control" />

 <input type="password" id="confirm"  name="" placeholder="Confirm Password" class="form-control" />

Another solution is to use oninput method.
document.getElementById('confirm').oninput=function(){
  //code here
}

A: I have checked your code on your given fiddle. There is nothing wrong in it except lastline as you have not div with this id.
    $("#textboxid").css({"background-color": "#fee2e2"});

Your code is absolutely correct and it is better to use onchange in this scenario. Just you have to understand how onchange works here. The onchange event is fired when the element loses the focus and the contents have changed since the last time the element got the focus.
I dont know what's wrong there, may be jquery file is not working or else.
This code is working.

                        <input type="password" id="password" name="" placeholder="Password" class="form-control" />

                        <input type="password" id="confirm" onChange="ppd();" name="" placeholder="Confirm Password" class="form-control" />

Javascript
function ppd(){
var password         = $("#password").val();
var confirm_password = $("#confirm").val();

if(password != confirm_password) {
    $("#confirm").css({'border-color': "#c33"});
    $("#password").css({"background-color": "red"});

}
}
I giving you link of my codepen with your own code.check here


text:
Q: 4-bit counters not working properly I have three SN74HC161N connected such that an overflow on the first triggers the second etc. (the normal ripple carry setup, where RCO feeds into ENT). The clock inputs of these are connected to a 1 MHz oscillator. The voltage in the circuit is 5V.
From what I can see from the data sheets (https://www.ti.com/lit/ds/symlink/sn74hc161.pdf and https://www.ctscorp.com/wp-content/uploads/MXO45_MXO45HS.pdf) everything should work properly. It seems like the maximum frequency for these counters would be 1 / 500 ns =  2.00 MHz, well above the 1 MHz frequency of my oscillators. I have verified that the counters work using a much slower clock (a 555 timer), but for some reason it doesn't count when using oscillators (I've tried several of them). Have I misunderstood the data sheets (English isn't my native language), or am I overlooking something here?

(Larger version of image)
Below are some pictures of the actual circuit. I've used yellow wires for ground connections (except the four going to LEDs). Red and orange (and one white) indicates power (5V). The green wires (and the longer oranges) are just used for connections between different counters. All capacitors are 0.1 µF, except for the one connected to the 555 timer (on the right) which is 3.3 µF. As the image shows, the long blue wire is connected to the clock inputs of the counters and is currently driven by the oscillator, meaning the 555 isn't really doing anything as for now.
Also a little note: In the schematic, the ENP, CLR* and LOAD* pins are directly connected to 5V, but in the actual hardware I've used green/orange wires to wire them together.
I apologise if my pick of colours doesn't seem natural, however my arsenal of wires is pretty limited at the moment (new ones arrive in a week or two).
The red and blue wires in the top left are connected to an Arduino Uno's 5V and GND pins.

A: Summary: Seeing those photos, there are several concerns (including the decoupling capacitors' location, type & value, and the lack of connections to 74HC161 inputs A-D). Making the circuit work reliably might be an iterative process for you.
However, the first and clearest problem is: You have connected the oscillator wrongly. You need to swap your connections to pins 8 & 14 on the oscillator.

Details:
Looking at the package drawing from the datasheet for your MXO45 oscillator, with my annotations in red:

For the MXO45 "DIP-14" version you have, it has 4 pins actually present in DIP pin positions 1, 7, 8, 14.
Its pinout is:

So in text form for the "DIP-14" version:

Pin
Symbol
Function

1
EOH
Enable (not used on MXO45 version)

7
GND
Ground

8
Output
RF Output

14
Vcc
Supply Voltage

But you have connected:

Pin
Symbol
Connection

1
EOH
Supply Voltage (not used on MXO45 version)

7
GND
Ground = OK

8
Output
Supply Voltage = NOT OK

14
Vcc
Output to 74HC161 = NOT OK

We can see those incorrect connections, in the photo of the oscillator on the breadboard you kindly added:

So your 74HC161 counters are not getting a clock signal, because they are connected to the power pin on the oscillator to which 5 V should be supplied.
Connecting an oscillator's output pin to the 5 V supply, might have permanently damaged it (I don't see a claim in the datasheet that the oscillator will survive a shorted output pin). Since you said that you have tried several oscillators, then you might have damaged them all.
If the oscillators you have are still undamaged then, as a starting point, swap the connections to oscillator pins 8 & 14, so that the 74HC161 counters are connected to the oscillator output on "pin 8" and supply 5 V Vcc to the oscillator on "pin 14".
I would also disconnect pin 1 of the oscillator, as your MXO45 version does not support the output enable function (see page 1 of the datasheet) - the MXO45T or MXO45HST 8-pin versions do support that functionality.

A: There are any number of possibilities. An obvious one is the parallel load inputs A-D and the various enable inputs. Are these left floating? If so, you are asking for trouble. With 74HC, ALL inputs must be tied to logic high or low - no exceptions.
Another thing - how is your circuit constructed? Are you using a ground plane? Or at least good tight construction with fairly beefy (and short) wires connecting the grounds together, as well as the +5 lines?
Finally, assuming your ground/power network is OK, what are you doing for decoupling? Each IC should have a 0.1 uF ceramic capacitor between Vcc and ground - and connected as close as possible to (in this case) pins 8 and 16.


text:
Q: How to remove main menu only on homepage? I have one issue that cant resolve.
Im trying to hide main menu on my homepage but keep floating menu when scroll down. I found this CSS:
.fusion-main-menu {
display:none;
}

but this code also remove menu items from sticky floating menu when user scroll. So i want to remove main menu only on homepage, and keep sticky floating menu . How to do that? Thanks

A: Try this, it will hide only when it's sticky:
.fusion-main-menu ul a.fusion-top-level-link {
    display: none !important;
}

.fusion-is-sticky .fusion-main-menu ul a.fusion-top-level-link {
    display: block !important;
}

or
.fusion-main-menu ul a.fusion-top-level-link {
    visibility: hidden !important;
}

.fusion-is-sticky .fusion-main-menu ul a.fusion-top-level-link {
    visibility: visible !important;
}


text:
Q: I cannot find my app on Google Play with app name. I can find using package name I have uploaded an app on Google Play "First Steps" two days back. When I try to find the app on Google Play using the name, I cannot find it. The package name is com.systology.firststeps. Using "systology", I am able to find it.
I gave the app name properly in Google Console. Also, in description, I have put the app name.
Can someone help in telling me what am I missing on?
Thank you

A: As you have given the name of your application First Steps so the google will always look for the first word to search for and will give you the result according to the first word of your application which matches the most of the application's on the playstore.
If you want to get the exact result of your application on play store you will have write First Step Systology then you will get your application only.
Check out https://play.google.com/store/search?q=First%20Steps%20systology&c=apps


text:
Q: How to capitalize ONLY the first letter of an HTML option element using CSS? text-transform: capitalize does not work in this case because the text is already uppercase.
<select>
    <option>
      OPTION
    </option>
</select>

This did not work either.
select{
  -webkit-appearance: none;
  text-transform: lowercase;
  display: inline;
}

select option::first-letter{
  text-transform: uppercase;
}

It should work on Chrome (at least) using CSS (and not JS).

A: In Chrome and Firefox, you can style an option element if its select has a size greater than 1.
You can exploit this as follows:

select {
  height: 1.4em;             /* show only one option when not focused */
}

select:focus {
  height: 100%;              /* show all options when focused */
}

option  {
  text-transform: lowercase; /* change to lowercase */
  padding-right: 2em;        /* the select's width is based on width of its longest non-transformed ... */
                             /* option.  padding ensures that option is completely visible */
  display: none;             /* hide all options by default (see below) */
}

option::first-letter {
  text-transform: uppercase; /* change first letter to uppercase */
}

option:checked, select:focus option {
  display: block;            /* show selected option, or show all options when the select is focused */
}
<select size="4">
  <option selected>NOW IS THE TIME</option>
  <option>for all good men</option>
  <option>tO Come To tHe aid</option>
  <option>of the party</option>
</select>

It won't quite act like a normal select box, and Chrome has a strange behavior in that the selected option will have a gray background.  Can't figure out how to prevent that.


text:
Q: Where do files go when you delete them programatically with swift? Where do files go when you delete them programatically? I deleted them with this code, but the Trash for today is empty. Is it possible to retrieve them?
let filemgr = NSFileManager.defaultManager()
        do{
            let filelist = try filemgr.contentsOfDirectoryAtPath(fontFolderPath)
            for filename in filelist {
                do{ try filemgr.removeItemAtPath(fontFolderPath+filename)} catch{}
            }
        }catch{}

A: Using the URL related API of NSFileManager you have two options:

*

*func removeItemAtURL(_ URL: NSURL) throws
deletes the item immediately like /bin/rm in Terminal.app and has the same functionality as removeItemAtPath.

*func trashItemAtURL(_ url: NSURL,
resultingItemURL outResultingURL: AutoreleasingUnsafeMutablePointer<NSURL?>) throws
moves the item to the trash folder returning the item's location in the trash via the inout pointer.

A: The removeItemAtPath method deletes them. They're gone. If you want to move something to the trash, you need to use NSWorkSpace. You can see an example of moving an entire directory to the trash here: Move directory to trash

A: basically unixy systems manage files the same way, there is a ref count, that is the number of hard links + times the file is open... So you can rm an open file, and the file will still exist, you can write to it, and read from it, with a valid file descriptor or FILE * stream object, then when it is closed the file will actually be removed from the disk...
int fd = open("somefile", O_RDWR);
unlink("somefile"); // removes somefile from the directory listing, but not disk
write(fd, "hello", 5);
lseek(fd,0,SEEK_SET); // seek to start of file
char buffer[6] = {0};
read(fd,buffer,5); // reads in "hello"
close(fd); // last reference removed, file is removed.

if you want to move a file to the Trash, that is a different operation and specific to OS X and iOS


text:
Q: -ms-high-contrast-adjust equivalent in IE9 One of our CSS files uses -ms-high-contrast-adjust: none to make sure some background features show up even under high contrast mode. It works fine on IE10 and IE11. Now we're trying to port the same CSS to IE9, and obviously it's not supported.
What's the equivalent of the -ms-high-contrast-*** property under IE9? Is there some other way to trick the browser to not change features with the "high contrast mode" setting?

A: There ain't an equivalent.

Remarks
  The -ms-high-contrast media feature was introduced in Windows 8.

It's for ie10.
You can test it with media-queries like:
@media screen and (-ms-high-contrast: active) {/* ... */}
@media screen and (-ms-high-contrast: black-on-white) { /* */ }
@media screen and (-ms-high-contrast: white-on-black) { /* */ }

http://msdn.microsoft.com/en-us/library/windows/apps/hh465764.aspx
Some developers use it to target IE10 with media queries :
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
   /* i-love-ie */
}

PS, this is kind of freaky, you want a browser to force an OS to display in a specific way, or display in a specific way over the OS.
[HOLD ON]
i JUST found this article from Steve Faulkner : http://blog.paciellogroup.com/2010/01/high-contrast-proof-css-sprites/

CSS sprites using the before: pseudo element
An alternative to implementing CSS sprites using the traditonal
  background-image method is available and it resolves the issue of
  images not being displayed in high contrast mode. This alternative
  method makes use of the CSS before: pseudo element (note: the after:
  pseudo element could also be used). Example:
Link with a home icon and text with default display colors. Link with
  a home icon and text with windows high contrast colors.

CSS
span.test1:before {
margin-right: -10px;
content: url(icons.png);
position:relative;
left:-2px;
top:-109px;
}

span.test1 {width:17px;
height:18px;
display:inline-block;
overflow:hidden;}

HTML
Home

I have no time to test it. Give it a try and come back to us so i can 'correct' this answer if needed.


text:
Q: How to handle mobile hardware back button in react js Product Search Page Screeshot

*

*User lands on to Home page.

*Then home to Search page.

*Then go to Filter page when tap on filter button on search page.

*Then select Filter like category, color which updates the browser URL.

*When new query and user press apply button.

*Then we that query string we come back on search page and product loads again.

Now problem is

*

*When we press back button we again go to filter

*When we to got home page when we are on search.

*When we select filter on filter page like category, colors and press back button
filters get unselected as URL again update, so how to tackle that or disable hardware back button of mobile phone.
Filter Page Screenshot


text:
Q: How to Analyze Frequency Data with Between-Within Factors I'm trying to analyze data from an intervention study that has 70 participants separated into two groups (Control and Intervention - Between Subjects) and looks at pre-post data (Within Subjects)  The dependent variable is the number of times a certain document was accessed.  Prior to the intervention, baseline data was examined in both groups, the intervention was implemented, and then the number of times the document was accessed was examined again to see whether there were difference between the control and intervention group.
        BASELINE | POST
CONTROL     6       17
INTERV      3       11

Considering we have 1 between variables (group) and 1 within variable (time), with frequency/count data as the DV, what's the best analysis for this time of data? I know we can't do Chi-Squares because of the within-subjects metric.
Edit: To answer some questions below, I have individual subject data (i.e. if the individual accessed the data at baseline, and if they accessed it post-int).  The group were randomized; n = 35 for the control and n = 36 for the intervention group.  I can't explain why Control accessed the doc more during baseline, other than simple variance.
Any help would be appreciated, thanks.

A: I suggest a nonlinear multilevel model with a logistic link.
One level is the individual and the other level is the group. Although it's better to have more time points, these models sometimes work well even with only two time points.


text:
Q: programmatically manipulate survey list perform add update delete operation I want to create Polling app. For that i want to learn about survey list. That can I add update delete survey list data Programmatically.? First of all i want to create a web part which perform this but I am not able to find any logic according to this on google.
I am trying to search web part which lets me know how to manipulate Survey List?

A: surveys are just another type of lists, you insert items the same way you do it with normal lists
Here is sample code for manipulate list
SPList list = web.Lists["My survey"];
web.AllowUnsafeUpdates =true;
SPListItem item = list.Items.Add();
item["This is my question number 1"] = "this is the answer";
item.Update();
web.AllowUnsafeUpdates =false;

Hope this helps


text:
Q: Instantiated a struct which is a part of iOS framework and has internal access control I would like to instantiate a struct which is a part of third party iOS framework and cannot be instantiated from outside means has internal init. But I need to create for Unit testing. Any idea how to achieve this?

A: As Writing Test Classes and Methods documentation states:

Xcode provides a two-part solution to this problem:

*

*When you set the Enable Testability build setting to Yes, which is true by default for test builds in new projects, Xcode includes the
-enable-testing flag during compilation. This makes the Swift entities declared in the compiled module eligible for a higher level of access.

*When you add the @testable attribute to an import statement for a module compiled with testing enabled, you activate the elevated access
for that module in that scope. Classes and class members marked as
internal or public behave as if they were marked open. Other entities
marked as internal act as if they were declared public.

@testable import MySwiftFramework


text:
Q: Component dependency issue when upgrading Magento 2 from 2.0.7 to 2.1.0 I need to upgrade from magento 2 2.0.7 to 2.1.0. I tried by using composer  commands.
composer require magento/product-community-edition 2.1.0 --no-update

composer update

But I got an error like below:

*

*Can only install one of: magento/framework[100.1.0, 100.0.9].

*Can only install one of: magento/framework[100.1.0, 100.0.10].

*magento/product-community-edition 2.1.0 requires magento/framework 100.1.0 -> satisfiable by magento/framework[100.1.0].

*Installation request for magento/product-community-edition 2.1.0 -> satisfiable by magento/product-community-edition[2.1.0].

Could someone please give me some ideas?


text:
Q: How does $(2k+1)^2$ become $4k^2 + 4k + 1$? I'm currently following a course where the professor did the following simple calculation:
$$(2k+1)^2 = 4k^2 + 4k + 1$$
Now, I just do not understand any world where this can be the case.
Could someone please explain to me why $(2k+1)\times(2k+1)$ can ever result in only one $1$, and reduced to $2k$?
This is so extremely nonsennsical for me.

A: Recall the distribution property:
$$a(b+c) = ab + ac$$
In this case, we can distribute the factor of $2k+1$:
$$(2k+1)^2 = (2k+1)(2k+1) = (2k+1)2k + (2k+1)1$$
You can already at this point see why we would have $1$ as your constant: the first term will have $k$'s in it because of the $2k$ factor, while the latter term is just $2k+1$, explaining where the $1$ comes from.

You could alternatively use the formula for squaring a binomial:
$$(a+b)^2 = a^2 + 2ab + b^2$$
Then, in $(2k+1)^2$, $a=2k,b=1$:
$$(2k+1)^2 = (2k)^2 + 2(2k)(1) + (1)^2 = 4k^2 + 4k + 1$$

Perhaps a diagram? Imagine a square of width $2k+1$. You can visualize it as so:

The area of this square is obviously $(2k+1)^2$, right? If you add up the area of each rectangle however, you'll get $4k^2 + 4k +1$, establishing equality between the two exressions.


text:
Q: Issue with downloading file express.js I have been trying to download file from Google drive api using express.js
So I have been getting file stream from Drive and sending it in response. I am also setting content-disposition:attachment, fileName and Content-type.
When I am testing this route using fiddler it is showing the content type and fileName. But when called in browser it downloads the files but does not set the fileName and its extension.
E.g: MineType is image/jpeg and it is downloading the file as jfif format with random name.
Some help will be really appreciated. Thanks
Following are the code snippets I am using

function downloadFile(auth,fileId){
  return new Promise((success,failure)=>{
    const drive = google.drive({version: 'v3', auth});
    drive.files.get({
      fileId:fileId,
      alt:'media'
    },
    (err,res)=>{
      if(err)
        return failure("Unable to download file");
      return success(res.data);
    });

  });
}

app.get('/DownloadFile/:id',function(req,res){
 res.header('Access-Control-Allow-Origin', '*');
   res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
 Drive.readFile(CREDENTIALS_PATH)
 .then((credentials)=>{
  readTokens() //will call db.readTokens here
  .then((returnObj)=>{
   token=returnObj.token;
   refreshToken=returnObj.refreshToken;
   Drive.createAuthOjectWithTokenRefresh(credentials,token,refreshToken)
   .then((oAuth2Client)=>{
    Drive.getFileDetails(oAuth2Client,req.params.id)
    .then((details)=>{
     res.header("Content-Disposition","attachment");
     res.header("filename",details.name);
     res.header("Content-Type",details.mimeType);
     Drive.downloadFile(oAuth2Client,req.params.id)
     .then((file)=>{
      res.send(file);
      res.end();
     })
     .catch((err)=>{
      res.end(err.message);
     });
    })
    .catch((err)=>{
     res.end(err.message);
    });
   })
   .catch((err)=>{
    res.end(err.message);
   });

  })
  .catch((err)=>{
   res.redirect("/Authenticate");
   res.end();
  });
 })
 .catch((err)=>{
  res.redirect(err);
 });
})

A: After some testing and brainstorming found the issue. So Google Drive Api sends the file data in JSON string format. When sent as string it losses most of the characters and the file gets corrupted. Found that Get functions receives an optional parameter named responseType which can receive 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' as value. This optional parameter is not documented in the drive api.
https://developers.google.com/drive/api/v3/reference/files/get
What worked for me:
drive.files.get({
  fileId:fileId,
  alt:'media'
},{
  responseType:'arraybuffer'
},
(err,res)=>{
  if(err)
    return failure("Unable to download file");
  return success(res.data);
});


text:
Q: Trying to ask for the exact time when I can tour an apartment which I am interesting renting I was requesting a tour of an apartment I am interested in renting. The future landlord said I could come later afternoon after the cleaning is done. So I want to ask for the exact (or at least approximate) time when the cleaning is done, and the place is ready for me to take a tour. I was struggling to say that, here are a few ways that I have thought of:

*

*"when exactly can I come to take a tour?"

*"what's the ETA on the cleaning?"

Can you folks also suggest a few other ways to say this?

A: "ETA" sounds a little silly.  Like you are some kind of military guy.  Unless you are talking about an "Expected Time of Arrival", don't use ETA.
The first is fine.  Or you could confirm a time and let them respond

I'll come for the tour at 4 pm.  See you then.

If 4pm is too early, it is up to the estate agent to contact you.


text:
Q: In Python using Pandas, is it possible to read 4B rows chunkwise and filter each chuck against a 30M row dataframe already in memory? Have a 4B row table in Oracle and a 30M row CSV, both tables share 2 columns on which I want to filter the large table using the smaller table. Due to security restrictions, I cannot load the 30M row CSV into Oracle and run a single join which would be ideal. I have also tried to use SAS Enterprise Guide for this process, but it seems to choke on the large join and fails to return before the connection to the Oracle table times out.
Python seems to be a possible solution, but the 4B row table will not fit into memory, even when reducing to the 6 columns I need (6 strings each under 25 chars). Ideally, I'd like to do the following:
csv_df = pd.read_csv(file_path)
result_df = (empty dataframe)
df_chunks = pd.read_sql(sql_query, con, chunksize = 10000000)
    for df_chunk in df_chunks:
      # convert chunk to dataframe
      # join chunk_dataframe to csv_df to get a filtered result
      # concatenate filtered result to result_df

The dataframe result_df will then be the set of all filtered rows from the 4B row Oracle table.
Thanks for any assistance!

A: You could do it like this:
csv_df = pd.read_csv(file_path)
result_df = (empty dataframe)
df_chunks = pd.read_sql(sql_query, con, chunksize = 10000000)
chunk_list = []
for df_chunk in df_chunks:
    result = pd.merge(df_chunk, csv_df, on=['XXX'])
    chunk_list.append(result)
result_df = pd.concat(chunk_list)


text:
Q: Can't import components into React main JS file I've been trying to learn React for a while now, and my mentor gave me the task of learning how to create (in React) a to-do list. I've been watching a tutorial, everything went well at first, but I got stuck when starting to use components.
In the tutorial, he creates a different component for the "form", which I'll recall in the App.js file.
Here is the App.js file:
    import './App.css';
import Form from './components/Form';

function App() {
  return (

 Adi's ToDo list

  );
}

export default App;

Here is also the Form.js file:
function Form() {
  return (
    <form>
      <input type="text" class="todo-input" />
      <button class="todo-button" type="submit">

      </button>

        <select name="todos" class="filter-todo">
          <option value="all">All</option>
          <option value="completed">Completed</option>
          <option value="uncompleted">Uncompleted</option>
        </select>

    </form>
  );
}

export default Form;

VSC tells me to remove import Form from and to just use import './components/Form'; but that doesn't change anything.

A: You need to actually use Form component for VSC to not suggest removing it. Try:

 Adi's ToDo list

  <Form />


text:
Q: Seaborn, only plot 3 ticks on the y axis I have been trying to get 3 ticks on my y axis in a seaborn plot using plt.MaxNLocator(3), but for some reason it occasionally gives me 2 ticks.
Please let me know if anyone can recreate the issue from the code below, or suggest any workaround -
import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.boxplot(x="day", y="total_bill", data=tips)
g.yaxis.set_major_locator(plt.MaxNLocator(3))
plt.show()

I believe that there should be 3 ticks on the y axis.
I would just increase the number to 4 - but this only happens occasionally depending on the axis scale so it is not ideal to tweak it for every figure.
Thanks for the help.

A: One way is to specify the minimum number of ticks to be 3. From the MaxNLocator docs:

min_n_ticks int, default: 2

g.yaxis.set_major_locator(plt.MaxNLocator(3, min_n_ticks=3))


text:
Q: Implementing simple Parallax: Images "jumpy" in Firefox and Safari I have the following use-case:

*

*a couple of content-elements with images in between

*the images should always be displayed as a whole (relate to the contain-value for the background-size-property)

*this behaviour should be the same on all viewports, resulting in the image to scale in size (but always being fully visible)

*when scrolling, every image is supposed to scroll to the top normally

*once an image hits the top, a parallax-effect should kick in

You can see my implementation here:
http://codepen.io/AvantiC/pen/BpReza
It works quite well in Chrome, the scrolling and parallax seems really smooth. But when I test the page in Firefox or Safari, the images behave "jumpy"/"jerky" (not sure whats the right word here ;) ).
I am not sure though wether it's a problem with Firefox/Safari or wether my implementation is faulty and Chrome is just somehow making up for it internally.
Maybe someone can point me in the right direction. :)
Greetings,
AvantiC

A: Rather than set the image position each and every frame, try changing the CSS so that the image stays still once the user scrolls past a certain point.


text:
Q: Bootstrap 3 - Navbar collapses on click This is an odd bug.  Each time I go to a new page by clicking a link in the navbar, the navbar will collapse and add a horizontal bar for a split second.

I have dug into some of the js and I think the class .collapsing is added for that short amount of time.  Here is what I found in the inspector.

Here is a link to the site: http://dev.apaxsoftware.com/
From there you can click through the pages on the navbar and see the issue.

A: The problem is that the navbar links contain:
data-toggle="collapse" data-target=".navbar-collapse" which was probably used to close the navbar after clicking on a link. A better solution is to use:
data-toggle="collapse" data-target=".in" so that only the active link is targeted.