text:
Q: All my devices are incompatible with lower API then compileSdkVersion 26 I already almost done in the development the apps.
I'm using android studio 3.1 But when I test using the lower API my apps doesn't works even I already set the minSdkVersion 15.
I hope you can give me some advise on this matter.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.fadhli.picbetaversionstable"
        minSdkVersion 15
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            postprocessing {
                removeUnusedCode false
                removeUnusedResources false
                obfuscate false
                optimizeCode false
                proguardFile 'proguard-rules.pro'
            }
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.basgeekball:awesome-validation:1.3'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.android.volley:volley:1.0.0'

    implementation 'com.android.support:support-v13:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.google.android.gms:play-services-places:11.6.0'
//    implementation 'com.jaredrummler:material-spinner:1.2.3'
    compile 'com.github.ganfra:material-spinner:2.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}


text:
Q: What is the use of SQL Server Integration Services Server in SQL Server 2016? In SQL Server there is a separate Server we install for SSIS but when we deploy a project it goes to SQL Server Database engine (Integration Services Catalogs, SSISDB).

What is the use of this Integration Services here? I'm new to this and couldn't find any article talking about this Integration Services login.

A: In SSIS, when you choose package deployment model and create a deployment utility ie Deployment manifest, at that time we have option of deploy it on integration services.
In SQL 2012+ By default we use project deployment which creates our .dtsx in SSISDB folder under Integration  Service Catalog.
As said in comments, it is just for compatibility purpose now.
Here is a short demonstration of how to use it :

then click next :

Now you will be able to see the package inside MSDB folder.
From here you can run the package as well as maintain it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: $\lim \sup $ : "Infinitely Often" vs "Eventually" statements I can't get the meaning of "Infinitely Often" as well as "Eventually" statements in the following :
1) if $z > \lim \sup x_n$ , then   :   $x_n < z$ eventually (that is, for all sufficiently large $n$ )
2) if $z < \lim \sup x_n$ , then   :   $x_n > z$ infinitely often (that is, for infinitely many $n$)
Any help to get meaning of these both points? The intuition behind?

A: In terms of convergence of a sequence, it doesn't matter what happens at the start, just the long-term behaviour. You can change the first million terms of a sequence without any effect on its limiting behaviour. So any statement about terms of the sequence that is true except possibly in the first million terms might as well be true if you're only interested in limiting behaviour. And the same would work for any value of a million, i.e. for any statement that's true for all $n\geq m$ , where $m$ is any constant you like. This is what it means to be eventually true.
"Infinitely often" is the opposite: if a statement such as $x_n>z$ is true infinitely often then there's no $m$ after which its negation, $x_n\leq z$, is always true (otherwise $x_n>z$ would be true at most $m$ times, i.e. finitely often). So $\neg(P\text{ eventually})$ is the same as $((\neg P)\text{ infinitely often})$.
lim sup is the answer to a question about which bounds hold eventually. If $z$ is eventually an upper bound, then $x_n\leq z$ for all $n\geq m$ and some $m$. We can turn that around: for a fixed $m$ what is the smallest $z$ which is an upper bound for all $n\geq m$? Call this $z_m$, then the lim sup is the limit of this value as $m\to\infty$. So if $z$ is bigger than the limit of $z_m$, there certainly must be an $m$ for which $z_m<z$, and this gives you (1).

A: Consider the following subsets of $\mathbb N$: $$A = \{2n\mid n\in\mathbb N\},\quad B = \{ n + 100\mid n\in\mathbb N\}.$$ Set $A$ contains infinitely many positive integers, while set $B$ not only contains infinitely many positive integers, it contains all but finitely many positive integers, or you can say that $n\in B$ for sufficiently large $n$ (you can't say the same for $A$).
Can you see the difference and which kind of subset ($A$ or $B$) corresponds to your statements?


text:
Q: Function that can count how many numbers in array A fall in the range from low to high. I'm completing a problem set for an introductory computer science class and I'm a bit confused as to what I'm supposed to be doing with this program. The question is: In one file there is a list of of scores for some participants in an athletic competition. The list is organized in the order in which the participants registered for the competition, not in order of score. A separate file contains a set of ranges. Your job is to write a program that can read the data in these two files and print a table showing how many of the participants fell into each of the given ranges.
The question is copied word for word, but I have a few questions about this question. if you could leave a comment stating your opinion about the following, that would be nice:
1) Okay, so I've written some code in order to  read the numbers from the first data file, place the numbers in the array A and return a count of the number of numbers read or N, whichever is smaller. Which follows as:
#include <stdio.h>

int readNumbers(FILE* input, int A[], int N)
{
    int n;
    n = 0;
    while (n < N&&!feof(input))
    {
        fscanf_s(input, "%f", &A[n]);
        n++;
    }
    return n;
}
int count(const int A[], int N, int low, int high){

}

2) My confusion lies in using this second function to count how many numbers in array A fall in the range from low to high, inclusive. The parameter N tells you how many numbers are in the array. And use these two functions to construct and print a table of how many participants are in each of the categories given in the second file.
Now that I try to talk myself through it, I am now even more confused. Maybe I'm just making the question more difficult. Any tips will help. Thanks

A: *

*
to count how many numbers in array A fall in the range from low to high, inclusive.

That count() could be implemented like this
int count(const int A[], int N, int low, int high){
        int i, cnt;

        for (i = cnt = 0; i < N; i++) {
                if (low <= A[i] && A[i] <= high)
                        cnt++;
        }
        return cnt;
}

*
use these two functions to construct and print a table of how many participants are in each of the categories given in the second file.

You could achieve this by using a simple loop
for (i = 0; i < number_of_categories; i++) {
        printf("%d - %d : %d\n", low[i], high[i],
                        count(A, N, low[i], high[i]));
}

Suppose you already put all those categories information to low[] and high[].

A: Not sure what the input files are supposed to look like, I guessed one number per line.
Scores file:
0
1
2
3
4
5
6
7
8
9
10
19
29
39
49
59
69
79
89
99
99
99
99
99
99
99
100

Ranges File:
0
10
11
20
21
30
31
40
41
50
51
60
61
70
71
80
81
90
91
100

Source:
#include <stdio.h>
#include <stdlib.h>

int readNumbers(FILE* input, int A[], int N)
{
    int n = 0;
    while (n < N && !feof(input))
    {
        fscanf_s(input, "%d", &A[n]);
        n++;
    }
    return n;
}
int count(const int A[], int N, int low, int high) {
    int i = 0, numbers_in_range = 0;

    for (i = 0; i < N; i++) numbers_in_range += (A[i] >= low && A[i] <= high) ? 1 : 0;

    return numbers_in_range;
}
inline int exiting(char* reason)
{
    if(reason != 0) printf("%s\n", reason);
    printf("Usage: rangechecker \"scoresfilename\" \"rangesfilename\"\n");
    printf("exiting...\n");
    exit (-1);
}

int main(int argc, char** argv) {

    int* scores = 0;
    int* ranges = 0;

    int num_scores = 0, num_ranges = 0;

    FILE* scoresfptr;
    FILE* rangesfptr;

    switch (argc) {
        case 1:
        case 2:
        exiting(0);
        break;
        case 3:
        //verify files exist and open them
        if((scoresfptr = fopen(argv[1], "r")) == NULL || (rangesfptr = fopen(argv[2], "r")) == NULL)
        {
            exiting("One of the files does not exist or cannot be opened.");
        }
    break;
    default:
        exiting(0);
        break;
    }
    //kind of dumb, but because N is a passed value you kinda gotta
    //know N ahead of the call to readnumber or count
    //that, or I am just tired.
    int ch = 0;
    //assuming instructions are correct, a list, 1 number per line
    //will fail if extra newlines in file
    do {
        ch = fgetc(scoresfptr);
        if (ch == '\n')
            num_scores++;
    } while(ch != EOF);
    //now we have N, can call readnumbers.  Put file pointer back at start of file.
    rewind(scoresfptr);
    //Can also now allocate memory for A[].
    scores = (int*)calloc(num_scores, sizeof(int));
    //check return value to see if anything was read in
    if(readNumbers(scoresfptr, scores, num_scores) > 0) {
        //musta been something in the file
        //get the ranges
        ch = 0;
        //assuming instructions are correct, a list, 1 number per line
        do {
            ch = fgetc(rangesfptr);
            if (ch == '\n')
                num_ranges++;
        } while(ch != EOF);
        //now we have N, can call readnumbers.  Put file pointer back at start of file.
        rewind(rangesfptr);
        //Can also now allocate memory for A[].
        ranges = (int*)calloc(num_ranges, sizeof(int));
        //check return value to see if anything was read in
        if(readNumbers(rangesfptr, ranges, num_ranges) > 0) {
            //now we can call count
            //print header column
            printf("ranges\tscores in range\n");
            for (int i = 0, j = 0; i < num_ranges/2; i++, j += 2)
            {
                printf("%d-%d:\t%d\n",  *(ranges + j),
                                    *(ranges + j + 1),
                                    count(scores, num_scores,   *(ranges + j),
                                                                *(ranges + j + 1)));
            }
        }
        else {
            exiting("Ranges File empty.");
        }
    }
    else {
        exiting("Scores File empty.");
    }
    free(scores);
    free(ranges);
    fclose(scoresfptr);
    fclose(rangesfptr);
    return(0);
}

Output:
ranges  scores in range
0-10:   11
11-20:  1
21-30:  1
31-40:  1
41-50:  1
51-60:  1
61-70:  1
71-80:  1
81-90:  1
91-100: 8


text:
Q: Joining four more table using Laravel Eloquent ORM I have a Category ID, Color ID, Size ID, Brand ID in a product table. How can I relate to all the tables using Eloquent ORM? I want to write a query in the product controller and bring all the data in the table. How can I do this without a query builder?

A: You need to made relationship in Product Model.
class Product extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category','category_id','id');
    }

    public function color()
    {
        return $this->belongsTo('App\Color','color_id','id');
    }
    public function size()
    {
        return $this->belongsTo('App\Size','size_id','id');
    }
    public function brand()
    {
        return $this->belongsTo('App\Brand','brand_id','id');
    }
}

Now in controller you can get as below.
$products = Product::with(['category','color','size','brand'])->get();


text:
Q: Request parameter filtering on update action of HABTM model relationship A Doctor can perform surgeries at many Hospitals.
class Doctor < ActiveRecord::Base
  has_and_belongs_to_many :hospitals
end

A Hospital can have many Doctors performing surgeries in it.
class Hospital < ActiveRecord::Base
  has_and_belongs_to_many :doctors
end

The new join table migration looks like this.
class CreateDoctorsHospitals < ActiveRecord::Migration
  def change
    create_table :doctors_hospitals, id: false do |t|
      t.belongs_to :doctor
      t.belongs_to :hospital

      t.timestamps
    end
  end
end

We would like to update the @doctor object, and give it some Hospitals.
<%= form_for(@doctor) do |f| %>
<%= f.label :notes %>

<%= f.text_area :notes %>

