text:
Q: How to restart the SHA256MigrationJob without restarting Artifactory? I keep encountering the below error message in the sha256_migration.log.  It doesn't restart after failure, however if I restart the artifactory service it begins the SHA256 migration from where it left off until it fails again.
2018-11-13 10:24:35,060 [art-exec-3] [ERROR] (o.a.s.j.m.s.Sha256MigrationJob:78) - Caught unexpected exception during SHA256 Migration job, operation will break.
org.springframework.core.task.TaskRejectedException: Executor [org.artifactory.schedule.ArtifactoryConcurrentExecutor@70a2137a] did not accept task: org.artifactory.schedule.aop.AsyncAdvice$$Lambda$654/1640835804@7dbf55d3
        at org.springframework.core.task.support.TaskExecutorAdapter.submit(TaskExecutorAdapter.java:93)
        at org.springframework.scheduling.concurrent.ConcurrentTaskExecutor.submit(ConcurrentTaskExecutor.java:143)
        at org.artifactory.schedule.aop.AsyncAdvice.submitWorkQueueTask(AsyncAdvice.java:235)
        at org.artifactory.schedule.aop.AsyncAdvice.submit(AsyncAdvice.java:217)
        at org.artifactory.schedule.aop.AsyncAdvice.executeInvocation(AsyncAdvice.java:146)
        at org.artifactory.schedule.aop.AsyncAdvice.invoke(AsyncAdvice.java:124)
        at org.artifactory.schedule.aop.AsyncAdvice.invoke(AsyncAdvice.java:62)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
        at com.sun.proxy.$Proxy144.updateSha2(Unknown Source)
        at org.artifactory.storage.jobs.migration.sha256.Sha256MigrationJob.migrationLogic(Sha256MigrationJob.java:134)
        at org.artifactory.storage.jobs.migration.MigrationJobBase.migrationLoop(MigrationJobBase.java:106)
        at org.artifactory.storage.jobs.migration.MigrationJobBase.runMigration(MigrationJobBase.java:83)
        at org.artifactory.storage.jobs.migration.MigrationJobBase.onExecute(MigrationJobBase.java:73)
        at org.artifactory.schedule.quartz.QuartzCommand.execute(QuartzCommand.java:48)
        at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
        at org.artifactory.concurrent.ArtifactoryRunnable.run(ArtifactoryRunnable.java:30)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.util.concurrent.RejectedExecutionException: Task org.artifactory.concurrent.ArtifactoryRunnable@4afb003 rejected from java.util.concurrent.ThreadPoolExecutor@33daf5aa[Running, pool size = 64, active threads = 64, queued tasks = 10000, completed tasks = 120723]
        at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
        at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
        at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
        at org.artifactory.schedule.ArtifactoryConcurrentExecutor.execute(ArtifactoryConcurrentExecutor.java:69)
        at org.springframework.core.task.support.TaskExecutorAdapter.submit(TaskExecutorAdapter.java:88)
        ... 19 common frames omitted

My artifactory.system.properties regarding sha256migration
##SHA2 Migration block
artifactory.sha2.migration.job.enabled=true
artifactory.sha2.migration.job.queue.workers=100

My setup:

*

*Cloned production instances of Artifactory infrastructure into test instance (save for IP address and DNS records).

*Ensure that DB and filestore configurations (db.properties and binarystore.xml) were updated accordingly on the cloned instances.

Things I've tried without luck:

*

*I ran the Artifactory GC couple of times.

*Increase the CPU count to 16

*Increase the RAM to 16G

*Ensure that I am running the latest Oracle Java 8u192

What I know:

*

*It keep running fine for a while until it crashes.

*When I restart artifactory service, the migration resumes and the total artifacts to migrate is lower.

*I cannot keep restarting Artifactory in production to finish the sha256migrationjob, I have over 500k artifacts.

My question:

*

*Any way method to restart the SHA256MigrationJob without restarting Artifactory?

*Is there a way to find the artifact that it has trouble migrating to SHA256?

*In the stack trace above, I feel the issue is at com.sun.proxy.$Proxy144.updateSha2(Unknown Source).

-- Workaround --
I ended up creating a new VM and installed a clean copy Artifactory 6.5.3 (with latest Oracle Java 8 Server-JRE).  In the above issue, I was doing an in-place upgrade, just in a new folder.
I moved the necessary files in the etc to the new VM; such as master.key, binarystore.xml, db.properties and etc.  I then executed the bin/installService.sh [user] [group], this creates the /etc/opt/jfrog/artifactory configuration symlink/folder move.  My filestore and artifactory database are running on different VMs, thus only Artifactory and it's file configurations needed to be ported.
The new Artifactory 6.5.3  version started up without issues.
The sha256migrationjob is actually running without any problems.  Last upgrade run I did, it worked fine without the job dying.
Notes:  I did also sanely adjust the configuration values on the queue workers.  https://www.jfrog.com/confluence/display/RTF/Checksum-Based+Storage#Checksum-BasedStorage-ConfiguringtheMigrationProcess

A: tl;dr decrease artifactory.sha2.migration.job.queue.workers to somewhere around 2 - 2 * number of cores.
What you are experiencing is an exhaustion of the ThreadPoolExecutor.
The size of the thread pool by default is 4 * [number of cores].
In your case 64 (16 cores * 4)
However the limit on the number of threads you have configured for the sha256 migration job is 100.
On an artifactory instance without any load, this will not cause any failures, because there is a queue backing up the thread pull (in your case the size is 10000).
In your case the thread pull and the queue are full.
If I understand correctly you have overcame the issue. But for other people bumping into this thread, I would recommend decreasing the value of artifactory.sha2.migration.job.queue.workers to no more than half of the thread pull number of threads.
So in your case 32: (16 * 4)/2


text:
Q: convert spanish characters in HTML doc I have a HTML file and it has some information in spanish. I am using a third party control to convert this HTML file into RTF document. The third party software I am using is Subsystems HTML Addon.
The HTML file has
<META http-equiv="Content-Type" content="text/html; charset=utf-8">

I think the subsystems software is not able to recognize the characters greater than 127.
I tried replacing the characters with ASCII>127 to their HTML entity code For ex, ò with • and then sending the document to converter but that didn't help.
Any one has any ideas?

A: The magic word is encoding. The question is what encoding your HTML file is in, and what encoding you need in your RTF file.
Here is some very good basic reading on the issue if you're interested. Otherwise, you'll have to determine the HTML files actual, and the RTF file's actual encodings.

A: Did you try just asking their technical support? The product page says it supports Arabic/Hebrew and Asian languages, so it sounds like they definitely support values above ASCII 127. It's probably an issue with getting the right encoding.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is Heroku telling me it cannot find a package.json in my module when I do a heroku push I created my own npm package from a fork of react-coverflow.  It appears to be working fine in my app locally using it this way: "npm install react-coverflow-mod" --save.
I can run my app using "run with debug (F5)" in VsCode and npm start on the client folder to start the React front end.
Then I do an npm run build on the client folder, and it works just fine.
When I do a heroku push it fails everytime with this error:

npm ERR! code ENOLOCAL
npm ERR! Could not install from "../../react-coverflow-mod"
as it does not contain a package.json file.

1. I know there is a package.json in the module because I can install it via "npm install react-coverflow-mod": https://www.npmjs.com/package/react-coverflow-mod
2.  The installed module has a package.json file in it
3. My github repo has a package.json in it:  https://github.com/leroyvaughan/react-coverflow
I'm not sure how I can fix this.  Do I need a package.json to go into the /Dist folder?  What is wrong here with Heroku.

A: It seams like heroku try to install a package from a relative path instead of the published name. That would perfectly explain why you can run locally but not on a production environment.
Open your project and search for the exact string displayed in your log: "../../react-coverflow-mod" and you should be able to find quickly where it is.
If you run on a unix system (don't know about windows) you can do a search using grep:
grep -rnw '/path/to/somewhere/' -e '../../react-coverflow-mod'

Make sure it includes your root folder which contain package.json, and might we wise to ignore node_modules which is always massive.


text:
Q: Getting all products with sql I'm trying to learn magento but I have to finish the project that I'm working on as fast as I  can. So I'm stuck in somewhere. Then I decided to use pure sql. (I know it's really messy)
So is anynone know how can I get all products with sql? I researched database but can't find.
I need product name, thumbnail, price, rating, reviews count and attributes.

A: Do it clean!
<?php

require_once 'app/Mage.php';
umask(0);
Mage::app();

$collection = Mage::getResourceModel('reports/product_collection')
    ->addAttributeToSelect('*')
    ->addStoreFilter()
    ->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());

foreach ($collection as $product) {
    // build your JSON here
}


text:
Q: How to see if a list of strings is contained (not equal) within another list of strings I have a list of strings that are set up in a date format (the date is text so I will keep it that way).
I need to check it against another list of strings where the list of strings that are date format type could be anywhere in those list of strings.
I've tried all kinds of .Any() with .Contains(), but .Contains forces you to take a string and I need to look at the entire string because it will not be equal.
            var innerTextList = getMainData.Select(s => s.InnerText).ToList();
            bool hasMatch = innerTextList.Contains(dateList.Select(s => s)).Any();

Example:
List of strings (date text format) -DateTextList
"Thu, Mar 28"
"Fri, Mar 29"
"Sat, Mar 30"

List of Strings - RecordTextList
"Thu, Mar 28vs Pittsburgh W5-3 1-0Duke 1-0Taillon 0-1Hernandez 144,049"
"Sun, Mar 31vs Pittsburgh 1:10 PM Roark Musgrove Tickets as low as $14"
"Tue, Mar 26vs Pittsburgh 1:10 PM Roark Musgrove Tickets as low as $14"
So if any of the DateTextList records is contained in the list of records of RecordTextList, I want to return TRUE.

A: Try this:
bool hasMatch = DateTextList.Any(x => RecordTextList.Any(y => y.Contains(x)));


text:
Q: Postgres Trigger to INSERT UPDATE DELETE on similar derivative table Description:

*

*I am running postgresql 13

*I have two tables under different schemas, t1 and t2.

*t2 is derivative of t1 in the sense that they share all the same
columns and data, but t2 is always downstream of t1 as far as
validity.

*The rows in both tables share the same primary key, which is what I assume would be used as the link between them.

The ask:

*

*I would like to create a trigger that reflects any changes in t1 and syncs t2 to be the same.

*I started with INSERT or UPDATE, but if DELETE is easily added, I would like to implement that as well.

Trigger Code:
-- Trigger for t1 to t2 --

CREATE OR REPLACE FUNCTION t1_schema.sync_trigger()

RETURNS TRIGGER AS

$$
BEGIN
    INSERT INTO t2_schema.t2 (col1, col2, col3)
    VALUES (NEW.col1, NEW.col2, NEW.col3);
    RETURN NEW;
END
$$ LANGUAGE plpgsql;

