text:
Q: Solr suggest most common result without returning entire phrase We are looking to implement a suggest drop down for searching a Solr core.
We already have basic search without suggestions implemented, so the cores are set up.  I'm trying to be thorough with the details for my question, without over complicating.
If they are searching a single word, we want the most common single matching word to be suggested.
If they are searching more than one word, we want the most common combined phrase to be suggested.  If the combined phrase isn't there, we want the most common result from one of the words in the phrase.
I was trying to implement a solution for the suggest without having to create another core, where I have to parse out the words, phrases, and counts.
I've looked into spell checker and suggest components.
The problem I've had with suggest is that it only returns the entire field.  We want it to only return as many words as they start typing.
The problem I've had with spell checker is that it doesn't return the correct results if the word is spelled correctly (makes sense, it's a spell checker).  And, if we spellcheck multiple words, they are separated in the results.  If they search more than one word and there's a match we expect both words returned if they are in the same order, and we expecting the user to use the correct spelling.
Documents scenario in the core we are searching:
{title: 5ft transparent tape},
{title: 5ft transparent dressing},
{title: onsite training},
{title: tape dispenser},
{title: countertop tape dispenser},
{title: 3ft tape measure},
{title: 5ft tape measure},
{title: 10ft tape measure},
{title: tape media}

Only begin to suggest after 3 characters.  Only want 1 result.
search: "tra"
returns: transparent

^^ idea: returns most common single word that matches, "transparent" appears more than "training".
search: "tape me"
returns: "tape measure"

^^ idea: returns most common two words that match, "tape measure" appears more than "tape media".
search: "cassette tape"
returns: "tape"

^^ idea: "cassette tape" does not exist, neither does "cassette", so it returns the most common word that does, "tape".
Nice to have, but not required:
search: "tape " (with space)
returns: "tape measure"

^^ idea: it knows the space means they are about to enter another word and returns most common two words that start with the first word, "tape measure" appears more than "tape media" and "tape dispenser".
Any ideas on how to achieve this by using the existing core?  I've thought of a way to do it with a new core, by slicing and dicing the data, and creating a suggest component, but I'd like to use the core we have.  Is it possible with a custom token filter? A custom token filter is currently over my head, but I'd give it a shot if it's possible.
Thanks for any help!

A: I had to find the correct filter.  ShingleFilterFactory - This filter constructs shingles, which are token n-grams, from the token stream. It combines runs of tokens into a single token.
https://lucene.apache.org/solr/guide/7_0/filter-descriptions.html#shingle-filter

<fieldType name="spellcheck_phrase" class="solr.TextField" positionIncrementGap="100">
  <analyzer>
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.ShingleFilterFactory" maxShingleSize="4" outputUnigrams="false"/>
  </analyzer>
</fieldType>

Example of the analyzer above:
In: "To be, or not to be."
Tokenizer to Filter: "To"(1), "be"(2), "or"(3), "not"(4), "to"(5), "be"(6)
Out: "To be"(1), "To be or"(1), "To be or not"(1), "be or"(2), "be or not"(2), "be or not to"(2), "or not"(3), "or not to"(3), "or not to be"(3), "not to"(4), "not to be"(4), "to be"(5)

A: Have a look at the AnalyzingInfix suggester
https://lucidworks.com/2015/03/04/solr-suggester/


text:
Q: Understanding recursion in javascript and alternative Why does my browser slows down when this list data is huge in below code :
var list = [];

/*
  Creating some huge dummy data
  Interstingly, when I change the value of i from 10000
  to 100000, the browser hangs(becomes unresponsive)
*/
for(i=0;i<10000;i++){
  list.push(i);

}

/*Recursive function*/
var nextListItem = function() {
    var item = list.pop();

    if (item) {
        console.log(item);
        // process the list item...
        nextListItem();
    }
};
nextListItem(); // Commented this as browser becomes unresponsive.

jsbin
I could not find a straight answer to my question from google, so though off getting help from SO experts. I am assuming it has something to do with browser memory as I can see the loop starts in a great speed and slowly slows down and becomes unresponsive. But not sure why?

A: JavaScript doesn't have tail call elimination. Hence if you loop through a list recursively you'll be wasting a lot of resources. Eventually you might even end up exhausting the stack space.
One possible solution to this problem is to call the tail call asynchronously so that the main function finishes execution before the tail call function begins execution. This ensures that the stack space doesn't increase:

var list = [];

for (var i = 0; i < 10000; i++) list.push(i);

var start = new Date;

nextListItem();

function nextListItem() {
    var item = list.pop();

    if (item) {
        console.log(item);
        setTimeout(nextListItem, 0);
    } else console.log(new Date - start);
}

See the following question for more details:
What's the difference between a continuation and a callback?

Edit: A faster solution (as suggested by T.J. Crowder):

var list = [];

for (var i = 0; i < 10000; i++) list.push(i);

var start = new Date;

nextListItem();

function nextListItem() {
    var item = list.pop();

    if (item) {
        console.log(item);
        if (item % 100) nextListItem();
        else setTimeout(nextListItem, 0);
    } else console.log(new Date - start);
}

The loop is more sluggish as it prints to the console in bursts of 100 items. However it completes execution much faster.

A: I would suggest to use Javascript Promise for this.
function nextListItem2 (list) {
    return new Promise(function(resolve, reject) {
        var item = list.pop();
        if(item) {
            console.log(item);
            return nextListItem(list);
        } else {
            resolve();
        }
    });
}

nextListItem2(list);

redpajama_set_name: RedPajamaStackExchange


text:
Q: V-html directive not working with fetched data Maybe someone can help me solving the problem with v-html directive
I have a column in database table with pure html code. I'm getting it through PHP script via fetch.
Here's the code of fetch request (just a usual fetch code):
const vacancies: Array<Vacancy> = await fetch(SCRIPT_URL)
    .then((data: Response) => data.json())
    .then((data: Array<Vacancy>) => {
        this.vacancies = data;
    })
    .catch(error => {
        console.error(error);
    })

This code is executed on mounting the application. Then i'm trying to render it with following code:

But when I'm reloading the page, v-html doesn't render this like html - it renders it like unescaped html:

 Lorem ipsum

dolor sit amet

consectetur adipiscing elit

eiusmod tempor


text:
Q: str_replace() making wrong replacement How is this possible that the str_replace() function below returns biWeekly and not Every Other Week ?
$payFrequency = "biweekly";
$postData['payFrequency'] = str_replace(array('weekly','biweekly','twicemonthly','monthly'),array('Weekly','Every Other Week','Twice a Month','Monthly'), $payFrequency, $cnt);
echo "$cnt {$postData['payFrequency']}\n"; // SHOWS 1 biWeekly

A: You should swap first and second items in both arrays.
$payFrequency = "biweekly";
$postData['payFrequency'] = str_replace(array('biweekly','weekly','twicemonthly','monthly'),array('Every Other Week','Weekly','Twice a Month','Monthly'), $payFrequency, $cnt);
echo "$cnt {$postData['payFrequency']}\n"; // SHOWS 1 biWeekly

this would work.

A: It replaces the "weekly" in "biweekly" with "Weekly", which afterwards does not match "biweekly" anymore.

A: because biweekly contains "weekly" which is your first match in the array
array('weekly','biweekly','twicemonthly','monthly')

Thus it converts that first then return.
You could swap your order of replacements:
$payFrequency = "biweekly";

$postData['payFrequency'] = str_replace(
        array('biweekly','weekly','twicemonthly','monthly'), // biweekly then weekly
        array('Every Other Week','Weekly','Twice a Month','Monthly'), $payFrequency, $cnt
);

echo "$cnt {$postData['payFrequency']}\n";

A: str_replace is case-sensitive, so biweekly gets replaced, but biWeekly does not. Use str_ireplace if you want a case-insensitive replace.


text:
Q: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager' on a null object reference I made a recyclerview in a Fragment, with code like this, before I made this, in the usual activity, and I tried to make it in Fragment Activity, but it happened even error
public class GaweanFragment extends BaseFragment {

@BindView(R.id.rv_gawean_fragment)
RecyclerView rv_gawean_fragment;
@BindView(R.id.prbLoading)
ProgressBar prbLoading;
@BindView(R.id.txvUser)
TextView txvUser;
@BindView(R.id.txvDescription)
TextView txvDescription;
@BindView(R.id.btnSubmit)
Button btnSubmit;
@BindView(R.id.lnrNoList)
LinearLayout lnrNoList;

@BindDrawable(R.drawable.ic_obs_on_white_36px)
public Drawable observationOn;
@BindDrawable(R.drawable.ic_obs_off_white_36px)
public Drawable observationOff;
@BindDrawable(R.drawable.ic_sc_on_white_36px)
public Drawable storecountOn;
@BindDrawable(R.drawable.ic_sc_off_white_36px)
public Drawable storecountOff;

@BindString(R.string.error_no_internet)
public String errorInternet;
@BindString(R.string.request_failed)
public String requestFailed;
@BindString(R.string.error_location_not_found)
public String errorLocationNotFound;
@BindString(R.string.please_wait)
public String pleaseWait;
@BindColor(R.color.colorPrimary)
public int colorPrimary;
@BindColor(R.color.grey_600)
public int colorGrey;

@BindString(R.string.no_order_list_please_order)
public String errorNoList;

private LatLng myLocation;
private Boolean isObservation = true;
private Boolean isStoreCount = false;
private Boolean isMapReady = false;

private GaweanPresenter presenter;
private List<Job> gaweanJobs;
private Job selectedJob;
private android.location.Location locA;
private Float radiusKilometer;

@Override
protected int getLayout() {
    return R.layout.f_gawean;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    initRV();

    presenter = new GaweanPresenter(this);
    gaweanJobs = new ArrayList<>();

    if (ThemeUtil.getThemes() == ThemeUtil.THEME_OBSERVATION) {
        loadObservation();
    } else {
        loadStoreCount();
    }

}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

}

@Override
public void onResume() {
    super.onResume();
    gaweanJobs = new ArrayList<>();
    if (ThemeUtil.getThemes() == ThemeUtil.THEME_OBSERVATION) {
        loadObservation();
    } else {
        loadStoreCount();
    }
}

@Override
public void busHandler(RxBusObject.RxBusKey busKey, Object busObject) {
    switch (busKey) {
        case MAP_READY:
            myLocation = (LatLng) busObject;
            if (myLocation != null) {

                isMapReady = true;

                if (isObservation) {
                    presenter.getAssignList(GaweanPresenter.OBSERVATION, Double.toString(myLocation.latitude), Double.toString(myLocation.longitude));
                    presenter.getApplyList(GaweanPresenter.OBSERVATION, Double.toString(myLocation.latitude), Double.toString(myLocation.longitude));
                }

                if (isStoreCount) {
                    presenter.getAssignList(GaweanPresenter.STORE_COUNT, Double.toString(myLocation.latitude), Double.toString(myLocation.longitude));
                    presenter.getApplyList(GaweanPresenter.STORE_COUNT, Double.toString(myLocation.latitude), Double.toString(myLocation.longitude));
                }
            }
            break;

        case SELECT_PLACE:
            Place place = (Place) busObject;

            for (int i = 0; i < gaweanJobs.size(); i++) {
                if (place.getId().equals(gaweanJobs.get(i).getIdJob())) {
                    selectedJob = gaweanJobs.get(i);
                    break;
                }
            }

            showCheckInDialog();

            break;

        case LOCATION_CHANGE:
            myLocation = (LatLng) busObject;
            if (myLocation != null) {
                if (gaweanJobs.size() > 0)
                    loadList();
            }
            break;
    }
}

public void initRV() {
    final LinearLayoutManager llManager = new LinearLayoutManager(getContext());
    llManager.setOrientation(LinearLayoutManager.VERTICAL);
    rv_gawean_fragment.setLayoutManager(llManager);
}

public void loadList(List<Job> jobList) {
    gaweanJobs.addAll(jobList);

    Collections.sort(gaweanJobs, new Comparator<Job>() {
        @Override
        public int compare(Job lhs, Job rhs) {
            // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending

            Double leftDistance = 0d;
            Double rightDistance = 0d;
            if (lhs.getStoreDist() != null) {
                try {
                    leftDistance = Double.parseDouble(lhs.getStoreDist());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (lhs.getAreaDist() != null) {
                try {
                    leftDistance = Double.parseDouble(lhs.getAreaDist());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (rhs.getStoreDist() != null) {
                try {
                    rightDistance = Double.parseDouble(rhs.getStoreDist());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (rhs.getAreaDist() != null) {
                try {
                    rightDistance = Double.parseDouble(rhs.getAreaDist());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return rightDistance > leftDistance ? -1 : (rightDistance < leftDistance) ? 1 : 0;
        }
    });

    rv_gawean_fragment.setVisibility(View.VISIBLE);
    lnrNoList.setVisibility(View.GONE);
    prbLoading.setVisibility(View.GONE);
    JobListAdapter jobListAdapter = new JobListAdapter(getContext(), gaweanJobs, myLocation);
    rv_gawean_fragment.setAdapter(jobListAdapter);
    rv_gawean_fragment.setNestedScrollingEnabled(true);

    if (gaweanJobs.size() > 0) {

    }
}

public void loadList() {
    rv_gawean_fragment.setVisibility(View.VISIBLE);
    lnrNoList.setVisibility(View.GONE);
    prbLoading.setVisibility(View.GONE);
    rv_gawean_fragment.setAdapter(new JobListAdapter(getContext(), gaweanJobs, myLocation));
    rv_gawean_fragment.setNestedScrollingEnabled(true);
}

public void showNoList(String message, String action) {
    if (gaweanJobs.size() == 0) {
        rv_gawean_fragment.setVisibility(View.GONE);
        lnrNoList.setVisibility(View.VISIBLE);
        prbLoading.setVisibility(View.GONE);
        if (!message.equals(""))
            txvDescription.setText(message);
        btnSubmit.setText(action);
    }
}

private void showCheckInDialog() {
    NumberFormat formatter = new DecimalFormat("#0.00");

    locA = new android.location.Location("");
    locA.setLatitude(myLocation.latitude);
    locA.setLongitude(myLocation.longitude);

    radiusKilometer = Float.parseFloat(selectedJob.getRadiusMeter()) / 1000;

    String name = "";
    String date = "Deadline: " + DateUtil.format(DateUtil.format(selectedJob.getDueDate(), "yyyy-MM-dd"), "EEE, dd-MMM-yyyy");

    String description = selectedJob.getDescription();

    if (selectedJob.getName() != null && !selectedJob.getName().equals("")) {
        name = selectedJob.getStoreName() + "\n";
    } else {
        name = selectedJob.getAreaName() + "\n";
    }

    String title = "";
    switch (selectedJob.getIdJobType()) {
        case "2":
            title = "Barcode Scan";
            break;
        case "3":
            title = "Area Survey";
            break;
        default:
            title = "Observasi";
    }

    new MaterialDialog.Builder(getContext())
            .backgroundColor(Color.WHITE)
            .title(title)
            .titleColor(colorPrimary)
            .content(name + description + "\n\n" + date + "\n\n" + "Ingin memulai job ini?")
            .contentColor(getResources().getColor(R.color.grey_600))
            .positiveText("Ya")
            .positiveColor(colorPrimary)
            .negativeText("Tidak")
            .negativeColor(getResources().getColor(R.color.grey_600))
            .onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (selectedJob.isApporved()) {
                        //STORE COUNT
                        if (selectedJob.getIdJobType().equals("1")) {
                            float distance = 0f;

                            if (selectedJob.getAreas() != null) {
                                for (int i = 0; i < selectedJob.getAreas().size(); i++) {
                                    Area area = selectedJob.getAreas().get(i);

                                    if (area.getDist() != null) {
                                        if (i == 0) {
                                            Location locB = new Location("");
                                            locB.setLatitude(Double.parseDouble(area.getLatitude()));
                                            locB.setLongitude(Double.parseDouble(area.getLongitude()));
                                            distance = locA.distanceTo(locB) / 1000;
                                        }

                                        if (Double.parseDouble(area.getDist()) < distance) {
                                            Location locB = new Location("");
                                            locB.setLatitude(Double.parseDouble(area.getLatitude()));
                                            locB.setLongitude(Double.parseDouble(area.getLongitude()));
                                            distance = locA.distanceTo(locB) / 1000;
                                        }
                                    }
                                }
                            }

                            if (distance <= radiusKilometer) {

                            } else {

                            }
                        } else if (selectedJob.getIdJobType().equals("2")) {

                        } else if (selectedJob.getIdJobType().equals("3")) {
                            List<LatLng> areas = new ArrayList<>();
                            for (Area area : selectedJob.getAreas()) {
                                areas.add(new LatLng(Double.parseDouble(area.getLatitude()), Double.parseDouble(area.getLongitude())));
                            }

                            if (PolyUtil.containsLocation(myLocation, areas, true)) {

                            } else {

                                float distance = 0f;

                                if (selectedJob.getAreas() != null) {
                                    for (int i = 0; i < selectedJob.getAreas().size(); i++) {
                                        Area area = selectedJob.getAreas().get(i);

                                        if (area.getDist() != null) {
                                            if (i == 0) {
                                                Location locB = new Location("");
                                                locB.setLatitude(Double.parseDouble(area.getLatitude()));
                                                locB.setLongitude(Double.parseDouble(area.getLongitude()));
                                                distance = locA.distanceTo(locB) / 1000;
                                            }

                                            if (Double.parseDouble(area.getDist()) < distance) {
                                                Location locB = new Location("");
                                                locB.setLatitude(Double.parseDouble(area.getLatitude()));
                                                locB.setLongitude(Double.parseDouble(area.getLongitude()));
                                                distance = locA.distanceTo(locB) / 1000;
                                            }
                                        }
                                    }
                                }

                                if (distance <= 0.5) {

                                } else {

                                }

                            }
                        } else if (selectedJob.getIdJobType().equals("4")) {

                        }

                    }
                }
            })
            .show();
}

public void showLoading() {
    prbLoading.setVisibility(View.VISIBLE);
    lnrNoList.setVisibility(View.GONE);
    rv_gawean_fragment.setVisibility(View.GONE);
}

public void loadObservation() {

    isObservation = true;
    isStoreCount = false;

    if (isMapReady) {
        presenter.getAssignList(GaweanPresenter.OBSERVATION, Double.toString(myLocation.latitude), Double.toString(myLocation.longitude));
        presenter.getApplyList(GaweanPresenter.OBSERVATION, Double.toString(myLocation.latitude), Double.toString(myLocation.longitude));
    }

}

public void loadStoreCount() {

    isObservation = false;
    isStoreCount = true;

    if (isMapReady) {
        presenter.getAssignList(GaweanPresenter.STORE_COUNT, Double.toString(myLocation.latitude), Double.toString(myLocation.longitude));
        presenter.getApplyList(GaweanPresenter.STORE_COUNT, Double.toString(myLocation.latitude), Double.toString(myLocation.longitude));
    }

}

@OnClick(R.id.btnSubmit)
public void onClickSubmit(Button v) {
    if (v.getText().toString().equals("Coba Lagi")) {
        if (ThemeUtil.getThemes() == ThemeUtil.THEME_OBSERVATION) {
            loadObservation();
        } else {
            loadStoreCount();
        }
    } else {
        HomeActivity.startActivity(getActivity());
    }
}

but, i have problem like this, in my recycler view, this is the Log
Process: com.mogawe.mosurvei, PID: 4807
                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
                                                                   at com.mogawe.mosurveibeta.view.fragment.menu.GaweanFragment.initRV(GaweanFragment.java:215)
                                                                   at com.mogawe.mosurveibeta.view.fragment.menu.GaweanFragment.onCreate(GaweanFragment.java:130)

the error is on this line of code
rv_gawean_fragment.setLayoutManager(llManager);

actually what caused this error, and how to debug it. Maybe just it, i hope you can help me in this error, thanks

A: You problem is

When you call initRV in onCreate method .The Activity may be not created .

So you can call it in your onActivityCreated method .
And rv_gawean_fragment.setLayoutManager(llManager); will work ok in onActivityCreated method .
You can do this .
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    initRV();
}

A: You need to initialize butterknife before using views in your layout so add this line to onViewCreated method ButterKnife.bind(this, view); and replace your onCreate code in on activity create method
Hope this helps!


text:
Q: Dúvida sobre extração de valores usando soup.findAll() em Python Boa tarde a todos.
Estou estudando python e aprendendo a fazer extração de dados em sites e para dá início a esse aprendizado estou criando um programa que irá extrair os dados da lotofacil do site da caixa econômica e me retornar os valores sorteados em determinado concurso.
Pelos exemplos que vi na internet, é possível fazer a busca pela  e pelo  ou <parâmetro>, no entanto, verifiquei que a página, da caixa, que possui todos os resultados por concurso não possui um , ou seja, só possuem o  e  dentro de uma tabela .
Já consegui extrair os dados de toda a linha de determinado concurso, no entanto, não estou conseguindo tratar os dados da linha e pegar somente: número do concurso e números sorteados. O meu código ele está mostrando todo os valores da linha.
Alguém poderia me dá uma luz?
import requests
from bs4 import BeautifulSoup

req = requests.get( "http://loterias.caixa.gov.br/wps/portal/loterias/landing/lotofacil/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbz8vTxNDRy9_Y2NQ13CDA0sTIEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wBmoxN_FydLAGAgNTKEK8DkRrACPGwpyQyMMMj0VAcySpRM!/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0K85260Q5OIRSC42046/res/id=historicoHTML/c=cacheLevelPage/=/" )
soup = BeautifulSoup( req.content, "html.parser" )

todas_linhas = soup.findAll("tr")

## LOCALIZA EM TODAS AS LINHAS 'td' O texto '2208', GUARDA DA VARIÁVEL temp ##
# A CONDIÇÃO if VERFICA NA VARIÁRIL temp E SÓ RETORNA OS VALORES QUE SÃO DIFERENTES DE None #

for tr in todas_linhas:
    temp = tr.find('td', text='2208')
    if temp != None:
        print (tr.text)

Espero que tenham entendido a minha dúvida e obrigado pela atenção.

A: Cara, essa deu trabalho hein. kkkkkk.
Seu código está no caminho correto, o problema está na página que em algumas linhas foi adicionado uma nova tabela, por exemplo, coluna cidade além de algumas sujeirinhas na transformação de tag html para texto.
Segue a solução abaixo, transformando o retorno num dataframe, será perfeito para analises, filtros e gráficos se desejar.
Mais abaixo, um código exibindo linha por linha, veja que ele zera a contagem e trás sujeira de uma linha para outra.
import time
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np

url = "http://loterias.caixa.gov.br/wps/portal/loterias/landing/lotofacil/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbz8vTxNDRy9_Y2NQ13CDA0sTIEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wBmoxN_FydLAGAgNTKEK8DkRrACPGwpyQyMMMj0VAcySpRM!/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0K85260Q5OIRSC42046/res/id=historicoHTML/c=cacheLevelPage/=/"
req = requests.get(url)
soup = BeautifulSoup(req.content, "html.parser" )

todas_linhas = soup.findAll("tr")

lista = []
lista_aux = []
for x in todas_linhas:
    z = x.text
    i = 0
    linhas_validas = 'N'
    lista_aux = []

    #Transforma o texto em lista
    for xx in z.split('\n'):

        if i == 1 and xx != "":
            linhas_validas = 'S'

        if linhas_validas == 'S' and i >=1 and i<=17:
            lista_aux.append(xx)

        i += 1

    if linhas_validas == "S" and len(lista_aux) ==17:
        lista.append(lista_aux)

#Transformar lista em dataframe
df = pd.DataFrame(lista)

#Pega primeira linha
headers = df.iloc[0]

#Transforma linha em cabeçalho
df.columns = [headers]

#Apaga a primeira linha porque virou cabeçalho
df = df.iloc[1:]

#imprime os 10 primeiros registros
print(df.head(5).to_string())

#Imprime todo o dataframe
#print(df.to_string())

#Imprime a quantidade de linhas e colunas
print()
print('Linhas e Colunas Total:')
print(df.shape)

import time
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np

url = "http://loterias.caixa.gov.br/wps/portal/loterias/landing/lotofacil/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbz8vTxNDRy9_Y2NQ13CDA0sTIEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wBmoxN_FydLAGAgNTKEK8DkRrACPGwpyQyMMMj0VAcySpRM!/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0K85260Q5OIRSC42046/res/id=historicoHTML/c=cacheLevelPage/=/"
req = requests.get(url)
soup = BeautifulSoup(req.content, "html.parser" )

todas_linhas = soup.findAll("tr")

for x in todas_linhas:
    z = x.text
    i = 0
    for xx in z.split('\n'):
        print(str(i)+" - "+str(xx))
        i += 1

Pesquisar o concurso
print()
print('Digite o Código do Concurso: ')
codigoConcurso = input()

df_desejado = df.iloc[[int(codigoConcurso)-1]]

print(df_desejado)

data = str(df_desejado.iloc[0][1])
bola1 = str(df_desejado.iloc[0][2])
bola2 = str(df_desejado.iloc[0][3])
#outras variaveis
bola15 = str(df_desejado.iloc[0][16])

print()
print('data: '+str(data))
print('bola 1: '+str(bola1))
print('bola 3: '+str(bola2))
print('bola 15: '+str(bola15))

A: Obrigado por ajudar Gilmar Vaz. Agora vou estudar Interface gráfica para integrar ao código.
import time
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np

url ="http://loterias.caixa.gov.br/wps/portal/loterias/landing/lotofacil/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbz8vTxNDRy9_Y2NQ13CDA0sTIEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wBmoxN_FydLAGAgNTKEK8DkRrACPGwpyQyMMMj0VAcySpRM!/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0K85260Q5OIRSC42046/res/id=historicoHTML/c=cacheLevelPage/=/"
req = requests.get(url)
soup = BeautifulSoup(req.content, "html.parser" )

todas_linhas = soup.findAll("tr")

lista = []
lista_aux = []
resultado = []
for x in todas_linhas:
    z = x.text
    i = 0
    linhas_validas = 'N'
    lista_aux = []

    #Transforma o texto em lista
    for xx in z.split('\n'):

        if i == 1 and xx != "":
            linhas_validas = 'S'

        if linhas_validas == 'S' and i >=1 and i<=17:
            lista_aux.append(xx)

        i += 1

    if linhas_validas == "S" and len(lista_aux) ==17:
        lista.append(lista_aux)

#Transformar lista em dataframe
df = pd.DataFrame(lista)

#Pega primeira linha
headers = df.iloc[0]

#Transforma linha em cabeçalho
df.columns = [headers]

#Apaga a primeira linha porque virou cabeçalho
df = df.iloc[1:]

#imprime, por default, os 5 primeiros registros
#print(df.head().to_string())

#imprime, por default, os 5 últimos registros
print (df.tail().to_string())

#Imprime todo o dataframe
#print(df.to_string())

#Imprime a quantidade de linhas e colunas
print()
print('Linhas e Colunas Total:')
print(df.shape)

print()
print('Digite o Código do Concurso: ')
codigoConcurso = input()

df_desejado = df.iloc[[int(codigoConcurso)-1]]

print(df_desejado)

data = str(df_desejado.iloc[0][1])

print ('-')
resultadoString = (df_desejado.iloc[0][2:17].tolist())
# converter os valores String para int dentro da lista (resultado)
resultadoFinal = []
for i in resultadoString:
    resultadoFinal.append(int(i))
#print (resultadoFinal)

print()
print('data: '+str(data))

## Jogos feitos pelo usuário.
jogos = ([2,3,4,5,6,7,8,12,13,15,17,20,21,22,23], [5,6,7,8,9,10,11,12,16,17,19,20,22,23,24])

#---variáveis globoais-----#
contador = 0
pontos = 0

## Laço para conferir os 8 jogos feitos.
while (contador <= len(jogos)):
    for i in jogos[contador]:
        for j in resultadoFinal:
            if i == j:
                pontos += 1
    #totais.append(pontos)

    print("O jogo ", jogos[contador], " conseguiu ", pontos, " pontos!")
    pontos = 0
contador += 1


text:
Q: jQuery mobile doesn't trigger pageshow code between pages I am writing a jQuery mobile app that contains two HTML pages. When user navigates from index.html page to search.html page, jQuery should load elements into search.html page.
However, things seems to gone wrong. The script doesn't work as expected.
index.html
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">

<link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css" ></link>
<link rel="stylesheet" href="css/mahidol.min.css"></link>
<link rel="stylesheet" href="css/themes/jquery.mobile.icons.min.css"></link>

      Preferences

 Contact

      <form class="ui-filterable">
        Search from name
        <input id="filterBoxList" data-type="search" placeholder="Type here to search from department list">
      </form>

search.html
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<meta charset="utf-8"></meta>

<link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css" ></link>
<link rel="stylesheet" href="css/mahidol.min.css"></link>
<link rel="stylesheet" href="css/themes/jquery.mobile.icons.min.css"></link>

      Preferences

 Contact

      <form class="ui-filterable">
        Search from dept. list
        <input id="filterBoxName" data-type="search" placeholder="Type here to search from name">
      </form>

default.js (loaded the last)
$(document).on("pageshow","search.html",function(){
  var chx = 0;
  var m="";
  var k=[];
  $.mobile.loading( "show", {
          text: 'Loading',
          textVisible: true
  });
  if(loaded == false) // This will prevent event triggering more then once
  {
    for (var t in JSON.parse(localStorage.getItem('hr')))
    {
      m += "
" + JSON.parse(localStorage.getItem('hr'))[t].Name + " " + JSON.parse(localStorage.getItem('hr'))[t].Surname + "
";
    }
    $('#listie').append(m).listview('refresh');
    loaded = true;
  }
  $.mobile.loading( "hide" );
});

Things seems to be nice when the "search" page div is placed inside index.html (and the code is linked in single page, not two). However it does break when I tried splitting up the files into two files.
Anything I can do to fix this?

A: Well, solved...
Even though the div is on the same file, when using $(document).on("pageshow",src,function(){...}); to point to src, makes sure that src points to the div ID, not the file itself.
In this case, it's $(document).on("pageshow","#search",function(){...});.


text:
Q: How to Get the Coordinates of a Touch Gesture on a PKCanvasView using PencilKit? Swift 5 & Xcode 11 NOTE that I looked a lot everywhere but couldn't find a solution.
Using the Storyboard, I have a ViewController, with a View (UIView) and a Subview (PKCanvasView) where I want to use PencilKit to draw on the latter.
_
My objectives are:

*

*Draw only on this PKCanvasView

*Get the coordinates in real time of where I'm drawing on the PKCanvasView
My results:

*

*I can draw on the PKCanvasView only if I start from this view, and I can only draw within the frame of this PKCanvasView. That's good.

*I can only manage to get the coordinates of where I'm touching the screen IF I start the gesture on the UIView. BUT Not if I touch the PKCanvasView first.
My problem:
How do I get the coordinates of where I'm drawing on the PKCanvasView?
–
Below is my code:
import UIKit
import PencilKit

class ViewController: UIViewController {

    @IBOutlet weak var labelText: UILabel! //Label object to display the coordinates

    @IBOutlet weak var canvasView: PKCanvasView! //Subview to draw on

    override func viewDidAppear(_ animated: Bool) {
        canvasView.tool = PKInkingTool(.pen, color: .black, width: 10)
    }

    // MARK: FUNCTIONS //
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        touches.forEach { (touch) in
            updateGagues(with: touch)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        touches.forEach { (touch) in
            updateGagues(with: touch)
        }
    }

    private func updateGagues(with touch: UITouch) {
        let location = touch.preciseLocation(in: view)
        labelText.text = location.debugDescription
    }
}

A: I recently experienced the same problem of getting touch coordinates from my PKCanvasView. To do this, I created a subclass of PKCanvasView and overrode the touchesBegan function:
class Canvas: PKCanvasView {

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    touches.forEach { touch in
      print("touch location \(touch.location(in: self))")
    }
  }

}


text:
Q: Calculating slope through discrete points in Python I've graphed four separate points using matplotlib, and would like to find the slope of the best fit line through them. Alternatively, I'd like to graph these points as one line and find the slope if possible. I'm also trying to do this on a logarithmic scale. Here's what I have (the period calculations came from elsewhere in my code):
import matplotlib.pyplot as plt
# First orbit
x_0 = 10.0
a1 = x_0
T1 = len(range(1, 98))

# Second orbit
x_0 = 5.0
a2 = x_0
T2 = len(range(1, 63))

# Third orbit
x_0 = 7.0
a3 = x_0
T3 = len(range(1, 81))

# Fourth orbit
x_0 = 13.0
a4 = x_0
T4 = len(range(1, 138))

smaxis = [a1, a2, a3, a4]
T = [T1, T2, T3, T4]

# Plot period versus semi-major axis
for i in range(len(T)):
    plt.plot(T[i], smaxis[i], markersize=3, marker='o')
plt.xlabel('Period (T)')
plt.ylabel('Semimajor Axis (a)')
plt.xscale('log')
plt.yscale('log')
plt.title('Logarithmic scale of T vs a')

And my graph is shown here.
I've tried using using linregress with this code:
from scipy.stats import linregress
linregress(T, smaxis)

But I'm not convinced that's correct, since T and smaxis are lists, and I need the slope between the line of best fit through the discrete points shown. How can I do this?

A: Consider below code which uses numpy's polyfit.
x=T
y=smaxis
fit = np.polyfit(x, y, 1)
fit_fn = np.poly1d(fit)
s,i = fit
print("slope: ",s," intercept: ",i)
for i in range(len(T)):
    plt.plot(T[i], smaxis[i], markersize=3, marker='o')
plt.xlabel('Period (T)')
plt.ylabel('Semimajor Axis (a)')
plt.xscale('log')
plt.yscale('log')
plt.title('Logarithmic scale of T vs a')
plt.plot(x, fit_fn(x))
plt.show()

Output:

A: Here's how you catch and use the output of linregress.
from scipy.stats import linregress

slope, intercept, r_value, p_value, std_err = linregress(T, smaxis)

def a_predict(T):
    return intercept + slope*T

T_min, T_max = min(T), max(T)
a_min, a_max = a_predict(T_min), a_predict(T_max)

plt.plot([T_min, T_max], [a_min, a_max], 'r--')

print(slope, intercept, r_value, p_value, std_err)

output:
0.10753736192332683 -1.3585120207927215 0.9841584242334624 0.015841575766537552 0.013698301731763748

(I got this from the documentation).
But it may be more convenient for you to convert your lists into numpy arrays first.
import numpy as np
x = np.array(T)

Then you can do vectorized calculations as in the example in the documentation:
plt.plot(x, intercept + slope*x, 'r--')


text:
Q: How to reorder numbering in INT column in SQL? Let's say I have a table Customer
name                 seq
-------------------- -----------
Johnny               1
Jack                 3
Jim                  4

Both name and seq are primary key. This is my expected result
name                 seq
-------------------- -----------
Johnny               1
Jack                 2
Jim                  3

Any idea how to achieve this? I tried using UPDATE along with ROW_NUMBER but it won't let me due to num is a primary key column.
Note: The new sequence must be ordered by seq (not name).

A: You can update via a CTE
Declare @YourTable table (name varchar(25),seq int)
Insert Into @YourTable values
('Johnny',1),
('Jack',  3),
('Jim',   4)

;with cte as (
    Select *
          ,RN = Row_Number() over (Order By Seq)
    From  @YourTable
)
Update cte Set Seq=RN

Select * from @YourTable

Returns
name    seq
Johnny  1
Jack    2
Jim     3


text:
Q: Passing BigInteger as a Parameter I want to know how to pass a BigInteger Number as a parameter
I was trying to pass a Biginteger but the program recognizes it as a Integer and I get a error "Integer number too large"
enter image description here

A: Your method expects a BigInteger object. But you pass an int or long primitive.
You need to construct a BigInteger instance explicitly rather than pass a numeric literal.
BigInteger x = new BigInteger ( "123456" ) ;
someObject.someMethod( x ) ;

Or shorten that.
someObject.someMethod( new BigInteger ( "123456" ) ) ;

Using a numeric literal.
BigInteger x = BigInteger.valueOf ( 123_456 ) ;


text:
Q: transmit voice application force to close i am writing an application that send voice from one android device to another but when i click the button to send the application force to close i am using code similar to
Streaming voice between Android Phones over WiFi
and i will post the code below
the sender:
    public class MainActivity extends ActionBarActivity {
    private EditText target;
    private TextView streamingLabel;
    private Button startButton,stopButton;
    public byte[] buffer;
    public static DatagramSocket socket;
    private int port=50005;         //which port??
    AudioRecord recorder;
    //Audio Configuration.
    private int sampleRate = 16000;      //How much will be ideal?
    private int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
    private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    int minBufsize=4096;
    private boolean status = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        target = (EditText) findViewById (R.id.target_IP);
        streamingLabel = (TextView) findViewById(R.id.streaming_label);
        startButton = (Button) findViewById (R.id.start);
        stopButton = (Button) findViewById (R.id.stop);
        stopButton.setOnClickListener(new View.OnClickListener() {
        @Override
            public void onClick(View v) {
                status = false;
                recorder.release();
                Log.d("VS","Recorder released");

            }
        });
        startButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
             status = true;
             startStreaming();

        }
    });

    }
    public void startStreaming() {

        Thread streamThread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {

                    int minBufSize = 4096;//AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
                    DatagramSocket socket = new DatagramSocket();
                    Log.d("VS", "Socket Created");

                    byte[] buffer = new byte[minBufSize];

                    Log.d("VS","Buffer created of size " + minBufSize);
                    DatagramPacket packet;

                    final InetAddress destination = InetAddress.getByName(target.getText().toString());
                    Log.d("VS", "Address retrieved");

                    recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,sampleRate,channelConfig,audioFormat,minBufSize);
                    Log.d("VS", "Recorder initialized");

                    recorder.startRecording();

                    while(status == true) {

                        //reading data from MIC into buffer
                        minBufSize = recorder.read(buffer, 0, buffer.length);

                        //putting buffer in the packet
                        packet = new DatagramPacket (buffer,buffer.length,destination,port);

                        socket.send(packet);

                    }

                } catch(UnknownHostException e) {
                    Log.e("VS", "UnknownHostException");
                } catch (IOException e) {
                    Log.e("VS", "IOException");
                }

            }

        });
        streamThread.start();
     }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