<%= f.label :hospitals %>

<%= f.collection_select :hospital_ids, Hospital.all, :id, :name, {}, { multiple: true } %>

<%= f.submit %>
<% end %>

The generated HTML looks like this.
<form accept-charset="UTF-8" action="/doctors/1" class="edit_doctor" id="edit_doctor_1" method="post">

    <input name="utf8" type="hidden" value="✓">
    <input name="_method" type="hidden" value="patch">
    <input name="authenticity_token" type="hidden" value="xxx">

  Notes

  <textarea id="doctor_notes" name="doctor[notes]"></textarea>

  Hospitals

  <input name="doctor[hospital_ids][]" type="hidden" value="">
    <select class="form-control" id="doctor_hospital_ids" multiple="multiple" name="doctor[hospital_ids][]">
      <option value="1">First Hospital</option>
      <option value="2">Second Hospital</option>
      ...
      <option value="n">Nth Hospital</option
    </select>
  <input name="commit" type="submit" value="Update Doctor">
</form>

The DoctorsController's relevant snippets are here.
class DoctorsController < ApplicationController
  before_action :set_doctor, only: [:show, :edit, :update, :destroy]

  def update
    respond_to do |format|
      if @doctor.update(doctor_params)
        format.html { redirect_to edit_doctor_hospitals_path, notice: 'Doctor was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @doctor.errors, status: :unprocessable_entity }
      end
    end
  end

  def set_doctor
    @doctor = Doctor.find(params[:id])
  end

  def doctor_params
    params.require(:doctor).permit(:first_name, :last_name, :email, :status, :notes, :hospital_ids)
  end
end

While in the Update method, @doctor has been set: set_doctor has grabbed the doctor's id from the elusive 'params' and found the record and it's all good.
But look at the doctor param!! -> params[:doctor]=>{"notes"=>"Here be notes"}. Where are the hospital_ids? Here's what params looks like:
{
  "utf8"=>"✓",
  "_method"=>"patch",
  "authenticity_token"=>"xxx",
  "doctor"=>{
    "notes"=>"Here be notes"
  },
  "commit"=>"Update Doctor",
  "action"=>"update",
  "controller"=>"doctors",
  "id"=>"1"
}

If we look into request.params at this very same moment, we'll see that it includes the hospital_ids! Wonderful!
{
  "utf8"=>"✓",
  "_method"=>"patch",
  "authenticity_token"=>"xxx",
  "doctor"=>{
    "notes"=>"Here be notes",
    "hospital_ids"=>["", "1", "4", "10"] # I don't know what that blank one is for, but whatever.
  },
  "commit"=>"Update Doctor",
  "action"=>"update",
  "controller"=>"doctors",
  "id"=>"1"
}

So what is going on? I assume that params gets its data from request.params, so why does it lose hospital_ids?
@doctor.update(doctor_params) is obviously not updating the model with any hospitals.
Any ideas?

A: For HABTM, use require params like this:
  def doctor_params
    params.require(:doctor).permit(:first_name, :last_name, :email, :status, :notes, {:hospital_ids => []})
  end

Reference - https://coderwall.com/p/_1oejq


text:
Q: Geolocation doesn't work when building via phonegap build I have a phonegap project with geolocation.
When I build it via the site phonegap build, it doesn't work on my phone or tablet (samsung). Always a time-out on the device.
When I build it via the CLI and install it on my phone via cable, then the geolocation works.
Do I need to change some setting to make it work via phonegap build?

A: For phonegap-build, place this tag in your config.xml:
<feature name="http://api.phonegap.com/1.0/geolocation"/>

Additionally, be sure to include this in your head:
<script src="phonegap.js"></head>

After that, the API calls are the same.
*Note 1: do not attempt to actually put a phonegap.js file in your directory structure.
*Note 2: I have been hearing that some devices are having issues with GPS API's. If I find the SO post again I will post it here.


text:
Q: Understanding posets and lattices I'm studying Judson's text in abstract algebra that asks me to prove or disprove if the set of nonzero integers with the relation: $a \leq b$ if  $a|b$ is a lattice.  I'm stuck because I'm missing some understanding of the concepts on two levels:

*

*On a very basic level, I'm not understanding the definition of a lattice.  I need to show that for every pair $(a,b)$ where $a,b$ in the set, that this pair has a least upper bound and a greatest lower bound in the set.  Because every poset is reflexive by definition, for any pair $a,b$ (assume $a \ne b$), $a\leq a$ and $b \leq b$.  So, if $a \leq b$, then the greatest lower bound would just be $a$ because every other element $a'$ in the set $\leq a$ would necessarily have to be $\leq a$.  So, greatest lower bound is just $a$.  Likewise, least upper bound is just $b$.  So... every poset is a lattice. (?)

*Consider the problem of determining whether or not the relation $a \leq b$ if $a|b$ over the nonzero integers is a lattice.  Well, clearly for any $(a,b)$ in the set (which means $a \leq b$ or $b \leq a$), $\pm \text{lcm}(a,b)$ divides $a,b$ and $a,b$ are divisible by $\pm \text{gcd}(a,b)$.  So, if a least upper bound exists, it should be $\pm \text{lcm}(a,b)$.  Or, if a greatest lower bound exists, it should be $\pm \text{gcd}(a,b)$?  The minus sign is what's throwing me off in this particular example.
Thank you.

A: *

*Not every poset is a lattice, because not every two elements have to be in relation. Consider $(\mathbb{N}, |)$ (natural numberes ordered by divisibility): 6 and 14 are not comparable, since neither divides the other.
The join is 42, and the meet is 2.

*Your example is not even a poset, because $|$ is not antisymmetric on $\mathbb{Z} \setminus\{0\}$: we have $-n|n$ and $n|-n$, but $n\neq -n$.
If we were playing with $(\mathbb{N}, |)$, the $\operatorname{gcd}$ and $\operatorname{lcm}$ would make join and meet respectively as you expected.


text:
Q: a function that is in $L^2$ (the right version) Sorry I made a mistake when posting the last question. Actually my question is: can you give a  $f(x) $ such that $ f \in L^2 ( \mathbb R)$ but $  x^{-\frac{1}{2}} f \notin L^1 ( \mathbb R ) $. Thanks!

A: Take $$f(x)=\frac 1{\sqrt x\log x}\mathbf{\chi}_{[2,\infty)}(x).$$
Then $x\mapsto f^2(x)=(x\log^2x)^{-1}\mathbf{\chi}_{[2,\infty)}(x)$ is integrable and $x\mapsto x^{-1/2}f(x)=(x\log x)^{-1}\mathbf{\chi}_{[2,\infty)}(x)$ is not.


text:
Q: design pattern(GoF patterns) implementation in c++ What are the elegant design pattern(GoF patterns) implementation in c++ ?
Can anyone give me some examples of design pattern implementations based on template(which can be reused) ?
Example(Template based Singleton) :-
template<typename T>
class Singleton : public boost::noncopyable
{
public:
    static Singleton& GetInstance()
    {
        boost::call_once(&CreateInstance, m_onceFlg);
        return *m_pInstance;
    }
    virtual ~Singleton()
    {
    }
protected:
    Singleton ()
    {
    }
    static void CreateInstance()
    {
        m_pInstance.reset(new T());
    }
private:
    static boost::once_flag m_onceFlg;
    static boost::scoped_ptr<T> m_pInstance;
};

A: Take a look at Modern C++ Design by Alexandrescu
http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315
He covers template implementation of several design patterns. In fact, IIRC, one of the forewards is written by one of the GOF.

A: In my experience, there are really no good design pattern template libraries. A design pattern is difficult to capture correctly as a concrete template without caveats or imposing difficult to enforce restrictions on the classes that try to plug themselves into it.
Let's take your Singleton example. Well, I'm actually going to rewrite it so that I don't have to have Boost to use it:
template <typename T>
class Singleton {
    Singleton (const Singleton<T> &) = delete;
    Singleton & operator = (const Singleton<T> &) = delete;
    static Singleton<T> & GetInstanceInternal () {
        static T instance;
        return instance;
    }
protected:
    Singleton () {}
    ~Singleton () {}
public:
    static T & GetInstance () {
        return static_cast<T &>(GetInstanceInternal());
    }
};

Although this makes Singleton<T> a singleton, what is really wanted is to make the T a singleton. Well, you might say, this is no problem, because the usage is that T should inherit from Singleton<T> (as enforced by Singleton::GetInstanceInternal()):
class Foo : public Singleton<Foo> {
public:
    void foo () { /*...*/ }
};

A naive programmer would think "Job done!", because since Foo inherits from Singleton<Foo>, that makes Foo a singleton. But it doesn't, because it doesn't prevent this:
Foo x;

To fix this, the constructor should be made private (and therefore, Singleton<Foo> needs to be made a friend). To prevent calling the destructor directly, it should be made private as well.
class Foo : public Singleton<Foo> {
    friend class Singleton<Foo>;
    Foo () {}
    ~Foo () {}
public:
    void foo () { /*...*/ }
};

So, in addition to inheriting Singleton<Foo> there are additional requirements that inheritance alone cannot properly enforce. All these requirements can be documented, but it can be argued that using the templates become less useful, and it is almost as much work as putting the singleton functionality into Foo directly.


text:
Q: How to manage transient data in a Redux store I have a React/Redux application that requires me to manage temporary data in the application's state.
The user performs a client side Edit or Remove operation on the business data.
He then goes on to work on the App with the updated(temporary) data.
If satisfied with the edit/remove operation, user can then decide to 'SAVE' his action. This would commit changes to the backend server via an ajax call.
If not satisfied, user can choose to 'REVERT' the operation. This should bring the application data back to it's original state prior to Edit/Remove operation.
I'm required to manage the transient/temporary data till the user decides either to Save or Revert the changes made.
I've considered the option of maintaining the temporary data seperate from it's orginal structure. If successfully commited to server,
then update the origin from the API response and clear off the temporary data.
If action is reverted, the original data remains same and the temporary is cleared.
What would be a good approach to managing temporary Redux states such as this that can either go on to persist or be discarded..?


text:
Q: ¿Cómo está actuando la herencia en cascada dentro de esta lista? En el siguiente código trato de experimentar con las animaciones.
<!doctype html>

<meta charset="utf-8">
<title>Ejercicio_2</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimun-scale=1" />

Sin embargo, me ha surgido una duda en cuanto al ancho heredado en cascada. Yo entiendo lo siguiente:
(1) El slider tendrá el 22.25% del ancho que tenga el body.
(2) Cada ul tendrá un ancho cuatro veces mayor que el slider, pues hay cuatro imágenes y queremos que cada imagen ocupe el 100% del slider cuando aparezca.
(3) Aquí mi duda. Por lo que veo experimentalmente, los elementos li deben tener un ancho del 100% para que todos los elementos de la lista queden equitativamente repartidos. Ahora bien, acorde con la herencia en cascada y la lógica de las medidas relativas, ¿no debería ocupar, según la instrucción de anchura definida, cada li todo el ancho de la lista a la que pertenece? De esta manera, quedaría cada elemento li como cuatro veces el slider.
(4) Ajustamos el ancho de la imagen a la del li para que no queden huecos internos en los laterales.
Si unimos el punto 3 con el punto 4, es evidente que debería ocupar cada imagen un ancho cuatro veces mayor al slider. Sin embargo, el ajuste parece perfecto y las animaciones ocurren sin problemas.
¿Cómo está actuando entonces la cascada con la anchura de los li? Gracias.

A: La duda principal:

Por lo que veo experimentalmente, los elementos li deben tener un ancho del 100% para que todos los elementos de la lista queden equitativamente repartidos. Ahora bien, acorde con la herencia en cascada y la lógica de las medidas relativas, ¿no debería ocupar, según la instrucción de anchura definida, cada li todo el ancho de la lista a la que pertenece? De esta manera, quedaría cada elemento li como cuatro veces el slider.

Todo esto es correcto con una propiedad display diferente de flex para el contenedor y la explicación es muy sencilla:

*

*La suma del ancho de todos supera el 100% y el contenedor flex ajustará para que todos quepan en el contenedor, con la misma medida proporcional (100% / cantidad de elementos). Agrega (o elimina) un elemento para comprobarlo.

*La suma del ancho de todos es menor que el 100%, entonces se ajustarán para ocupar solo ese espacio en el contenedor. Cambia el ancho de los elementos a un número donde la suma no llegue a 100 para comprobarlo.

.slider{
        width: 22.25%;
        margin: auto;
        overflow: hidden;
    }

    /*Cuando llega a la última imagen, regresa hacia la primera directamente*/
    .slider #ul_1{
        width: 400%;
        padding: 0;
        display: flex;
        animation: cambio_1 20s infinite;
    }

    /*Cuando llega a la última imagen, regresa a la primera pasando antes por el resto*/
    .slider #ul_2{
        width: 400%;
        padding: 0;
        display: flex;
        animation: cambio_2 20s infinite alternate;
    }

    .slider ul li{
        /* La suma de elementos es mayor a 100% */
        width: 100%;
        list-style: none;
        background: #ccc;
        border: 1px red solid;
    }

    #ul_2 li{
        /* La suma de elementos no llega al 100% */
        width: 15%;
        list-style: none;
        background: #ccc;
        border: 1px red solid;
    }

    .slider ul li img{
        width: 100%;
    }

    @keyframes cambio_1{
        0% {margin-left: 0;}
        20% {margin-left: 0;}

        25% {margin-left: -100%;}
        45% {margin-left: -100%;}

        50% {margin-left: -200%;}
        65% {margin-left: -200%;}

        70% {margin-left: -300%;}
        95% {margin-left: -300%;}
    }

    @keyframes cambio_2{
        0% {margin-left: 0;}
        20% {margin-left: 0;}

        25% {margin-left: -100%;}
        45% {margin-left: -100%;}

        50% {margin-left: -200%;}
        70% {margin-left: -200%;}

        75% {margin-left: -300%;}
        100% {margin-left: -300%;}
    }