CREATE TRIGGER t1t2_test_sync
AFTER INSERT OR UPDATE ON t1_schema.t1
FOR EACH ROW
EXECUTE PROCEDURE t1_schema.sync_trigger()

When I execute this code and do a test UPDATE on t1, the same row on t2 does not reflect the changes or give me any errors.
I have tried:

*

*Discretely labeling all rows as updated with NEW. format, but run into the problem of primary key column not being editable in t2.

*Adding a WHERE clause after the VALUES clause, something like WHERE primary_key=NEW.primary_key, but I get an error.

*Another option I have seen is adding an IF statement before the
INSERT, or adding a WHEN clause in the trigger, but neither have
worked.

A: Your best approach is to not create t2 as a table. Instead create it as a VIEW on t1. This totally eliminates triggers to keep them synchronized because the actual source is the same. Follows the concept to store a single data point in only 1 place.  Keep in mind that if you store a single piece in 2 places, 1 on them will be wrong at some point. (see demo).
create view soq2.t2 as
            select *
              from soq1.t1;

Also if you need column names to change then use an alias during the create view;
create view soq2.t2a as
       select t1_id  as t2_id
            , name   as t2_name
            , status as t2_status
         from soq1.t1;

A: (A) Solution based on triggers
You maybe get an error when updating a row in t1 because your trigger function tries to insert a new row in t2 which has alreday been inserted in t2 by the same trigger function when it has been inserted in t1. You need to duplicate and specialize your trigger functions, one for insert, one for update, one for delete because the treatment to be triggered on t2 is different :
CREATE OR REPLACE FUNCTION t1_schema.sync_trigger_insert()
RETURNS TRIGGER AS
$$
BEGIN
    INSERT INTO t2_schema.t2 (col1, col2, col3)
    VALUES (NEW.col1, NEW.col2, NEW.col3);
    RETURN NEW;
END
$$ LANGUAGE plpgsql;

CREATE TRIGGER t1t2_test_sync_insert
AFTER INSERT ON t1_schema.t1
FOR EACH ROW EXECUTE PROCEDURE t1_schema.sync_trigger_insert() ;

CREATE OR REPLACE FUNCTION t1_schema.sync_trigger_update()
RETURNS TRIGGER AS
$$
BEGIN
    UPDATE t2
       SET col1 = NEW.col1
         , col2 = NEW.col2
         , col3 = NEW.col3
     WHERE primary_key_t2 = NEW. primary_key_t1 ; -- primary_key_t2 must be replaced by the set of columns which are in the primary key of t2 with AND operators, the same for NEW.primary_key_t1
    RETURN NEW;
END
$$ LANGUAGE plpgsql;

CREATE TRIGGER t1t2_test_sync_update
AFTER UPDATE ON t1_schema.t1
FOR EACH ROW EXECUTE PROCEDURE t1_schema.sync_trigger_update() ;

CREATE OR REPLACE FUNCTION t1_schema.sync_trigger_delete()
RETURNS TRIGGER AS
$$
BEGIN
    DELETE FROM t2
     WHERE primary_key_t2 = NEW. primary_key_t1 ; -- primary_key_t2 must be replaced by the set of columns which are in the primary key of t2 with AND operators, the same for NEW.primary_key_t1
    RETURN OLD; -- NEW is not available for triggers ON DELETE
END
$$ LANGUAGE plpgsql;

CREATE TRIGGER t1t2_test_sync_delete
AFTER DELETE ON t1_schema.t1
FOR EACH ROW EXECUTE PROCEDURE t1_schema.sync_trigger_delete() ;

(B) Solution based on foreign key
It is possible that a foreign key on t2 (col1,col2,col3) referencing t1 (col1, col2, col3) with the options ON UPDATE CASCADE ON DELETE CASCADE may deliver your expected result in a much more simple and efficient way, see the manual. In this case, you don't need the triggers ON UPDATE and ON DELETE anymore, but you still need the trigger ON INSERT.


text:
Q: How to map 3D spherical point configuration (not the earth) onto 2D plane? I have a 3d spherical point set of 10 points, (2 layers of pentagonal loudspeaker array) 2. I want to obtain 2D representation of this configuration. (Mollweide, Mercator, Cylindirical or Equirectangular projection?)
I will set the axis so that they give corresponding elevation and azimuthal angles. An example is given in 1 (Taken by ALLRADecoder vst plugin by IEM)
Is there a way to do this with a Python package like matplotlib, mayavi, or similar?

A: If you want to actually render something similar to above, you might want to look at PyOpenGL however it might not be the most intuitive package to dive into.
If you want to just get the 2d set of points this 3d object makes you could just look at doing some projection maths and then a package like pygame would be ideal for plotting this 2d representation and is quite user-friendly if you're new to python and graphics.


text:
Q: Função .filter() para um List Eu tenho uma classe Pessoa que tem as colunas Integer id. String name, e String date_born.
Na minha activity principal eu já estou recuperando a lista de pessoas que vem da minha requisição feita na API e já mando para minha função para agrupar.
private void loadList(List<Pessoas> listPessoas){
       Map<String, List<Pessoas>> listMap = listPessoas.stream().collect(Collectors.groupingBy(Pessoa::getDate_born)); //LISTA AGRUPADA
}

Mas eu preciso filtrar a lista antes de poder agrupar pelo campo date_born, aí vai minha pergunta.
private void loadList(List<Pessoas> listPessoas){
      List<Pessoas> listPessoasFiltered = ??
      Map<String, List<Pessoas>> listMap = listPessoasFiltered.stream().collect(Collectors.groupingBy(Pessoa::getDate_born));
}

Já existe uma função tipo .filter() que retorna a lista ou tem que implementar uma função de filtro para retornar minha lista de pessoas filtrada antes de agrupar as pessoas por este campo?
Lembrando não é dentro de um Adapter é um filtro de uma lista.

A: Você não precisa criar uma outra lista filtrada, pode aproveitar que está usando streams e usar o método filter:
Map<String, List<Pessoa>> map = listPessoas.stream()
    // filtrar pelo critério que vc precisa
    .filter(pessoa -> pessoa.getName().endsWith("o"))
    // agrupar por data de nascimento
    .collect(Collectors.groupingBy(Pessoa::getDate_born));

No exemplo acima, estou filtrando os nomes que terminam em "o", mas você pode usar qualquer critério que desejar (o importante é que o lambda passado para filter retorne true para os elementos que você quer manter).


text:
Q: How to use a same image multiple times by loading it only once when I need different id for every element I am a newbie to programming and web developing. The project I am doing is only for practice, if my approach seems ameteur to you, please suggest any better options.
I am trying to develop a parking lot booking system. And in the UI, I want to show all the empty/filled slots (like it is while booking movies or bus tickets).
I couldn't find a top view icon of a car, so I thought of using an image instead of icon.
But as of the image, if I use say 50 images on a single page, the page will get very heavy.
But one important thing is that I need all the elements as seperate entities, only then I will be able to book them with their id(unique address). So I want 50 different divs with seperate distinct ids but want to use only one image for all the slots, or a maximum of 2 different images(keeping the directions in mind).
how to display same image multiple times using same image in javascript
I went through this answer, and found a piece of code that might be useful:
var imgSrc = 'http://lorempixel.com/100/100';

function generateImage() {
  var img = document.createElement('img')
  img.src = imgSrc;

  return img;
}

for (var i = 0; i < 20; i++ ) {
  document.body.appendChild(generateImage());
}

While I can make use of a function and a loop in javascript to create as many copies of one image, I don't know how to alot them to the different div tags with distinct ids.

A: use a function :)
const addMessage = (element, msg, cls) => {
    const patt = new RegExp("<");
    const messageElement = document.createElement("div");
    if (patt.test(msg)) {
        messageElement.innerHTML = msg
    } else messageElement.textContent = msg;
    if (cls) messageElement.classList.add(cls);
    element.appendChild(messageElement);
}
const imgPath = "/somepath";
const body = document.querySelector("body");
addMessage(body, `<img src=${imgPath} class="whatever">`, "img1"); //creates new divs with classes. the 3rd arg is optional

A: the best approach for this is the client side already receiving all this content as a string but as it made clear that it is for study I deduce that it is not the intention to use back end to solve this problem
let allContent = '';

for (var i = 0; i < 20; i++ ) {
  allContent += `<div class="wrapper-image"><img src="/path"></div>`
}

document.getElementById('idWrapper').innerHTML = allContent;

speaking in performace the browser will only download the image once, so you can use it as many times as you like, which is disruptive to the changes you make in the DOM (remove, add or edit a content)
In my example you create all the content to be displayed on the page and then add it in a single time, it is not too bad if it is performace but the ideal is to do it on the back side
in the DIV you can put an image address of a variable to do some logical type this:
    let allContent = '';
    let imgOne = '/oneimg';
    let imgOne = '/twoImg';

    for (var i = 0; i < 20; i++ ) {
        if(i>10){
            allContent += `<div class="wrapper-image"><img src="${imgOne}"></div>`
        }else {
            allContent += `<div class="wrapper-image"><img src="${twoImg}"></div>`
        }
    }
    document.getElementById('idWrapper').innerHTML = allContent;


text:
Q: Java: Get all Strings using Regex I'm trying to get all the strings from a javascript script, I created a code, but it's not catching all, it's skipping some
My Code
String Strings;
    public String GetStrings(String str){
        try{
        String Str= str;
         Strings = "";
         while(true){
            Pattern pattern = Pattern.compile("('|\")");
            Matcher matcher = pattern.matcher(Str);
            if(matcher.find()){
                Pattern pattern1 = Pattern.compile("(" + matcher.group(1) + "[^" + matcher.group(1) + "]*" + matcher.group(1) + ")");
                Matcher matcher1 = pattern1.matcher(Str);
                if(matcher1.find()){
                    Strings += "|" + matcher1.group(1) + "|";
                    Str =  Str.replace(matcher1.group(1)," ");
                }
                }else{
                    break;
                    }
        }
        }catch(Exception err){return err.toString(); }
        return Strings;
        }

Input
var A="&";var B="(";var D="[]";var X="'";var W='&';var Q='';var STR="'";var Q="'******'";var G="^";var F="...";var T='$';var wm = "()"
console.log(A + B + D + "^" + wm + '#');

Output
|"&"||"("||"[]"||"'"||'&'||''||"'******'"||"^"||"..."||'$'||"()"||'#'|

As you can see not captured all the strings, some did not appear, if anyone has any solution or can point the problem, please help me

A: Input and expected output is not matching but according what i understood is
public String GetStrings(String str){
       StringBuffer b = new StringBuffer();
       for (int i = 0; i < str.length(); ++i) {

            char ch = str.charAt(i);

            if (Character.isWhitespace(ch))
                b.append("\\s");
            else if (Character.isDigit(ch))
                b.append("\\d");
            else if (Character.isUpperCase(ch))
                b.append("A-Z");
            else if (Character.isLowerCase(ch))
                b.append("a-z");
        }
                b.append("||");

        }