the reciever:
    public class MainActivity extends ActionBarActivity {
    private Button receiveButton,stopButton;

    public static DatagramSocket socket;
    private AudioTrack speaker;

    //Audio Configuration.
    private int sampleRate = 16000;      //How much will be ideal?
    private int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
    private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;

    private boolean status = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        receiveButton = (Button) findViewById (R.id.recieve);
        stopButton = (Button) findViewById (R.id.stop);
        stopButton.setOnClickListener(new View.OnClickListener() {
            @Override
                public void onClick(View v) {
                status = false;
                speaker.release();
                Log.d("VR","Speaker released");

                }
            });
        receiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
                public void onClick(View v) {
                 status = true;
                    startReceiving();

                }
            });
    }
    public void startReceiving() {

        Thread receiveThread = new Thread (new Runnable() {

            @Override
            public void run() {

                try {

                    DatagramSocket socket = new DatagramSocket(50005);
                    Log.d("VR", "Socket Created");

                    byte[] buffer = new byte[256];

                    //minimum buffer size. need to be careful. might cause problems. try setting manually if any problems faced
                    int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);

                    speaker = new AudioTrack(AudioManager.STREAM_MUSIC,sampleRate,channelConfig,audioFormat,minBufSize,AudioTrack.MODE_STREAM);

                    speaker.play();

                    while(status == true) {
                        try {

                            DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
                            socket.receive(packet);
                            Log.d("VR", "Packet Received");

                            //reading content from packet
                            buffer=packet.getData();
                            Log.d("VR", "Packet data read into buffer");

                            //sending data to the Audiotrack obj i.e. speaker
                            speaker.write(buffer, 0, minBufSize);
                            Log.d("VR", "Writing buffer content to speaker");

                        } catch(IOException e) {
                            Log.e("VR","IOException");
                        }
                    }

                } catch (SocketException e) {
                    Log.e("VR", "SocketException");
                }

            }

        });
        receiveThread.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