En este ejemplo puedes ver que el primer slider tiene 5 elementos y entre todos ocupan solo la anchura disponible; el segundo no llega a ocuparla porque las medidas entre todos son menores de 100%.
Para ser más específicos, de acuerdo a tu duda final:

¿Cómo está actuando entonces la cascada con la anchura de los li?

La respuesta se obtiene del manual de flex:

La propiedad CSS flex indica la capacidad de un elemento flexible para alterar sus dimensiones y llenar el espacio disponible. Los elementos flexibles pueden ser estirados para utilizar el espacio disponible proporcional a su factor de crecimiento flexible o su factor de contracción flexible para evitar desbordamiento.


text: Q: Shear stress calculation due to surfactant molecules I have an interface of two immiscible liquids. Is there a way to calculate the shear stress at this interface as a function of surfactant concentration?


text: Q: Using gem (socialization) method through AJAX in Rails I am using the Socialization gem and I have what I think is actually a basic rails question. I want to use the follow or like gem methods through AJAX. How do you use a gem method like that in ajax? Will I need to create a controller (the gem does not automatically generate them) or is there a simpler way?


text:
Q: Git Revert Not Working So i've got a develop branch with a commit that I want to revert. So I type in git revert <commit-hash>
But when it runs it says:
$ git revert 165702b305
On branch develop
nothing to commit, working directory clean

This commit has been tracked down as the culprit of a bug and id like to revert it, but for some reason its not working. Could it be corrupted somehow? Other answers and searches have not been able to help.

A: I had the same issue.
Using the following snippet worked for me:
git revert --no-commit <commit-id> -n HEAD

A: I following git command will be more specific.  It will point out that the revert will start at the HEAD pointer (where the branch is at right now) and end with commit 165702b305:
git revert 165702b305..HEAD

A: I had exact the same issue and the syntax below worked for me:
git revert -n master~5..master~2


text:
Q: async await utility function synchronization? If we define a utility function like this:
/**
 * Delete the entire database
 */
export async function deleteDatabase(db) {
  await db.delete()
}

And we call it.
deleteDatabase(db)
nextFunction()

Then next function will not be called before the db.delete() has completed correct?
I think this is how it works, so I just want to confirm the semantics.
DexieJS Demo
Incorporating the answers into this DexieJS Demo for those interested in the actual use case:
https://stackblitz.com/edit/typescript-dexie-one-to-many

A: "Then next function will not be called before the db.delete() has completed correct?" Wrong. It will be called BEFORE async operation has completed.

const delay = ms => new Promise(resolve => setTimeout(resolve, ms))

async function deleteDatabase() {
  console.log('Deleting DB')
  await delay(1000)
  console.log('DB deleted')
}

function nextFunction() {
  console.log('Next function')
}

deleteDatabase()
nextFunction()

You need to have another async/await wrapper function or use .then to chain promises
deleteDatabase().then(nextFunction)

A: deleteDatabase(db)

This expression returns with promise immediately.
So nextFunction() will be called before the db.delete() has completed
You should await for deleteDatabase(db) as well

A: If they're in a async context, the next function won't be called, only if you put the await before the deleteDatabase
Like this:
async myFunc(db) {
    await deleteDatabase(db)
    nextFunction()
}

Or even:
async myFunc(db) {
    return deleteDatabase(db)
        .then(() =>
            nextFunction()
        )
}

A: If you call it like
deleteDatabase(db)
nextFunction()

The next function will be called immediately as you are not awaiting it.
You need to await
await deleteDatabase(db)
nextFunction()


text:
Q: C#: how to hide a method from the stack trace? I have a dead simple one-liner method that I don't want to see in the stack trace: is that possible? maybe mark it with an attribute?
Just to clarify, I'm not trying to print the trace, or rethrow, or have auto step-through in the debugger. I'd like the method to not show up in the trace in the first place, because the trace is then handled by some third-party code. I want control at runtime, I'm not interested about debugging.
I'm saying this because most of what I've read on StackTrace seem to be about these topics.

A: This can only be done when your method is inlined. Either the JIT does it, or you do it yourself (change the code). The JIT however, is pretty conservative about inlining methods and practically only does that when the method is very small, or when the method is used in a loop.

A: As it is said in answer for other question Most Useful Attributes, you need to specify System.Diagnostics.DebuggerHidden attribute for your method.


text:
Q: How to combine several ppp object I'm not sure if it's a meaningful question but I don't understand how (and if) is it possible to combine a list of ppp objects into a unique ppp object. For example
library(spatstat)
#> Loading required package: spatstat.data
#> Loading required package: nlme
#> Loading required package: rpart
#>
#> spatstat 1.62-2       (nickname: 'Shape-shifting lizard')
#> For an introduction to spatstat, type 'beginner'

ppp1 <- ppp(runif(20), runif(20), c(0,1), c(0,1))
ppp2 <- ppp(runif(20), runif(20), c(0,1), c(0,1))

do.call("rbind", list(ppp1, ppp2))
#>      window n  x          y          markformat
#> [1,] List,4 20 Numeric,20 Numeric,20 "none"
#> [2,] List,4 20 Numeric,20 Numeric,20 "none"
do.call("ppp", list(ppp1, ppp2))
#> Error in ppp(structure(list(window = structure(list(type = "rectangle", : is.numeric(x) is not TRUE

Created on 2020-01-30 by the reprex package (v0.3.0)
I think that the result should be a ppp object created by rbinding the coordinates and marks and window object should be the union of the owin objects. Is that a reasonable idea? Is that already coded or documented somewhere?

A: It was a stupid question, it's all documented here: https://rdrr.io/cran/spatstat/man/superimpose.html.


text:
Q: 46 Control Files for SQL Loader I have to load 46 tables with data using SQL Loader for Oracle. All the data files are CSV.
The column order in the CSV matches the column order in the table.
I need to create a control file for each table.
What is the best way for me to mass produce these files?

A: I know this is an old question, but it is still a relevant question.  For future searchers here is a procedure I added to our utility package that generates a skeleton control file for a table.  Pass it the table name and it outputs a default control file that you can tweak where needed.  You may need to edit to fit your needs first.
Call like this:
set serveroutput on;
exec utils.gen_ctl_file('TABLE_NAME');

The procedure:
/********************************************************************************************************
Name:       GEN_CTL_FILE

Desc:       Generates a skeleton control file from a table for loading data via SQL*Loader.

Args:       tablename_in IN VARCHAR2, delim_in VARCHAR2 DEFAULT '|'

Returns:    None.

Usage:      utils.gen_ctl_file('tablename');

Notes:      Prints a skeleton control file.

            If a template for a fixed-length data file is desired, use 'FIXED' for the delim_in string.

            Example usage:

            set serveroutput on;
            execute utils.gen_ctl_file('tablename');

************************************************************************************************************************/
PROCEDURE GEN_CTL_FILE(tablename_in IN VARCHAR2, delim_in VARCHAR2 DEFAULT '|') IS
ERRNULLTABLENAME     CONSTANT NUMBER        := -20103; -- User-defined error numbers and messages.
ERRNULLTABLENAMEMSG  CONSTANT VARCHAR2(100) := 'A table name is required.';
USAGE                CONSTANT VARCHAR2(100) := '*   USAGE: UTILS.GEN_CTL_FILE(tablename_in IN VARCHAR2, fieldsep_in VARCHAR2 DEFAULT ''|'')';
v_delim                       VARCHAR2(20)  := NVL(delim_in, '|');
err_nbr  NUMBER;
err_msg  VARCHAR2(1000);