A: You need to use following regex:
(\"(.*?)\")|(\'(.*?)\')

example:
public String getStrings(String str){
   String regex = "(\\\"(.*?)\\\")|(\\'(.*?)\\')";

   Pattern pattern = Pattern.compile(regex);
   Matcher matcher = pattern.matcher(str);

   String output = "";
   while (matcher.find()){
       output = output+"|"+matcher.group(0)+"|";
   }

   return output;

}

Output:
|"&"||"("||"[]"||"'"||'&'||''||"'"||"'******'"||"^"||"..."||'$'||"()"||"^"||'#'|

Regex Explanation


text:
Q: when I Try to set Default value in Reactive Forms it Shows me NULL I crate 1 Reactive form and try to set default which is comes from function when i try to do that the value shows me null

here is some code picture. you can get some idea not necessary to read

Here is code of Reactive Form where i'm storing the Default value

here you can see the output of code that it shows the null value
Thank You.

A: You can not set value Directly like you declare
Use patchValue
Code:
this.projectForm.patchValue({
      p_startTime: this.starttime,
      p_endTime: this.endtime,
      P_sessionTime:this.totaltime
    });

use this code in pauseTimer()


text:
Q: Prove that $x=5\cos(6x)$ for some $x$ in the interval $\left(\frac{\pi}{6},\frac{\pi}{3}\right)$
Prove that $x=5\cos(6x)$ for some $x$ in the interval $\left(\frac{\pi}{6},\frac{\pi}{3}\right)$ using the the IVT

I'm not entirely sure how to prove this but I set it up this way:

$f(x)=x-5\cos(6x)$

And so

$f(a)=f\left(\frac{\pi}{6}\right)=\frac{\pi}{6}+5$

And

$f(b)=f\left(\frac{\pi}{3}\right)=\frac{\pi}{3}-5$

And so by the intermediate value theorem:

$f\left(\frac{\pi}{6}\right)\lt 0\lt f\left(\frac{\pi}{3}\right)$

Am I missing anything?

A: Yes, your answer is correct except for two details.
(1) you need to add explicitly that $f$ is continuous. In other words, "since $f$ is continuous on $[\frac{\pi}{6},\frac{\pi}{3}]$ it follows from the IVT that $f(x)=0$ for some $x\in(\frac{\pi}{6},\frac{\pi}{3})$. [Thanks to @ZainPatel ]
(2) you garbled your signs near the end it is $$f\left(\frac{\pi}{6}\right)>0>f\left(\frac{\pi}{3}\right)$$


text:
Q: Lebesgue integral question from wiki I have started studying Lebesgue integration and I have a question regarding the Lebesgue integral.
In the wikipedia entry of "Lebesgue integration" they define the Lebesgue integral as:
Let $f: \mathbb{R} \rightarrow \mathbb{R}^{+}$ be a positive real-valued function.
$$\int f d\mu = \int_{0}^{\infty}f^{*}(t)dt$$ where $f^{*}(t) = \mu(\{x |f(x) > t\})$.
The Lebesgue integration notes that I am studying defines the Lebesgue integral of a positive measurable function as $$\int f d \mu = \text{sup}\{ \int \phi d\mu :\text{    } \phi \text{ is a simple function and } 0 \leq \phi \leq f \}$$ I want to know if this wiki definition is equivalent to the integral constructed from simple functions, if so how can this be easily shown?

A: A hint: break the Riemann integral into the limit of a summation, and it should be clear that they are the same. $f^*(t)dt$ is the area on the strip between two step functions that are a distence $dt$ apart.

A: Define $\int f d\mu$ as usual. (I.e. Supremum of $\sum x \mu(s^{-1}(x))$ where $s$ is a simple measurable function such that $s≦f$.)
Note that $f^*$ is almost everywhere continuous since it is monotonically decreasing. Moreover, it is continuous. (Why?)
So $\int_0^\infty f^*(t)dt$ is well-defined where the integral here is Riemann.
Since $f^*$ is continuous, as Stella mentioned, it can be represented as a summation.
Moreover, do you know a theorem :"For every nonnegative measurable function, there exists a monotonically increasing sequence of simple measurable functions converging to that measurable function"?
Construction in that proof shows that the above summation is exactly the Lebegue integral of $f$.


text:
Q: Constructible Polygon and Fermat's Prime I came across this puzzle at some online contest(now completed)

Alexander, son of Phillip of Macedon, has ascended the throne of his father following his assassination. In these tumultuous times, he appoints you as head of the architectural division of his mighty army. The general of the army wants all the catapults to be inducted in the artillery which have a n-sided polygon base, and no two or more of them should have the same type of polygon as their base.However, for the structures to be agile and economic, it is required that the n should be an odd number and the polygon of the base should be constructable with help of a compass and straightedge.
Given the above situation, you are required to find out the total number of logs of woods required - each log of wood for each side of the base of structure - for the construction of all such catapults

I thought the result would be equal to the sum of the first 5 Fermat's Prime but unfortunately that wasn't correct.
Do you think the data provided is not sufficient or am I missing something? What could the possible answer to this question?

A: You're missing something. Read what your Wikipedia link has to say about constructible polygons again:
An n-sided regular polygon can be constructed with compass and straightedge if and only if n is the product of a power of 2 and distinct Fermat primes. In other words, if and only if n is of the form $n = 2^kp_1p_2…p_s$, where k is a nonnegative integer and the $p_i$ are distinct Fermat primes.
(My emphasis)

A: A fairly specific hint: is a 15-gon constructable or not?  How, and why?
(Hint to the hint: what is $\dfrac{2\pi}{5}-\dfrac{\pi}{3}$?  Why does this matter?)
Now can you see which $n$-gons you might have left off your list?


text:
Q: wget - does -nc option skip downloading existed files? I'm downloading a website with wget. the command is as below :
wget -nc --recursive --page-requisites --html-extension --convert-links --restrict-file-names=windows --domain any-domain.com --no-parent http://any-domain.com/any-page.html

does -nc option skip downloading existed files even when we download a website recursively? It seems -nc option not works.

A: the man say that :
-nc
--no-clobber
           If a file is downloaded more than once in the same directory, Wget's behavior depends on a few options, including -nc.  In certain cases, the local file will be clobbered, or overwritten, upon
           repeated download.
Here is more details (from the man too) :
When running Wget with -r or -p, but without -N, -nd, or -nc, re-downloading a file will result in the new copy simply overwriting the old.

A: Yes, the -nc option will prevent re-download of the file.
The manual page is confusing because it describes all of the related options together.
Here is pertinent bits from the man page:

When running Wget with -r or -p, but without -N or -nc, re-downloading a file will result in the
  new copy simply overwriting the old.  Adding -nc will prevent this behavior, instead causing the
  original version to be preserved and any newer copies on the server to be ignored.

A: The option --convert-links seams to conflict with -nc. Try removing it.


text:
Q: How to do the mapping to update an existing entity, while allowing to set property values in destination to null? I have an Identity 2.0 User with some custom fields and in order to update them I can do manual mapping like this:
public async Task<ActionResult> UserProfile([Bind(Include = "FullName,Gender,DateBirth")] ApplicationUser model)
{
    var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
    // do stuff... validation...

    user.FullName = model.FullName;
    user.Gender = model.Gender;
    user.DateBirth = model.DateBirth;

    await UserManager.UpdateAsync(user);
}

I'm going to add at least 10 more fields, so I tried using AutoMapper like this:
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

// Ignore id
Mapper.CreateMap<ApplicationUser, ApplicationUser>()
    .ForMember(o => o.Id, m => m.Ignore());
Mapper.Map(model, user);

await UserManager.UpdateAsync(user);

AutoMapper is setting all fields inexistent in model to null, e.g. Email, Password, etc are being set to null. I.e. it is overwriting the existing user completely. So I tried:
Mapper.CreateMap<ApplicationUser, ApplicationUser>()
    .ForMember(o => o.Id, m => m.Ignore())
    .ForAllMembers(a => a.Condition(s => !s.IsSourceValueNull));

But with that if I set a property as null in model, the existing user will not be updated and will keep the original value (FullName and Gender can be null). It only updates if model has a non null value, if the value is null, it will keep existing user value for the field.
How to do the mapping to update an existing entity, while allowing to set existing values to null?
UPDATE #1: for some reason now after mapping model to user, the email property is being set to: AppName.Models.ApplicationUser. That means the email is being set to the ApplicationUser namespace. (I didn't change anything, and I'm not sending a new email from the form).
UPDATE #2: Creating a ViewModel and having a simple mapping like this solved the issue:
Mapper.CreateMap<ProfileViewModel, ApplicationUser>().

Thing is: is it possible to accomplish what I want without a ViewModel? This way keeping my original problem and question.


text:
Q: Error with exit code -1073740791 (0xC0000409) in python so the program that I am trying to make accepts only a valid month and year between 2018-2050 but pycharm crushes with the message "Process finished with exit code -1073740791 (0xC0000409)" and I know in which line it does that, but I dont know how to fix it, here is the code I am using and the error appers in the last elif when ok is clicked. I have tried reinstalling python and pycharm, as suggested in other posts but nothing happens.
import sys
from PyQt5.QtWidgets import (QVBoxLayout,QHBoxLayout,QPushButton,
QLineEdit,QApplication,QLabel,QCheckBox,QWidget)

class Window(QWidget):
def __init__(self):
    super().__init__()
    self.init_ui()

def accepted(month, year):
    conf = True
    try:
        int(month)
        int(year)
    except ValueError:
        conf = False
    if conf:
        if (int(month) > 12 or int(month) < 1) or (int(year) < 2019 or
int(year) > 2050):
            conf = False
    return conf

def init_ui(self):

    self.btn1=QPushButton('OK')
    self.btn2=QPushButton('Clear')
    self.btn3=QPushButton('Cancel')

    self.txt1=QLabel('Month input')
    self.txt2=QLabel('Year Input')

    self.b1=QLineEdit()
    self.b2=QLineEdit()

    h_box1: QHBoxLayout=QHBoxLayout()
    h_box1.addWidget(self.txt1)
    h_box1.addWidget(self.b1)

    h_box2 = QHBoxLayout()
    h_box2.addWidget(self.txt2)
    h_box2.addWidget(self.b2)

    h_box3=QHBoxLayout()
    h_box3.addWidget(self.btn1)
    h_box3.addWidget(self.btn2)
    h_box3.addWidget(self.btn3)

    layout=QVBoxLayout()
    layout.addLayout(h_box1)
    layout.addLayout(h_box2)
    layout.addLayout(h_box3)

    self.setLayout(layout)
    self.setWindowTitle('Calendar Manager')
    self.show()

    self.btn1.clicked.connect(self.buttons)
    self.btn2.clicked.connect(self.buttons)
    self.btn3.clicked.connect(self.buttons)

def buttons(self):
    clicked=self.sender()
    if clicked.text() == 'Clear':
        self.b1.clear()
        self.b2.clear()
    elif clicked.text() == 'Cancel':
        sys.exit()
    elif clicked.text() == 'OK':
        if not accepted(self.b1.text(),self.b2.text()):
            self.b1.clear()
            self.b2.clear()
        else:
            pass

app=QApplication(sys.argv)
a_window=Window()
sys.exit(app.exec_())

A: So the problem is the self in two instances, first as an argument in def accepted and secondly the self.accepted when I call it.

A: As you mentioned, the problem is with function accepted. If you intended it to be a class method, it should have been defined as:
def accepted(self, month, year):
    ....

You don't use 'self' in the method, so it could be turned into a static method:
@staticmethod
def accepted(month, year):
    ....


text:
Q: Rank Nullity "Converse"? The rank nullity theorem requires a linear map $T:V \longrightarrow W$ between a finite dimensional domain VS and some VS W.
The conclusion of the theorem is that $\text{Dim}(V) = \text{Dim}(\text{Ker}(T))+\text{Dim}(\text{Ran}(T))$.
My question is, if I have a linear map $T: V \longrightarrow W$ between any two vector spaces and $\text{Dim}(\text{Ker}(T))+\text{Dim}(\text{Ran}(T)) < \infty$, then is $\text{Dim}(V) < \infty$ with $\text{Dim}(V) = \text{Dim}(\text{Ker}(T))+\text{Dim}(\text{Ran}(T))$?
Apologies if this is blatantly true or false.
Thank you.

A: Suppose $\dim{V} = \infty$, then we can write $V = \ker{T} \oplus U$, where $U$ is an infinite dimensional subspace of $V$. Let $\{u_i\}_{i \in I}$ be a Hamel basis for $U$, then $\{T(u_i)\}$ would be a Hamel basis for $\operatorname{Ran}{T}$. This means $\operatorname{Ran}{T}$ would need to be infinite dimensional, which it isn't. Hence, we have a contradiction, and $\dim V < \infty$.


text:
Q: How to store a list of Objects that might change in future? I have set of Objects of the same class which have different values of their attributes.
and I need to find the best match from a function under given scenarios out of these objects.
In future these objects might increase as well.
Quite similar to the way we have Color class in awt.
we have some static color objects in the class with diff rgb values.
But in my case say, I need to chose the suitable color out of these static ones based on certain criteria.
So should I keep them in an arrayList or enum or keep them as static vars as in case of Colors.
because I will need to parse through all of them and decide upon the best match.
so I need them in some sort of collection.
But in future if I need to add another type I will have to modify the class and add another list.add(object) call for this one and then it will violate the open-close principle.
How should I go about it ?
EDIT:
To be more precise I have a roughly 7-8 branches of  restaurants which wont increase that much..may be by 3-4 in few years and I need a function that will return the nearest Restaurant satisfying few other criteria.
and For that I need to parse through all of them to decide which one suits the customer the most.

A: It really depends on how many objects you have and how many dimensions each object is free to move in.
Finding the closest match for a mutli-dimensional value is something which lends itself to spatial databases and space partitioning trees e.g. a k-d tree. Of course if you only have a few dozen objects then just checking them all is also an option.
I think your analogy of the Color class may be throwing you slightly as (AFAIK) I don't think Color provides any nearest matching capabilities anyway and also you probably need to leave the RGB colour space to define a useful distance metric

A: Go with an ArrayList.  You can modify it freely and search it fast.  You won't violate the open-close principle.
Exception:  if you have a lot of entries, say over a million, and you're running at 80%+ on your CPU and want more speed, things get interesting.  Large arrays can do odd things to memory in this situation if you are not careful, and ArrayList will do awkward things when you're not looking.  Also, if you want to spot the closest object in the list to some arbitrary object--say, the closest color you have to something with an RGB of 233.121.55--you'll need a multi-dimensional storage system.  Say a quadtree or, with colors an octree.  (If your colors have an alpha component, I suppose you'd need a hexadecimaltree.)
But I'm betting the ArrayList will work just fine for you.  You can scan 100,000 entries in an ArrayList in the blink of an eye.

