text:
Q: Realizar una prueba unitaria en NodeJs. Con mocha y chai; Estoy realizando una prueba unitaria a una funcion, y lo que quiero es simular la comunicacion con el DTA(Que no se comunique con la base de datos); Por ejemplo: Esta es la funcion a la cual quiero realizarle la prueba...
public add(a, b): Promise<any> {
    return new Promise((resolve, reject) => {
        this.queueDta.add(a, b)
        .then(() => resolve({status: "created"}))
        .catch(() => reject({code: "QUE01"}));
    });
}

Y pues al realizar la prueba, quiero que la funcion add que esta conectada con el DTA, se ejecute pero de forma falsa y retorne true;
Cree un stub al DTA para modificar la función, pero los toma de forma diferente, por lo tanto, agrega la información a la base de datos.
context("addToQueue", () => {
    let data;
    it("ADD", async () => {
        const queueBns2 = new queueBns.QueueBns();
        const queueDta2 = new queueDta.QueueDta();
        let result2;

        data = sandbox.stub(queueDta2, "add").value(true);
        result2  = await queueBns2.add(1, 2);
          //-- Aca irian los expect, para validar la funcion ---
    });
});

Estaba buscando la manera de instanciar la clase de otra forma pero no sé, de que forma puedo modificar esa función y que el BNS utilice la función falsa. Gracias por su colaboración. Estoy pendiente :).

A: Encontre la solucion y es la siguiente:
El archivo de mi prueba en este caso se llama

QueueBns.spec.ts

Mis importaciones son:
declare var require: any;
import * as chai from "chai";
import "mocha";
import "reflect-metadata";

const sinon = require("sinon");
const expect = chai.expect;
let sandbox;
import * as sinonChai from "sinon-chai";
import { QueueBns, QueueDta } from "..";

const chaiIsPromised = require("chai-as-promised");
chai.use(chaiIsPromised);
chai.use(sinonChai);

Y la prueba es la siguiente:
describe("QueueBns", () => {

afterEach(() => { sandbox.restore(); });

before(() => { sandbox = sinon.sandbox.create(); });

let instance2;

context("addToQueue", () => {
    let data;
    it("ADD", async () => {
        instance2 = new QueueBns();
        let result2;
        data = sandbox.stub(QueueDta.prototype, "add").resolves({nada: "Johan"});
        result2  = await instance2.add(1, 2);

        console.log("result2", result2); // El resultado es: {nada: "Johan"}
    });
});

});

QueueBns.ts

import {injectable} from "inversify";
import {QueueDta} from "../data/QueueDta";
@injectable()
class QueueBns {
private queueDta: QueueDta;

constructor() {
    this.queueDta = new QueueDta();
}

public add(a, b): Promise<any> {
    return new Promise((resolve, reject) => {
        this.queueDta.add(a, b)
        .then((data) => resolve(data))
        .catch(() => reject({code: "QUE01"}));
    });
 }
}
export {QueueBns};

QueueDta.ts

import { db } from "../../../app.config";
export class QueueDta {
    public add(a, b): Promise<any> {
        return new Promise<any>((resolve, reject) => {
            db.collection("suma")
            .add({a, b})
            .then(() => resolve(true))
            .catch((error) => reject(error));
        });
    }
}

Como tal podemos observar en la prueba, que logramos modificar el resultado de la funcion add que se encuentra en QueueDta.ts
Espero les sirva si alguno se encuentra con el mismo problema :).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Easypost.com integration laravel - send forms I am quite a beginner in Laravel. I understood CRUD, OOP, created some small apps.
But now I need to integrate easypost.com API to Laravel project.
I wanna create a simple postage calculator for now.
I have a page where are forms on the bottom and below forms, I wanna show all postage options with rates, etc.
Now I have PostageCalculator controller and putting to index function this:
public function index()
{

    \EasyPost\EasyPost::setApiKey(env('EASYPOST_API'));

    $shipment = \EasyPost\Shipment::create(array(
        "to_address" => array(
          'name' => 'Dr. Steve Brule',
          'street1' => '3993 Glen Meadow Dr',
          'city' => 'Norcross',
          'state' => 'GA',
          'zip' => '30092',
          'country' => 'US',
          'phone' => '3331114444',
          'email' => 'dr_steve_brule@gmail.com'
        ),
        "from_address" => array(
          'name' => 'EasyPost',
          'street1' => '417 Montgomery Street',
          'street2' => '5th Floor',
          'city' => 'Brno',
          'state' => 'CZ',
          'zip' => '60200',
          'country' => 'CZ',
          'phone' => '3331114444',
          'email' => 'support@easypost.com'
        ),
        "parcel" => array(
          "length" => 1,
          "width" => 1,
          "height" => 1,
          "weight" => 352.74
        )
      ));

    return view ('pages.rates', [
        'shipment' => $shipment

     ]);

}

So I send $shipment variable to rates.blade.php view and use foreach to show all info I need.
But also I have a form, where I want to select for example shipping and delivery country and can allow users to type their weight, dimensions, etc, so I created this form
     <form action="/rates" method="post">
        @csrf
        @method('post')

    {{-- Zeme odeslani --}}

        Země odeslání
        @error('text')

{{$message}}

        @enderror
      <select class="form-select" aria-label="Default select example">
        <option selected>Vyberte zemi</option>
        <option value="CZ" name="CZ">Česká republika</option>
        <option value="US" name="US">USA</option>
        <option value="SK" name="SK">Slovensko</option>
      </select>

    Země doručení
    @error('text')

{{$message}}

    @enderror
  <select class="form-select" aria-label="Default select example">
    <option selected>Vyberte zemi</option>
    <option value="CZ" name="CZ">Česká republika</option>
    <option value="US" name="US">USA</option>
    <option value="SK" name="SK">Slovensko</option>
  </select>

        Rozměry:
        @error('text')

{{$message}}

        @enderror

<input type="text" class="form-control" name="weight" placeholder="Váha (kg)" >

<input type="text" class="form-control" name="width" placeholder="Šířka (cm)" >

<input type="text" class="form-control" name="height" placeholder="Výška (cm)" >

<input type="text" class="form-control" name="`lenght`" placeholder="Délka (cm)" >

      < button type="submit" class="btn btn-primary">Spočítat cenu</button>
    </form>

and button with type="submit".
My problem is I know that I need to somehow use the store () function at my controller to get the request from the form, however, I don't know how.
I wanted to take $shipment request from index() function, but I am using foreach at the blade and it doesn't know variable $shipment.
and also I have no idea how to works with 2 options forms.
if I have select
<select class="form-select" aria-label="Default select example">
        <option selected>Vyberte zemi</option>
        <option value="CZ" name="CZ">Česká republika</option>
        <option value="US" name="US">USA</option>
        <option value="SK" name="SK">Slovensko</option>
      </select>

one select form is for ship address from and the second one for the delivery address.
How to get requests from the form and show the results from EasyPost on the same package calculator page?
tried something like:
'country' => $request->input['formname'],

but no luck.
Also, I have no idea how to create and separate values for a ship from and ship to select form.
Can you advise, please?
Thanks a lot., This is quite new for me.

A: To accomplish your need you have to think this process as an application lifecycle.
Basically; you want to show a form on a page, user needs to fill and post it, you will use inputs to prepare your address parameters and give them to Easypost api, when you got response from api, you will pass it to a view to show results on screen.
When I check your form blade, there isn't any name property on your select fields. You need something like this;
<select name="from_country" class="form-select" aria-label="Default select example">
    <option selected>Vyberte zemi</option>
    <option value="CZ" name="CZ">Česká republika</option>
    <option value="US" name="US">USA</option>
    <option value="SK" name="SK">Slovensko</option>
</select>

and other one;
<select name="to_country" class="form-select" aria-label="Default select example">
    <option selected>Vyberte zemi</option>
    <option value="CZ" name="CZ">Česká republika</option>
    <option value="US" name="US">USA</option>
    <option value="SK" name="SK">Slovensko</option>
</select>

Now you can access this fields selected options from request;
public function show_result(Request $request)
{
    $from_country = $request->from_country;
    // OR
    $from_country = $request->input('from_country');
}

You can find other usage examples of $request->input(...) here: https://laravel.com/docs/8.x/requests#retrieving-an-input-value
So; you need to create 2 routes; 1 for show form and 1 for process form and show results.
In the routes/web.php file;
Route::get('form', [\App\Http\Controllers\PostageCalculator::class, 'form']); // to show form
Route::post('result', [\App\Http\Controllers\PostageCalculator::class, 'result']); // to show results

In the app/Http/Controllers/PostageCalculator.php file;
// define your methods in your Controller class
public function form()
{
    $data = []; // prepare any daha if you need anything on your form but as I see you don't need any
    return view('form', $data);
}

public function result(Request $request)
{
    // if you need any validation for form fields you can use $request->validate([...]);
    // you can access all posted input fields which specified with a name
    $to_address = array(
          'name' => $request->input('to_address_name'),
          'street1' => $request->input('to_address_street1'),
          'city' => $request->input('to_address_city'),
          'state' => $request->input('to_address_state'),
          'zip' => $request->input('to_address_zip'),
          'country' => $request->input('to_address_country'),
          'phone' => $request->input('to_address_phone'),
          'email' => $request->input('to_address_email')
        );
    $from_address = array(
          'name' => $request->('from_address_name'),
          'street1' => $request->('from_address_street1'),
          'city' => $request->('from_address_city'),
          'state' => $request->('from_address_state'),
          'zip' => $request->('from_address_zip'),
          'country' => $request->('from_address_country'),
          'phone' => $request->('from_address_phone'),
          'email' => $request->('from_address_email')
        );
    $parcel = array(
          "length" => $request->input('length'),
          "width" => $request->input('width'),
          "height" => $request->input('height'),
          "weight" => $request->input('weight'),
        );

    \EasyPost\EasyPost::setApiKey(env('EASYPOST_API')); // you should use config('services.easypost.api_key') instead of env(...)

    $shipment = \EasyPost\Shipment::create([$to_address, $from_address, $parcel]);

    return view('result', compact('shipment'));
}