CURSOR COL_CUR  IS
  SELECT COLUMN_NAME,
  DECODE(COLUMN_ID, 1, ' ', ',') || RPAD(COLUMN_NAME, 32) || case upper(v_delim)
    when 'FIXED' then 'POSITION(99:99) '
    else NULL
  end|| DECODE(DATA_TYPE,
         'VARCHAR2', 'CHAR NULLIF(' || COLUMN_NAME || '=BLANKS)',
         'CHAR', 'CHAR NULLIF(' || COLUMN_NAME || '=BLANKS)',
         'FLOAT', 'DECIMAL EXTERNAL NULLIF(' || COLUMN_NAME || '=BLANKS)',
         'NUMBER', DECODE(                                                 DATA_PRECISION,
         0, 'INTEGER EXTERNAL NULLIF (' || COLUMN_NAME || '=BLANKS)',
         DECODE(DATA_SCALE, 0, 'INTEGER EXTERNAL NULLIF (' || COLUMN_NAME || '=BLANKS)', 'DECIMAL EXTERNAL NULLIF (' || COLUMN_NAME || '=BLANKS)')),
         'DATE', 'DATE "MM/DD/YYYY" NULLIF (' || COLUMN_NAME || '=BLANKS)',
         data_type)
           AS COL_DATA
  FROM  USER_TAB_COLUMNS
  WHERE TABLE_NAME = UPPER(tablename_in)
  ORDER BY COLUMN_ID;

BEGIN

IF tablename_in IS NULL THEN
  RAISE_APPLICATION_ERROR(ERRNULLTABLENAME, ERRNULLTABLENAMEMSG || CHR(10) || USAGE);
END IF;