A: Store the stores on disk. I would recommend using a database but for the small amount of data xml would do fine as well. On application start up read this list into a collection. You wouldn't need to create constants for each because you will just be querying the list when you need a store. This will keep you from having to update your code just to add a new store. Also since you are computing distances you will need a list of all the zip codes and their corresponding latitude and longitude so that you can compute the distance between two zipcodes. This could also be stored on disk and most likely will need updating more frequently than your store list. In addition, you could create an admin console that will let you add new stores and update zip codes without having to manually write to the storage mechanism you have chosen.

A: Simply store your objects in an ArrayList of type Object.  Then, you can add any type of object to that collection.  It can be a mixed, aka heterogeneous collection.
List<Object> mixedList = new ArrayList<Object>();
list.add(new String("I'm a string"));
list.add(new Integer(1));
list.add(new Long(1l));


text:
Q: Error 2003 (HY000) when i try to connect amazon rds server from ec2 server I know I need to configure the RDS security group to allow connection from EC2 security group.
I have an EC2 instance running in the default security group. so i added the EC2 Security Group to the RDS DB security group. When I try to connect using the mysql client from my EC2 instance it gives me the following error:
ERROR 2003 (HY000): Can't connect to MySQL server on 'xxxx.xxxx.us-east-1.rds.amazonaws.com' (110)

the command i used is:
mysql -udbuser -p -hxxxx.xxxx.us-east-1.rds.amazonaws.com

I found this post with the exactly same issue I have, but no one answers
https://forums.aws.amazon.com/message.jspa?messageID=328603
I am able to add CIDR/IP rules and works just fine from my laptop. However, I really need my ec2 instance hook up with my rds. Thanks in advance for any help.

A: I have fixed this issue by adding the public ip address of my EC2 server to the DB security group default policy.

A: To expand on the Yuzhou's answer, and answer Amit's question, you can create a new security group with the corresponding IP range/subnet of your EC2 instances(s).  You can use the exact IP(s), or use your VPC's subnet(s) as the range.
Once created, you can right click your RDS instance in the management console and select 'Modify'.   From there, you can change the associated security groups.

A: The answer given by Yuzhou Zhu will work, but a better option would be to add the security group of the EC2 instance to the security group of your RDS database. In this case even if you're not using an Elastic IP, still your solution will work even after stopping/starting your EC2 (which might change the public IP of your instance).

A: For my problem, aside from adding a new rule for allowing a certain of IP(s), public accessibility needs to be enabled too
【Modify]->[Network & Security]
Public accessibility
Info
Yes
EC2 instances and devices outside of the VPC hosting the DB instance will connect to the DB instances. You must also select one or more VPC security groups that specify which EC2 instances and devices can connect to the DB instance.

No
DB instance will not have a public IP address assigned. No EC2 instance or devices outside of the VPC will be able to connect.

Tick Yes, and apply changes.

A: To expand on the answer from mok, you need to specify the source client that will send incoming requests into your RDS> The source can be specified in the form of a security group or IP's. In my case during development I want to allow access from anywhere so I can troubleshoot from my laptop. Before I release for production, I will change the source to the security group associated with the EC2 instance. Earlier I was omitting a source completely, and hence my RDS security group was failing to create, albeit silently, making the problem even more enigmatic. Below is relevant snippet from my CloudFormation template,
MyDatabaseSecurityGroup:
    DependsOn: [MyVpc]
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Security group for Amazon RDS cluster
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 3306
          ToPort: 3306
          # TODO: After development phase completes, restrict access from EC2 only
          #       as opposed to the entire world by uncommenting below line
          #       and commenting out the one after it
          #SourceSecurityGroupId: !Ref MyWebSecurityGroup
          CidrIp: 0.0.0.0/0
      VpcId: !Ref MyVpc


text:
Q: ASP.NET how to convert string to Date without forward slashes Just wondering how I can convert the following string into a datetime 111222, at the moment it is telling me that this is not a valid datetime value..

A: You can use the DateTime.ParseExact method and supply the format your input is in.
Edit - added code:
  DateTime dt = DateTime.ParseExact("111222", "yyMMdd", CultureInfo.InvariantCulture);
  Console.WriteLine(dt.ToString());


text:
Q:
A: Creo que tienes una condición de carrera porque no esperas correctamente a que los scripts se carguen y se interpreten. Podrías cambiar un poco ese Hook para añadir un estado que permita saber cuándo es posible usar el código.
Te pongo un ejemplo simplificado que carga jQuery y lo usa sólo cuando está disponible:

const {useState, useEffect} = React;

function useScripts(url, type, id) {
  const [scriptLoaded,setScriptLoaded] = useState(false);
  useEffect(() => {
    const script = document.createElement("script");
    script.src = url;
    script.type = type || "text/javascript";
    script.id = id;
    document.body.appendChild(script);
    script.addEventListener('load',() => {
      setScriptLoaded(true);
      console.log('Script cargado, listo para su uso');
    });
    console.log('Script añadido');
    return () => {
      document.body.removeChild(script);
    };
  }, [url]); //esto asegura que sólo se ejecute una vez
  return scriptLoaded;
}

const App = () => {
  let loaded = useScripts('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js');
  if (loaded) {
    window.$('#test').text('Cargado');
  } else {
    console.log('Esperando la carga');
  }
  return ( Hola );
}

ReactDOM.render(<App />, document.getElementById('root'));

No Cargado


text:
Q: My ListView doesn't show anything I fetch data from sqlite in Lists to show them up into a fragment's ListView. I first created the ListView in the layout, it didn't work since Android Studio didn't find my ListView based on the id. Then I created the ListView programmatically and it shows nothing. The weird point is, enter code herein another fragment where i did the same, everything works perfectly.
My question is: Can you guys check if there is a mistake into my code or tell me what is going wrong there ?
I've tried everything i knew so far as a newbie but it doesn't work. Any help would be appreciated. Find attached parts of coding related this program. I'm working with a fragment navigation drawer...
Main Fragment
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;

import cm.opep.opep.DatabaseHelper;
import cm.opep.opep.R;
import cm.opep.opep.transfert.DbResponse;
import cm.opep.opep.transfert.DbTrajet;
import cm.opep.opep.transfert.PassagerAdapter;

public class DetailTrajetFragment extends Fragment {

    DatabaseHelper helper;
    PassagerAdapter ListAdapter;
    String et_iduser, et_idchauffeur, et_idtrajet, et_placesvoulues, et_rechercheDateD, et_rechercheHeureH, et_rechercheVilleA, et_rechercheVilleD;

    ArrayList<String> prenom_passager_arrayList = new ArrayList<>();
    ArrayList<String> age_passager_arrayList = new ArrayList<>();
    ArrayList<String> niveau_passager_arrayList = new ArrayList<>();
    ArrayList<String> id_passager_arrayList = new ArrayList<>();

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