To access input data with $request->input('name') you need give all fields their own unique name.
In resources/views/form.blade.php
<form action="{{ url('result') }}" method="post">
    @csrf
    From address:

    <input name="from_address_name" placeholder="from_address_name">

    <input name="from_address_street1" placeholder="from_address_street1">

    <input name="from_address_city" placeholder="from_address_city">

    <input name="from_address_state" placeholder="from_address_state">

    <input name="from_address_zip" placeholder="from_address_zip">

    <select name="from_address_country" class="form-select">
        <option selected>Select Country</option>
        <option value="CZ" name="CZ">Česká republika</option>
        <option value="US" name="US">USA</option>
        <option value="SK" name="SK">Slovensko</option>
    </select>

    <input name="from_address_phone" placeholder="from_address_phone">

    <input name="from_address_email" placeholder="from_address_email">

    To address:
    From address:

    <input name="to_address_name" placeholder="to_address_name">

    <input name="to_address_street1" placeholder="to_address_street1">

    <input name="to_address_city" placeholder="to_address_city">

    <input name="to_address_state" placeholder="to_address_state">

    <input name="to_address_zip" placeholder="to_address_zip">

    <select name="to_address_country" class="form-select">
        <option selected>Select Country</option>
        <option value="CZ" name="CZ">Česká republika</option>
        <option value="US" name="US">USA</option>
        <option value="SK" name="SK">Slovensko</option>
    </select>

    <input name="to_address_phone" placeholder="to_address_phone">

    <input name="to_address_email" placeholder="to_address_email">

    Parcel:
    <input type="text" class="form-control" name="weight" placeholder="Váha (kg)" >

        <input type="text" class="form-control" name="width" placeholder="Šířka (cm)" >

        <input type="text" class="form-control" name="height" placeholder="Výška (cm)" >

        <input type="text" class="form-control" name="`lenght`" placeholder="Délka (cm)" >

    <button type="submit">Show Results</button>
</form>

(I didn't use any class/styles here but every input field have a name)
Now your /form route works and shows a form. And you post it to /result route to catch input fields and calculate $shipment result. You need to show $shipment data on your resources/views/result.blade.php file.
In resources/views/result.blade.php file;

Calculation Result

@foreach($shipment->rates as $rate)
    {{ $rate->service }}

    {{ $rate->carrier }}

    {{ $rate->rate }}

@endforeach

Actually I didn't use easypost api before but I checked documentation: https://www.easypost.com/docs/api/php#shipments-create-codesample
I think that's all and you need to check and edit code samples from my answer.

A: Oh finally I understood this! I ll try it later again and will let you know
Thank you sooo much

A: I did session::put on the request and used this session for to pass data to the index(). This solution works, if you ll have something better, let me know thanks a looot


text:
Q: 'Hit on someone' means like 'flirt with someone'. Then when I wanna make the tone stronger, can i put 'up' like Hit up on someone
is it ok in american english, or british english?
or it would be ok but as a native(american or english), almost no one say 'hit up on someone'? 99% says 'hit on someone' only?
Thanks teachers:)

A: "Hit on" means to flirt.  "Hit up" means to initiate contact.  "Hit up on someone" is not something people say.
You could say "coming on" to someone, which is a bit more sexual than "hitting on".  "Courting" is a more formal process of flirting and dating with the purpose of marriage.

A: There are three idiomatic phrasal verbs:

*

*hit on - meaning to flirt : "John fancied Susan the moment he saw her, so he hit on her."

*hit up - meaning to request (someone) to do or give something : "John hit me up for more money."

*hit upon - meaning to mention or address; to suddenly have an idea; to discover something by chance : John will hopefully hit upon all of the customers' concerns during the meeting.
Your suggested usage of "hit up on" isn't idiomatic.  It is not an emphatic version of "hit on."  I don't see anyone inferring that meaning from the words themselves.

A: hit on. OED

colloquial (originally U.S.). to hit on: to make romantic or sexual
  advances towards.

To make hitting on someone seem or sound more emphatic in written form consider adding an exclamation point!  Other senses of hitting off, out, around have different meanings.


text:
Q: Is There a Way to Restrict Azure API Management Endpoint By Subscription? In Azure API Management, is it possible to restrict an endpoint for an API by a subscription?
I know it's possible to restrict access to the whole API/Product by subscription, but can that be filtered down even further such that a subscription could be limited to specific endpoints of an API?

A: Restricting access for specific endpoints can be achieved using policies, and more specifically through the use of the Validate JWT policy. It allows authorizing access to specific operations (specific endpoints) of the API.
The documentation has the following example which shows how to define a policy that restricts HTTP methods: https://learn.microsoft.com/en-us/azure/api-management/policies/authorize-request-based-on-jwt-claims. You can modify the when condition to check the request URL instead of the method.


text:
Q: When is a subset of a countable set finite? Suppose I have a countable set B, and a subset of it called A. I would like to know when is A finite.

From the comments: B is an infinite set. I know that B is equivalent to the natural numbers so every subset of B is either countable (when there exists a bijection between A and B) or A is a finite set (when? - Does it happens if there is no bijection from A to B?) – JanosAudron 10 mins ago

A: There are many definitions of finitude. Consider the following, due to Dedekind:

A set $A$ is finite iff there is no bijection between $A$ and any proper subset $B \subset A$.

Then there is also this definition from Tarski's 1924 paper:

A set $A$ is finite iff every nonempty family of its subsets has a minimal element.

Finally, and perhaps most obviously for your purposes, a set $A$ is finite just in case there is a bijection between $A$ and an initial segment of the natural numbers.

A: Recall that if $S\subseteq\mathbb N$ then $S$ is finite if and only if $S$ is bounded, namely there is some $k\in\mathbb N$ such that for every $n\in S$ we have $n<k$.
We can use transfer this property to $B$. If $B$ is finite, well $A$ has to be finite. However if $B$ is infinite then there is a function $f\colon\mathbb N\to B$ which is a bijection, we can therefore write $b_n=f(n)$, and therefore $B=\{b_n\mid n\in\mathbb N\}$.
Now $A\subseteq B$ is finite if and only if there is some $k\in\mathbb N$ such that if $b_n\in A$ then $n<k$.

A: Equip $B$ with the discrete topology. Then a subset $A$ is finite if and only if it is compact in this topology.


text:
Q: Tastypie building data bundle from canonical_resource_for('object') I am trying to write a Django TemplateView that returns a context parameter 'data' containing JSON based on tastypie's canonical resource:
resources
class FooResource(ModelResource):
    bars = fields.ToManyField('app.api.v1.resources.BarResource', 'bars', null=True, full=True)

    class Meta:
        queryset = Foo.objects.all()
        resource_name = 'foo'
        # ...

models
class FooDetailView(TemplateView):
    template_name = 'app/foo_detail.html'

    def get_detail(self, slug):
        foo_resource = v1_api.canonical_resource_for('foo')

        try:
            foo = foo_resource.cached_obj_get(slug=slug)
        except Foo.DoesNotExist:
            raise Http404

        bundle = foo_resource.full_dehydrate(foo_resource.build_bundle(obj=foo))
        return bundle.data

    def get_context_data(self, **kwargs):
        base = super(FooDetailView, self).get_context_data(**kwargs)
        base['data'] = self.get_detail(base['params']['slug'])
        return base

This works, however the reverse relationship between Foo and Bar doesn't seem to get serialized by the manual process. The TemplateView returns these as strings, here's the response:
{
    'title': u'I am Foo.title',
    'bars': [<Bundle for obj: '1' and with data: '{'title': u'I am Bar.title'}']
}

So, question, how do I iterate over the reverse relationships when building the bundle?

A: The answer was to run bundle through the resource.serializer after dehydrating
def get_detail(self, slug):
    qr = v1_api.canonical_resource_for('question')
    try:
        question = qr.cached_obj_get(slug=slug)
    except Question.DoesNotExist:
        raise Http404

    bundle = qr.full_dehydrate(qr.build_bundle(obj=question))

    # create response
    desired_format = qr.determine_format(self.request)
    serialized = qr.serialize(self.request, bundle, desired_format)
    return serialized


text:
Q: Android Studio fragment crashed onimagebuttonclick and when initializing objects
I would be grateful if you help, because I have been sitting for half a week on this problem. In general, I first created a regular layout and later added Navigation Dravel from the standard template. I was too lazy and just moved the layout by deleting the fragment. Later I did a lot of things, but in general here

The application crashes when I click on SFLCl this is the button ShowTurnList.

package esport.inyourlife.insport.ui.gallery;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.List;
import java.util.logging.ErrorManager;

import esport.inyourlife.insport.Constant;
import esport.inyourlife.insport.R;
import esport.inyourlife.insport.ShowTurnirs;
import esport.inyourlife.insport.Tournaments;

public class TournamentFragment extends Fragment {
    private EditText TName, TAdres, TDate, TTime, Find;
    private FirebaseDatabase isDB = FirebaseDatabase.getInstance();
    private DatabaseReference isRef = isDB.getReference("Tournaments");
    private ArrayAdapter adapter;
    private List<String> listData;
    private List<Tournaments> listTemp;
    private ListView turnirs, findList;
    private GalleryViewModel galleryViewModel;
    private Button bFind, bCreate;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        galleryViewModel =
                new ViewModelProvider(this).get(GalleryViewModel.class);
        View root = inflater.inflate(R.layout.fragment_tournament, container, false);
        //getDataFromDB(); //позже удалить нужно, не думаю что она должна находиться тут. Вместо этого шоутурниры
       // setOnClickItem();
        //turnirs = (ListView) getView().findViewById(R.id.TurnirList);
        //init();
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
        turnirs =  getView().findViewById(R.id.TurnirList);
    }

    //присвоение элементов к переменным
    private void init()//тут где то проблема нужно исправить 07.01
    {
        Toast.makeText(getActivity(), "Init", Toast.LENGTH_SHORT).show();
        /*TName = TName.findViewById(R.id.edNameTournament);
        TAdres = TAdres.findViewById(R.id.edAdres);
        TDate = TDate.findViewById(R.id.edTrnirDate);
        TTime = TTime.findViewById(R.id.edTrnirTime);
        listData = new ArrayList<>();
        listTemp = new ArrayList<>();
        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, listData);
        Find = Find.findViewById(R.id.edFindTournir);
        bFind = bFind.findViewById(R.id.btnFind);
        bCreate = bCreate.findViewById(R.id.btnCreate);*/
    }

    //верхнее меню, замена табхосту
    public void STLCl(View view){
       /*bFind.setVisibility(View.GONE);
        bCreate.setVisibility(View.GONE);
        Find.setVisibility(View.GONE);
        TName.setVisibility(View.GONE);
        TAdres.setVisibility(View.GONE);
        TDate.setVisibility(View.GONE);
        TTime.setVisibility(View.GONE);*/
        turnirs.setVisibility(View.VISIBLE);
      /*  findList.setVisibility(View.GONE);
        getDataFromDB();*/

    }
    public void SCcl(View view){
        bFind.setVisibility(View.GONE);
        bCreate.setVisibility(View.VISIBLE);
        Find.setVisibility(View.GONE);
        TName.setVisibility(View.VISIBLE);
        TAdres.setVisibility(View.VISIBLE);
        TDate.setVisibility(View.VISIBLE);
        TTime.setVisibility(View.VISIBLE);
        turnirs.setVisibility(View.GONE);
        findList.setVisibility(View.GONE);

    }
    public void SFcl(View view){
        bFind.setVisibility(View.VISIBLE);
        bCreate.setVisibility(View.GONE);
        Find.setVisibility(View.VISIBLE);
        TName.setVisibility(View.GONE);
        TAdres.setVisibility(View.GONE);
        TDate.setVisibility(View.GONE);
        TTime.setVisibility(View.GONE);
        turnirs.setVisibility(View.GONE);
        findList.setVisibility(View.VISIBLE);
    }