and here is the Logcat

12-09 09:13:37.829: E/Trace(609): error opening trace file: No such file or directory (2)
  12-09 09:13:38.890: I/Choreographer(609): Skipped 46 frames!  The application may be doing too much work on its main thread.
  12-09 09:13:38.900: D/gralloc_goldfish(609): Emulator without GPU emulation detected.
  12-09 09:13:39.070: I/Choreographer(609): Skipped 59 frames!  The application may be doing too much work on its main thread.
  12-09 09:13:57.070: D/VS(609): Socket Created
  12-09 09:13:57.101: D/VS(609): Buffer created of size 4096
  12-09 09:13:57.101: D/VS(609): Address retrieved
  12-09 09:13:57.130: E/AudioRecord(609): Unsupported configuration: sampleRate 16000, format 1, channelCount 1
  12-09 09:13:57.130: E/AudioRecord-JNI(609): Error creating AudioRecord instance: initialization check failed.
  12-09 09:13:57.140: E/AudioRecord-Java(609): [ android.media.AudioRecord ] Error code -20 when initializing native AudioRecord object.
  12-09 09:13:57.140: D/VS(609): Recorder initialized
  12-09 09:13:57.180: W/dalvikvm(609): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
  12-09 09:13:57.180: E/AndroidRuntime(609): FATAL EXCEPTION: Thread-69
  12-09 09:13:57.180: E/AndroidRuntime(609): java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.
  12-09 09:13:57.180: E/AndroidRuntime(609):  at android.media.AudioRecord.startRecording(AudioRecord.java:515)
  12-09 09:13:57.180: E/AndroidRuntime(609):  at com.example.voicesenderactivity.MainActivity$3.run(MainActivity.java:91)
  12-09 09:13:57.180: E/AndroidRuntime(609):  at java.lang.Thread.run(Thread.java:856)
  12-09 09:13:57.400: D/dalvikvm(609): GC_CONCURRENT freed 191K, 5% free 6239K/6535K, paused 15ms+4ms, total 248ms
  12-09 09:13:57.590: W/IInputConnectionWrapper(609): showStatusIcon on inactive InputConnection
  12-09 09:13:58.300: I/Choreographer(609): Skipped 53 frames!  The application may be doing too much work on its main thread.