        View v = inflater.inflate(R.layout.fragment_detail_trajet, container, false);
        helper = new DatabaseHelper(getActivity());
        getActivity().setTitle(String.valueOf("ID Trajet: " + getArguments().getString("idtrajet")));
        initUI(v);
        return v;
    }

    public void initUI(View v) {

        final TextView cptevilledepart = v.findViewById(R.id.propositionvilledepart);
        final TextView cptelieudepart = v.findViewById(R.id.cpte_lieudepart);
        final TextView cptedatedepart = v.findViewById(R.id.propositionDateD);
        final TextView cptedatearrivee = v.findViewById(R.id.cpte_date_arrivee);
        final TextView cpteheuredepart = v.findViewById(R.id.propositionHeureD);
        final TextView cptetaillebagage = v.findViewById(R.id.propositionbagage);
        final TextView cpteflexibilite = v.findViewById(R.id.flexibilite);
        final TextView cptedetour = v.findViewById(R.id.detour);
        final TextView cpteprix = v.findViewById(R.id.cpte_prix);
        final TextView cptecommentairechauffeur = v.findViewById(R.id.cpte_commentaire_chauffeur);
        final TextView cpteplacesdisponibles = v.findViewById(R.id.cpte_places_disponibles);
        final TextView cptevillearrivee = v.findViewById(R.id.propositionvillearrivee);
        final TextView cptelieudepot = v.findViewById(R.id.cpte_lieu_depot);
        final TextView cpteprenom = v.findViewById(R.id.prenom_chauffeur);
        final TextView cpteage = v.findViewById(R.id.age_chauffeur);
        final TextView cpteniveau = v.findViewById(R.id.niveau_chauffeur);
        Button bouton_reserver = v.findViewById(R.id.bouton_réserver);
        final TextView vide = v.findViewById(R.id.vide);

        ListView liste_passag = new ListView(this.getActivity());
        int i = 1226;
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, i, 0, 0);
        liste_passag.setLayoutParams(layoutParams);
        layoutParams.setMargins(0, i + 75, 0, 0);
        vide.setLayoutParams(layoutParams);

        et_iduser = getArguments().getString("id");
        et_idchauffeur = getArguments().getString("idchauffeur");
        et_idtrajet = getArguments().getString("idtrajet");
        et_placesvoulues = getArguments().getString("placesvoulues");
        et_rechercheVilleD = getArguments().getString("VilleDepart");
        et_rechercheVilleA = getArguments().getString("VilleArrivee");
        et_rechercheHeureH = getArguments().getString("Heure");
        et_rechercheDateD = getArguments().getString("Date");

        prenom_passager_arrayList.clear();
        id_passager_arrayList.clear();
        niveau_passager_arrayList.clear();
        age_passager_arrayList.clear();

        ArrayList<String> prenom_passager_arrayList = helper.getTrajetPrenomPassager(et_idtrajet);
        ArrayList<String> id_passager_arrayList = helper.getTrajetIDPassager(et_idtrajet);
        ArrayList<String> niveau_passager_arrayList = helper.getTrajetNiveauPassager(et_idtrajet);
        ArrayList<String> age_passager_arrayList = helper.getTrajetAgePassager(et_idtrajet);

        ListAdapter = new PassagerAdapter(this.getActivity(),
                prenom_passager_arrayList,
                id_passager_arrayList,
                niveau_passager_arrayList,
                age_passager_arrayList
        );
        liste_passag.setAdapter(ListAdapter);
        liste_passag.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View child, int position, long id) {

            }
        });
}

Adapter
package cm.opep.opep.transfert;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

import cm.opep.opep.R;

public class PassagerAdapter extends BaseAdapter {

    private Context contxt;
    private ArrayList<String> prenom;
    private ArrayList<String> idpassager;
    private ArrayList<String> niveau;
    private ArrayList<String> age;
    //private ArrayList<String> avis;
    //private ArrayList<String> note;

    public PassagerAdapter(Context context1, ArrayList<String> et_prenom, ArrayList<String> et_idpassager, ArrayList<String> et_niveau, ArrayList<String> et_age) {
        this.contxt = context1;
        this.prenom = et_prenom;
        this.idpassager = et_idpassager;
        this.niveau = et_niveau;
        this.age = et_age;
        //this.avis = et_avis;
        //this.note = et_note;
    }

    @Override
    public int getCount() {
        return prenom.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View child, ViewGroup parent) {

        Holder holder;
        LayoutInflater layoutInflater;

        if(child == null) {
            layoutInflater = (LayoutInflater) contxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            assert layoutInflater != null;
            child = layoutInflater.inflate(R.layout.fragment_detail_resultat_recherche_passager, parent,false);

            holder = new Holder();
            holder.pranom = child.findViewById(R.id.prenom_passager);
            holder.idpassenger = child.findViewById(R.id.idpassager);
            holder.niv = child.findViewById(R.id.niveau_passager);
            holder.old = child.findViewById(R.id.age_passager);
            //holder.mind= child.findViewById(R.id.avis_passager);
            //holder.rank= child.findViewById(R.id.note_passager);
            child.setTag(holder);
        }
        else {
            holder = (Holder) child.getTag();
        }
        holder.pranom.setText(prenom.get(position));
        holder.idpassenger.setText(idpassager.get(position));
        holder.niv.setText(niveau.get(position));
        holder.old.setText(age.get(position));
        //holder.mind.setText(avis.get(position));
        //holder.rank.setText(note.get(position));
        return child;
    }
    public class Holder {

        TextView pranom;
        TextView niv;
        TextView old;
        //TextView mind;
        TextView idpassenger;
        //TextView rank;
    }
}

DatabaseHelper
public ArrayList<String> getTrajetPrenomPassager(String et_idtrajet) {
    ArrayList<String> prenom_passager_arrayList = new ArrayList<>();
    String selectQuery = "SELECT * FROM " + TABLE_NAME11 + " INNER JOIN " + TABLE_NAME1 + " ON " + COLUMN_ID_PASSAGER + " = " + COLUMN_ID_USER + " WHERE (" + COLUMN_ID_TRAJET + " = '" + et_idtrajet + "' AND " + COLUMN_VALIDATION_RESERVATION + " != 'Invalidé' AND " + COLUMN_DATE_ANNULATION_DU_PASSAGER + " IS NULL) ORDER BY " + COLUMN_DATE_DE_RESERVATION + " ASC";
    db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            prenom_passager_arrayList.add(cursor.getString(cursor.getColumnIndex(COLUMN_PRENOM)));
        } while (cursor.moveToNext());
        cursor.close();
        db.close();
    }
    return prenom_passager_arrayList;
}

public ArrayList<String> getTrajetIDPassager(String et_idtrajet) {
    ArrayList<String> id_passager_arrayList = new ArrayList<>();
    String selectQuery = "SELECT * FROM " + TABLE_NAME11 + " INNER JOIN " + TABLE_NAME1 + " ON " + COLUMN_ID_PASSAGER + " = " + COLUMN_ID_USER + " WHERE (" + COLUMN_ID_TRAJET + " = '" + et_idtrajet + "' AND " + COLUMN_VALIDATION_RESERVATION + " != 'Invalidé' AND " + COLUMN_DATE_ANNULATION_DU_PASSAGER + " IS NULL) ORDER BY " + COLUMN_DATE_DE_RESERVATION + " ASC";
    db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            id_passager_arrayList.add(cursor.getString(cursor.getColumnIndex(COLUMN_ID_PASSAGER)));
        } while (cursor.moveToNext());
        cursor.close();
        db.close();
    }
    return id_passager_arrayList;
}

public ArrayList<String> getTrajetNiveauPassager(String et_idtrajet) {
    ArrayList<String> niveau_passager_arrayList = new ArrayList<>();
    String selectQuery = "SELECT * FROM " + TABLE_NAME11 + " INNER JOIN " + TABLE_NAME1 + " ON " + COLUMN_ID_PASSAGER + " = " + COLUMN_ID_USER + " WHERE (" + COLUMN_ID_TRAJET + " = '" + et_idtrajet + "' AND " + COLUMN_VALIDATION_RESERVATION + " != 'Invalidé' AND " + COLUMN_DATE_ANNULATION_DU_PASSAGER + " IS NULL) ORDER BY " + COLUMN_DATE_DE_RESERVATION + " ASC";
    db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            niveau_passager_arrayList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NIVEAU)));
        } while (cursor.moveToNext());
        cursor.close();
        db.close();
    }
    return niveau_passager_arrayList;
}

public ArrayList<String> getTrajetAgePassager(String et_idtrajet) {
    ArrayList<String> age_passager_arrayList = new ArrayList<>();
    String selectQuery = "SELECT * FROM " + TABLE_NAME11 + " INNER JOIN " + TABLE_NAME1 + " ON " + COLUMN_ID_PASSAGER + " = " + COLUMN_ID_USER + " WHERE (" + COLUMN_ID_TRAJET + " = '" + et_idtrajet + "' AND " + COLUMN_VALIDATION_RESERVATION + " != 'Invalidé' AND " + COLUMN_DATE_ANNULATION_DU_PASSAGER + " IS NULL) ORDER BY " + COLUMN_DATE_DE_RESERVATION + " ASC";
    db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            age_passager_arrayList.add(cursor.getString(cursor.getColumnIndex(COLUMN_AGE)));
        } while (cursor.moveToNext());
        cursor.close();
        db.close();
    }
    return age_passager_arrayList;
}


text:
Q: 'WSGIRequest' object has no attribute 'session' I get this error sometimes in custom Middleware in process_response method. I have the following list of middlewares:
MIDDLEWARE_CLASSES = [
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'application.middleware.LastCampaignSessionMiddleware'

]
So session middleware is placed before my middleware. I don't have any del request.session expressions in source code.
This is process_response method:
    def process_response(self, request, response):
        if 'last_campaign_id' in request.session and request.session['last_campaign_id']:
            if request.COOKIES['last_campaign_id'] != request.session['last_campaign_id']:
                response.set_cookie('last_campaign_id', request.session['last_campaign_id'])
        return response

Not sure why it could happen at all.
EDIT 03-08-2012 12-30
It looks like browser requesting favicon:
[03/Aug/2012 10:26:42] "GET /favicon.ico/ HTTP/1.1" 404 6701

Is there no default behavior in django to resolve this url? Because I didn't explicitly specify view which should handle this request. And I don't use favicon in page source code. So I guess it's browser who requests /favicon.ico. I guess in case of 404 error HttpRequest wouldn't construct properly so no wonder I have no session in request object. But it's just my assumptions.
Also if it necessary I am using django dev server while getting this error.
EDIT 13-00
I have fixed this problem with favicon but still getting error. Why session may not exist in request?

A: If you came here because you updated to Django 2.0 and get this error, you might want to know that name MIDDLEWARE_CLASSES was replaced with MIDDLEWARE.
More here https://stackoverflow.com/a/47650447/1218179 and here https://docs.djangoproject.com/en/2.0/topics/http/middleware/