//получение данных для первой вкладки Турниры
    private void getDataFromDB()
    {
        ValueEventListener vListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (listData.size() > 0){listData.clear();}
                if (listTemp.size() > 0){listTemp.clear();}
                for (DataSnapshot ss : snapshot.getChildren()){
                    Tournaments tournaments = ss.getValue(Tournaments.class);
                    assert tournaments != null;
                    listData.add(tournaments.TournName);
                    listTemp.add(tournaments);
                }
               //adapter.notifyDataSetChanged();
                //turnirs.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        };
        isRef.addValueEventListener(vListener);
    }
    //получение фильтрованных данных для поиска
    public void FindB(View view)
    {
        Query findQuery = isRef.child("Tournaments").orderByValue().equalTo(Find.getText().toString());
        findQuery.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot ds : snapshot.getChildren()){
                    Tournaments tournaments = ds.getValue(Tournaments.class);
                    assert tournaments != null;
                    listData.add(tournaments.TournName);
                    listTemp.add(tournaments);
                    }
                adapter.notifyDataSetChanged();
                findList.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getActivity(), error.getMessage().toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
//кнопка добавления записи в турниры
    public void btnCreateTournament(View view)
    {
        if (!TextUtils.isEmpty(TAdres.getText().toString()) && !TextUtils.isEmpty(TDate.getText().toString())){
            String id = isRef.getKey();
            String TourName = TName.getText().toString();
            String TAdress = TAdres.getText().toString();
            String ToDate = TDate.getText().toString();
            String ToTime = TTime.getText().toString();
            Tournaments newTrnir = new Tournaments(id, TourName, TAdress, ToDate, ToTime);
            isRef.push().setValue(newTrnir);
            if (newTrnir != null){
                Toast.makeText(getActivity(), "Succecc", Toast.LENGTH_SHORT).show();
            }
        }
    }
    //слушатель нажатий на "турнир"
    private void setOnClickItem()
    {
        turnirs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Tournaments tournaments = listTemp.get(position);
                    Intent i = new Intent(getActivity(), ShowTurnirs.class);
                    i.putExtra(Constant.TOUR_NAME, tournaments.TournName);
                    i.putExtra(Constant.TOUR_LINK, tournaments.TAdress);
                    i.putExtra(Constant.TOUR_DATE, tournaments.ToDate);
                    i.putExtra(Constant.TOUR_TIME, tournaments.ToTime);
                    startActivity(i);
            }
        });
    }
//слушатель ошибок, не работает нужно удалить
    public void onCancelled (ErrorManager errorManager){
    Toast.makeText(getActivity(), errorManager.toString(), Toast.LENGTH_SHORT).show();
}

}

and XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.gallery.TournamentFragment">

    <EditText
        android:id="@+id/edFindTournir"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/shFind"
        tools:visibility="gone" />

    <Button
        android:id="@+id/btnCreate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="btnCreateTournament"
        android:text="Создать"
        android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/edTrnirTime"
        tools:visibility="gone" />

    <EditText
        android:id="@+id/edAdres"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Место проведения"
        android:inputType="textPersonName"
        android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/edNameTournament"
        tools:visibility="gone" />

    <ListView
        android:id="@+id/FindList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnFind"
        tools:visibility="gone" />

    <EditText
        android:id="@+id/edTrnirDate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Дата"
        android:inputType="date"
         android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/edAdres"
        tools:visibility="gone" />

    <EditText
        android:id="@+id/edTrnirTime"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Время"
        android:inputType="time"
        android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/edTrnirDate"
        tools:visibility="gone" />

    <EditText
        android:id="@+id/edNameTournament"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Название турнира"
        android:inputType="textPersonName"
        android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/shFind"
        tools:visibility="gone" />

    <Button
        android:id="@+id/btnFind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="FindB"
        android:text="Поиск"
        android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/edFindTournir"
        tools:visibility="gone" />

    <ListView
        android:id="@+id/TurnirList"
        android:layout_width="403dp"
        android:layout_height="644dp"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/shFind"
        tools:visibility="gone">

    </ListView>

    <ImageButton
        android:id="@+id/ShowTurnList"
        android:layout_width="97dp"
        android:layout_height="43dp"
        android:onClick="STLCl"
        android:src="@drawable/common_google_signin_btn_icon_dark_normal_background"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:visibility="visible" />

    <ImageButton
        android:id="@+id/shCreate"
        android:layout_width="97dp"
        android:layout_height="43dp"
        android:layout_marginStart="96dp"
        android:onClick="SCcl"
        android:src="@drawable/common_google_signin_btn_icon_dark_normal_background"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:visibility="visible" />

    <ImageButton
        android:id="@+id/shFind"
        android:layout_width="97dp"
        android:layout_height="43dp"
        android:layout_marginStart="192dp"
        android:onClick="SFcl"
        android:src="@drawable/common_google_signin_btn_icon_dark_normal_background"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:visibility="visible" />

</androidx.constraintlayout.widget.ConstraintLayout>

Sorry translated for the vocabulary in Google translator

package esport.inyourlife.insport.ui.gallery;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.List;
import java.util.logging.ErrorManager;

import esport.inyourlife.insport.Constant;
import esport.inyourlife.insport.R;
import esport.inyourlife.insport.ShowTurnirs;
import esport.inyourlife.insport.Tournaments;

public class TournamentFragment extends Fragment {
    /*private EditText TName, TAdres, TDate, TTime, Find;
    private FirebaseDatabase isDB = FirebaseDatabase.getInstance();
    private DatabaseReference isRef = isDB.getReference("Tournaments");
    private ArrayAdapter adapter;
    private List<String> listData;
    private List<Tournaments> listTemp;*/
    private ListView turnirs;
   // private GalleryViewModel galleryViewModel;
    //private Button bFind, bCreate;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        /*galleryViewModel =
                new ViewModelProvider(this).get(GalleryViewModel.class);*/
        View root = inflater.inflate(R.layout.fragment_tournament, container, false);
        //getDataFromDB(); //позже удалить нужно, не думаю что она должна находиться тут. Вместо этого шоутурниры
       // setOnClickItem();
        //turnirs = (ListView) getView().findViewById(R.id.TurnirList);
        //init();
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //init();
        turnirs =  getView().findViewById(R.id.TurnirList);
    }

    //присвоение элементов к переменным
  /*  private void init()//тут где то проблема нужно исправить 07.01
    {
        Toast.makeText(getActivity(), "Init", Toast.LENGTH_SHORT).show();
        /*TName = TName.findViewById(R.id.edNameTournament);
        TAdres = TAdres.findViewById(R.id.edAdres);
        TDate = TDate.findViewById(R.id.edTrnirDate);
        TTime = TTime.findViewById(R.id.edTrnirTime);
        listData = new ArrayList<>();
        listTemp = new ArrayList<>();
        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, listData);
        Find = Find.findViewById(R.id.edFindTournir);
        bFind = bFind.findViewById(R.id.btnFind);
        bCreate = bCreate.findViewById(R.id.btnCreate);
    }*/

    //верхнее меню, замена табхосту
    public void STLCl(View view){
        try{ /*bFind.setVisibility(View.GONE);
            bCreate.setVisibility(View.GONE);
            Find.setVisibility(View.GONE);
            TName.setVisibility(View.GONE);
            TAdres.setVisibility(View.GONE);
            TDate.setVisibility(View.GONE);
            TTime.setVisibility(View.GONE);*/
            turnirs.setVisibility(View.VISIBLE);
           /* findList.setVisibility(View.GONE);
            getDataFromDB();*/
        }catch(Exception e){
            onPause();
            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace(); }

    }
   /* public void SCcl(View view){
        bFind.setVisibility(View.GONE);
        bCreate.setVisibility(View.VISIBLE);
        Find.setVisibility(View.GONE);
        TName.setVisibility(View.VISIBLE);
        TAdres.setVisibility(View.VISIBLE);
        TDate.setVisibility(View.VISIBLE);
        TTime.setVisibility(View.VISIBLE);
        turnirs.setVisibility(View.GONE);
        findList.setVisibility(View.GONE);

    }
    public void SFcl(View view){
        bFind.setVisibility(View.VISIBLE);
        bCreate.setVisibility(View.GONE);
        Find.setVisibility(View.VISIBLE);
        TName.setVisibility(View.GONE);
        TAdres.setVisibility(View.GONE);
        TDate.setVisibility(View.GONE);
        TTime.setVisibility(View.GONE);
        turnirs.setVisibility(View.GONE);
        findList.setVisibility(View.VISIBLE);
    }
//получение данных для первой вкладки Турниры
    private void getDataFromDB()
    {
        ValueEventListener vListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (listData.size() > 0){listData.clear();}
                if (listTemp.size() > 0){listTemp.clear();}
                for (DataSnapshot ss : snapshot.getChildren()){
                    Tournaments tournaments = ss.getValue(Tournaments.class);
                    assert tournaments != null;
                    listData.add(tournaments.TournName);
                    listTemp.add(tournaments);
                }
               //adapter.notifyDataSetChanged();
                //turnirs.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        };
        isRef.addValueEventListener(vListener);
    }
    //получение фильтрованных данных для поиска
    public void FindB(View view)
    {
        Query findQuery = isRef.child("Tournaments").orderByValue().equalTo(Find.getText().toString());
        findQuery.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot ds : snapshot.getChildren()){
                    Tournaments tournaments = ds.getValue(Tournaments.class);
                    assert tournaments != null;
                    listData.add(tournaments.TournName);
                    listTemp.add(tournaments);
                    }
                adapter.notifyDataSetChanged();
                findList.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getActivity(), error.getMessage().toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
//кнопка добавления записи в турниры
    public void btnCreateTournament(View view)
    {
        if (!TextUtils.isEmpty(TAdres.getText().toString()) && !TextUtils.isEmpty(TDate.getText().toString())){
            String id = isRef.getKey();
            String TourName = TName.getText().toString();
            String TAdress = TAdres.getText().toString();
            String ToDate = TDate.getText().toString();
            String ToTime = TTime.getText().toString();
            Tournaments newTrnir = new Tournaments(id, TourName, TAdress, ToDate, ToTime);
            isRef.push().setValue(newTrnir);
            if (newTrnir != null){
                Toast.makeText(getActivity(), "Succecc", Toast.LENGTH_SHORT).show();
            }
        }
    }
    //слушатель нажатий на "турнир"
    private void setOnClickItem()
    {
        turnirs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Tournaments tournaments = listTemp.get(position);
                    Intent i = new Intent(getActivity(), ShowTurnirs.class);
                    i.putExtra(Constant.TOUR_NAME, tournaments.TournName);
                    i.putExtra(Constant.TOUR_LINK, tournaments.TAdress);
                    i.putExtra(Constant.TOUR_DATE, tournaments.ToDate);
                    i.putExtra(Constant.TOUR_TIME, tournaments.ToTime);
                    startActivity(i);
            }
        });
    }
//слушатель ошибок, не работает нужно удалить
    public void onCancelled (ErrorManager errorManager){
    Toast.makeText(getActivity(), errorManager.toString(), Toast.LENGTH_SHORT).show();
}*/

}