text:
Q: SQL Trigger that creates new table when a new record is added to current table It's been quite a few years since I have done DB work.  I am working through mysql workbench (using MS Access as a frontend).
I have a base table that I am multilinking (basically a name index type of thing). Through a form, the table is updated (a record added) and I want that new record to trigger an event that creates a table and that table is named based on what the user inputted in the form/record.
Any thoughts on how to do this?  Good tutorial/documentation that you would recommend reading?
Thanks!

A: First things first
this would you use, to create special table per id Name and table you have to add
DELIMITER $$

CREATE TRIGGER after_table_insert
AFTER INSERT
ON tabl1 FOR EACH ROW
BEGIN
    SET @sql = CONCAR("CREATE TABLE table_",NEW.name,"_",NEW.ID, " (id INT,name TEXT)");
    PREPARE stmt1 FROM @sql;
    EXECUTE stmt1;
    DEALLOCATE PREPARE stmt1;
END$$

DELIMITER ;

If you had a table for all
CREATE TABLE Table1_companion
( id BIGINT AUTO_INCREMENT PRIMARY KEy
, Refid  INTEGER
,col1 TEXT
,col2 TEXT
,FOREIGN KEY (Refid) REFERENCES tavle1(id));

So you have
SELECT t1.*,t2.* FROM table1 t1 INNER JOIN Table1_companion t2 ON t1.id = t2.Refid;