A: The problem was in middlewares order.
CommonMiddleware returns HttpResponsePermanentRedirect in cases when to request url have been added 'www' or trailing '/' (APPEND_SLASH and PREPEND_WWW in settings). In such case django stops looking through middleware list for process_request methods and begins to run process_response methods.
It's bad there is no information about such behavior for standard django middlewares (i.e. middleware could return in some cases HttpResponse object).


text:
Q: What are Selenium Docker image release versions for browser capabilities? Where is a list of all Docker image release versions for Selenium browser capabilities?
For instance, I can't find it on the standalone-chrome-debug Docker Hub page, or in the GitHub repo. I'm guessing the version numbers should sync with ChromeDriver versions.
image: selenium/standalone-chrome-debug:2.27 does not work, and I'd like to lock the version number.
Notice comments at end of images:
# docker-compose.yml
...
services:
   selenium:
     image: selenium/standalone-firefox-debug:2.47.1 # works (found this on a blog)
     # image: selenium/standalone-chrome-debug # works
     # image: selenium/standalone-chrome-debug:2.27 # breaks
...

Perhaps it's hiding in plain sight. Thanks for any tips!

A: In the change log of Chromedriver you can see comments like:
----------ChromeDriver v2.27 (2016-12-23)----------
Supports Chrome v54-56

You can extract it from there though there is no mention of Selenium versions as Chromedriver can be connected directly without the need of a Selenium server nor grid meaning they are independent.
Not sure if will help your case but I kept historical correlation between versions of Selenium, Chromedriver, Chrome, Firefox in the releases page of my project:
https://github.com/elgalu/docker-selenium/releases


text:
Q: What is Solr differential update execution time?
I am a newbie on Solr. I have set up the basics and is working properly. Now, I am using DIH for importing data from MySql. I will be using differential update for every update/insert in the MySql table. I want to know the approximate execution time. I cannot find any documentation on execution time.

Thanks!!

A: I've never even heard of differential update with respect to Solr.  Do you mean Atomic Updates?
http://wiki.apache.org/solr/Atomic_Updates
The amount of time that an atomic update takes is approximately the amount of time required to retrieve the existing record using the uniqueKey field value plus the amount of time required to index the new document, representing the retrieved values modified by the changes requested.
If you don't mean atomic updates, what DO you mean?


text:
Q: Simple BASH script to become a multi-process/'threaded' BASH script? I have the following, working BASH script, which I run on a Mac Pro 2010/Mojarve OS:
#!/bin/bash

c=0
cnt=0

# count up wav files
cnt=$(find /hummdinger/LoCI/LoCI_orig/VO/WAV_Processed/ -name "*.wav" | wc -l)
echo "there are $cnt .wav voice samples."

# go through and run rhubarb on them
for f in $(find /hummdinger/LoCI/LoCI_orig/VO/WAV_Processed/ -name "*.wav")
do
    c=$((c+1))
    echo "$c of $cnt";
    f=$(basename "$f" .wav)
    /hummdinger/LoCI/LoCI_orig/TSV/rhubarb-lip-sync-1.10.0-osx/rhubarb /hummdinger/LoCI/LoCI_orig/VO/WAV_Processed/"$f".wav -o /hummdinger/LoCI/LoCI_orig/LOCI_GAME_FILES/Compiled/Windows/sync/"$f".tsv
done;

It takes a list of WAV files, goes through each, scans the file and then produces output and stores the generated TSV files somewhere else. The point of 'rhubarb' is to produce lip-sync information from a recording (the WAV files). etc. etc. blah blah.
The one problem with this script is it takes ~10-12 HOURS to run over about 3,000 wav files. On my crappier, non-ECC ram, one-time-it-corrupted-the-whole-lot-and-I-made-a-vow-to-never-use-it-again Mac Mini 2018, it took about 3 hours.
But this is a Mac Pro, meaning though it's old (2010), but it's very reliable and has 12x Xeons. This is pretty low intensity work, so I'm missing out on that extra juice by making it single processor. I just want to get this script working with 10-15-30 threads, and hopefully this will speed it up and it'll be done in an hour or less; not most of the day.
My thoughts are: divide the directory of WAVs into groups of (total_files/15), put these listings in file1-15.txt, then read each one back and process it in 15 separate threads. But that's about as far as I've gotten :P
Can anyone help with making this a muti-process script? I'm an amateur and made this script with help from reddit.

A: With GNU Parallel you can do something like this:
rhubarb=/hummdinger/LoCI/LoCI_orig/TSV/rhubarb-lip-sync-1.10.0-osx/rhubarb

find /hummdinger/LoCI/LoCI_orig/VO/WAV_Processed/ -name "*.wav" |
  parallel $rhubarb {} -o {.}.tsv

Or (if you really need the output in a different dir):
find /hummdinger/LoCI/LoCI_orig/VO/WAV_Processed/ -name "*.wav" |
  parallel $rhubarb {} -o /hummdinger/LoCI/LoCI_orig/LOCI_GAME_FILES/Compiled/Windows/sync/{/.}.tsv

A: Write your script so that it iterates over its arguments.  For example:
#!/bin/bash

rhubarb='/hummdinger/LoCI/LoCI_orig/TSV/rhubarb-lip-sync-1.10.0-osx/rhubarb'
outdir='/hummdinger/LoCI/LoCI_orig/LOCI_GAME_FILES/Compiled/Windows/sync/'

for fn in "$@"; do
    bn=$(basename "$fn" .wav)
    "$rhubarb" "$fn" -o "$outdir/$bn.tsv"
done

Save this as, e.g., myscript1.sh and make it executable with chmod +x myscript1.sh.
You can run this directly, but it will process each file sequentially.  Instead, you want to run it with GNU parallel or xargs -P.  E.g. with a wrapper script like the following, which divides the number of files to process by the number of cores you have.
Note that depending on exactly what rhubarb does, this is likely to be more of an I/O-bound task than CPU-bound so adding too many cores isn't going to help - in fact, it will probably slow things down as there will be too much contention for disk I/O...especially if you are running this on a HDD rather than an SSD.
You might want to hard-code something like cores=4 or cores=8 in the script below rather than use lscpu | awk ... as I have (I wrote it like that because I'm running a threadripper 1950x with 16 cores and 32 threads....and I didn't want to run 32 jobs in parallel.  And also as an example of how you can extract useful info from lscpu).
Also recommended: if you have more than one drive, try to arrange things so that the directory you read the .wav files from is on one drive and the directory you write the .tsv files to is on another.  This will eliminate I/O contention between reading and writing the files.    If the .tsv files aren't huge, write them to a temporary directory on a tmpfs ramdisk and move them to their final location at the end of the script.
#!/bin/bash

wavdir="$1"

cores=$(lscpu | awk -F': +' '/^CPU\(s\):/ {cpus=$2};
                             /^Thread\(s\) per core:/ {tpc=$2};
                             END { print int(cpus / tpc) }')

count=$(find "$wavdir" -type f -name "*.wav" -print0 |
          perl -0ne '$c++;END{print $c}')

let files_per_thread=count/cores

find "$wavdir" -type f -name "*.wav" -print0 |
    xargs -0 -r -L "$files_per_thread" -P "$cores" /path/to/myscript1.sh

save this as, e.g., myscript2.sh and make it executable with chmod +x myscript2.sh.
This is the script you run from the command line or cron, or whatever.  It, in turn, uses xargs to run multiple instances of myscript1.sh in parallel.
Run it like:
./myscript2.sh /hummdinger/LoCI/LoCI_orig/VO/WAV_Processed/

BTW, this uses NUL as the separator between filenames so is safe to use with any filename (using newline as the filename separator is not safe because newline is a valid character within a filename).


text:
Q: Representation of roots of unity. How to represent solutions of $\sqrt[26]{1}$ with solutions of $\sqrt[26]{-1}$?
I know that $$w_{k}=\cos\left(\frac{0+2k\pi}{26}\right)+i\sin\left(\frac{0+2k\pi}{26}\right), \; \; k=\overline{0,25}$$
and $$z_{k}=\cos\left(\frac{\pi+2k\pi}{26}\right)+i\sin\left(\frac{\pi+2k\pi}{26}\right), \; \; k=\overline{0,25}$$
But I cannot establish connection that would rewrite $\sqrt[26]{1}$ using $\sqrt[26]{-1}$ i.e. $w_k$ using $z_k$.

A: Note that $1=e^{i(2k\pi)}$ and $-1=e^{i(2k+1)\pi}$
Thus
$$w_k=\sqrt[26]{1}=e^{\frac{i(2k\pi)}{26}}=e^{\frac{i((2k+1-1)\pi)}{26}}=e^{\frac{i[(2k+1\pi)]-i\pi}{26}}=z_ke^{\frac{-i\pi}{26}}=z_k\sqrt[26]{-1}$$

A: You yourself have already written the relation inadvertently. Here it is in a clearer form:
$$\sqrt[26]{-1}=\sqrt[26]{1} e^{i\pi/13}$$


text:
Q: Read array line by line 3 values by 3 values I want to read my array line by line 3 values by 3 values. So when I recover 3 values put in my matrix etc etc...
for(int i=0; i<_height; i++) {
    for(int j=0; j<_width; j++) {
        result = ifile.get();
        (image)[i][j]= (int)result;
        // Display the array which contains data
        cout << (image)[i][j] << " ";
    }
    cout << endl;
}

A: Try this:
for (unsigned int row = 0; row < 3; ++row)
{
    for (unsigned int column = 0; column < 3; ++column)
    {
        inFile >> image[row][column];
    }
}

Since your values are separated by "white space", which is spaces, tabs or newlines, this should work regardless of whether all values are on one line or many.
Edit 1: A safer alternative
The above assumes there is always 9 values and they are all valid integers.
If something goes awry, the above won't work.  The following is a more robust method.
unsigned int row = 0;
unsigned int column = 0;
bool all_values_read = false;
int value = 0;
while ((inFile >> value) && !all_values_read)
{
  image[row][column] = value;
  ++column;
  if (column >= 3)
  {
      column = 0;
      ++row;
      if (row >= 3)
      {
         all_values_read = true;
      }
  }
}

A: You could implement something like follows:
int count = 0;
for(int i=0; i<_height; i++) {
    for(int j=0; j<_width; j = j +3) {
        result = ifile.get(i,j);
        (image)[i][count]= (int)result;
        count += 1;
        // Display the array which contains data
        cout << (image)[i][count] << " ";
    }
    count = 0;
    cout << endl;
}

Where the get(int i, int j) function is a function that recovers the three values (or less if the line ends before j+3) starting from the position j of the i-th row.


text:
Q: FOSUserBundle check path blank page on production I have a site with FOSUserBundle. It works perfectly on both dev and prod environments on my local MAMP server. It works perfectly on my normal web server (dev and prod), but not in the other one. Recently I have uploaded my site on client's production server and I cannot login. In Dev it works, in prod it does not. There are no problems witch cache directory or logs. I get white page on /check route. It is weird cause app/check.php says that server is OK with PHP 5.6 IT work on my server but not here. Any guess how to debug it?

A: OK, I have tried everything, also things proposed by @k0pernikus and @zizoujab. I have added the same logs dev has, checked server config with app/check.php, checked Apache errors etc. Nothing. Non of these returned any errors.
It turned out that somehow server admin has reservered /check path for something. We have even checked cache files with routing definitions until we got to app.php file and it turned out that script doesn't even go there in case we use /check path. We have checked multiple pages at the same server and everywhere the problem is the same (even on pages not made with Symfony).
The funniest (or the worst) part of it is that for 30 minutes while talking to admin, he didn't know what is the reason for that. Still we are waiting for an answer but for now we had to change routing so that there is no /check path. As soon as we will receive an answer, I will post it here.
EDIT-------
It turned out that the server owner has thier API which uses /check globally. They trying to figure out if they can switch if off for user's servers.


text:
Q: Como tornar uma tabela responsiva usando (Twitter) Bootstrap? Estou trabalhando numa aplicação web usando Ruby On Rails 4 e grande parte da interface consiste de tabelas.
Gostaria que sugerissem uma forma de detectar o tamanho da tela em uso e, com base nisso, ocultar certas colunas de cada tabela.

A: Com o Twitter Bootstrap tudo fica mais fácil, basta você criar o HTML corretamente e incluir as classes certas em suas tags, visto que ele já tem todo o CSS criado para que você utilize o design responsivo.
Esse é um HTML básico de uma tabela responsiva:

...

...

Aqui explica direitinho: Bootstrap

A: Aqui tem uma opções interessantes pra tabelas responsivas:
http://elvery.net/demo/responsive-tables/
E não sei também qual versão do Bootstrap você está usando, mas a 3 tem umas alterações no modo de usar a grid...

A: Podes ocultar qualquer objecto por classe ou id usando o seguinte código:
@media (max-width:768px) {
    #id_a_ocultar_em_tablet {
        display: none;
    }

    .classe_a_ocultar_em_tablet {
        display: none;
    }
}