I commented everything, all the code that I wrote except SFLCl, nothing helped. At the moment, it should just show the ListView turnirs, but the error still remains

A: solved the problem by adding setOnClickListener

package esport.inyourlife.insport.ui.gallery;

import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.List;
import java.util.logging.ErrorManager;

import esport.inyourlife.insport.Constant;
import esport.inyourlife.insport.R;
import esport.inyourlife.insport.ShowTurnirs;
import esport.inyourlife.insport.Tournaments;

public class TournamentFragment extends Fragment {
    private FirebaseDatabase isDB = FirebaseDatabase.getInstance();
    private DatabaseReference isRef = isDB.getReference("Tournaments");
    private ArrayAdapter adapter;
    private List<String> listData;
    private List<Tournaments> listTemp;
    private ListView turnirs;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        GalleryViewModel galleryViewModel = new ViewModelProvider(this).get(GalleryViewModel.class);
        View root = inflater.inflate(R.layout.fragment_tournament, container, false);
        //getDataFromDB(); //позже удалить нужно, не думаю что она должна находиться тут. Вместо этого шоутурниры
        // setOnClickItem();
        //turnirs = (ListView) getView().findViewById(R.id.TurnirList);
        //init();
        EditText tName = (EditText) root.findViewById(R.id.edNameTournament);
        EditText tAdres = (EditText) root.findViewById(R.id.edAdres);
        EditText tDate = (EditText) root.findViewById(R.id.edTrnirDate);
        EditText tTime = (EditText) root.findViewById(R.id.edTrnirTime);
        EditText Find = (EditText) root.findViewById(R.id.edFindTournir);
        Button bCreate = (Button) root.findViewById(R.id.btnCreate);
        Button b2 = (Button) root.findViewById(R.id.shCreate);
        Button bFind = (Button) root.findViewById(R.id.btnFind);
        ListView turnirs = (ListView) root.findViewById(R.id.TurnirList);
        ListView findList = (ListView) root.findViewById(R.id.FindList);
        ImageButton b1 = (ImageButton) root.findViewById(R.id.ShowTurnList);
        ImageButton b3 = (ImageButton) root.findViewById(R.id.shFind);
        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 {
                    bFind.setVisibility(View.GONE);
                    bCreate.setVisibility(View.VISIBLE);
                    Find.setVisibility(View.GONE);
                    tName.setVisibility(View.VISIBLE);
                    tAdres.setVisibility(View.VISIBLE);
                    tDate.setVisibility(View.VISIBLE);
                    tTime.setVisibility(View.VISIBLE);
                    turnirs.setVisibility(View.GONE);
                    findList.setVisibility(View.GONE);

                }
            }
        });
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bFind.setVisibility(View.GONE);
                bCreate.setVisibility(View.GONE);
                Find.setVisibility(View.GONE);
                tName.setVisibility(View.GONE);
                tAdres.setVisibility(View.GONE);
                tDate.setVisibility(View.GONE);
                tTime.setVisibility(View.GONE);
                turnirs.setVisibility(View.VISIBLE);
                findList.setVisibility(View.GONE);
                getDataFromDB();
                if (listData != null){turnirs.setAdapter(adapter);}
            }
        });
        b3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bFind.setVisibility(View.VISIBLE);
                bCreate.setVisibility(View.GONE);
                Find.setVisibility(View.VISIBLE);
                tName.setVisibility(View.GONE);
                tAdres.setVisibility(View.GONE);
                tDate.setVisibility(View.GONE);
                tTime.setVisibility(View.GONE);
                turnirs.setVisibility(View.GONE);
                findList.setVisibility(View.VISIBLE);
            }
        });
        //получение фильтрованных данных для поиска
        bFind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Query findQuery = isRef.child("Tournaments").orderByValue().equalTo(Find.getText().toString());
                findQuery.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        for (DataSnapshot ds : snapshot.getChildren()){
                            Tournaments tournaments = ds.getValue(Tournaments.class);
                            assert tournaments != null;
                            listData.add(tournaments.TournName);
                            listTemp.add(tournaments);
                        }
                        adapter.notifyDataSetChanged();
                        findList.setAdapter(adapter);
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        Toast.makeText(getActivity(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
        //кнопка добавления записи в турниры
        bCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(tAdres.getText().toString()) && !TextUtils.isEmpty(tDate.getText().toString())){
                    String id = isRef.getKey();
                    String TourName = tName.getText().toString();
                    String TAdress = tAdres.getText().toString();
                    String ToDate = tDate.getText().toString();
                    String ToTime = tTime.getText().toString();
                    Tournaments newTrnir = new Tournaments(id, TourName, TAdress, ToDate, ToTime);
                    isRef.push().setValue(newTrnir);
                    if (newTrnir != null){
                        Toast.makeText(getActivity(), "Successful", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        return root;
    }

//получение данных для первой вкладки Турниры
    private void getDataFromDB()
    {
        ValueEventListener vListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (listData.size() > 0){listData.clear();}
                if (listTemp.size() > 0){listTemp.clear();}
                for (DataSnapshot ss : snapshot.getChildren()){
                    Tournaments tournaments = ss.getValue(Tournaments.class);
                    assert tournaments != null;
                    listData.add(tournaments.TournName);
                    listTemp.add(tournaments);
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
            }
        };
        isRef.addValueEventListener(vListener);
    }

    //слушатель нажатий на "турнир"
    private void setOnClickItem()
    {
        turnirs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Tournaments tournaments = listTemp.get(position);
                    Intent i = new Intent(getActivity(), ShowTurnirs.class);
                    i.putExtra(Constant.TOUR_NAME, tournaments.TournName);
                    i.putExtra(Constant.TOUR_LINK, tournaments.TAdress);
                    i.putExtra(Constant.TOUR_DATE, tournaments.ToDate);
                    i.putExtra(Constant.TOUR_TIME, tournaments.ToTime);
                    startActivity(i);
            }
        });
    }

}


text:
Q: SQL How to create a separate record for comma delimited values in within a field I have a table which have two fields ID and Source. Source col. have multiple emails with comma separated. I want to create a separate record for each email with same ID.
So data looks like this
ID .    Source
1 .     a@a.com,b@b.com,c@c.com

I want to be looks like this;
ID .     Source
1.       a@a.com
1.       b@b.com
1.       c@c.com

I tried using "STRING_SPLIT" function but it didn't work, SFMC didn't recognize this function. Any other work around???

A: You can use CROSS APPLYs to unfurl the CSV list:
Schema:
CREATE TABLE ListSubs
    ([list] varchar(13), [subscribers] varchar(500))
;

INSERT INTO ListSubs
    ([list], [subscribers])
VALUES
    ('1', 'a@a.com,b@b.com,c@c.com'),
    ('2', 'd@d.com,e@e.com,f@f.com')
;

Query:
SELECT
  a.list
  , a.subscribers
  , SUBSTRING(a.subscribers, 1, ISNULL(p1 - 1, LEN(a.subscribers))) sub1
  , SUBSTRING(a.subscribers, p1 + 1, ISNULL(p2, LEN(a.subscribers) + 1) - p1 - 1) sub2
  , SUBSTRING(a.subscribers, p2 + 1, ISNULL(p3, LEN(a.subscribers) + 1) - p2 - 1) sub3
  , SUBSTRING(a.subscribers, p3 + 1, ISNULL(p4, LEN(a.subscribers) + 1) - p3 - 1) sub4
  , SUBSTRING(a.subscribers, p4 + 1, ISNULL(p5, LEN(a.subscribers) + 1) - p4 - 1) sub5
  , SUBSTRING(a.subscribers, p5 + 1, ISNULL(p6, LEN(a.subscribers) + 1) - p5 - 1) sub6
  , SUBSTRING(a.subscribers, p6 + 1, ISNULL(p7, LEN(a.subscribers) + 1) - p6 - 1) sub7
from ListSubs a
CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers), 0)) b(p1)
CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p1 + 1), 0)) c(p2)
CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p2 + 1), 0)) d(p3)
CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p3 + 1), 0)) e(p4)
CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p4 + 1), 0)) f(p5)
CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p5 + 1), 0)) g(p6)
CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p6 + 1), 0)) h(p7)
where isnull(a.subscribers,'') != ''