And when you have a n:m Relationship
You need two tables
CREATE TABLE Table1_companion
( tc_id BIGINT AUTO_INCREMENT PRIMARY KEy
,col1 TEXT
,col2 TEXT);

CREATE TABLE Table1_relation
(
, Ref_id  INTEGER
, Ref_tc_id   BIGINT
,FOREIGN KEY (Ref_id) REFERENCES table1(id)
,FOREIGN KEY (Ref_tc_id) REFERENCES Table1_companion(tc_id ));

Of course you need two joins for that.
You could take a look at normalization.
With that you have a relational database, that works with every rdms.
this is of course only a basic idea,  you must have your own datatypes and foreign keys need of both sides the same datatype, and always remember have every information only once in  your database


text:
Q: Hyperledger Fabric Smart Contract with private data works in vscode but not in external app. How can I write data to multiple implicit collections? Summary: An external app can submit a transaction that writes to a single implicit private collection but fails when writing to 2 implicit collections. Everything works OK when using the vscode blockchain extension instead of the external app.
Details:
I am using the vscode blockchain extension (v2.0.8) When used, it installs microfab version 0.0.11.
I am using a 2-org network created in the vscode extension using the 2-org template.
I have a Smart Contract that writes data to 2 implicit private collections (for Org1 and Org2).
Here is the relevant portion of the smart contract (typescript):
    @Transaction()
    public async createMyPrivateAsset(ctx: Context, myPrivateAssetId: string): Promise<void> {
        const exists: boolean = await this.myPrivateAssetExists(ctx, myPrivateAssetId);
        if (exists) {
            throw new Error(`The asset my private asset ${myPrivateAssetId} already exists`);
        }

        const privateAsset: MyPrivateAsset = new MyPrivateAsset();

        const transientData: Map<string, Uint8Array> = ctx.stub.getTransient();
        if (transientData.size === 0 || !transientData.has('privateValue')) {
            throw new Error('The privateValue key was not specified in transient data. Please try again.');
        }
        privateAsset.privateValue = transientData.get('privateValue').toString();

        const collectionName: string = await getCollectionName(ctx, ctx.clientIdentity.getMSPID());
        await ctx.stub.putPrivateData(collectionName, myPrivateAssetId, Buffer.from(JSON.stringify(privateAsset)));
    }

    @Transaction()
    public async createMyPrivateAssetMultiple(ctx: Context, myPrivateAssetId: string): Promise<void> {
        const exists: boolean = await this.myPrivateAssetExists(ctx, myPrivateAssetId);
        if (exists) {
            throw new Error(`The asset my private asset ${myPrivateAssetId} already exists`);
        }

        const privateAsset: MyPrivateAsset = new MyPrivateAsset();

        const transientData: Map<string, Uint8Array> = ctx.stub.getTransient();
        if (transientData.size === 0 || !transientData.has('privateValue')) {
            throw new Error('The privateValue key was not specified in transient data. Please try again.');
        }
        privateAsset.privateValue = transientData.get('privateValue').toString();

        for (const mspid of ['Org1MSP', 'Org2MSP']) {
            var collectionName: string = await getCollectionName(ctx, mspid);
            await ctx.stub.putPrivateData(collectionName, myPrivateAssetId, Buffer.from(JSON.stringify(privateAsset)));
        }
    }

    @Transaction(false)
    @Returns('MyPrivateAsset')
    public async readMyPrivateAsset(ctx: Context, myPrivateAssetId: string): Promise<string> {
        const exists: boolean = await this.myPrivateAssetExists(ctx, myPrivateAssetId);
        if (!exists) {
            throw new Error(`The asset my private asset ${myPrivateAssetId} does not exist`);
        }

        let privateDataString: string;

        const collectionName: string = await getCollectionName(ctx, ctx.clientIdentity.getMSPID());
        const privateData: Uint8Array = await ctx.stub.getPrivateData(collectionName, myPrivateAssetId);

        privateDataString = JSON.parse(privateData.toString());
        return privateDataString;
    }

createMyPrivateAsset writes to a single implicit collection: everything OK.
createMyPrivateAssetMultiple writes to 2 implicit collections: fails in external app.
Both transactions work perfectly when I use the vscode Transaction View to submit transactions.
For createMyPrivateAssetMultiple, I submit using the Org1 gateway and then call readMyPrivateAsset using the Org1 gateway and also using the Org2 gateway and the private data is returned correctly.
Now, when I use an external app, the transaction createMyPrivateAsset works but createMyPrivateAssetMultiple does not.
Here is the relevant portion of the app (typescript):
    // connection
    const gateway: Gateway = new Gateway();
    const connectionProfilePath: string = path.resolve(__dirname, '..', connectionFile);
    const connectionProfile = JSON.parse(fs.readFileSync(connectionProfilePath, 'utf8'));
    const connectionOptions: GatewayOptions = { wallet, identity: identity, discovery: { enabled: true, asLocalhost: true } };
    await gateway.connect(connectionProfile, connectionOptions);

    // Get the network (channel) our contract is deployed to.
    const network = await gateway.getNetwork('mychannel');

    // Get the contract from the network.
    const contract = network.getContract('private-contract');

Here is the transaction submission for createMyPrivateAsset
      let transientData = {
        'privateValue': Buffer.from(`Private value for asset ${assetId}`)
      };
      const trans:Transaction = contract.createTransaction('createMyPrivateAsset');
      const buffer: Buffer = await trans.setTransient(transientData).submit(assetId);

This works fine in the app.
Here is the code for createMyPrivateAssetMultiple
      let transientData = {
        'privateValue': Buffer.from(`Private value for asset ${assetId}`)
      };
      const trans:Transaction = contract.createTransaction('createMyPrivateAssetMultiple');
      const buffer: Buffer = await trans.setTransient(transientData).submit(assetId);

For this transaction, the app throws this (using Org1 gateway):
2022-06-07T13:21:50.727Z - warn: [TransactionEventHandler]: strategyFail: commit failure for transaction "4e9921b590a361ae01bba673e1d3d204d106522780c820055cec0345e1e67e6f": TransactionError: Commit of transaction 4e9921b590a361ae01bba673e1d3d204d106522780c820055cec0345e1e67e6f failed on peer org1peer-api.127-0-0-1.nip.io:8084 with status ENDORSEMENT_POLICY_FAILURE