@media (max-width:480px) {
    #id_a_ocultar_em_smartphone {
        display: none;
    }

    .classe_a_ocultar_em_smartphone {
        display: none;
    }
}

Com as regras acima, podes criar CSSs especiais para cada dispositivo, caso queiras apenas esconder ou mostrar objectos podes usar estas classes, e fica tudo mais simples:
.visible-phone
.visible-phone
.visible-tablet
.visible-desktop
.hidden-phone
.hidden-tablet
.hidden-desktop

Por exemplo:

Este texto nao aparece num smartphone

Este texto SÓ aparece num smartphone

A: Simplesmente use o componente .table-responsive que fornece o Bootstrap:

        ...

Pode encontrar mais informação na documentação do projeto.
Não é necessário hackear o CSS ou usar outros componentes diferentes da tabela como foi sugerido.


text:
Q: MVC - How to pass data from view to controller I'm learning the MVC pattern right now and I have a short question concerning models and view. I have the following model:
class Person {
  private String name;
  private int age;
}

Now I want my view to ask some input to create a new Person:
public void askPerson() {
  System.out.println("Enter name:");
  //read with System.in
  System.out.println("Enter age:");
  //read with System.in
}

What is now the correct way to create this model. Should I:
1) save the user input in variables in my view and get them in my controller through getters in order to create the model in the controller (getName(), getAge()) or
2) should I create the model in the view and return it as a result of askPerson()?
What is in general the best way to pass such data from the view to the controller?
Thank you!

A: The cleanest way is to let controllers listen on the view. In turn the view can tell the controller something needs to happen.
Here is a fully functional example that can be compiled and run
In short it boils down to this.
In this example we assume the controller is already added as an observer to the view.
The view that will notify it's observers (controller).
class CreatePersonView extends Observable implements View {
    public void display() {
        System.out.println("\nWelcome to the create person view!");
        System.out.println("----------------------------------");

        System.out.print("Name: ");
        String name = System.console().readLine().trim();

        System.out.print("Age: ");
        int age = Integer.valueOf(System.console().readLine().trim());

        Map<String, Object> data = new HashMap<String, Object>();

        data.put("name", name);
        data.put("age", age);

        // generate the event
        setChanged();
        notifyObservers(data);
    }
}

The controller that will consume the event.
class Controller implements Observer {

    PersonService service;

    public void setPersonService(PersonService service) {
        this.service = service;
    }

    // simplified version
    public void update(Observable sender, Object arg) {
        Map data = (Map)arg;
        Person p = service.create((String)data.get("name"), (Integer)data.get("age"));

        //debug
        System.out.println("Created new person: " + p);
    }
}

The main benefit here is that the controller doesn't know anything about the implementation of the view and vice versa. Making them loosely coupled and interchangeable. Which is the whole purpose of MVC.

A: Create your bean object, fill it and send it from View to Controller. A similar post can give you help to write the code. Here is the link:
MVC sending data from View to Controller
Ok as per your request, let me put some code here. This code is created only for the purpose of your understanding. So modify it as per your need and feel free to make any improvements.
Model class
class MyModel {
      private String name;
      private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "MyModel [name=" + name + ", age=" + age + "]";
    }

}

View Class
class MyView {
/**
 * Create view elements, take user inputs and
 * set the in the model object. Finally send it
 * to the controller for processing
 */

private void onSomeViewEvent(Object myevent) {
    MyModel model = new MyModel();

    // take the properties from event and set in model
    model.setAge(25);
    model.setName("Yourname");

    // send to controller
    MyController controller = new MyController();
    controller.processRequest(model);
}

}
Controller Class
class MyController {

    public void processRequest(MyModel model) {

        /**
         * Inspect the model and process it as per your need.
         */
    }
}


text:
Q: Why does my generator block Flask from sending SSE responses? I am trying to use Flask to serve an SSE request, but my client only receives the events after my generator function has stopped / the connection is closed.
Here is the simplest reproduction I have been able to produce to demonstrate this:
#!/usr/bin/env python

from flask import Flask, Response
from time import sleep

def stream():
    n = 10
    while n > 0:
        yield "data: hi\n\n"
        sleep(0.5)
        n = n - 1

app = Flask(__name__)

@app.route("/events")
def streamSessionEvents():
    return Response(
        stream(),
        mimetype="text/event-stream"
    )

app.run(debug=True, threaded=True)

Here is my test client:
<!doctype html>
<html>
<head>
    <script>
        var source = new EventSource(
            "/events"
        );
        source.onmessage = function(event)
        {
            console.log(event);
        };
    </script>
</head>
<body>
</body>
</html>

The stream() generator will produce ten events and then return (I've deliberately done this to demonstrate the problem, ideally the generator would keep going forever), at which point the connection is dropped.  The client page logs nothing until this point, then it spits out all ten events (if I dont have the counter variable in stream() then the page never gets any events).
I havent used Python or Flask a great deal and this has me very stuck, I cant see what I'm doing differently to other examples around the net.  Any help very much appreciated.

A: Two things might interfere:

*

*You have debug set to True, which installs middleware (specifically the Werkzeug debugger) that may break streaming.
From the Flask streaming patterns documentation:

Note though that some WSGI middlewares might break streaming, so be careful there in debug environments with profilers and other things you might have enabled.

However, using either curl or Chrome on your test code with Flask 0.10.1 and Werkzeug 0.9.4 I see the data: hi responses come streaming through properly, regardless of the debug flag setting. In other words, your code is working correctly with the most recent versions of the Flask stack.

*EventSource streams are subject to same-origin policy limits. If you are not loading the HTML page from the same host and port, the request to your Flask server will be denied.
Adding the test page source in the Flask server at a separate route works for me:
@app.route('/')
def index():
    return '''\
<!doctype html>
<html>
<head>
    <script>
        var source = new EventSource(
            "/events"
        );
        source.onmessage = function(event)
        {
            console.log(event);
        };
    </script>
</head>
<body>
</body>
</html>
'''


text:
Q: echo response php +json encode My problem is that in the first code below it doesn't display the data on browser, just shows a black page. There are no errors in the logs.
Another thing this displays the data using var_dump or print_r but then it doesn't encode in the right json format.
Is there a way of echoing the response? On the second code I follow exactly the same procedure as the first and it shows me the data I want without var_dum or print_r.
First code
<?php
/*
 * Following code will list all the products
 */
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/conectaDB.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
// get all products from products table
$result = mysql_query("select cd.id, cd.dt_ini_camp, cd.dt_fim_camp, cd.descricao, (select sum(quantidade) from lin_doc where id_cab_doc = cd.id) as qtd from cab_doc cd where cd.id_tipo_doc = 1") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["cab_doc"] = array();
    while ($row = mysql_fetch_array($result)) {
        var_dump($row);
        // temp user array
        $linha                = array();
        $linha["id"]          = $row["id"];
        $linha["dt_ini_camp"] = $row["dt_ini_camp"];
        $linha["dt_fim_camp"] = $row["dt_fim_camp"];
        $linha["descricao"]   = $row["descricao"];
        $linha["qtd"]         = $row["qtd"];
        // push single product into final response array
        array_push($response["cab_doc"], $linha);
    }
    // success
    $response["success"] = 1;
    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";
    // echo no users JSON
    echo json_encode($response);
}
?>