SQLFiddle.
If you want them in individual rows, then you could do this using the same method by splitting everything out in unions:
select
  x.list
, x.sub
from (

    SELECT
    a.list
    , SUBSTRING(a.subscribers, 1, ISNULL(p1 - 1, LEN(a.subscribers))) sub
    from ListSubs a
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers), 0)) b(p1)

    union

    SELECT
    a.list
    , SUBSTRING(a.subscribers, p1 + 1, ISNULL(p2, LEN(a.subscribers) + 1) - p1 - 1) sub
    from ListSubs a
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers), 0)) b(p1)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p1 + 1), 0)) c(p2)

    union

    SELECT
    a.list
    , SUBSTRING(a.subscribers, p2 + 1, ISNULL(p3, LEN(a.subscribers) + 1) - p2 - 1) sub
    from ListSubs a
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers), 0)) b(p1)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p1 + 1), 0)) c(p2)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p2 + 1), 0)) d(p3)

    union

    SELECT
    a.list
    , SUBSTRING(a.subscribers, p3 + 1, ISNULL(p4, LEN(a.subscribers) + 1) - p3 - 1) sub
    from ListSubs a
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers), 0)) b(p1)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p1 + 1), 0)) c(p2)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p2 + 1), 0)) d(p3)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p3 + 1), 0)) e(p4)

    union

    SELECT
    a.list
    , SUBSTRING(a.subscribers, p4 + 1, ISNULL(p5, LEN(a.subscribers) + 1) - p4 - 1) sub
    from ListSubs a
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers), 0)) b(p1)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p1 + 1), 0)) c(p2)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p2 + 1), 0)) d(p3)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p3 + 1), 0)) e(p4)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p4 + 1), 0)) f(p5)

    union

    SELECT
    a.list
    , SUBSTRING(a.subscribers, p5 + 1, ISNULL(p6, LEN(a.subscribers) + 1) - p5 - 1) sub
    from ListSubs a
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers), 0)) b(p1)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p1 + 1), 0)) c(p2)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p2 + 1), 0)) d(p3)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p3 + 1), 0)) e(p4)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p4 + 1), 0)) f(p5)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p5 + 1), 0)) g(p6)

    union

    SELECT
    a.list
    , SUBSTRING(a.subscribers, p6 + 1, ISNULL(p7, LEN(a.subscribers) + 1) - p6 - 1) sub
    from ListSubs a
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers), 0)) b(p1)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p1 + 1), 0)) c(p2)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p2 + 1), 0)) d(p3)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p3 + 1), 0)) e(p4)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p4 + 1), 0)) f(p5)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p5 + 1), 0)) g(p6)
    CROSS APPLY (select NULLIF(CHARINDEX(',', a.subscribers, p6 + 1), 0)) h(p7)
) x
where x.sub is not null

SQLFiddle

A: You may be able to figure out some implementation using SubString which Marketing CLoud does not seem to have a problem with.
For instance, this will get you the first email address:
SELECT SUBSTRING([source], 1, CASE CHARINDEX(',', [source])
        WHEN 0
            THEN LEN([source])
        ELSE CHARINDEX(',', [source]) - 1
        END) AS Email
FROM _table

Can you expand upon that to fit your needs?
Implementations are really limited without user functions, variables, temp tables which are not supported based upon the documentation here: https://help.salesforce.com/articleView?id=mc_as_sql_reference.htm&type=5


text:
Q: Javascript protobuf performance Two different modules are available for protobuf in nodejs -

*

*https://github.com/dcodeIO/ProtoBuf.js/

*https://github.com/google/protobuf/tree/master/js - official but less features than the other module. Specifically, doesn't have typescript integration.

Which one has better performance?

A: From the protobuf.js performance section, protobuf.js is significantly more performant than the official implementation.


text:
Q: Log file in c:\windows\temp I took a look in my c:\windows\temp directory and I found lots of file.log files. The names are built with this syntax: Machinename-YYYYMMDD-XXXX.log.
And I found this:
Timestamp   Process TID Area    Category    EventID Level   Message Correlation
01/30/2016 12:43:10.754 OFFICEC2 (0xde8)    0xb6c       Click-To-Run Telemetry  aqkhc   Medium  {"MachineID":"a3c8037bfedf40479c3023588639eb6d","SessionID":"b292f44b-e5a6-41c3-a68e-000582c1e920","GeoID":"84","Ver":"0.0.0.0","ExeVer":"15.0.4787.1002","SecuritySessionId":"0","ModulePath":"C:\Program Files\Microsoft Office 15\ClientX64\OfficeC2RClient.exe","CommandLine":"/update SCHEDULEDTASK displaylevel=False","Bitness":"64","IntegrityLevel":"0x4000"}
01/30/2016 12:43:10.754 OFFICEC2 (0xde8)    0xb6c       Click-To-Run Telemetry  aqkhe   Medium  {"MachineID":"a3c8037bfedf40479c3023588639eb6d","SessionID":"b292f44b-e5a6-41c3-a68e-000582c1e920","GeoID":"84","Ver":"0.0.0.0","OSVersion":"6.2","SP":"0","ProductType":"1","ProcessorArch":"9","Locale":"1036"}
01/30/2016 12:43:10.770 OFFICEC2 (0xde8)    0xb6c       Click-To-Run Telemetry  amebh   Medium  ClientExe complete. {"MachineID":"a3c8037bfedf40479c3023588639eb6d","SessionID":"b292f44b-e5a6-41c3-a68e-000582c1e920","GeoID":"84","Ver":"15.0.4787.1002","Action":"1","Result":"0"}
01/30/2016 12:43:10.770 OFFICEC2 (0xde8)    0xb6c       Logging Liblet  aqc99   Medium  Logging liblet uninitializing.

Most of the files are this long but some are much longer. All the logs turn around OFFICE2. Could those logs files come from a malicious program ?
P.S: I perform multiple scans for malware with multiple proven applications every month.

A: Click-to-run is a feature that Microsoft uses to distribute software over the Internet.
Like many other dodgy software of today (Chrome, Spotify, etc.) the "installer" runs with standard user privileges and writes files to locations where non-admin users can write to. In this case, some updater has chosen to write its logs to your temp directory.
There's probably no harm in this if your anti-virus did not detect any threats, but such practice does weaken overall security.


text:
Q: Cannot read property 'apply' of undefined error in lightning i am trying to add two input fields , one output field and one button in lightning component and then upon adding this component to app builder , i am getting this error.
Code is as follows:
Component:
<aura:component controller="JN_TimeZoneIssue" implements="flexipage:availableForAllPageTypes" >

  <ui:inputText label="Enter the time " aura:id="name" value="{!v.dateAndTime}"/>
   <ui:inputText label="Enter the time zone " aura:id="name1" value="{!v.timeZone}" />
   <ui:outputText aura:id="nameOutput" value="{!v.outputTime}"/>
    <ui:button aura:id="outputButton" label="Convert Time" press="{!c.calculateTime}"/>

</aura:component>

Component controller:
({
    getInput : function(component, event, helper) {
             //: function(cmp, event) {
      var selectedTime = component.find("name").get("v.value");
      var selectedTimeZone = component.find("name1").get("v.value");
     // var outName = cmp.find("nameOutput");
      var action = component.get("c.calculateTime");
         action.setParams({
            "selectedTime": selectedTime
             "selectedTimeZone" :selectedTimeZone

        });
        action.setCallback(this, function(data) {
        component.set("v.outputTime", data.getReturnValue());
        });
        $A.enqueueAction(action);

          }

})

Apex COntroller:
public class JN_TimeZoneIssue {

   @AuraEnabled public String timeZone{get;set;}
   @AuraEnabled public Datetime dateAndTime{get;set;}
 //  @AuraEnabled public boolean showOutput{get;set;}
   @AuraEnabled public String updatedTime{get;set;}

@AuraEnabled
    public static String calculateTime(String selectedTimeZone, Datetime selectedTime){
        String newTime =   selectedTime.format('MM/dd/yyyy hh:mm:ss a',+selectedTimeZone);
        return newTime;
    }

}

A: Your component is missing a lot of information
1) None of the attributes are declared in your component.
2) Rewire you button to call getInput method missing in client side controller.
3) This is the actual reason why you are seeing the error"Cannot read property 'apply' of undefined" , you are missing a comma between the 2 parameters in your setparams:
 action.setParams({
            "selectedTime": selectedTime,
             "selectedTimeZone" :selectedTimeZone

        });


text:
Q: Mallow's Cp Question When comparing each individually generated model's $C_p$ to the number of parameters, which number of parameters is the comparison to? Each individual model or the overall number of parameters?

A: You compare it to the number of parameters in each individual model. The idea is that for good models, Mallow's $C_p$ is close to the number of parameters, while for poor models it will be much higher. When looking at a large number of models $C_p$ is sometimes plotted against $p$, and then the line $C_p=p$ is drawn in to help with the comparison.
Edit:  For an example:

Though they've plotted the line $C_p=p+1$ rather than $C_p=p$.


text:
Q: Adding properties to created Redux Store in Typescript I'm having issues adding a property when I create a new Redux Store in Typescript:
const bindMiddleware = middleware => {
  if (process.env.NODE_ENV !== 'production') {
    const { composeWithDevTools } = require('redux-devtools-extension')
    return composeWithDevTools(applyMiddleware(...middleware))
  }
  return applyMiddleware(...middleware)
}

function configureStore (initialState = exampleInitialState) {
  const sagaMiddleware = createSagaMiddleware()
  const store = createStore(
    rootReducer,
    initialState,
    bindMiddleware([sagaMiddleware])
  )

  store.sagaTask = sagaMiddleware.run(rootSaga)

  return store
}

export default configureStore

with the following error message:
27:9 Property 'sagaTask' does not exist on type 'Store<{ error: any; count: number; lastUpdate: number; light: boolean; placeholderData: any; } | { lastUpdate: any; light: boolean; count: number; error: boolean; placeholderData: any; }, any>'.
    25 |   )
    26 |
  > 27 |   store.sagaTask = sagaMiddleware.run(rootSaga)
       |         ^
    28 |
    29 |   return store
    30 | }