The microfab docker container log includes this:
> WARN 0ff Failed fetching private data from remote peers for dig2src:[map[{b16526e4cd2ac3f431103cda23a6f64adc12acab0550eff18c1f25f1cc0d8bc1 private-contract _implicit_org_Org2MSP 6 0}:[]]], err: Empty membership channel=mychannel
...
[        org2peer] 2022-06-07 13:22:50.794 UTC [gossip.privdata] RetrievePvtdata -> WARN 220 Could not fetch all 1 eligible collection private write sets for block [20] (0 from local cache, 0 from transient store, 0 from other peers). Will commit block with missing private write sets:[txID: 4e9921b590a361ae01bba673e1d3d204d106522780c820055cec0345e1e67e6f, seq: 0, namespace: private-contract, collection: _implicit_org_Org2MSP, hash: 3e0f263d2edcfaf29df346504a40fdbadce0807938f204fe3e6bf753b751d9a3

Also, package.json includes this:
  "dependencies": {
    "fabric-network": "~2.1.0"
  },

Can anyone shed light on this problem?

A: You should definitely be using fabric-network@2.2.x, not 2.1.x.
I suspect what is happening is the VS Code client is not using service discovery and sending proposals for endorsement to all network peers, whereas the standalone client application is using service discovery by default and only sending proposals to orgs required by the chaincode endorsement policy. To get it to consider the collection endorsement policy you would need to add a chaincode interest to the Contract object before submitting transactions:
https://hyperledger.github.io/fabric-sdk-node/release-2.2/module-fabric-network.Contract.html#addDiscoveryInterest
There is a working example of this in the Fabric samples:
https://github.com/hyperledger/fabric-samples/blob/8ca50df4ffec311e59451c2a7ebe210d9e6f0004/asset-transfer-private-data/application-javascript/app.js#L166-L178
Alternatively you could either:

*

*Disable service discovery in the Gateway connection options.

*Explicitly set the endorsing orgs for a given transaction invocation:
https://hyperledger.github.io/fabric-sdk-node/release-2.2/module-fabric-network.Transaction.html#setEndorsingOrganizations
In general it's much better to be using service discovery so I would not recommend option 1.
The best approach would actually be to use Fabric v2.4+ and the Fabric Gateway client API:
https://hyperledger.github.io/fabric-gateway/
With this API the client (generally) does not need to worry about the organizations required for endorsement when using private data collections or state-/key-based endorsement policies. Things just work automagically.


text:
Q: Plotting a cycloid does not output a plot This is my first time  evaluating Mathematica to study differential geometry (Curves and Geometry by Alfred Gray) before I consider buying the Mathematica cloud version. I simply wish to plot a cycloid
cycloid[a_,b_][t_] := {a t - b Sin[t], a - b Cos[t]};
α = cycloid[1, 1];
ParametricPlot[α[t], {t, -3 π, 3 π},
  PlotRange->{{-3 π, 3 π} {-2, 4}}, Ticks -> None]

However, it outputs a blank as shown

A: Try this particular set first:
a = 2; b = 1; cycloid[ t_] := {a  t - b Sin[t], a - b Cos[t]};
ParametricPlot[
  cycloid[t], {t, -3 π, 3 π}, PlotRange -> All,
  GridLines -> Automatic, PlotStyle -> {Thick, Red},
  AspectRatio -> 0.2
]


text:
Q: airflow - how to set the time on the web ui's tree view to UTC? I'm starting out with apache airflow and have a DAG up and running.
Now I'm using the web ui to monitor the DAG runs and I cannot understand the time shown on the tree view page. This image illustrates my situation:

I don't understand the time axis shown on marker (3) on the image. The ui's time seems to be in UTC, as shown on marker (1). The selected interval is set to 2017-07-11 12:06:25 as shown on marker (2). The DAG runs depicted on the image have executed at around 11h 12h, so I cannot understand why it says 07PM on the temporal axis in the UI (marker 3). Is this expected behavior? Is the UI picking up another time zone for the diagram?
Apart from this everything seems to be working OK.

A: Even though airflow is a very useful and highly customizable due to nature of written fully in python; the same thing was an issue I have been struggling with.
Unfotunately Airflow Web UI is only cpable of using UTC time. It is been indicated on their official documentation too.
In, https://airflow.apache.org/timezone.html you'll find

Please note that the Web UI currently only runs in UTC.

Probably a custom implementation is required to do that.
I will post here when this feature is added or if I would find a solution.


text:
Q: Is the attraction between two magnets stronger than a magnet and metal? I can imagine that it's stronger but what are the mechanisms in place that make this happen? And how much stronger?

A: Thinkable are three scenarios.

*

*You use two identical permanent magnets. The attraction between them is stronger than that between a magnet and a magnetisable metal.
The reason for this is that the additional magnetic field of the magnetized metal comes from the alignment of the electrons or protons with their magnetic dipole moment to the applied magnetic field. These electrons have their own orientation equilibrium and the magnet cannot align the same amount of electrons in the metal as the magnet.

*You use two permanent magnets of different strength. The attraction of the stronger magnet and the metal could be greater than between the two magnets.
The explanation is basically the same as in case 1. The orientation of additional electrons inside the smaller magnet could be less than the induces re-orientation of electrons in the metal.

*The force of attraction between a permanent magnet and a metal is stronger than between two permanent magnets.
The crystalline metal structure is small in parts obtained by rapid cooling. The magnetic domains in such a metal developed poorly. This gives the probability of aligning many electrons in the metal, and this could end in a chain reaction of self-inductance; the metal transforms into a strong permanent magnet.
Normally the metal is not a compound with rare earths, unlike the permanent magnets. Then the electron configuration of the metal does not lead to such a strong magnetic field as with permanent magnets.


text:
Q: Advice on setting up new TreeView Data Type I would like some advice and or tips on how to go about setting up a new Object Class for a TreeView using the TreeView's Node.Data property.
I know how to create a basic Object type that can write/read from the .Data property, I do something like this:
type
  TMyData = class(TComponent)
  private
    FString1: String;
    FString2: String;
    FInteger1: Integer;
  published
    property String1: String read FString1 write FString1;
    property String2: String read FString2 write FString2;
    property Integer1: Integer read FInteger1 write FInteger1;
  end;

To write a value to one of the properties Node.Data property:
TMyData(TreeView1.Selected.Data).String1:= 'save this String';

To read a value:
ShowMessage(TMyData(TreeView1.Selected.Data).String1);

Thats a pretty basic example of assigning Data to a Tree Node, Now this is where I need the help and advice, tips etc...
From my example above, you can easily read/write standard properties such as String, Integer, Boolean etc. What about including and reading/writing to and from say a TListBox or TListView?
Instead of writing standard data to a Tree Node, how about adding items to that TListView and writing the contents of that TListView to the TreeView Node.
What if when clicking on one of the Tree Nodes, instead of returning a string, it could populate that TListView with Items and Images that were saved to earlier.
(1) This is the main form where you can add the Nodes to the TreeView. I actually use a more enhanced function to add to my TreeView, like so:
function AddMyDataNode(ATreeView: TTreeView; NodeName: String; NodeImage: Integer;
    String1, String2: String; Integer1: Integer;
    SelectNode: Boolean): TTreeNode;
var
  Obj: TMyData;
  Node: TTreeNode;
begin
  Result:= nil;

  Obj:= TMyData.Create(nil);
  try
    Obj.String1:= String1;
    Obj.String2:= String2;
    Obj.Integer1:= Integer1;

    Node:= ATreeView.Items.AddObject(ATreeView.Selected, NodeName, Obj);
    Node.ImageIndex:= NodeImage;
    Node.SelectedIndex:= NodeImage;

    Result:= Node;

    if SelectNode then
      Node.Selected:= True;

    ATreeView.SetFocus;
  except on E: Exception do
    ShowMessage('Could not add MyData Node: ' + E.Message);
  end;
end;

Editing a Node will show another form called the Data Form...:
(2) This Data Form is where the data from the Node on the Main Form is read/written. With an addition of a TListView. The ListView should also be read/saved with the standard properties too.
Adding/Editing a ListView item may include other standard properties, such as:
(3) The values on this form are saved into the ListView data.
So in a nutshell:

*

*The TreeView Node.Data stores
standard properties and also a
TListView.

*This Data is show on another form
called Data Form.

*The ListView on the Data Form also
has data.

*Editing the ListView on the Data Form
will show an additional Form with
standard properties.

I would like to know how I could best approach this, what tips could you provide, what is the easiest way to achieve something like this etc?
Writing/Reading to and from the ListView is easily implemented I imagine in that it can be done by accessing the ListView Items.Item[x].Data property. Getting the ListView Data to store with the TreeView is the problem, I don't know how I could implement this type of behaviour.
I would like to know advice on things like how I could define the Types etc.
I look forward to hearing your ideas on this.

A: I think your confusion is thinking of storing Visual Forms and components including their data. I believe you can do this with the the streaming system - although I never have! I like to keep the data and the visuals as separate as possible.
So you need a custom list to put in MyData that contains all the data and settings that need to go in the listview something like MyDataList: (I'm typing this straight in!)
type

TMyDataViewData = class(TPersistent)
  Caption: string;
  ImageIndex: Integer;
  StateIndex: Integer;
  Group: Integer;
  MemoData: TStrings;
end;

TMyDataViewDataList = class(TPersistent)
  TheList: TObjectList;
  property Items[Index:Integer]:MyDataViewData read getItems write SetItems;
  property Count: Integer read GetCount;
  .
  .
  .
end;

  TMyData = class(TComponent)
  private
    FString1: String;
    FString2: String;
    FInteger1: Integer;
  private
    MyForm: TMyEditform;
  published
    procedure Edit(Owner: TComponent);
    property String1: String read FString1 write FString1;
    property String2: String read FString2 write FString2;
    property Integer1: Integer read FInteger1 write FInteger1;
    property TheDataList: TMyDataViewDataList read fTheDataList write fTheDataList;
end;

procedure TMyData.Edit;
var
  F: TMyEditForm;
begin
  F:= TMyEditForm.create(Owner);
  F.DataList := TheDatalist;  // data for listview and memos
  F.ShowModal;
  .
  .
  .
end;

Then in your Treeview you only need to do:
  If TreeNode.Data is TMyData then
    TMyData(TreeNode.Data).Edit(Self);

After the edit all the data for changing the treeview node info should be in MyData
   so you can do
  Node.Text := TMyData(Node.Data).TheDataList.Items[0].Caption;

or
for i := 0 to TMyData(Node.data).TheDataList.Count do
    Node.AddChild(TMyData(Node.Data).TheDataList.Items[i].Caption);

You can also easily expose properties of the Datalist to TMyData directly :)
and such like. Probably a few syntax error in there!

A: I don't see any problems with your approach. You can let your data object contain a list of objects (I don't know why you inherit from TComponent in a class that has nothing to with visual components):
TMyData = class
private
  FString  : String;
  FInteger : Integer;
  FItems   : TList <TItem>   // where TItem is your custom object class
public
  // ... properties ...
end;

This list is then displayed in the list box:
 for Item in MyData.Items do
   ListBox.Items.AddObject (Item.ToString, Item);

If you edit one of the items, you do the same thing: get the object out of the list box's data and pass it on to the next form.
Hope that helps.


text:
Q: how to fix Error: java.lang.ClassNotFoundException on frida I'm trying to bypass a root detection mechanism on an android app using Frida, I've tried so many different scripts (frida code share) and different approaches (like hiding root) with no luck!
So I tried to locate the class and method responsible for checking if the device is rooted or not and changing it's return value.
This is my script :
setTimeout(function() { // avoid java.lang.ClassNotFoundException
  Java.perform(function() {
    var hook = Java.use("app.name.RootUtils");
    console.log("info: hooking target class");

    hook.isRooted.overload().implementation = function() {
      console.log("info: entered target method");
      return Java.use("java.lang.Boolean").$new(false);
    }
  });
},0);

If I inject this code normally it won't work because it looks like the isRooted method will get called before it
If I use spawn to run the app and change this method return value it fails with error :

frida.core.RPCException: Error: java.lang.ClassNotFoundException: Didn't find class ...

I've also tried spawning the app and then using objection to run "android root disable" but it will return this error :

frida.core.RPCException: TypeError: cannot read property 'getApplicationContext' of null
at getApplicationContext (src/android/lib/libjava.ts:21)

I'm not sure if this is a problem with Frida or my system or ...
I think if I was able to make my main code runs at exactly after the class gets loaded (like using a loop to check or using a hook) the problem would be fixed but I don't know how to write that kind of code in js for frida.
I'm on macOS 11.5.1 using python 3.9 and installed latest version of frida and objection
I've tested on one rooted phone with android 10 and an emulator with android 6

A: I was able to solve this issue with a simple yet not very technical solution.
I used a setInteval to run my hooking over and over until it gets to work, (as @Robert mentioned, I also needed to wrap hooking inside a try catch to prevent the code from stoping after first try)
This may not work for everyone but since it worked for me I will post the final code, may it helps someone else in the future :)
Java.perform(function() {
  var it = setInterval(function(){
    try{
      var hook = Java.use("app.name.RootUtils");
      console.log("info: hooking target class");

      hook.isRooted.overload().implementation = function() {
        console.log("info: entered target method");
        clearInterval(it);
        return Java.use("java.lang.Boolean").$new(false);
      }
    } catch(e) {
      console.log("failed!");
    }
  },200); // runs every 200milisecods
});

PS : you may need to change interval time to match your app needs, it worked for me with 200 miliseconds.

A: Sometimes app would do encryptions in its class loader, you may need to replace Java.classFactory.loader with the app's customized class loader in order to make Java.use function properly.
Here's how it's done:
Java.perform(function() {

    //get real classloader
    //from http://www.lixiaopeng.top/article/63.html
    var application = Java.use("android.app.Application");
    var classloader;
    application.attach.overload('android.content.Context')
        .implementation = function(context) {
            var result = this.attach(context); // run attach as it is
            classloader = context.getClassLoader(); // get real classloader
            Java.classFactory.loader = classloader;
        return result;
    }

    //interesting classes
    const interestingClassPath = "com.myApp.SometingInteresting";
    interestingClass = Java.use(interestingClassPath);

   //do whatever you like here
})