DBMS_OUTPUT.PUT_LINE('--');
DBMS_OUTPUT.PUT_LINE('-- NOTE - When using DIRECT=TRUE to perform block inserts to a table,');
DBMS_OUTPUT.PUT_LINE('--        the table''s triggers will not be used! Plan accordingly to');
DBMS_OUTPUT.PUT_LINE('--        manually perform the trigger actions after loading, if needed.');
DBMS_OUTPUT.PUT_LINE('--');
DBMS_OUTPUT.PUT_LINE('OPTIONS (DIRECT=TRUE)');
DBMS_OUTPUT.PUT_LINE('UNRECOVERABLE');
DBMS_OUTPUT.PUT_LINE('LOAD DATA');
DBMS_OUTPUT.PUT_LINE('APPEND');
DBMS_OUTPUT.PUT_LINE('INTO TABLE ' || UPPER(tablename_in));
DBMS_OUTPUT.PUT_LINE('EVALUATE CHECK_CONSTRAINTS');
if upper(v_delim) != 'FIXED' then
  DBMS_OUTPUT.PUT_LINE('FIELDS TERMINATED BY ''' || v_delim || ''' TRAILING NULLCOLS');
end if;
DBMS_OUTPUT.PUT_LINE('(');

-- The cursor for loop construct implicitly opens and closes the cursor.
FOR COL IN COL_CUR
LOOP
  DBMS_OUTPUT.PUT_LINE(COL.COL_DATA);
END LOOP;
DBMS_OUTPUT.PUT_LINE(')' || CHR(10));

EXCEPTION
WHEN OTHERS THEN
  err_nbr  := SQLCODE;
  err_msg  := SUBSTR(SQLERRM, 1, 1000);
  -- if any error occurs, print the SQLCODE message.
  DBMS_OUTPUT.PUT_LINE('ERROR: ' || err_nbr || ' occurred: ' || err_msg);
END; -- GEN_CTL_FILE

A: I have been do similar thing (about 120 tables with over 1500 columns). I used excel (because my working result is an excel file).
From Excel macro I read tables meta from DB as Adam Musch suggested, then fill into the Sheets.
I think this will work for you too.
Or you can create a tool use you familiar language to do the same.


text:
Q: 'Programs hacking programs' & 'The code is hidden in tumblers' In The Matrix Reloaded, Neo said, "programs hacking programs".
I don't think it is a complete sentence. What is omitted here? What does it mean? A program can hack another program or what?
Besides, Seraph said, "The code is hidden in tumblers. One position opens a lock. Another position opens one of these doors."
What's meant by tumbler here? A position can open a lock? Sounds really weird to me.

A:
programs hacking programs

It's simply stating what he observes. I could be looking at a pond and say

Ducks eating bread.

What's missing is simply something like "it's", as in :

"It's programs hacking programs."

You could imagine a lot more around that sentence:

Gosh, so what I am looking at here, is programs hacking programs!

As for the tumblers, this might give a clue.

4 A pivoted piece in a lock that holds the bolt until lifted by a key.
5 An electrical switch worked by pushing a small sprung lever.

Both could apply - but seen as the Matrix deals with electronics, I'd say that maybe 5 is more likely?
If you google on tumbler switch you may get an idea of what is meant with the positions it can be in.

A position opens a lock

You would have to interpret as

When the switch is in a certain position, a lock is opened.

A: "Programs hacking programs" I guess are programs created to hack another programs.
Tumbler is a moving part of a locking device. One position of the tumbler unlocks, the other position locks the device.

A: about the programs hacking programs:maybe theyre sentient programs that can act as a code generator for themselves and hack other programs or create viruses from their code to hack other programs thats what i imagined when he said that,this is just my opinion...

A: When Seraph says one tumbler position opens a lock he means a normal key put in normal lock opens a normal door. When he says another position opens one of these doors, he means when you insert a special key, that positions the lock tumbler in just the right way, it makes the door open to a different place. A place that corresponds to the code that's been activated in the tumbler


text:
Q: django-rest-framework : list parameters in URL I am pretty new to django and django-rest-framework, but I am trying to pass lists into url parameters to then filter my models by them.
Lets say the client application is sending a request that looks something like this...
  url: "api.com/?something=string,string2,string3&?subthings=sub,sub2,sub3&?year=2014,2015,2016/"

I want to pass in those parameters "things", "subthings", and "years" with their values.
Where the url looks something like this?
NOTE: Trick is that it won't be always an array of length 3 for each parameter.
Can someone point me in the right direction for how my url regex should be handing the lists and also retrieving the query lists in my views.
Thanks!

A: Checkout this doc http://www.django-rest-framework.org/api-guide/filtering/
Query params are normally not validated by url regex

A: To show how I did this thanks to the document links above.
Note: I used pipes as my url delimiter and not commas -> '|'.
in my urls.py
url(r'^$', SomethingAPIView.as_view(), name='something'),

in my views.py
class SomethingAPIView(ListAPIView):
  # whatever serializer class

  def get_queryset(self):
    query_params = self.request.query_params
    somethings = query_params.get('something', None)
    subthings = query_params.get('subthing', None)
    years = query_params.get('year', None)

    # create an empty list for parameters to be filters by
    somethingParams = []
    subthingsParams = []
    yearParams = []

    # create the list based on the query parameters
    if somethings is not None:
      for something in somethings.split('|'):
        countryParams.append(int(something))
    if subthings is not None:
      for subthing in subthings.split('|'):
        subthingsParams.append(int(subthing))
    if years is not None:
      for year in years.split('|'):
        yearParams.append(int(year))

    if somethings and subthings and years is not None:
      queryset_list = Model.objects.all()
      queryset_list = queryset_list.filter(something_id__in=countryParams)
      queryset_list = queryset_list.filter(subthing_id__in=subthingsParams)
      queryset_list = queryset_list.filter(year__in=yearParams)
      return queryset_list

I do need to check for an empty result if they are not valid. But here is starting point for people looking to pass in multiple values in query parameters.
A valid url here would be /?something=1|2|3&subthing=4|5|6&year=2015|2016.


text:
Q: Can not be loaded because it comes from a more recent Sirius release I have a problem opening a project in my own computer. So in the first time i created this project on my pc, than put it on git i went to the university i continued working on it and when i re-pulled the version of my project which is after modifying it on the university's computer trying to open it i encountered this problem :
An internal error occurred during: "Loading models".
The modeling project "FIL" is invalid: Problem during loading models:
The Sirius resource (platform:/resource/FIL/model/fIL.aird) can not be loaded because it comes from a more recent Sirius release.
Representation version is: 15.0.0.202209061200
Last Sirius migration version is: 15.0.0.202201261500
I assume it's because of versions differences between the sirius used on those 2 different computer , i didn't find how to update or change the version in my personal computer. Can you please help me ?
Thank you , and have a nice day.

A: re-installing the sirius from the market is a solution for that.


text:
Q: How to validate authenticode for Javascript in C# I was able to sign a js file with PowerShell Set-AuthenticodeSignature.
After that i can see signature appeared in file in form of:
// SIG // Begin signature block
// SIG // MIIKgAYJKoZIhvcNAQcCoIIKcTCCCm0CAQExCzAJBgUr
// SIG // ....
// SIG // End signature block

I can validate signature using Get-AuthenticodeSignature. It says that sig is valid, but I cant find a way to validate signature in C# code.
All of those options failed:

*

*X509Certificate.CreateFromSignedFile

*X509Certificate object c# performance and memory issues alternative – fixed

*Used WinVerifyTrust from Wintrust.dll

*Ported part of Get-AuthenticodeSignature from PowerShell!

Maybe there are some specific apis to validate js signatures?

A: I recently encountered similar problem and let me show what I did to solve this problem. Before I go , there are few assumptions I make now. Please correct me if I am wrong.

*

*wintrust is working for all other cases other than script files like
.js or .vbs

*You might have attempted "wintrustverify" from an
    console application (C#)

I figured it out this happens only with script files as I have mentioned above because wintrust behaves wierdly when its methods are being executed from free-threaded apartment model (MTA). Once it's been wrapped inside a STA thread, it started working for me. Later I came to know it is a historical issue that we should have taken a precaution when we deal with any COM components interoperations from .Net application.
Here is the code snippet, you can replace the verifysignature with your wintrust code logic and try. I hope this helps.
            public static void CheckSignature()
            {
                STAApartment apt = new STAApartment();
                var result = apt.Invoke(() =>
                {
                    return VerifySignature(@".\signedjsfile.js", false);
                });
                Console.WriteLine(result);
            }

            private static WinVerifyTrustResult VerifySignature(string filePath, bool verifySignatureOnly)
            {

                using (var wtd = new WinTrustData(new WinTrustFileInfo(filePath))
                {
                    dwUIChoice = WintrustUIChoice.WTD_UI_NONE,
                    dwUIContext = WinTrustDataUIContext.WTD_DATA_UI_EXECUTE,
                    fdwRevocationChecks = WinTrustDataRevocationChecks.WTD_REVOCATION_CHECK_WHOLECHAIN,
                    dwStateAction = WintrustAction.WTD_STATEACTION_IGNORE,
                    dwProvFlags = verifySignatureOnly ? WintrustProviderFlags.WTD_HASH_ONLY_FLAG : WintrustProviderFlags.WTD_REVOCATION_CHECK_CHAIN
                })
                {
                    var result = WinTrust.WinVerifyTrust(
                        WinTrust.INVALID_HANDLE_VALUE, new Guid(WinTrust.WINTRUST_ACTION_GENERIC_VERIFY_V2), wtd
                    );
                    return result;
                }
            }

            public class STAApartment
            {
                public T Invoke<T>(Func<T> func)
                {
                    var tcs = new TaskCompletionSource<T>();
                    Thread thread = new Thread(() =>
                    {
                        try
                        {
                            tcs.SetResult(func());
                        }
                        catch (Exception e)
                        {
                            tcs.SetException(e);
                        }
                    });
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    return tcs.Task.Result;
                }
            }

A: WinVerifyTrust supports verifying files other than executables using the WTD_CHOICE_BLOB flag. Make sure you provide the WINTRUST_BLOB_INFO struct with the correct subject interface package (SIP). From what I can see, Get-AuthenticodeSignature command uses the PowerShell SIP {603bcc1f-4b59-4e08-b724-d2c6297ef351} to verify the signature. I assume Set-AuthenticodeSignature uses the same SIP to sign the script.


text:
Q: QGIS - Is it possible to filter records by the current date? Is it possible to filter the records of a layer in QGIS with the current date? The field I want to filter is a date-column and the layer is stored in a GeoPackage.
The problem I see is that I can't use the functions (now(), substr(),...) as in the field calculator or select by expression dialogs.
But maybe there is some kind of hack possible to do it in a different kind of way?
EDIT:
I think I wasn't asking clear enough. So I was asking about this filter-dialog:

In this dialog there is no possibility to use the functions from the field calculator or select by expression dialogs.
QGIS-Version: 3.22.4 LTR

A: It is important to know, that

The filter is made at the data provider (OGR, PostgreSQL, MSSQL…)
level. So the syntax depends on the data provider (DateTime is for
instance not supported for the ESRI Shapefile format).

See the docs.
So if you have your data in GeoPackage Format, the Syntax follows SQLite. To filter for today in a date column, use:
"yourdatefield" = CURRENT_DATE

A: You just need to use the proper syntax, as geopackage are based on sqlite database you need to use the sqlite fonction and syntax on your filter.
The proper syntax (for getting date before today) would be : "DATE_FIELD" < DATE('now') (note that now is a string so it's delimited by single quote)

A: You can use the function now() in the Expression builder, but you probably need to modify the result a bit to fit your data.
Depending on what format your date column has, you can write a short expression to help solve this.
E.g. if you have a column formatted as Date and Time (in my example called date-time) and only want to use the date, you would have to substract the rest of the column and then concatenate a wildcard to the end of the string, like so:
"date-time" LIKE concat(substr(now(),0,10),'%')
I hope that helps to tweak your data as needed.


text:
Q: In the day/ in day Can you make some sentences with the words "in day" and explain also what it means compared to "in the day"?
I can think of is feet in the day, but why can it be feet in day?

A: It's possible.

Later in day, more troops are likely to get in.

'back in the day' is an idiom where you have 'in the day' used.

Back in the day, we had an apartment with a swimming pool.

'in the day' (except for its idiomatic use) means the particular day. Rewriting the same example...

Later in the day on Friday, the troops took over the entire city.

However, I see that 'in day' and 'in the day' both are frequently used. I think there's no major difference in that.


text:
Q: How to get data, passed by a view composer to certain views, inside the controller? My View Composer passes some data to certain views (and it works, of course):
use Illuminate\View\View;
use App\Util\Helper

class PublicSettingsComposer
{
    public function compose(View $view)
    {
        $view->with('settings', Helper::readSettingsFromFile()); // json
    }
}

The appropriate provider is added into the configuration and it provides this composer correctly for all specific views:
view()->compose('public.layouts.*', 'App\Http\ViewComposers\PublicSettingsComposer');

However, inside (only) one of my views I need specific information from database, but therefore I have to use some data, that had been passed by my View Composer:
class BranchController extends Controller
{
    public function branches()
    {
        $settings = retrieve_settings_passed_by_PublicSettingsComposer; // This is what I need
        $headquartersId = $settings->headquartersid;
        return view('public.layouts.branches', [
            'headquarters' => Branch::find($headquartersId) // Branch is a Model
        ]);
    }
}

FYI: Laravel version I'm using is: 5.5

P.S. @moderators: Please, be careful with considering my question as a duplicate. I know there are many questions about view composers and passing data to the views and grabbing data from within controllers. However, I really could not find any question with this context (titles are often misleading).

A: I see two rather simple solutions for this. The first one is to cache the parsed file within each request. The other is to use an actual cache for this job.
The first option is very straight forward to implement. In your Helper class you'll have to introduce a static property to hold the parsed contents of the read file. Then, just like you do within the singleton pattern, you either return the cached data or you first parse the file, cache the data and return it afterwards. This scenario solves your actual problem of parsing the settings twice per requests if used in two places of your app.
class Helper
{
    protected static $cachedSettings;

    public function readSettingsFromFile()
    {
        if (!self::$cachedSettings) {
            self::$cachedSettings = // Do the parsing here. This should be your current implementation of Helper::readSettingsFromFile(). You can also put this in its own function.
        }

        return self::$cachedSettings;
    }
}

The other option is to use an actual cache (an external one). You can either cache the parsed file for a specific amount of times (like 1, 3, 5 or 10 minutes or even longer). Or you cache it forever and invalidate the cache when you update the settings (if this happens within your app and you know it was updated).
This solution does only make sense if your settings do not change too frequently though. It also depends a bit on the amount of requests you expect towards your app. If your settings change not too frequently (less than every x minutes) and your app is used frequently (multiple requests every x minutes), then it could be a viable solution.
class Helper
{
    public function readSettingsFromFile()
    {
        return Cache::remember(function () {
            $settings = // Put your current calculation here

            return $settings;
        }, 3 * 60); // 3 * 60 = 180 seconds
    }
}


text:
Q: Pandas data reshaping, turn multiple rows with the same index but different values into many columns based on incidence I have the following table in pandas
user_id idaggregate_info    num_events  num_lark_convo_events   num_meals_logged    num_breakfasts  num_lunches num_dinners num_snacks  total_activity  sleep_duration  num_activity_events num_weights num_notifs  idusermission   completed   mission_delta
0   0   406 94  20  7   2   2   2   1   4456    47738   72  0   18  1426    0   NaT
1   1   1247    121 48  26  8   7   2   9   48695   37560   53  14  48  1379    1   7 days 10:04:28
2   1   1247    121 48  26  8   7   2   9   48695   37560   53  14  48  1379    1   NaT
3   2   2088    356 32  15  6   6   1   2   41598   184113  314 1   21  967 1   8 days 00:03:05
4   2   2088    356 32  15  6   6   1   2   41598   184113  314 1   21  967 1   NaT

Some user_ids have multiple lines that are identical except for their different mission_delta values. How do I transform this into one line for each id, with a columns named "mission_delta_1", "mission_delta_2" (the number of them vary, it could be 1 per user_id to maybe 5 per user_id so naming has to be iterative_ etc so output would be:
user_id idaggregate_info    num_events  num_lark_convo_events   num_meals_logged    num_breakfasts  num_lunches num_dinners num_snacks  total_activity  sleep_duration  num_activity_events num_weights num_notifs  idusermission   completed   mission_delta_1 mission_delta_2
0   0   406 94  20  7   2   2   2   1   4456    47738   72  0   18  1426    0   NaT
1   1   1247    121 48  26  8   7   2   9   48695   37560   53  14  48  1379    1   7 days 10:04:28  NaT
2   2   2088    356 32  15  6   6   1   2   41598   184113  314 1   21  967 1   8 days 00:03:05     NaT

Not a duplicate as those address exploding all columns, there is just one that needs to be unstacked. The solutions offered in the duplicate link fail:
df.groupby(level=0).apply(lambda x: pd.Series(x.values.flatten()))

produces the same df as the original with different labels
    0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16
    0   0   406 94  20  7   2   2   2   1   4456    47738   72  0   18  1426    0   NaT
    1   1   1247    121 48  26  8   7   2   9   48695   37560   53  14  48  1379    1   7 days 10:04:28
    2   1   1247    121 48  26  8   7   2   9   48695   37560   53  14  48  1379    1   NaT
    3   2   2088    356 32  15  6   6   1   2   41598   184113  314 1   21  967 1   8 days 00:03:05

The next options:
result2.groupby(level=0).apply(lambda x: pd.Series(x.stack().values))

produces:
0     0         0
  1       406
  2        94
  3        20
  4         7

and
df.groupby(level=0).apply(lambda x: x.values.ravel()).apply(pd.Series)

produces the original dataframe:
    0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16
    0   0   406 94  20  7   2   2   2   1   4456    47738   72  0   18  1426    0   NaT
    1   1   1247    121 48  26  8   7   2   9   48695   37560   53  14  48  1379    1   7 days 10:04:28
    2   1   1247    121 48  26  8   7   2   9   48695   37560   53  14  48  1379    1   NaT
    3   2   2088    356 32  15  6   6   1   2   41598   184113  314 1   21  967 1   8 days 00:03:05

In essence, I want to turn a df:
id    mission_delta
0     NaT
1     1 day
1     2 days
1     1 day
2     5 days
2      NaT

into
id    mission_delta1  mission_delta_2 mission_delta_3
0     NaT     NaT        NaT
1     1 day   2 days    1 day
2     5 days   NaT      NaT

A: You might try this;
grp = df.groupby('id')
df_res = grp['mission_delta'].apply(lambda x: pd.Series(x.values)).unstack().fillna('NaT')
df_res = df_res.rename(columns={i: 'mission_delta_{}'.format(i + 1) for i in range(len(df_res))})

print(df_res)

   mission_delta_1 mission_delta_2 mission_delta_3
id
0              NaT             NaT             NaT
1            1 day          2 days           1 day
2           5 days             NaT             NaT


text:
Q: Predicate logic rectified form I have this predicate logic expression
$$\forall X (\forall X p(X) \vee q(X))$$
Which of these expressions are the rectified form?
$$ \forall Y (\forall X p(X) \vee q(Y)) $$
$$ \forall X( \forall Y p(Y) \vee q(Y)) $$
I have been told that the rectified form of a predicate can be obtained by renaming bound variables so that no variable appears in two quantifiers.
According to that in my opinion the answer should be the first one but using software I get the second one.

A: I am with you. The first one is equivalent to the original, but in the second one the $Y$ in $q(Y)$ has become a free variable and the $\forall X$ is a null quantifier, while the original expression did not have any free variables or null quantifiers.  Are you sure the software did not say $\forall X (\forall Y p(Y) \lor q(X))$? What software is this?


text:
Q: Apache NetBeans 12.3 y eclipse 2021-06 (4.20.0) ,problemas con el jar En el netbeans me genera el jar pero no lo consigo lanzar desde el sistema, en el editor funciona perfectamente.
Product Version: Apache NetBeans IDE 12.3
Java: 16.0.2; Java HotSpot(TM) 64-Bit Server VM 16.0.2+7-67
Runtime: Java(TM) SE Runtime Environment 16.0.2+7-67
System: Windows 10 version 10.0 running on amd64; Cp1252; es_ES (nb)
En eclipse me genera el jar con avisos:(Version: 2021-06 (4.20.0))
-La exportacion de Jar a finalizado con avisos
Detalles:
Exportado con avisos de compilación: AppWin/src/pruu.java,
en este caso si funciona el jar en el sistema,
El codigo es el mismo en los dos editores, es simplemente una ventana
vacía, si ahora que es aun menos que un "Hola mundo" tengo estos problemas, como será cuando termine mi proyecto algo bastante mas complejo, con bases de datos, imágenes, etc...
Me da enteramente igual usar un editor o el otro, pero quisiera solucionar uno de los dos problemas.
Que pasa, o que me falta en el netBeans para que ejecte el jar.
En eclipse a que se refiere este aviso,como se soluciona o hay que ignorarlo.
Muchas gracias a todos soy nuevo en el foro y en java soy un aficionado, perdonen si he faltado a alguna de sus reglas

A: En Eclipse salta esa ventana al exportar el JAR, cuando en el código te marca alguna advertencia, no eliminaste las importaciones que no estas usando, o dejaste alguna variable sin usar, en si todo lo que te marque en amarillo es una advertencia/aviso, pero no un error, por lo que te dejara exportar sin problemas.

En el caso de NetBeans no puedo darte una respuesta acertada, puede ser que compilaste el archivo en una versión de Java superior a la que hay instalada en el sistema, con Eclipse Luna, pasaba que solo podías ejecutarlo en el IDE pero al crear el JAR no abría el programa.
Quizás puedas ejecutarlo desde la Terminal y ver que dice.
java -jar C:/Users....Programa.jar

Mensaje al intentar ejecutar el archivo JAR, que compile con java 10, pero tengo instalado Java 8 en el sistema:
Exception in thread "main" java.lang.UnsupportedClassVersionError: main/Main has been compiled by a more recent version of the Java Runtime (class file version 54.0), this version of the Java Runtime only recognizes class file versions up to 52.0


text:
Q: doctrine:generate:crud for Entites outside a bundle When I try to create a doctrine crud for an entity I get an 'Unknown entity namespace alias' exception.

I have the following project structure

With a series of bundles (in the Bundles directory) using the Entities in the src\Project\Entity directory.
As you can see my entity namespace is
    namespace Project\Entity;

I have a feeling it might be to do with the auto_mapping, but I have been playing with this for 4-5 hours and am getting nowhere.
Any suggestions?

A: Solution:
Create a command which extends the base doctrine crud command
extends \Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineCrudCommand
Modifying
 $entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace('Project').'\\'.$entity;

to the namespace of the entity. By default it assumes the entity is in the Bundle where you want the CRUD to be created.
By setting
$this->setName('project:generate:crud');

in the Configre() function you can call the function from your command line
Example:
<?php

namespace Project\Bundle\UtilityBundle\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Sensio\Bundle\GeneratorBundle\Command\Validators;

class GenerateDoctrineCrudCommand extends \Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineCrudCommand
{
protected function configure()
{
    parent::configure();

    $this->setName('project:generate:crud');
    $this->setDescription('CRUD generator that supports entities outside a bundle');
}

protected function execute(InputInterface $input, OutputInterface $output)
{
    $questionHelper = $this->getQuestionHelper();

    if ($input->isInteractive()) {
        $question = new ConfirmationQuestion($questionHelper->getQuestion('Do you confirm generation', 'yes', '?'), true);
        if (!$questionHelper->ask($input, $output, $question)) {
            $output->writeln('<error>Command aborted</error>');

            return 1;
        }
    }

    // Note: this expects an argument like InterpracCorporateFrontendBundle:Notification
    list($bundle, $entity) = explode(':', $input->getOption('entity'));

    $format = Validators::validateFormat($input->getOption('format'));
    $prefix = $this->getRoutePrefix($input, $entity);
    $withWrite = $input->getOption('with-write');
    $forceOverwrite = $input->getOption('overwrite');

    $questionHelper->writeSection($output, 'CRUD generation');

    $entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace('Project').'\\'.$entity;
    $metadata    = $this->getEntityMetadata($entityClass);
    $bundle      = $this->getContainer()->get('kernel')->getBundle($bundle);

    $generator = $this->getGenerator($bundle);
    $generator->generate($bundle, $entity, $metadata[0], $format, $prefix, $withWrite, $forceOverwrite);

    $output->writeln('Generating the CRUD code: <info>OK</info>');

    $errors = array();
    $runner = $questionHelper->getRunner($output, $errors);

    // form
    if ($withWrite) {
        $output->write('Generating the Form code: ');
        if ($this->generateForm($bundle, $entity, $metadata)) {
            $output->writeln('<info>OK</info>');
        } else {
            $output->writeln('<warning>Already exists, skipping</warning>');
        }
    }

    // routing
    if ('annotation' != $format) {
        $runner($this->updateRouting($questionHelper, $input, $output, $bundle, $format, $entity, $prefix));
    }

    $questionHelper->writeGeneratorSummary($output, $errors);
}
}

A: The problem is that you are keeping your entities outside bundles. Since this is not standard behaviour, you have to extend or create another GenerateDoctrineCrudCommand to be able to pass namespace alias.


text:
Q: JPA query for parent and child Model Since 3 days I am looking for a solution to my problem. Traditionally I have a table and its detail table in mysql. It is done with JPA play framework 1.2.x. I need to implement a query having purpose of filter. I have an Event model object and every Event has features. The relation between them is as below.
@Entity(name="event")
public class Event extends Model{
public String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "event", cascade = CascadeType.ALL)
public List<Features> features;
}

@Entity(name ="features")
public class Features extends Model{
public String name;
@ManyToOne
public Event event;
}

So, after that i need to query my data according to feature id. For example if feature_id come for 1,2 and 3. my query should return only the events which has features having 1,2 and 3 id.
I really need your help stackoverflow..

A: select e from Event e
where 3 = (select count(f.id) from Feature f where f.id in (1, 2, 3) and f.event = e)

should do the trick (it assumes that  given event doesn't have multiples instances of the same feature, though).
To generalize it, let's say idSet is your set of feature IDs, the query would thus be
select e from Event e
where :idCount = (select count(f.id) from Feature f where f.id in :ids and f.event = e)

and you would bind idSet.size() to idCount, and idSet to ids.
The query could also be written as the following, which would also make it work for a ManyToMany association:
select e from Event e
where :idCount = (select count(f.id) from Event e2
                  join e2.features f
                  where f.id in :ids
                  and e2 = e)


text:
Q: Code and intellectual property Years ago I developed a website in Flash for one of my clients. I was in charge of code/animation and also maintaining Hosting and Domain.
I also have a basic contract with my client and in the contract it does not mention who is the owner for the code.
My Client (ex client) decided suddenly to work with a different company, so they moved the website without asking my permission and left me with unpaid bills for hosting and domain registration.
Now the website is running on the same name but with a different extension, the website is managed by my competitor.
The other company probably used some SWF Decompiler and uploaded the entire website on the new domain.
My question:

*

*Even if in our contract it is not mentioned who the owner of the code/website, I would like to know if I have some right on the code/website I developed?

*Do you now any international regulation on this matter (I'm in Europe)?

If you like please share your opinion or similar story on this, I would appreciate it.

A: Ask your local lawyer. Only he can help you.

A: Depending on your contract, normally the IP is yours until you're paid, but you really need it spelled out in the contract to have the best fallback (this is a good video to watch: http://vimeo.com/22053820). Have you been paid at all or just not fully?
Why do you think that your competitor used a SWF Decompiler to upload the site? If nothing has changed they could just save off the SWF and uploaded it.
My advice would be to get a lawyer and discuss it with them, as depending where you are, the law could be different.


text:
Q: Why would GC.AddMemoryPressure deadlock / hang? Solved: It turns out that the affected machine had .NET 4.5 beta installed.

I have a C# application using .NET4 that deadlocks / hangs indefinitely in a call to
GC.AddMemoryPressure(12000000)

Since it is an in production app I can't really share any code - however I would like to get some hints on what might make GC.AddMemoryPressure hang.

A: Hint from documentation:

You must ensure that you remove exactly the amount of pressure you
  add. Failing to do so can adversely affect the performance of the
  system in applications that run for long periods of time.

That means that you have to be very careful in balancing between these two calls:
AddMemoryPresure and RemoveMemoryPreasure
It's, by the way, suggested to use in case when you allocate a large amount of unmanaged resources, in this way signaling GC about the fact that it has to take in a count also that amomunt of memory.
In vast magiority of cases the simple Dispose(), Finalize() correct management would be enough.

A: Thanks for your input.
It turns out that the affected machine had .NET 4.5 beta installed.
It seems that it wasn't deadlocked since one core was fully saturated. The call to AddMemoryPressure seemed to end up in the function clr!CNameSpace::GcScanRoots that never returned.
Uninstalling 4.5 beta and installing .NET 4 seems to have fixed the problem.
If this was truly the problem then I sure hope MS fix it before release.

A: I wouldn't mess with manual GC. Make sure your resources are disposed of and finished after they are used. GC manually can screw up the system. .NET manages GC pretty well as long as objects are deleted in the program.


text:
Q: Recyclerview GridlayoutManager OnBindViewHolder position & getAdapterPosition() is wrong when scrolling I am using Recyclerview with GridLayoutManager to view multiple viewholders with different types and different SpanSize:
listsLayoutManager.setSpanCount(6);
listsLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (adapter.getItemViewType(position) == VODsGridRVAdapter.TYPE_TITLE || adapter.getItemViewType(position) == VODsGridRVAdapter.TYPE_HEADER)
                return 6;
            return 1;
        }
    });

Here is the getItemViewType method:
 @Override
public int getItemViewType(int position) {
    if (position == 0)
        return TYPE_HEADER;
    return dataList.get(position - 1).isTitle() ? TYPE_TITLE : TYPE_ITEM;
}

where position 0 is always for the header.
When scrolling the view, the onBindViewHolder gives wrong position and the getAdapterPosition is doing that so.
is there any solution for this problem but to use         holder.setIsRecyclable(false);
?

A: After 36 hours of debugging and trying, I was able to solve this problem by removing the adapter.setHasStableIds(true); line from my Activity.


text:
Q: Load ICollectionView With Task Library I've the following problem:
if I load a simple list into ICollectionView which is bound on my wpf listbox, then CurrentChanged event being raised as I expected:
List<int> l = new List<int>();
l.Add(1);
l.Add(2);
MyCollection = CollectionViewSource.GetDefaultView(l);
MyCollection.CurrentChanged += MyCollection_CurrentChanged; // ok, it's raised

However, Imagine I'm loading data into another thread, then, I would like the same behaviors, that is raising currentChanged event, but it doesn't work:
 List<int> l = new List<int>();
            Task.Factory.StartNew(() =>
            {
                l.Add(1);
                l.Add(2);
            })
            .ContinueWith((r) =>
                {

                    MyCollectio = CollectionViewSource.GetDefaultView(l);
                    MyCollectio.CurrentChanged += MyCollectio_CurrentChanged; // ko, it isn't raised.

                }, TaskScheduler.FromCurrentSynchronizationContext());

Note that I'm using TaskScheduler.FromCurrentSynchronizationContext() in order to work on UI thread, however it doesn't work. I also tried with Application.Current.Dispatcher.Invoke without luck.

A: I think that the root cause is inside your xaml.
If you are using <ListBox />, or any other ItemsControl, that inhireted from Selector,  try to set IsSynchronizedWithCurrentItem to True, like this:
<ListBox ItemsSource="{Binding MyCollectio}"
         IsSynchronizedWithCurrentItem="True"
         />

I have tried this, and this works fine, with and without TPL Task
In the MainWindow.xaml.cs I have this (try it, the xaml should contain the ListBox mentioned above):
public MainWindow()
{
    InitializeComponent();

    MyVM con = new MyVM();
    DataContext = con;
    List<int> l = new List<int>();
    Task.Factory.StartNew(() =>
    {
        l.Add(1);
        l.Add(2);
        l.Add(3);
        l.Add(4);
        l.Add(5);
        l.Add(6);
    })
    .ContinueWith((r) =>
    {

        con.MyCollectio = CollectionViewSource.GetDefaultView(l);
        con.MyCollectio.CurrentChanged += MyCollectio_CurrentChanged;
    }, TaskScheduler.FromCurrentSynchronizationContext());
}

void MyCollectio_CurrentChanged(object sender, EventArgs e)
{
    MessageBox.Show("Curren really changed!!!");
}

...

public class MyVM : ViewModelBase
{
    public ICollectionView MyCollectio
    {
        get
        {
            return _MyCollectio;
        }

        set
        {
            _MyCollectio = value;
            RaisePropertyChanged("MyCollectio");
        }
    }
    private ICollectionView _MyCollectio;
}

...

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}


text:
Q: Django Oscar automatically empties the basket on redeeming an expired voucher When a customer applies a voucher to an item in the cart and the voucher expires during the checkout process or inside the cart itself. During the checkout process, when clicked on place order, the cart automatically empties and the customer is sent this error, You need to add some items to your basket to checkout, this happens during the check_basket_is_not_empty method.
Can someone help me understand which part of Django-Oscar could be modifying the cart in such drastic way. My initial thought was, that the cart was getting emptied because some oscar component was trying to remove the voucher and was removing the cart item as well. But during some more checks I find out that the voucher is successfully removed but the cart item only gets removed inside the PaymentDetailsView, probably.
I don't have the code to PaymentDetailsView. I started the job as a Django developer a couple of days ago and I was thrown into this huge django-oscar code base, which I am completely unfamiliar with. I am not allowed to post any code online. I don't know what to do, and don't want to get fired. Any help would be highly appreciated.

A: I still don't know what's causing this bug, but I came up with this solution. When you click "place order", the PaymentDetailsView class gets triggered, and the first function to deal with all the data is the submit one. So inside that, you can manually check the vouchers you have in the request and remove the vouchers manually.
# removing expired vouchers:
for voucher in self.request.basket.vouchers.all():
     if voucher.is_expired() or not voucher.is_available_to_user(user=self.request.basket.owner)[0]:
        self.request.basket.vouchers.remove(voucher)
        messages.error(self.request,_("The '%(code)s' voucher has expired") % {'code': voucher.code})


text:
Q: Code Coverage for Cucumber Tests using Jacoco I am trying to integrate Jacoco to get the code coverage for my Cucumber tests using Maven. Following is my project structure:

*

*-src-main-java-Pages

*-src-main-java-Helper

*-src-test-java-resources-features

*-src-test-java-Steps
Following is the Jacoco configuration in my POM.xml
          <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.2</version>
            <configuration>
                <destFile>${basedir}/target/coverage-reports/jacoco.exec</destFile>
                <dataFile>${basedir}/target/coverage-reports/jacoco.exec</dataFile>
                <outputDirectory>${basedir}/target/coverage-reports/jacoco</outputDirectory>
            </configuration>
            <executions>
                <execution>
                    <id>prepare-agent</id>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                </execution>
                <execution>
                    <id>report</id>
                    <goals>
                        <goal>report</goal>
                    </goals>
                </execution>
                <execution>
                    <id>check</id>
                    <goals>
                        <goal>check</goal>
                    </goals>
                    <configuration>
                        <rules>
                            <rule>
                                <element>PACKAGE</element>
                                <includes>
                                    <include>**/*Steps.*</include>
                                </includes>
                            </rule>
                            <rule>
                                <element>PACKAGE</element>
                                <excludes>
                                    <exclude>**/*Pages.*</exclude>
                                    <exclude>**/*Page.*</exclude>
                                </excludes>
                            </rule>
                        </rules>
                    </configuration>
                </execution>
            </executions>
        </plugin>

I am able to generate the code coverage report. However, in the report, it covers all the classes in the -src-main packages. As per different google researches and SO posts, I tried to modify my POM to exclude Pages and include only Steps in my code coverage report. But somehow, it keeps on displaying all the files in the main package.
Am I taking the wrong approach? I just want to create a report which does code coverage for only the tests that I execute rather than all the files in the main package.

A: See https://maven.apache.org/guides/mini/guide-configuring-plugins.html - you specify exclusions in configuration of
<execution>
    <id>check</id>
    <goals>
        <goal>check</goal>

but not in configuration of
<execution>
    <id>report</id>
    <goals>
        <goal>report</goal>

so it has effect on check, but not on report.


text:
Q: SQL Server - Select Left Join NULL record WHERE condition I am trying to perform a SELECT query on two tables joined with a LEFT JOIN where there may not be a record in the joined table. Something like:
--SELECT row using AreaID
SELECT *
FROM Rate
LEFT JOIN Area
ON Rate.AreaID = Area.AreaID
WHERE ProductID = @ProductID
AND Area.PostcodeOutcode = @PostcodeOutcode

This works when @PostcodeOutcode exists in the Area table, but I still need to return the record in the left table if there is not a record in the right table.
I am fudging it currently by doing this, but I know there is a better solution:
DECLARE @AreaID int
SELECT @AreaID = AreaID
FROM Area WHERE PostcodeOutcode = @PostcodeOutcode

--SELECT row using AreaID
SELECT *
FROM Rate
WHERE ProductID = @ProductID
AND
(
    AreaID = @AreaID
    OR (@AreaID IS NULL AND AreaID IS NULL)
)

I know this is probably simple, but my SQL knowledge is limited.  Please help.
Thanks
Alex

A: move the area check to the join
SELECT * FROM Rate
LEFT JOIN Area
  ON Rate.AreaID = Area.AreaID and Area.PostcodeOutcode = @PostcodeOutcode
WHERE ProductID = @ProductID

Update for the revised question in comments, Is this what you want?
SELECT Rate.RatePercent FROM Rate
INNER JOIN Area
  ON Rate.AreaID = Area.AreaID and Area.PostcodeOutcode = @PostcodeOutcode
WHERE
  ProductID = @ProductID
UNION ALL
SELECT Rate.RatePercent FROM Rate
where
  ProductID = @ProductID
and
  AreaId is null
and
 not exists(select PostCodeOutCode From Area where PostCodeOutCode=@PostCodeOutcode)

A: There is a difference for left join between these two:
Select *
From Table1 t1
Left Outer Join Table2 t2 On t2.id = t1.id
Where t2.somevalue = @SomeParameter

And
Select *
From dbo.Table1 t1
Left Outer Join dbo.Table2 t2 On t2.id = t1.id And t2.somevalue = @SomeParameter

The latter will filter Table2, while the former will filter the join between Table1 and Table2. So, this means that the first query will join all rows in the two tables on id and then filter the ones where somevalue doesn't match the parameter, i.e. this will usually also filter out the ones where somevalue is null, because there was no row.
The second query will join table1 with table2 on id, but table2 is filtered on matching parameter first, so the non-matching rows are also returned, and are thus not filtered out.
And a side note: you should always supply the schema of your tables in your queries (for performance reasons).


text:
Q: How to project an identical listview in one activity onto a popupwindow in another activity? In my loginpage for my game I have made it so that you can type in your player name and this is listed in a listview below.
(https://gyazo.com/19ab8f8af96ad6a304b4116e48d47dfc
Within my gamescreen (2nd activity) I have made a pop up window for the highscores.
My question: How can I copy that same identical list that is created within the loginpage of player names to my popupwindow within the 2nd activity screen.
This is how the pop up window looks like:
https://gyazo.com/a03f3e79c521cdea151fec769b34da8e
Because I already have had to pass data from the list to my 2nd activity I have created the following:
public void openActivity2() {
    Intent intent = new Intent(this, Gamescreen.class);
    intent.putStringArrayListExtra("names", list);
    startActivity(intent);

Now this is how I have made the pop up window (and I have attempted to get the list from the intent)
highscores.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
            ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.highscores, null);

            popupWindow = new PopupWindow(container, 1150, 1500, true);
            popupWindow.showAtLocation(constraintLayout, Gravity.NO_GRAVITY, 140, 395);
            Intent iin= getIntent();
            list= iin.getStringArrayListExtra("names");
            if(list!=null)
            {
                scores=list;
            }


text:
Q: How can i add cc to mail function? this is my code, But i am getting blank mails also. what was the wrong with this?
    'success',
            'message'=>'Thank you for contact us. As early as possible  we will contact you '
        );
    $name = @trim(stripslashes($_POST['name']));
    $email = @trim(stripslashes($_POST['email']));
    $subject = @trim(stripslashes($_POST['subject']));
    $message = @trim(stripslashes($_POST['message']));

    $email_from = $email;
    $email_to = 'To: <someone@gmail.com>, <anotherone@gmail.com>' . "\r\n";

    $body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;

    $success = @mail($email_to, $subject, $body, 'From: <'.$email_from.'>');

    echo json_encode($status);
    die;

A: Please read documentation mail function Here they explained detailedly.
Particularly Example #4 Sending HTML email
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);


text:
Q: Boost.Asio async_send question I'm using Boost.Asio for a server application that I'm writing.
async_send requires the caller to keep ownership of the data that is being sent until the data is sent successfully. That means my code (which looks like the following) will fail, and it does, because data will no longer be a valid object.
void func()
{
    std::vector<unsigned char> data;

    // ...
    // fill data with stuff
    // ...

    socket.async_send(boost::asio::buffer(data), handler);
}

So my solution was to do something like this:
std::vector<unsigned char> data;

void func()
{
    // ...
    // fill data with stuff
    // ...

    socket.async_send(boost::asio::buffer(data), handler)
}

But now I'm wondering if I have multiple clients, will I need to create a separate vector for each connection?
Or can I use that one single vector? If I'm able to use that single vector, if I overwrite the contents inside it will that mess up the data I'm sending to all my clients?

A: I solved a similar problem by passing a shared_ptr to my data to the handler function.  Since asio holds on to the handler functor until it's called, and the hander functor keeps the shared_ptr reference, the data stays allocated as long as there's an open request on it.
edit - here's some code:
Here the connection object holds on to the current data buffer being written, so the shared_ptr is to the connection object, and the bind call attaches the method functor to the object reference and the asio call keeps the object alive.
The key is that each handler must start a new asyc operation with another reference or the connection will be closed.  Once the connection is done, or an error occurrs, we simply stop generating new read/write requests.  One caveat is that you need to make sure you check the error object on all your callbacks.
boost::asio::async_write(
    mSocket,
    buffers,
    mHandlerStrand.wrap(
        boost::bind(
            &TCPConnection::InternalHandleAsyncWrite,
            shared_from_this(),
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred)));

void TCPConnection::InternalHandleAsyncWrite(
    const boost::system::error_code& e,
    std::size_t bytes_transferred)
{

A:
But now I'm wondering if I have
  multiple clients, will I need to
  create a separate vector for each
  connection?

Yes, though each vector does not need to be in global scope. The typical solution to this problem is to retain the buffer as a member of an object, and  bind a member function of that object to a functor passed to the async_write completion handler. This way the buffer will be retained in scope throughout the lifetime of the asynchronous write. The asio examples are littered with this usage of binding member functions using this and shared_from_this. In general it is preferable to use shared_from_this to simplify object lifetime, especially in the face of io_service:stop() and ~io_service(). Though for simple examples, this scaffolding is often unnecessary.

The destruction sequence described
  above permits programs to simplify
  their resource management by using
  shared_ptr<>. Where an object's
  lifetime is tied to the lifetime of a
  connection (or some other sequence of
  asynchronous operations), a shared_ptr
  to the object would be bound into the
  handlers for all asynchronous
  operations associated with it.

A good place to start is the async echo server due to its simplicity.
boost::asio::async_write(
    socket,
    boost::asio::buffer(data, bytes_transferred),
    boost::bind(
        &session::handle_write,
        this,
        boost::asio::placeholders::error
    )
);

A: The way that I've been doing it is to really take the "TCP is a stream" concept to heart. So I have a boost::asio::streambuf for each connection to represent what I send to the client.
Like most of the examples in boost, I have a tcp_connection class with an object per connection. Each one has a memeber boost::asio::streambuf response_; and when I want to send something to the client I just do this:
std::ostream responce_stream(&response_);
responce_stream << "whatever my responce message happens to be!\r\n";

boost::asio::async_write(
    socket_,
    response_,
    boost::bind(
        &tcp_connection::handle_write,
        shared_from_this(),
        boost::asio::placeholders::error,
        boost::asio::placeholders::bytes_transferred));

A: You can't use a single vector unless you send the same and constant data to all the clients (like a prompt message). This is caused by nature of async I/O. If you are sending, the system will keep a pointer to your buffer in its queue along with some AIO packet struct. As soon as it's done with some previous queued send operations and there's a free space in its own buffer, the system will start forming packets for your data and copy chunks of your buffer inside the corresponding places in TCP frames. So if you modify content of your buffer along the way, you'll corrupt the data sent to the client. If you're receiving, the system may optimize it even further and feed your buffer to the NIC as a target for DMA operation. In this case a significant number of CPU cycles can be saved on data copying because it's done by DMA controller. Probably, though, this optimization will work only if NIC supports hardware TCP unload.
UPDATE: On Windows, Boost.Asio uses overlapped WSA IO with completion notifications via IOCP.

A: Krit explained the data corruption, so I'll give you an implementation suggestion instead.
I would suggest that you use a separate vector for each send operation that is currently being executed. You probably don't want one for each connection since you might want to send several messages on the same connection sequentially without waiting for completion of the previous ones.

A: A possible fix would be to use a shared_ptr to hold your local vector and change the handler's signature to receive a shared_ptr so to prolong the life of the data until the sending is complete (thanks to Tim for pointing that out to me):
void handler( boost::shared_ptr<std::vector<char> > data )
{
}

void func()
{
    boost::shared_ptr<std::vector<char> > data(new std::vector<char>);
    // ...
    // fill data with stuff
    // ...

    socket.async_send(boost::asio::buffer(*data), boost:bind(handler,data));
}

A: You will need one write buffer per connection, others have been saying to use a vector per connection as was your original idea, but I would recommend for simplicity to use a vector of strings with your new approach.
Boost.ASIO has some special cases built around using strings with its buffers for writes, which make them easier to work with.
Just a thought.


text:
Q: Como acessar valor dropdonw sem refresh Existe um meio de pegar o valor da opção escolhida do meu select, na mesma página, sem enviar o formulário, no momento em que o usuário faz um alteração?
<select id="s_um" name="s_um">
                <option id="um_1" value="0"> 0 </option>
                <option id="um_2" value="1"> 1 </option>
                <option id="um_3" value="2"> 2 </option>
                <option id="um_4" value="3"> 3 </option>
                </select>

<select id="s_dois" name="s_dois">
                <option id="dois_1" value="0"> 0 </option>
                <option id="dois_2" value="1"> 1 </option>
                <option id="dois_3" value="2"> 2 </option>
                <option id="dois_4" value="3"> 3 </option>
                </select>

Gostaria de somar os valores escolhidos.

A: Podes fazer assim com jQuery:

$("select").change(function() {
  alert($(this).val()); // ou text()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="s_um" name="s_um">
  <option id="um_1" value="0">0</option>
  <option id="um_2" value="1">1</option>
  <option id="um_3" value="2">2</option>
  <option id="um_4" value="3">3</option>
</select>

<select id="s_dois" name="s_dois">
  <option id="dois_1" value="0">0</option>
  <option id="dois_2" value="1">1</option>
  <option id="dois_3" value="2">2</option>
  <option id="dois_4" value="3">3</option>
</select>

Ou em javascript:
document.querySelector('select').addEventListener('change', function() {
  console.log(this.value);
});

Veja funcionando em:  jsfiddle

A: Você pode fazer assim:
$('#s_dois').change(function() {

var soma = parseInt($('#s_um option:selected').val()) + parseInt($('#s_dois option:selected').val());

alert(soma);

})

Veja o fiddle:
https://jsfiddle.net/hq8mv7xw/
Você pode fazer o evento para os dois selects também:
$('#s_um, #s_dois').change(function() {

var soma = parseInt($('#s_um option:selected').val()) + parseInt($('#s_dois option:selected').val());

alert(soma);

})


text:
Q: Plotting pandas dataframe with string labels I have a pandas dataframe that has several fields. The ones of importance are:
In[191]: tasks[['start','end','appId','index']]
Out[189]:
             start               end                           appId  index
2576 1464262540102.000 1464262541204.000  application_1464258584784_0012      1
2577 1464262540098.000 1464262541208.000  application_1464258584784_0012      0
2579 1464262540104.000 1464262541194.000  application_1464258584784_0012      3
2583 1464262540107.000 1464262541287.000  application_1464258584784_0012      6
2599 1464262540125.000 1464262541214.000  application_1464258584784_0012     26
2600 1464262541191.000 1464262541655.000  application_1464258584784_0012     28
.
.
.
2701 1464262562172.000 1464262591147.000  application_1464258584784_0013     14
2718 1464262578901.000 1464262588156.000  application_1464258584784_0013     28
2727 1464262591145.000 1464262602085.000  application_1464258584784_0013     40

I want to plot a line for each row that goes from the coords (x1=start,y1=index),(x2=end,y1=index). Each line will have a different color depending on the value of appId which is a string. This is all done in a subplot I have inside a time series plot. I post the code here but the important bit is the tasks.iterrows() part, you can ignore the rest.
def plot_stage_in_host(dfm,dfg,appId,stageId,parameters,host):
    [s,e] = time_interval_for_app(dfm, appId,stageId, host)
    time_series = create_time_series_host(dfg, host, parameters, s,e)
    fig,p1 = plt.subplots()
    p2 = p1.twinx()
    for para in parameters:
        p1.plot(time_series.loc[time_series['parameter']==para].time,time_series.loc[time_series['parameter']==para].value,label=para)
    p1.legend()
    p1.set_xlabel("Time")
    p1.set_ylabel(ylabel='%')
    p1.set(ylim=(-1,1))
    p2.set_ylabel("TASK INDEX")
    tasks = dfm.loc[(dfm["hostname"]==host) & (dfm["start"]>s) & (dfm["end"]<e) & (dfm["end"]!=0)] #& (dfm["appId"]==appId) & (dfm["stageId"]==stageId)]
    apps = tasks.appId.unique()
    norm = colors.Normalize(0,len(apps))
    scalar_map = cm.ScalarMappable(norm=norm, cmap='hsv')
    for _,row in tasks.iterrows():
        color = scalar_map.to_rgba(np.where(apps == row['appId'])[0][0])
        p2.plot([row['start'],row['end']],[row['index'],row['index']],lw=4 ,c=color)
    p2.legend(apps,loc='lower right')
    p2.show()

This is the result I get.

Apparently is not considering the labels and the legend shows the same colors for all the lines. How can I label them correctly and show the legend as well?

A: The problem is that you are assigning the label each time you plot the graph in the for loop using the label= argument. Try removing it and giving p2.lengend() a list of strings as an argument that represent the labels you want to show.
p2.legend(['label1', 'label2'])

If you want to assign a different color to each line try the following:
import matplotlib.pyplot as plt
import numpy as np
xdata = [1, 2, 3, 4, 5]
ydata = [[np.random.randint(0, 6) for i in range(5)],
        [np.random.randint(0, 6) for i in range(5)],
        [np.random.randint(0, 6) for i in range(5)]]
colors = ['r', 'g', 'b']  # can be hex colors as well
legend_names = ['a', 'b', 'c']
for c, y in zip(colors, ydata):
    plt.plot(xdata, y, c=c)
plt.legend(legend_names)
plt.show()

It gives the following result:

Hope this helps!


text:
Q: How to do a minimal install of 20.04? I'm wanting to do a minimal install of Ubuntu 20.04 LTS on a VM I'm making.  My original thought was to use either the network installer or the minimal CD, but both of those seem to be gone right now.  How would I be able to get that kind of install on 20.04 LTS?

A: The Netinstall/Minimal image (two names for the same thing) was a byproduct of the Debian installer server build. While popular with some users, the Ubuntu developers never supported it.
Ubuntu Server recently changed to a new installer, so the Netinstall image will longer be created. The final 20.04 Netinstall image is here.

*

*For a VM, consider using a daily cloud image: https://cloud-images.ubuntu.com/focal/current/

*For Bare Metal, consider simply using an older Netinstall image, then release-upgrading those minimal packages to 20.04, then installing the rest of your system.

*Netbooting the server installer is still possible, see https://discourse.ubuntu.com/t/netbooting-the-live-server-installer/14510
There are many other options: Vagrant, pre-built VMs, Ubuntu Core, Ubuntu Base, etc. It really depends upon what you want your final system configuration to look like.

A: You still can get netboot installer (mini.iso, for now it is called Legacy Ubuntu Server Installer) from direct link below
http://archive.ubuntu.com/ubuntu/dists/focal/main/installer-amd64/current/legacy-images/netboot/mini.iso

A: You can select "Minimal installation" in the graphic assistant. This will install a web browser and basic utilities. But you still have to download the full 3Gb iso for that.