The output of this code is a blank page.
Second code
The below works fine and displays the data:
<?php
/*
 * Following code will list all the products
 */
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/conectaDB.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_POST["id"])) {
    $id = $_POST['id'];
    // get all products from products table
    $result = mysql_query("SELECT id, id_estab, dt, hr, quantidade FROM lin_doc WHERE id_cab_doc = $id") or die(mysql_error());
    // check for empty result
    if (mysql_num_rows($result) > 0) {
        // looping through all results
        // products node
        $response["lin_doc"] = array();
        while ($row = mysql_fetch_array($result)) {
            //var_dump($row);
            // temp user array
            $linha               = array();
            $linha["id"]         = $row["id"];
            $linha["id_estab"]   = $row["id_estab"];
            $linha["dt"]         = $row["dt"];
            $linha["hr"]         = $row["hr"];
            $linha["quantidade"] = $row["quantidade"];
            // push single product into final response array
            array_push($response["lin_doc"], $linha);
        }
        // success
        $response["success"] = 1;
        // echoing JSON response
        echo json_encode($response);
    } else {
        // no products found
        $response["success"] = 0;
        $response["message"] = "No products found";
        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    // echoing JSON response
    echo json_encode($response);
}
?>

Output of second code:

{"lin_doc":[{"id":"66","id_estab":"12","dt":"2013-03-26","hr":"16:30:00","quantidade":"373.000"},{"id":"148","id_estab":"16","dt":"2013-07-08","hr":"20:45:00","quantidade":"119.000"},{"id":"260","id_estab":"14","dt":"2012-09-20","hr":"20:00:00","quantidade":"324.000"},{"id":"275","id_estab":"33","dt":"2012-07-23","hr":"22:00:00","quantidade":"489.000"},{"id":"306","id_estab":"25","dt":"2012-07-27","hr":"20:45:00","quantidade":"338.000"},{"id":"468","id_estab":"15","dt":"2013-04-23","hr":"20:45:00","quantidade":"263.000"},{"id":"546","id_estab":"18","dt":"2013-05-22","hr":"11:15:00","quantidade":"87.000"},{"id":"578","id_estab":"11","dt":"2013-03-06","hr":"13:30:00","quantidade":"30.000"},{"id":"601","id_estab":"07","dt":"2013-02-23","hr":"20:00:00","quantidade":"87.000"},{"id":"617","id_estab":"14","dt":"2012-11-23","hr":"20:45:00","quantidade":"234.000"},{"id":"651","id_estab":"03","dt":"2013-05-12","hr":"20:45:00","quantidade":"311.000"},{"id":"752","id_estab":"06","dt":"2013-01-13","hr":"13:30:00","quantidade":"219.000"},{"id":"803","id_estab":"22","dt":"2013-02-23","hr":"16:30:00","quantidade":"396.000"},{"id":"819","id_estab":"06","dt":"2012-10-21","hr":"18:15:00","quantidade":"333.000"},{"id":"850","id_estab":"03","dt":"2013-01-19","hr":"14:30:00","quantidade":"265.000"},{"id":"899","id_estab":"22","dt":"2013-06-15","hr":"13:00:00","quantidade":"453.000"},{"id":"993","id_estab":"10","dt":"2013-02-03","hr":"19:30:00","quantidade":"441.000"}],
  "success":1}

A: In your connect: mysql_set_charset('utf8', $link);
try:
<?php
$link = mysql_connect('db_host', 'db_user', 'db_password');
mysql_set_charset('utf8', $link);
$db_selected = mysql_select_db('your_db', $link);

or encode your array:
foreach( $row as $value ) {
    $value = utf8_encode( $value );
}

I'm not sure if your query is ok in this point:
"as qtd from cab_doc cd where cd.id_tipo_doc = 1"
                    ^^^^


text:
Q: Adding a captcha plugin for comments in the site Hi, I am new to WordPress.I need to add captcha in my site just before the comments section. Wherever there is comments, I need to display the captcha. I do not have a form. How can I do it?

A: Actually there are a lot of solution for this. Simply a google could answer you the whole. And also WordPress plugin repository could help you. But to pinpoint, you can use Plugins easily. Try anyone of them:

*

*Captcha — WordPress plugin

*SI CAPTCHA Anti-Spam — WordPress plugin

*more...
And also, Akismet is a very good plugin to get the spam out of a WordPress site. And the good news is: Akismet is freely distributed with WordPress.

A: You can check this plugin for adding captcha in your site wherever you want inside any form Really Simple Captcha


text:
Q: Does differential sending benefit current sensing circuits in the same way as differential voltage sending? I'd like to send two currents along a long twisted pair (well, ~5m, but I want to be very careful about noise in this experiment). The two currents are produced by two photodiodes with equal and opposite bias voltages, with the same incident light, giving equal and opposite currents. At the receiver end, these currents are sensed by a transimpedance amplifier into an ADC.
Sending voltages differentially gives a benefit to common mode noise rejection. Does the same benefit apply to differential sending of currents? I am unsure as to the mechanism by which "pick-up" from EM interference affects the signal. I'm interested in sensing signals up to around 100kHz.

A: Yes, differential currents help reduce externally coupled noise just like differential voltages do.
External noise sources aren't just voltage or just current sources since they have neither zero nor infinite impedance.  See what Thevenin and Norton had to say.
You say you are interested in signals up to 100 kHz, but failed to mention the lowest frequency of interest.  If you aren't trying to measure down to DC, then a transformer front end on the receiving amplifier might help a lot.  The magnetic field in the transformer is only a function of the current thru the primary.  The common mode voltage of the primary is largely ignored, except for whatever capacitive coupling there is between primary and secondary.  Some transformers have a shield between primary and secondary for this purpose.  You connect the shield to the ground of the circuit that receives the signals from the secondary.  Such a setup can have very high input signal common mode rejection ratios.


text:
Q: Keeping Table Rows Together as default in MS Word I would like my table in Word (MS 365) to never page break in a row.

*

*Ideally it would be a permanent setting, but

*if that isn't possible, then one setting for all tables in my entire document would be nice.

I know how to do it table by table - see this SE post, where a nice answer is give here: "Keeping Table Rows Together".

A: New Tables: Consider saving a formatted but blank table as a Quick Table

*

*Format a sample table, with blank contents and set the rows to not
allow breaking across pages.

*Then save it as to the QuickTables Gallery.

Note that you can do this in the general gallery or you can save it in a particular template. Here is my writing on where Building Blocks can be stored. Give it a descriptive name. You may want to start the name with an underscore.

Note that this is set with an underscore before both the name and the category. It will show up at the top of the alphabetical list of Quick Tables. "_Mine" category is ahead of the "General" category.

You can insert a Quick Table by simply typing the start of the name!
The name should be something you would not normally be typing. In this instance, when you type "_rows" you should get a prompt allowing you to insert the table. This is the standard action for AutoText and other Building Blocks. Typing the first four (unique) characters of the name gives access.

You can change the formatting of the newly added table.
Once you have inserted the new table using your Quick Table, you can apply different table styles if you want and can add or delete rows/columns. You can also create multiple Quick Tables with different formatting but the non-breaking characteristic.
On a Mac
Instead of using Quick Tables, you would save your table as AutoText. Again, you want a name that is not going to show up in ordinary typing.
Existing Tables require a macro solution
The following macro will set any tables in the body of the document to not allow rows to break. Note the limitations.
Sub TableRowsNoBreak()
    ' Charles Kenyon 2021-June-7
    ' Change all tables in a document to the setting of not allowing rows to break across pages
    ' Will work on tables in body of document (not in Headers/Footers or TextBoxes) - these should not have page breaks anyway
    ' May not work on nested tables
    ' https://superuser.com/questions/1655136/keeping-table-rows-together-as-default-in-ms-word
    '
    Dim oTable As Table
    Dim oDoc As Document
    Set oDoc = ActiveDocument
    '
    For Each oTable In oDoc.Tables
        oTable.Rows.AllowBreakAcrossPages = False
    Next oTable
    Set oDoc = Nothing
    Set oTable = Nothing
End Sub

Installing Macros by Word MVP Graham Mayor
Note also, that this setting to not break may be broken in some instances by the paragraph setting of "Keep lines together" or "Keep With Next."


text:
Q: How to organize files in Git Repository I have a project that I've been working on for a while now and so far it has been just me working on it However, now someone new is about to join to help me with the project and I want to organize the files in my git repository. It's an iOS project. Right now the files are all over the place in the repo, but organized in Xcode. So for example, in Xcode there's the main project folder then there's three sub folders (i.e. Utilities, Main, Objects) and each folder has it's respective .h and .m files. But on my git repo on Github, the files are all over the place. If I try to create folders within the local repo directory and put the .h and .m files in there, the file names become red in Xcode. How can I organize my repo like it is in Xcode?

A: Venmo has a great open source command line tool (called Synx) that might be just what you're looking for:
https://github.com/venmo/synx

A: This has been a question I have dealt with in organizing iOS files/folders.
Once your project starts involving more than a few simple UIViews and images, yes, I think an organization structure is necessary. I have been a fan of folder references in XCode to keep organized. This way the XCode sidebar simply reflects your exact directory structure in Finder, as opposed to showing you all the files organized in your own fake yellow folders that don't actually correspond to real directories.
Here is great post to help you sort out references vs groups: http://vocaro.com/trevor/blog/2012/10/21/xcode-groups-vs-folder-references/
So yes, if you decide to change to using references, you will have to re-add all your files, and relink all your assets appropriately. The article talks about some downsides of doing this, but I haven't personally experienced them.
Keep in mind re-organizing all your files now might be a bit of work, but you will thank yourself in the long run!

The other way of doing it is to put all your files/assets in directories, delete the files in the sidebar in XCode, and then add the all again, thus updating their reference paths. Then you can manually create yellow folders (groups) to mimic your folder structure in Finder. But you will always have to remember to keep your structure updated since it doesn't happen automatically. The post above does a better job of explaining it.


text:
Q: Ignore the WHERE statement based on conditions in MySQL Let's say that I have a table with some columns and one column is named col. I want to apply the following filter in a SELECT statement if possible.

*

*if col = "" THEN return the whole table

*otherwise return only the rows where col = the given value
Example:
col output

10     9
 9     8
 0    10

If I want to filter the results based on column col then
I could do a simple:
SELECT * FROM table
WHERE col = 10

and I would get only the rows where col=10.
But I would like to get the full table if the condition was col = ".
EDIT: Unfortunately, I cannot use the SET keyword to set variables.

A: Assuming that the "given value" is contained inside a user variable or parameter:
WHERE @var = '' OR col = @var
WHERE :var = '' OR col = :var
WHERE ? = '' OR col = ?

If you are "building" the query somehow you could simply skip the where clause based on the input.

A: Where is the 'given value' coming from if you can't put it in a variable?
Is it kept on another, single row, table? If it is, you could do this with a join:
select m.* from maintable m
join giventable g on 1=1
where g.givenvalue=''
or m.col=g.givenvalue

Or is it passed as a parameter to a stored procedure or function? If so, you can use almost exactly the syntax in the first answer:
select * from maintable m
where param1=''
or m.col=param1


text:
Q: Justify conditional If there is an interpretation $I$ in wich $A=\forall x (P(x)\rightarrow Q(x))$ is true, then $(P(x)\rightarrow Q(x))$ is not true ands is not false in $I$.
I need to justifiy this is false. So, if A is true for $I$ this means that every valuation on $I$ satisfies A. A little more formally, valuation $v$ satisfies $\forall x (P(x)\rightarrow Q(x))$ iff $v$ satisfies $P(x)\rightarrow Q(x)$ and every x-equivalent valuation $v'$  satisfies $P(x)\rightarrow Q(x)$. Therefore, it doesnt exists a valuation on $I$ in wich $P(x)\rightarrow Q(x)$ is false, then $P(x)\rightarrow Q(x)$ is true for $I$.
Is this ok?

A: I think you did a fine job with the proof.
So the only suggestion I'll make is simply a matter of "parsing"/choice of words, not directly related to the "content" of the proof. I'll italicize the word choices, then follow each italicization with a suggested replacement, which you can "take or leave."
"...  [M]ore formally, valuation $v$ satisfies $\forall x (P(x)\rightarrow Q(x))$ iff [if and only if] $v$ satisfies $P(x)\rightarrow Q(x)$, and every x-equivalent valuation $v'$  satisfies $P(x)\rightarrow Q(x)$. Therefore, it doesn't exists [there does not exist] a valuation on $I$ in [for?] which $P(x)\rightarrow Q(x)$ is false, then [and hence it follows that] $P(x)\rightarrow Q(x)$ is true for $I$."