A: Class not found
How do you know the class is app.name.RootUtils have you decompiled to app using Jadx or apktool? How about the method where RootUtils.isRooted() is called? Is there any special code that loads the RootUtils class e.g. from a non-standard dex file included in the app? If the class is loaded from a special dex file you could hook this dex loading mechanism and first execute it and then install your hook for RootUtils.isRooted().
Alternatively assuming RootUtils.isRooted() is called only from one other method and does not use special code for loading the RootUtils class you could hook that method and use the this hook to install install your RootUtils.isRooted() hook.
Error handling
The correct way to handle errors in JavaScript is using try catch block, not the setTimeout function:
Java.perform(() => {
    try {
        var hook = Java.use("app.name.RootUtils");
        ...
    } catch (e) {
        console.log("Failed to hook root detection" + e);
    }
}

Regarding your problems hooking the class


text:
Q: Running microphone signal through stereo jack I've recently mounted a 3.5mm connector onto a walkie talkie, so that I can plug in a headset. It works really well, though I've had the idea that since it's a stereo jack and the singal is mono, I could use the second connector pin to run signal from microphone to the walkie talkie. I'm not sure how though. Would connecting the microphone's output to one of the microphone contacts on the walkie talkie be enough? If so should it be + or - ? How do electronics usually handle electret microphones?
Do send a constant current to one pin and use the second as output (treat the mic as a switch) or is it different?
Thanks for any suggestions.
PS: just to clear any confusion I've already attached the microphone output to the stereo jack, I just need to figure out how to attach it to the walkie talkie

A: Find the existing wiring to the walkie-talkie internal microphone and wire it through your added 3.5mm connector. Most of those 3.5mm connectors have "closed circuit" switches which will connect the radio's internal microphone to the radio circuit except when you plug in your headset.

A: Padding...  This should work for you:


text:
Q: Passing Argument to MATLAB Function in Python Results in Error: Size inputs must be numeric I'm currently working on a python script that passes an argument to a function getWeight.m written in MATLAB.
getWeight.m returns a weight matrix with the same dimensions given the size of an RGB image. It's source code can be found here.
I'm running the following python script:
import matlab.engine
eng = matlab.engine.start_matlab()

import cv2

image = cv2.imread('warped_image.png')

weight = eng.getWeight(image.shape) # (575, 503, 3)
print(weight)

Passing image.shape of class tuple as an argument to the function yields the following error:
Size inputs must be numeric
Are there any workarounds to this error?
Here's the error after following @Chris method:
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    weight = eng.getWeight(matlab.int8(list(image.shape))
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matlab/
mlarray.py", line 106, in __init__
    raise ex
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matlab/
mlarray.py", line 104, in __init__
    super(int8, self).__init__('b', initializer, size, is_complex)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matlab/
_internal/mlarray_sequence.py", line 57, in __init__
    self._data = flat(self, initializer, init_dims, typecode)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matlab/
_internal/mlarray_sequence.py", line 338, in flat
    return array.array(typecode, nested_list)
OverflowError: signed char is greater than maximum

A: Check out how matlab converts python types: https://www.mathworks.com/help/matlab/matlab_external/pass-data-to-matlab-from-python.html
A python tuple will be converted to a matlab cell array, so in your getWeight function when you access the indeces with size(3) you're selecting a cell rather than the value of the cell.
You can change your getWeight function to pull out the values of the cells (e.g., size{3}) and it should work. If this function is used in many other places you may want to add some checks within getWeight to see if size is a normal array (when it should use size(3)) vs a cell array.
You could also change the input to accept integers instead, e.g., getWeight(s1,s2,s3) and then call it with eng.getWeight(image.shape[0],image.shape[1],image.shape[2]). But again, if getWeight is used elsewhere you'll have to refactor every call.
Finally, you could try converting the tuple to a "matlab numeric array object" and then passing that array to getWeight. See the documentation here for how to create a matlab array in python: https://www.mathworks.com/help/matlab/matlab_external/matlab-arrays-as-python-variables.html I don't have matlab on my present computer, but I believe the following code would work:
import matlab.engine

eng = matlab.engine.start_matlab()

import cv2

image = cv2.imread('warped_image.png')

weight = eng.getWeight(matlab.int8(image.shape))
print(weight)

The examples of creating the matlab arrays in the matlab documentation all use lists (for example A = matlab.int8([1,2,3,4,5])), so you may need to convert that image.shape tuple to a list, but I suspect the tuple will work...


text:
Q: Mandelbrot's Coastline Paradox Formula I was reading Benoit Mandelbrot's paper on the coastline paradox, where he lays out a formula for determining the length of a coastline/border/self-similar curve:
L(G)=F*G1-D
Where G represents the length of the segments used to measure the coastline, D represents the Hausdorff Dimension of the shape/coastline being measured, and F represents a "positive constant prefactor".
My question is, what is constant that F represents, and how can I find it? Mandelbrot doesn't seem to elaborate on this, and nowhere on the web that I've found explains what F represents.


text:
Q: How to convert 70dpi image to 300dpi? I am developing a PHP app where user will create the image using front end tools.
After user finish creating image he/she will upload to server.
But the image comes to server is only 70dpi.
I have to convert it to 300dpi image.
Is it possible with php script to do?
Or there is another php web server solution to this?
Please help me...........
I have tried this code....
$image = new Imagick('source.jpg');
$image->setImageResolution(300,300);
$image->resampleImage(300,300,Imagick::FILTER_UNDEFINED,1);
$image->writeImage('out.jpg');

but no output...no result at all.

A: Using PHP's Imagick class, you can increase the dpi from 70 to 300 by setting resolution & resample the image.
<?php

$image = new Imagick('source.jpg');
$image->setImageResolution(300,300);
$image->resampleImage(300,300,Imagick::FILTER_UNDEFINED,1);
$image->writeImage('out.jpg');

Although, sampling-up may not increase image quality.

A: The answers by @emcconville works.
Try to cache the data in php buffers and then print it.


text:
Q: First and last sortable items don't consistently move out of the way in jQuery UI Sortable In a Web app I'm writing, users can add their own customized buttons to a control panel and then change the order of those buttons via drag-and-drop. I'm using jQuery UI's Sortable Widget to make the magic happen.
The buttons are arranged in a single row, left to right. I'm using flexbox to style them, and I've set the sortable method to allow movement only along the X axis. Everything is working well for the most part, BUT…

*

*Sometimes when I drag a button all the way to the beginning of
the row, the leftmost button won't move out of the way to make space
for it.

*The same thing happens, sometimes, when the row has filled up with
buttons and I try to drag a button all the way to the end of the row. (The rightmost button won't budge.)

At first, I couldn't figure out why the buttons at the far left and right sometimes behaved as desired and sometimes didn't. Eventually I realized it all depended on where I grabbed the button I was dragging. The JSFiddle I've set up illustrates the problem:
https://jsfiddle.net/DanRobinson/8nap51Lg/78/
In the Fiddle, if you grab the middle button close to its left edge, you can successfully drag it to the beginning of the row, but not to the end of the row. Conversely, if you grab that same button close to its right edge, you can drag it to the end of the row, but not to the beginning.
I want the buttons to behave consistently no matter where the user happens to grab them. Is there a setting in the Sortable Widget that will solve this problem? (Changing the "tolerance" setting to "pointer" doesn't seem to help.)
HTML:

Custom Button 1

Custom Button 2 is wider than the others

Custom Button 3

CSS:
#container {
    display: flex;
    flex-direction: row;
    padding: 10px;
    border: 1px solid black;
    margin-top: 20px;
    width: 600px;
}

#container > div {
    flex: 0 1 auto;
    padding: 2px 8px;
    margin: 0 5px;
    border: 1px solid #777;
    border-radius: 3px;
    background-color: #E1E1E1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    cursor: default;
}

Javascript:
$(document).ready(function () {

    $("#container").sortable({
        axis: "x",
        containment: "parent",
    });

});

A: $(document).ready(function () {
    $("#container").sortable({
        axis: "x",
        containment: "parent",
        start: function(e, ui) {
            // get the instance of the sortable.
            // instance method is new to jquery ui 1.11, for previous versions
            // you can use $(this).data()['ui-sortable'];
            var sort = $(this).sortable('instance');
            // this makes the placeholder fit with the row that's being dragged
            ui.placeholder.height(ui.helper.height());
            // containment property of the sortable instance is not the same
            // as the containment option. The property is calculated
            // from the option. You need to adjust bottom coordinates
            // to take into account the row you just removed from it and the click offset.
            sort.containment[3] += ui.helper.height() * 1.5 - sort.offset.click.top;
            // Since your handle is centered, and pointer coordinates are used
            // for sortable, but top coordinates are used for containment
            // you can have issues with top row. Adjusting with the click offset
            // will resolve the issue.
            sort.containment[1] -= sort.offset.click.top;
        },
        helper: function(e, row) {
            // From http://www.paulund.co.uk/fixed-width-sortable-tables.
            // Sets the width of each cell to be its original width.
            // This reverts the default`enter code here` behaviour of the row collapsing into a narrower stub when being dragged.
            row.children().each(function() {
              $(this).width($(this).width());
            });
            return row;
        }
    });
});


text:
Q: can we write mongodb crud queries and aggregate query together? In MongoDB can we execute below written query?
db.dbaname.find(userName:"abc").aggregate([])

else is there any other way we can execute CRUD and aggregate query together.

A: Short answer - No you can't do this : .find(userName:"abc").aggregate([])
aggregation-pipeline is heavily used for reads which is mostly similar to .find() but capable of executing complex queries with help of it's multiple stages & many aggregation-operators. there are only two stages in aggregation $out & $merge that can perform writes to database - these stages are not that much used compared to other stages & needs to be used only when needed & as they need to be last stages in aggregation pipeline, then all the previous stages are to be tested very well. So when it comes to CRUD eliminating CUD you'll benefit over R - Reads.
Same .find(userName:"abc") can be written as :
.aggregate( [ { $match : { userName:"abc"} } ] ) // Using `$match` stage


text:
Q: Recognize and use Hardware RAID 5 Should I abandon this setup altogether and just use software RAID?
I am running 20.04 LTS on a SSD and have 3 1TB drives setup with a RAID 5 array through Asus/AMD RAIDXpert.
I can see all the drives in gparted and lshw -C disk shows
      *-disk:0
       description: ATA Disk
       product: KINGSTON SV300S3
       physical id: 0
       bus info: scsi@1:0.0.0
       logical name: /dev/sda
       version: BBF0
       serial: 50026B7746002607
       size: 111GiB (120GB)
       capabilities: partitioned partitioned:dos
       configuration: ansiversion=5 logicalsectorsize=512 sectorsize=512 signature=f76fefc9
  *-disk:1
       description: ATA Disk
       product: WDC WD10EZEX-00B
       vendor: Western Digital
       physical id: 1
       bus info: scsi@2:0.0.0
       logical name: /dev/sdb
       version: 1A01
       serial: WD-WCC3FL8EZ2YN
       size: 931GiB (1TB)
       configuration: ansiversion=5 logicalsectorsize=512 sectorsize=4096
  *-disk:2
       description: ATA Disk
       product: WDC WD10EZEX-00B
       vendor: Western Digital
       physical id: 2
       bus info: scsi@4:0.0.0
       logical name: /dev/sdc
       version: 1A01
       serial: WD-WCC3FKE06EZ4
       size: 931GiB (1TB)
       configuration: ansiversion=5 logicalsectorsize=512 sectorsize=4096
  *-disk:3
       description: ATA Disk
       product: WDC WD10EZEX-00B
       vendor: Western Digital
       physical id: 3
       bus info: scsi@5:0.0.0
       logical name: /dev/sdd
       version: 1A01
       serial: WD-WCC3FL8EZLVA
       size: 931GiB (1TB)
       configuration: ansiversion=5 logicalsectorsize=512 sectorsize=4096

Here are the images from the RAID config utility that I accessed during bootup.
LD View
LD Definition
I also saw this AMD RAIDXpert driver (rcraid) PPA and followed the instructions on the page, but am not sure what it did, if anything.
I also found this rcraid on github but this was aimed at booting from RAID. I'm booting from the SSD and trying to use hardware RAID for storage. FYI, following those instructions prevented me from booting until I reverted the changes to grub through recovery mode.

A: This is not a real hardware RAID card in that it still needs OS support and is at least partly closed source software.
You would be better off using the software RAID capabilities of Linux itself, as made available to you in the Ubuntu installer or the OS after install, or else just expose them as separate devices.


text:
Q: How can I build a list of world geo locations and their relative geographical hierarchies? I want to build a database of geographical locations and would like to be able to identify locations that fall inside other locations. For example, The Empire State Building is going to have one geo-coordinate, but my database would be able to tell me that it falls inside Manhattan, which falls inside New York City, which is in the state of New York and so forth.
I've been looking at OpenStreetMap which seems to have a pretty decent database but as best I can tell, I would need to create a set of polygon structures representing each region and then detect if a coordinate falls inside a given region's polygon. Is there a better way to do this, or is there a data source where all of this has already been calculated?

A: Try the Yahoo! GeoPlanet Data at http://developer.yahoo.com/geo/geoplanet/data/
It is already organised into a hierarchy structure, countries, admin divisions and places.
You can also extend the data by using the 'Geo' methods of the YQL API at http://developer.yahoo.com/yql/console/

A: You also may want to look into the Geonames database.  While it is not classified using hierarchical method, you could probably derive the information out of it.
If you really want to dive into building a geographical database where you can analyze the data, take a look at loading your data into the free/open-source PostgreSQL/PostGIS stack.  With that you can actually write SQL that answers questions like "show me all points [within a city/county/state boundary]" or "[within X distance from Y location]".
Good places to learn more about PostGIS is at the BostonGIS website, the GIS.StackExchange pages, or of course the manual but who reads those anymore...

A: I'm pretty sure the google maps API has regions defined as polygons. And by regions I means, State, City, Zip Code, or just about anything that could be defined as a "region"
You would have to hit-test (Google Maps might have a function for this already) a point to see if it is inside a polygon.
You could also use the lookup address by GeoLocation functions to find which region(s) a point resides in, and just use that.


text:
Q: How to get array of specific attributes values in cypress I have a few elements in DOM and each of them has its own attribute 'id'. I need to create a function which iterates throw all of these elements and pushes values into the array. And the happy end of this story will be when this function will give me this array with all 'id' values.
I have tried this:
function getModelIds() {
  let idList = [];
  let modelId;
  cy.get(someSelector).each(($el) => {
    cy.wrap($el).invoke('attr', 'id').then(lid => {
      modelId = lid;
      idList.push(modelId);
    });
  });
  return idList;
}

Will be very appreciated if you help me with rewriting this code into a function which will return an array with all 'id' values.

A: You can have a custom command:
Cypress.Commands.add(
  'getAttributes',
  {
    prevSubject: true,
  },
  (subject, attr) => {
    const attrList = [];
    cy.wrap(subject).each($el => {
      cy.wrap($el)
        .invoke('attr', attr)
        .then(lid => {
          attrList.push(lid);
        });
    });
    return cy.wrap(attrList);
  }
);

You can use it later like this:
cy.get(someSelector)
  .getAttributes('id')
  .then(ids => {
    cy.log(ids); // logs an array of strings that represent ids
  });


text:
Q: How to use and print from constructor I'm trying to create a simple card game where two players receive random cards. I have decided to use the constructor to make it simple and use less space. Can someone help me and explain how to generate random card in my main program from my Card class.
public class clsCard {

    private int value;
    private int rank, suit;
    private final int MaxFaceValue= 10;
    private static String[] suits = {"Joker","hearts","spades","diamond","clubs"};
    private static String[] ranks = {"Joker","Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};

    public clsCard(int suit, int rank)
    {
        this.rank= (int)(Math.random()*ranks.length);
        this.suit= (int)(Math.random()*suits.length);
    }

    public @Override String toString()
    {
        if(ranks[rank].equals("Joker") || suits[suit].equals("Joker"))
            return "Joker";
        else
        return ranks[rank] + " of " + suits[suit];
    }
    public int getRank()
    {
        return rank;
    }
    public int getSuit()
    {
        return suit;
    }
}

A: To start with you need all of the cards and then to randomly choose from this. You might need some basic classes to do this. This is just one way to do this - create a deck, something like:
import java.util.ArrayList;

public class Deck {

    private ArrayList cards;

    public enum Suit {Joker, Spade, Club, Heart, Diamond};

    public Deck() {
        cards = new ArrayList<Card>();

        // Add all appropriate cards
        for(int i = 1; i < 14; i++) {
            cards.add(new Card(i, Suit.Spade));
            cards.add(new Card(i, Suit.Club));
            cards.add(new Card(i, Suit.Heart));
            cards.add(new Card(i, Suit.Diamond));
        }

        cards.add(new Card(0, Suit.Joker));
        cards.add(new Card(0, Suit.Joker));

    }

    public Card dealRandomCard() {
        int random = (int)(Math.random()*cards.size());
        Card c = cards.get(random)
        cards.remove(random);
        return c;
    }

}

This is with a Card class too, expand on:
public class Card {

    public Card(int i, Suit s) {

    }

}

Then you can build from there.


text:
Q: Advanced Real Calculus - Differentiability I struggling with some problems. Thank you for any help:
This function is given : $ f(x,y)=(e^x-1)\frac y{(x^2+y^2)^\alpha}\;$ , and they ask the values of $\;\alpha\;$ for which f is can be defined in origin and is differentiable at $\;(0,0)\;$ .
I tried in (1) to check when is $\;f\;$ continuous at $\;(0,0)\;$, and so the limit must exist, so if we take for example $\;y=x\;$ and let $\;x\to 0\;$ we have
$\;(e^x-1)\frac x{2^\alpha x^{2\alpha}}\to0\;$
if $\;1-2\alpha\ge 0\implies \alpha\le\frac12\;$
and we can put $\;f(0,0)=0\;$ . But I know there can be functions continuous but not differentiable so I'm stucked because the condition above is perhaps not enough.


text:
Q: Проблема с Живой Лентой при загрузке сообщений Проблема в том, что в живой ленте - когда выбрана вкладка "Все",ограничен список загружаемых сообщения, до 19 только. (пропадает "листалка" для сообщений) При работе на других вкладках - Общение, Дела, Мое - загрузка сообщения не ограничена.
Код подключения компонента
$APPLICATION->IncludeComponent(
    "bitrix:socialnetwork.log",
    "",
    Array(
        "USER_VAR" => $arResult["ALIASES"]["user_id"],
        "GROUP_VAR" => $arResult["ALIASES"]["group_id"],
        "PAGE_VAR" => $arResult["ALIASES"]["page"],
        "PATH_TO_USER" => $arResult["PATH_TO_USER"],
        "PATH_TO_MESSAGES_CHAT" => $arResult["PATH_TO_MESSAGES_CHAT"],
        "PATH_TO_VIDEO_CALL" => $arResult["PATH_TO_VIDEO_CALL"],
        "PATH_TO_GROUP" => $arParams["PATH_TO_GROUP"],
        "PATH_TO_SMILE" => $arResult["PATH_TO_SMILE"],
        "PATH_TO_USER_BLOG_POST" => $arResult["PATH_TO_USER_BLOG_POST"],
        "PATH_TO_GROUP_BLOG_POST" => $arParams["PATH_TO_GROUP_POST"],
        "SET_NAV_CHAIN" => $arResult["SET_NAV_CHAIN"],
        "SET_TITLE" => $arResult["SET_TITLE"],
        "ITEMS_COUNT" => 999,
        "NAME_TEMPLATE" => $arParams["NAME_TEMPLATE"],
        "SHOW_LOGIN" => $arParams["SHOW_LOGIN"],
        "DATE_TIME_FORMAT" => $arResult["DATE_TIME_FORMAT"],
        "SHOW_YEAR" => $arParams["SHOW_YEAR"],
        "CACHE_TYPE" => $arParams["CACHE_TYPE"],
        "CACHE_TIME" => $arParams["CACHE_TIME"],
        "PATH_TO_CONPANY_DEPARTMENT" => $arParams["PATH_TO_CONPANY_DEPARTMENT"],
        "SHOW_EVENT_ID_FILTER" => "Y",
        "SHOW_SETTINGS_LINK" => "Y",
        "SET_LOG_CACHE" => "Y",
        "USE_COMMENTS" => "Y",
        "BLOG_ALLOW_POST_CODE" => $arParams["BLOG_ALLOW_POST_CODE"],
        "PAGER_DESC_NUMBERING" => "N",
        "AJAX_MODE" => "Y",
        "AJAX_OPTION_SHADOW" => "N",
        "AJAX_OPTION_HISTORY" => "N",
        "AJAX_OPTION_JUMP" => "N",
        "AJAX_OPTION_STYLE" => "Y",
        "CONTAINER_ID" => "log_external_container",
        "SHOW_RATING" => $arParams["SHOW_RATING"],
        "RATING_TYPE" => $arParams["RATING_TYPE"],
        "AVATAR_SIZE" => $arParams["LOG_THUMBNAIL_SIZE"],
        "AVATAR_SIZE_COMMENT" => $arParams["LOG_COMMENT_THUMBNAIL_SIZE"],
        "NEW_TEMPLATE" => $arParams["LOG_NEW_TEMPLATE"],
        "PAGE_SIZE" => 10,
        "LOG_DATE_DAYS" => 365
     ),
     $component
);

В параметрах компонента настроено кол-во выводимых сообщений 999. Подскажите, в чем дело?


text:
Q: Each child in a list should have unique key prop and my browser router is also undefined How to clear this problem.
Error in browser router
http://localhost:3000/Questions/undefined and
Each child in a list should have unique key prop.
import React from 'react'
import Questions from './Questions'

const QuestionList = ({questionsList}) => {
 return (
<>
     {
      questionsList.map((question)=>(
        <Questions question={question} key={question.id}/>
      ))
     }
</>
 )
}

I am trying to build the new component page,i am expected that new component page is created,but as the result is Each child in a list should have unique key prop and my browser router is also undefined.