Any suggestions?

A: @types/
| - redux.d.ts
src/
| ...
| ... store.ts

in redux.d.ts
import * as Redux from "redux"

declare module "redux" {
  export interface Store {
    sagaTask: ... // provide the types for `store.sagaTask` here
  }
}

in store.ts
const store = createStore(...)
store.sagaTask = ...

this is known as declaration merging / module augmentation.
You need to also setup your tsconfig.json to read types from this @types dir. Add "typeRoots": [ "./@types", "./node_modules/@types" ] to this file (note: these are relative to your baseDir, so modify accordingly.
Also note that you're creating a contract between your types and the code you write. If you fail to setup your middleware properly, sagaTask will be Required in types but undefined in reality.

A: I haven't used Saga so I'm not sure about best practices or what ramifications this approach might have, but the issue is that the Store type doesn't have a sagaTask, so TypeScript won't let this happen. The easiest way that I can see to solve this is to extend Store and add a sagaTask field, then copy the old store to a new object of the extended type.
The downside to this is that you could easily run into a situation where a function is expecting an object with a Store type, so it won't accept this new object.
Are you sure this needs to be a property of the store, or can you just run sagaMiddleware.run(rootSaga)?


text:
Q: Python Date Utility Library Is there a library in python that can produce date dimensions given a certain day?  I'd like to use this for data analysis.  Often I have a time series of dates, but for aggregation purposes I'd like to be able to quickly produce dates associated with that day - like first date of month, first day in week, and the like.
I think I could create my own, but if there is something out there already it'd be nice.
Thanks

A: Have a look at dateutil.
The recurrence rules and relative deltas are what you want.
For example, if you wanted to get last monday:
import dateutil.relativedelta as rd
import datetime

last_monday = datetime.date.today() + rd.relativedelta(weekday=rd.MO(-1))

A: time and datetime modules
For some of your purposes you can use time module with strftime() method or date module with its strftime() method. It allows you to pull, among other data:

*

*number of the week of the year,

*number of the weekday (you can also use weekday() method for getting weekday number between 0 for Monday and 6 for Sunday),

*year,

*month,

Which will suffice to calculate first day of the month, first day of the week and some other data.
Examples
To pull the data you need, do just:

*

*to pull the number of the day of the week
>>> from datetime import datetime
>>> datetime.now().weekday()
6

*to pull the first day of the month use replace() function of datetime object:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2012, 3, 3, 21, 41, 20, 953000)
>>> first_day_of_the_month = datetime.now().replace(day=1)
>>> first_day_of_the_month
datetime.datetime(2012, 3, 1, 21, 41, 20, 953000)

EDIT: As J.F. Sebastian suggested within comments, datetime objects have weekday() methods, which makes using int(given_date.strftime('%w')) rather pointless. I have updated the answer above.


text:
Q: C# Console.WriteLine not printing in one line Now if you run this it does not output each Console.WriteLine in one line, why?
I know console.writeline goes to next line when done but the problem is it jumps to next line while printing when it print the exception var it is not in the same line as the rest of the writeline
The error occurs inside the Display() function at the number 6 variable (exception) it is not in the same line as the rest of the writeline, why?
And also there are no line breaks where the error ocurs.
Ans can be any number you like.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace EquationSolver
{
    class Program
    {
        public static string exception = "No Solution Found yet";
        public static int go = 40;
        public static Decimal x = 0, formul = 0;
        public static Decimal pref = -100000, next = 100000,ans;
        public static Decimal stepval = next / 10;
        public static Decimal prefrem = 1234567890123.1234567890m, nextrem = 1234567890123.1234567890m;
        public static Decimal nextremfirst = 0;
        public static void Answer()
        {
          Console.WriteLine("Enter ans");
          ans = (Convert.ToDecimal(Console.ReadLine()));

        }
        public static void Main(string[] args)
        {
            //Console.WriteLine("Enter ans");
            //Answer(Convert.ToDecimal(Console.ReadLine()));
            Answer();
            //Console.Clear();

            while (true)
            {
                for (var i = 0; i <= go; i++)
                {
                    for (x = pref; x <= next; x += stepval)
                    {
                        formul = x;
                        if (formul < ans)
                            prefrem = x;
                        else if (formul > ans)
                        {
                            if (nextremfirst == 0)
                            {
                                nextrem = x;
                                nextremfirst += 2;
                            }
                        }
                        else if (formul == ans)
                        {
                            AnsFound();
                            break;
                        }
                        else
                        {
                            Error();
                        }
                        Display();
                    }

                    if (formul == ans)
                    {
                        AnsFound();
                        break;
                    }
                    if (prefrem != 1234567890123.1234567890m)
                        pref = prefrem;
                    if (nextrem != 1234567890123.1234567890m)
                        next = nextrem;
                    nextremfirst = 0;
                    stepval /= 10;
                    if (formul != ans)
                        NoAnsyet();

                    //Console.WriteLine();
                }
                Finnish();
            }
        }
        public static void Display()
        {
            //Console.ReadKey();
            //Console.WriteLine("Formul: {0} x: {1} Ans: {2} Status: {3}", //formul, x, ans, exception);

//Here is the error:
            Console.WriteLine("Pref:{0} Next:{1} Step:{2} Formul:{3} x:{4} Ans:{5} Status:{6}",pref,next,stepval,formul,x,ans,exception);
        }
        public static void Finnish()
        {
            if (formul != ans)
                Error();
            exception = "\ncomplete";
            Console.WriteLine(exception);
            pref = -100000;
            next =  100000;
            stepval = next /= 10;
            Console.ReadKey();
            Console.Clear();
            //Console.WriteLine("Enter ans:");
            //Answer(Convert.ToDecimal(Console.ReadLine()));
            Answer();
        }
        public static void AnsFound()
        {
            exception = "\nSolution Found!";
            //Console.WriteLine("x: {0} Ans: {1} Status: {2}", x, ans, exception);
            //Console.WriteLine("Pref:{0} Next: {1} Stepval: {2}     Formul:{3} x:{4} Ans:{5}  Status:{}", pref, next, stepval, formul, x, ans, exception);

        }
        public static void NoAnsyet()
        {
            exception = "\nNo Solution yet...";
            //Console.WriteLine(exception);
        }
        public static void Error()
        {
            exception = "\nNo Solution error!!";
            Console.WriteLine(exception);
        }
    }
}

A: WriteLine writes in a New Line. You should try
Console.Write()
If you want to print right after your previous print.

A: Because you set exception = "\ncomplete"; at different places. The \n at the beginning is a new line character.
Remove the \n
exception = "complete";

Same problem with other texts like "\nSolution Found!".

Using string interpolation makes string formatting more readable:
Replace
Console.WriteLine("Pref:{0} Next:{1} Step:{2} Formul:{3} x:{4} Ans:{5} Status:{6}",
    pref, next, stepval, formul, x, ans, exception);

by
Console.WriteLine(
$"Pref:{pref} Next:{next} Step:{stepval} Formul:{formul} x:{x} Ans:{ans} Status:{exception}");

A: The value to your variable exception is the reason why the console is printing on a different basically if you put a special character \n means new line hence all the methods you are calling have this special character.
Solution remove special characters and use the Console.WriteLine or Console.Write methods

A: As per the code provided you have not called the method i made some changes to the code
       Edited code
and try to run the code status :No solution found yet
Thanks


text:
Q: create a python module with C and Python code I have a small python module I have created with the Python C API which I call mycore.
I have also created some utility scripts in Python which are related.
How can I put both in the same module namespace?  I know I can call Python code from my C code but surely there is an easier way to do that.
Thanks

A: The obvious way is by making mycore a package. Create a mycore/__init__.py that imports both the C part, typically named something like _mycore, and the Python part:
from _mycore import *
from _mycorepy import *

In the same directory you'd have a _mycore.so and _mycorepy.py.
Another way to mix Python and C code is by invoking PyRun_String on the embedded Python. This might be what you mean by I know I can call Python code from my C code..., but just in case, here is a simple example with the potentially tricky refcounting details:
PyObject *get_factory()
{
  PyObject *g, *runret, *factory;
  // prepare a dictionary for the module to run in
  g = Py_BuildValue("{s:O}", "__builtins__", PyEval_GetBuiltins());
  if (!g)
    return NULL;
  // run Python code in the dictionary -- the code may import modules, etc.
  runret = PyRun_String("\
def factory():\n\
    return 42\n", Py_file_input, g, NULL);
  Py_XDECREF(runret);
  if (!runret) {
    Py_DECREF(g);
    return NULL;
  }
  Py_DECREF(runret);
  // pick the stuff you care about from the dictionary and return it
  factory = PyDict_GetItemString(g, "factory");
  Py_INCREF(factory);
  Py_DECREF(g);
  return factory;
}

A: OK, this worked for me.  My circumstances may be different.  My C module was built internally and provided to my embedded Python with a call to PyImport_AppendInittab().
But I still had some accompanying Python code that I wanted associated with the same namespace.
So I got it working by naming my C code _mygadget and the Python file mygadget.py.  For the first line of mygadget.py I wrote:
from _mygadget import *

This seems to work.  I don't know what would happen if I had a Python method and C call with the same name.  I am avoiding that at present.


text:
Q: how can I remove SVN bindings from folder using GUI SVN tool I have SVN bound folder that is copied from my colleague's machine. that folder contains svn bound hidden folders which are difficult to remove manualy. Is there a way to remove the svn bindings from folder using tortoise svn GUI tool

A: It might not be the GUI tool, but there is an excellent shell command that can do this.

A: If you export the working copy to the same folder, the .svn subdirectories are removed. This is not coincidence but a feature of TortoiseSvn.

A: How to unversion a working copy and Removing a working copy from version control describe what you need.

A: Writing a  small GUI program or batch file that recursively search in parent folder for .svn hidden folders and delete might be also possible for this or something similar maybe the SVN command line does.


text:
Q: Moments of a probability distribution $X_{1} \sim B(n_{1},p_{1})$ and $X_{2} \sim B(n_{2},p_{2})$ are independent. Let $Y = X_{1} + X_{2}$. I have worked out the moment generating function to be $$M_{Y}(t) = (p_{1}e^{t} + 1 - p_{1})^{n_{1}}(p_{2}e^{t}+1-p_{2})^{n_{2}}$$
Now to find the expectation of $Y$:
$$E[Y] = \frac{\mathrm{d}M_{Y}(t)}{\mathrm{d}t}\left.\right|_{t = 0} = \frac{\mathrm{d}}{\mathrm{d}t}\left[(p_{1}e^{t} + 1 - p_{1})^{n_{1}}(p_{2}e^{t} + 1 - p_{2})^{n_{2}}\right]_{t=0}$$
$$= n_{1}p_{1}e^{t}(p_{1}e^{t}+1-p_{1})^{n_{1}-1}(p_{2}e^{t} + 1 - p_{2})^{n_{2}} + n_{2}p_{2}e^{t}(p_{1}e^{t}+1-p_{1})^{n_{1}}(p_{2}e^{t}+1-p_{2})^{n_{2}-1}\left.\right|_{t=0}$$
$$= e^{t}(p_{1}e^{t}+1-p_{1})^{n_{1}-1}(p_{2}e^{t}+1-p_{2})^{n_{2}-1}(n_{1}p_{1}(p_{2}e^{t}+1-p_{2})+n_{2}p_{2}(p_{1}e^{t}+1-p_{1}))\left.\right|_{t=0}$$
$$=  e^{t}(p_{1}e^{t}+1-p_{1})^{n_{1}-1}(p_{2}e^{t}+1-p_{2})^{n_{2}-1}(n_{1}p_{1}p_{2}e^{t} + n_{1}p_{1} - n_{1}p_{1}p_{2} + n_{2}p_{1}p_{2}e^{t} + n_{2}p_{2}  - n_{2}p_{1}p_{2})\left.\right|_{t=0}$$
$$=n_{1}p_{1} + n_{2}p_{2}$$
Now for $E[Y^{2}]$ we must differentiate $\frac{\mathrm{d}M_{Y}(t)}{\mathrm{d}t}$ which is clearly a tedious job, is there a way to skip this?

A: Set $X_{1}=U_{1}+\cdots+U_{n_{1}}$ and $X_{2}=V_{1}+\cdots+V_{n_{2}}$
where the $U_{i}$ and $V_{j}$ are independent and Bernouilli-distributed
with parameters $p_{1}$ for the $U_{i}$ and $p_{2}$ for the $V_{j}$.
Then $Y=U_{1}+\cdots+U_{n_{1}}+V_{1}+\cdots+V_{n_{2}}$. Now work out
$Y^{2}$ and find $\mathbb{E}$Y$^{2}$ as a sum of expectations that
are not difficult to find.
Likewise you could find $\mathbb E Y$ on an easy way.
Another route is making use of $\mathbb{E}Y^{2}-\left(\mathbb{E}Y\right)^{2}=\text{Var}Y=\text{Var}X_{1}+\text{Var}X_{2}$


text:
Q: Importing Public Folder Images In Src Css Files In Reactjs I need to import some assets from public folder. I can do it easily in html; it wont give an error.
However, I can not do it with css url() method.
I need to do this since react encodes images that are smaller than 10Kb to base 64 and uses that encoded text instead of image path.
As I've read in some articles, this does not benefit performance since css is a render blocking resource and adding to its text, makes parsing it longer.
Here's my folder structure:

My .scss file is inside src/components and this is how i've tried importing the image:
background-image: url("/media_assets/img/footer-xsm.png");

And my package.json:
{
  "name": "roomeet",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@glidejs/glide": "^3.4.1",
    "@loadable/component": "^5.14.1",
    "@testing-library/jest-dom": "^5.11.5",
    "@testing-library/react": "^11.1.2",
    "@testing-library/user-event": "^12.2.2",
    "bootstrap": "^4.5.3",
    "js-cookie": "^2.2.1",
    "node-sass": "^4.14.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-lazyload": "^3.1.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.0",
    "source-map-explorer": "^2.5.2",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "analyze": "source-map-explorer 'build/static/js/*.js'",
    "bundle-report": "webpack-bundle-analyzer --port 4200 dist/stats.json"
  },
}

Edit:
This is the error that it's giving:
Error: Can't resolve '../media_assets/img/footer-xsm.png' in 'C:\VSCode Projects\rmt_cln\src\components'

A: i'm currently unable to comment so i'll have to write it as an answer, can you pleas try
background-image: url("./media_assets/img/footer-xsm.png");

if it didn't work just flag it as unuseful and go check this you'll find a solution there


text:
Q: PowerShell - How to get Environment Variable value using wildcards I have some variables that i need to get the value from, the thing is that in the middle of the name i can have any possible value because it's the artifacts name.
Example:
I have these environment variables:
RELEASE_ARTIFACTS__TESTECOMPLETEPR__PROJECTNAME
RELEASE_ARTIFACTS__TESTECOMPLETEPR_REPOSITORY_NAME
And i need something like:
$repoId = (Get-Item -Path Env:RELEASE_ARTIFACTS_*_REPOSITORY_ID).Value
or
$repoId = $Env:RELEASE_ARTIFACTS_*_REPOSITORY_ID
But the * doesn't seem to work.
How can i do this?

A: Wildcard expressions are supported, with all providers, in the -Path parameter of the Get-Item cmdlet, and also with Get-Content, which is preferable here because it returns the environment-variable value directly (no need for (...).Value); to demonstrate:
$env:RELEASE_ARTIFACTS_FOO_REPOSITORY_ID = 1

Get-Content env:RELEASE_ARTIFACTS_*_REPOSITORY_ID # -> 1

Perhaps surprisingly, they are also supported when you use namespace variable notation, though you must then enclose the reference in {...} (because a * would otherwise not be recognized as part of a variable name):
${env:RELEASE_ARTIFACTS_*_REPOSITORY_ID} # -> 1

Caveats:Tip of the hat to Daniel.

*

*If the wildcard pattern matches multiple items (environment variables in this case), a statement-terminating error occurs. Use the Get-Content (or Get-Item) approach to retrieve multiple values (items).

*

*Given this awkwardness, along with the escaping pitfalls discussed below, it would make sense not to support wildcard matching in namespace variable notation, as suggested in GitHub issue #9225; while technically a breaking change, my sense is that not much real-world code would be impacted.

*Strangely, namespace variable notation with wildcard patterns does not work with variables (where the notation is rarely used to begin with, however, given that $variable:foo offers no advantage over $foo): ${variable:HOM*} performs no wildcard matching and behaves like an undefined variable (it quietly evaluates to $null by default).

*

*While the Get-Content / Get-Item approach does work, note that there's also a dedicated Get-Variable cmdlet (use -ValueOnly to get just the value) - e.g. Get-Variable HOM* -ValueOnly - which additionally supports accessing variables in different scopes, via the -Scope parameter.

Namespace variable notation vs. Get-Content:

*

*Namespace variable notation is both more concise and performs better (because a cmdlet call isn't involved).

*However, the Get-Content approach is sometimes required, namely when you use a variable to specify the environment-variable name or name pattern; that is, assuming variable definition $envVarName = 'RELEASE_ARTIFACTS_*_REPOSITORY_ID':

*

*${env:$envVarName} does not work,

*but Get-Content env:$envVarName does.

*Escaping pitfalls:

*

*Escaping wildcard metacharacters such as [ that you want to be interpreted verbatim is currently challenging, due to the bugs discussed in this answer.

*If the whole name should be used verbatim, you can avoid the need for escaping by using Get-Content's -LiteralPath parameter instead; however, this isn't an option with namespace variable notation, where names are invariably treated as wildcard patterns.


text:
Q: Configure BIND to prefer IPv4 without disabling IPv6 Our office network is internally dual-stack, but the connection to the rest of the Internet is IPv4-only.  I've got BIND 9.9 set up on a Linux box to handle DNS resolution.
Is there a way to configure BIND to prefer to use IPv4 when contacting other DNS servers without disabling IPv6?  I'd like to leave IPv6 enabled so everything Just Works once we get an IPv6 connection to the outside world, but without clogging the logs with error (network unreachable) resolving 'microsoft.com/DS/IN': 2001:7fd::1#53 messages in the meantime.

A: Can't remember where I found this solution, but here it is
In /etc/bind/named.conf.local:
// disable lookup over IPv6
server ::/0 {
        bogus yes;
};

It then pretends that IP addresses in the IPv6 range are non reachable and does it with IPv4 instead.

A: I suggest changing the clients, not the DNS server.
clients usually ask for DNS entries by requesting A and/or AAAA records. there is a sorting algorithm to prefer V6 over V4 if there are both answers from DNS. every connection is effectively made by the clients.
to prefer IPv4 over V6 so can set
precedence ::ffff:0:0/96  100

in /etc/gai.conf on every client. this works at least on GNU/Linux. I don't know how to make Windows to do this.
HTH


text:
Q: Proof that every map produces a planar graph - Four Colour Theorem I was watching this Youtube video:
https://www.youtube.com/watch?v=NgbK43jB4rQ
At around the 6 minute mark, it's mentioned that the $K_5$ doesn't produce a valid map. I'm guessing it has something to do with the graph being nonplanar.
So I wanted to prove that all maps produce a planar graph.
Here's my attempt
Proof by induction.
Base case: A map with just one area, produces a planar graph.
Inductive Hypothesis: Assume that any map with N areas produces a planar graph.
Inductive Step: Uses inductive hypothesis to prove that any graph with N+1 area will also produce a planar graph.
Since any graph with N area produces a planar graph, then no graph with N areas has a subgraph that is isomorphic to $K_5$ or $K_{3,3}$. So we have to show that in the worst case scenario, where our graph has a subgraph that's 1 vertex away from being $K_5$ or $K_{3,3}$, that it's not possible to add a vertex to make it so. I'm having trouble at this point.
Would appreciate the help.
Thanks

A: The intuition for why maps correspond to planar graphs is that you can use a map to draw a planar representation of its graph.
(The comments are right that we need to be somewhat careful about what maps are, what kind of lines we are allowed to draw, and the difference between a graph a drawing of a graph. So to turn this intuition into a proof, we'll need to do some work once we figure out what the right definitions are.)

Start with a map (source):

Its graph has a vertex for every region of this map, and an edge between two vertices if and only if the two corresponding regions are adjacent. The graph must exist; we must prove that it is planar. To do this, we will construct a planar embedding of this graph.
We begin by

*

*putting a vertex in each region, and

*whenever two regions border each other, putting a tick mark somewhere along the border.

(Mathematically, the vertices and the tick marks are just points chosen either from the regions or from their borders.)
Now, within each region, draw paths from the vertex to the tick marks around each border:

Care must be taken at this step that the paths we draw stay in the region they're at, and don't intersect each other. It's here that we need to think very carefully about our definition of what sort of regions a map is allowed to have.
The point of adding the tick marks, however, is that this step doesn't care at all about what the map looks like globally. All you have to do is to look at the regions one at a time, and draw paths from the vertex to the tick marks. We'll never have to worry about paths in one region intersecting paths in another, because all the paths we draw stay in a single region.
(You have to prove that you can avoid two paths in the same region intersecting each other. There's a number of ways to say "if there's an intersection point, we can deform the paths until there isn't", but this step is topology, not graph theory.)
At this point, you're done! We've constructed a planar embedding of the graph for our map in which no edges cross.


text:
Q: NullPointerException when uploading a file When uploading a file, I get the following error:

Struts Problem Report Struts has detected an unhandled exception: Messages: File: java/io/File.java Line number: 317
Stacktraces java.lang.NullPointerException java.io.File.(File.java:317)
    example.uploadFile.execute(uploadFile.java:36)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)

index.jsp
<form action="upload" method="post" enctype="multipart/form-data">
    <label for="myFile">Upload your file</label>
    <input type="file" name="myFile" />
    <input type="submit" value="Upload"/>
</form>

uploadFile.java
package example;
import java.io.File;
import org.apache.commons.io.FileUtils;
import java.io.IOException;
import com.opensymphony.xwork2.ActionSupport;

public class uploadFile extends ActionSupport {
   private File myFile;
   private String myFileContentType;
   private String myFileFileName;
   private String destPath;

   public String execute() {

      destPath = "C:\\Program Files\\Apache Software Foundation\\Apache Tomcat 8.0.3\\work";

      try{
         System.out.println("Src File name: " + myFile);
         System.out.println("Dst File name: " + myFileFileName);
         File destFile  = new File(destPath, myFileFileName);
         FileUtils.copyFile(myFile, destFile);
      }catch(IOException e){
         return ERROR;
      }

      return SUCCESS;
   }

   public File getMyFile() {
      return myFile;`
   }
   public void setMyFile(File myFile) {
      this.myFile = myFile; this the file which user selects to upload
   }
   public String getMyFileContentType() {
      return myFileContentType; content type of the uploading file
   }
   public void setMyFileContentType(String myFileContentType) {
      this.myFileContentType = myFileContentType;`
   }
   public String getMyFileFileName() {
      return myFileFileName;
   }
   public void setMyFileFileName(String myFileFileName) {
      this.myFileFileName = myFileFileName;
   }
}

struts.xml
<struts>
    <include file="example.xml"/>
    <constant name="struts.devMode" value="true" />
    <constant name="struts.multipart.maxSize" value="1000000" />

    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
       <action name="upload" class="example.uploadFile">
            <interceptor-ref name="basicStack"/>
            <interceptor-ref name="fileUpload">
                <param name="allowedTypes">image/jpeg,image/gif</param>
            </interceptor-ref>
            <result name="success">/success.jsp</result>
            <result name="error">/error.jsp</result>
        </action>
    </package>
</struts>

A: To work properly, the FileUpload Interceptor must run before some other Interceptors in the basicStack;
you can check it out in the struts-default.xml:
Example 1:
<!-- Sample file upload stack -->
<interceptor-stack name="fileUploadStack">
    <interceptor-ref name="fileUpload"/>
    <interceptor-ref name="basicStack"/>
</interceptor-stack>

Example 2:
<interceptor-stack name="defaultStack">
    <interceptor-ref name="exception"/>
    <interceptor-ref name="alias"/>
    <interceptor-ref name="servletConfig"/>
    <interceptor-ref name="i18n"/>
    <interceptor-ref name="prepare"/>
    <interceptor-ref name="chain"/>
    <interceptor-ref name="scopedModelDriven"/>
    <interceptor-ref name="modelDriven"/>
    <interceptor-ref name="fileUpload"/>
    <interceptor-ref name="checkbox"/>
    <interceptor-ref name="datetime"/>
    <interceptor-ref name="multiselect"/>
    <interceptor-ref name="staticParams"/>
    <interceptor-ref name="actionMappingParams"/>
    <interceptor-ref name="params">
        <param name="excludeParams">^action:.*,^method:.*</param>
    </interceptor-ref>
    <interceptor-ref name="conversionError"/>
    <interceptor-ref name="validation">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
    <interceptor-ref name="workflow">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
    <interceptor-ref name="debugging"/>
    <interceptor-ref name="deprecation"/>
</interceptor-stack>

Then place it manually before the basicStack declaration, or use a stack (the defaultStack, or the fileUploadStack) and include the Interceptor's name before the parameter's name, for example:
<interceptor-ref name="defaultStack">
    <param name="fileUpload.allowedTypes">image/jpeg,image/gif</param>
</interceptor-ref>

or
<interceptor-ref name="fileUploadStack">
    <param name="fileUpload.allowedTypes">image/jpeg,image/gif</param>
</interceptor-ref>


text:
Q: Databricks geospatial (latitude/longitude) plot Is it possible to visualize (latitude, longitude) data on a world map in an Azure Databricks Notebook? Scatter plot is the closest I got. The documentation tells about the existence of Map (Markers), but I didn't find such. Other possibilities are also welcome.
Here is the example of loading geospatial data from the Databricks doc:
%sql
CREATE TABLE IF NOT EXISTS default.sf_fire_incidents
USING com.databricks.spark.csv
OPTIONS (PATH 'dbfs:/databricks-datasets/learning-spark-v2/sf-fire/sf-fire-incidents.csv',
         HEADER "true",
         INFERSCHEMA "true");

SELECT location,
   `Estimated Property Loss`,
   coordinates[0]  AS LAT,
   coordinates[1] AS LONG
 FROM (SELECT location,
        `Estimated Property Loss`,
         split(btrim(location, '() '), ', ') AS coordinates
       FROM default.sf_fire_incidents
       ORDER BY `Estimated Property Loss` DESC,
                location)
 LIMIT 2000;

Scatter plot (LAT, LONG) is the closest I have, but I am unable to show the positions on a world map.

A: I think your best bet would be using the python library folium.
link to docs : https://python-visualization.github.io/folium/quickstart.html#Markers
You will start by initializing your map object.
import folium
# location refers to where the map will be centered at the begining
m = folium.Map(location=[45.372, -121.6972], zoom_start=12, tiles="Stamen Terrain")

Then convert your query result to pandas dataframe, you can do for example :
YOUR_QUERY = """
SELECT location,
   `Estimated Property Loss`,
   coordinates[0]  AS LAT,
   coordinates[1] AS LONG
 FROM (SELECT location,
        `Estimated Property Loss`,
         split(btrim(location, '() '), ', ') AS coordinates
       FROM default.sf_fire_incidents
       ORDER BY `Estimated Property Loss` DESC,
                location)
 LIMIT 2000;
"""
pdf = spark.sql(YOUR_QUERY).toPandas()

And finally iterate over your rows and add your markers to the map object like such :
for index, lines in pdf.iterrows():
 folium.Marker([lines[LAT], lines[LONG]], popup=f"{index}").add_to(m)

Don't forget to show the map at end by just calling the object :
m


text:
Q: Hide day from datepicker I need hide the day field from a datepicker, I found this method, but the problems is in the version of Android 2.3.3, works fine, but in the version 4x of android not hides the day field. I guess is the library  "java.lang.reflect.Field" is obsolete , but I'm not sure of this.
I found this solution here
may be going on here?
final DatePicker datePicker = new DatePicker(this);
                LLayout.addView(datePicker);

                hideDayField(datePicker, "mDayPicker");

    private void hideDayField(DatePicker datePicker, String name) {
    try {
        java.lang.reflect.Field field = DatePicker.class.getDeclaredField(name);
        field.setAccessible(true);
        View fieldInstance = (View) field.get(datePicker);
        fieldInstance.setVisibility(View.GONE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

A: That approach you're taking uses reflection to mess with some hidden fields of the DatePicker-class. The problem with this is, that when the internals of a class change (e.g. the name of the field you're getting changed) this won't work anymore.
See the Docs on Reflection.
In your linked question, there are some other options provided, which might be better suited.

A: I have done something similar hiding the day and the month, found the solution here
try {
    java.lang.reflect.Field[] f = picker.getClass().getDeclaredFields();
    for (java.lang.reflect.Field field : f) {
        if (field.getName().equals("mDayPicker") || field.getName().equals("mDaySpinner")
           || field.getName().equals("mMonthPicker") || field.getName().equals("mMonthSpinner")) {
           field.setAccessible(true);
           Object dmPicker = new Object();
           dmPicker = field.get(picker);
           ((View) dmPicker).setVisibility(View.GONE);
        }
    }
}

Hope it helps.


text:
Q: Absence of an ouput from the thread running in the wrapper class scoped_thread If to run this program using www.ideone.com
#include <iostream>
#include <thread>
#include <utility>
#include <stdexcept>

class scoped_thread
{
private:
    std::thread t;

public:
    explicit scoped_thread( std::thread t ) : t( std::move( t ) )
    {
        if ( not this->t.joinable() )
        {
            throw std::logic_error( "No thread" );
        }
    }

    ~scoped_thread()
    {
        t.join();
    }

    scoped_thread( const scoped_thread & ) = delete;
    scoped_thread & operator =( const scoped_thread & ) = delete;
};

void h()
{
    std::cout << "h() is running\n";
    for ( size_t i = 0; i < 10000; i++ );
    std::cout << "exiting h()\n";
}

void f()
{
    scoped_thread t( std::thread( h ) );
}

int main()
{
    f();

    std::thread t( h );
    t.join();

    return 0;
}

then the output is
h() is running
exiting h()

that corresponds to the thread t launced in main.
However a simialr output from the thread launched using the class scoped_thread is absent. Why?

A: It's the Most Vexing Parse:
scoped_thread t( std::thread( h ) );

This defines a function t taking an std::thread named h and returning a scopted_thread. To actually declare the object, declare instead:
scoped_thread t{ std::thread(h) };