text:
Q: Retrive data from mysql on my android application I am try to retrive(read) an array of course form database (mysql) and display it as list of item in my android activity the problem is i have more than one row in my table (course) but it retrive only the first row also if the table (course) have know data insert my application step after the run even that i have case in my code that display toast message that say there is no course
class JSONParser.java
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
   }

class ViewALLCourseStudent.java
package com.ksu.sms;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ViewALLCourseStudent extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser(); //class

    ArrayList<HashMap<String, String>> coursesList;

    //url to get all products list
    private static String url_all_course = "http://10.0.2.2/SmsPhp/view_all_course.php";
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_course = "course";
    private static final String TAG_CourseID = "CourseID";
    private static final String TAG_Name = "Name";

    // course JSONArray
    JSONArray courses = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_all_course_student);

        coursesList = new ArrayList<HashMap<String, String>>();

        // Loading courses in Background Thread
        new LoadAllCourses().execute();

        // Get list view
        ListView lv = getListView();
     // on seleting single course
        // launching Edit course Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

             public void onItemClick(AdapterView<?> parent, View view,
                     int position, long id) //one of the list
             {
                 // getting values from selected ListItem
                 String CourseID = ((TextView) view.findViewById(R.id.CourseID)).getText()
                         .toString();
                 // Starting new intent
                 Intent ViewCourseStudent = new Intent(getApplicationContext(),
                         ViewCourseStudent.class);
                 // sending Course ID to next activity
                 ViewCourseStudent.putExtra(TAG_CourseID, CourseID);

                 // starting new activity and expecting some response back
                 startActivityForResult(ViewCourseStudent, 100);
             }
         });

     }
 // Response from view course Activity

    @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user view course
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

}
    /**
     * Background Async Task to Load all course by making HTTP Request
     * */
    class LoadAllCourses extends AsyncTask<String, String, String>
    {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ViewALLCourseStudent.this);
            pDialog.setMessage("Loading Courses. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        /**
         * getting All products from u r l
         * */
        @Override
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_course, "GET", params);

            // Check your log cat for JSON response
            Log.d("All courses: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // course found
                    // Getting Array of course
                    courses = json.getJSONArray(TAG_course);

                    // looping through All courses
                    for (int i = 0; i < courses.length(); i++)//course JSONArray
                    {
                        JSONObject c = courses.getJSONObject(i); // read first

                        // Storing each json item in variable
                        String CourseID = c.getString(TAG_CourseID);
                        String Name = c.getString(TAG_Name);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_CourseID, CourseID);
                        map.put(TAG_Name, Name);

                        // adding HashList to ArrayList
                        coursesList.add(map);
                    }
                } else {
                    Toast.makeText(getBaseContext(),"there is no course" ,Toast.LENGTH_LONG).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            ViewALLCourseStudent.this, coursesList,
                            R.layout.list_item, new String[] { TAG_CourseID,
                                    TAG_Name},
                            new int[] { R.id.CourseID, R.id.Name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

and php for view all course
   <?php

/*
 * Following code will list all the course
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();
// get all courses from course table
$result = mysql_query("SELECT *FROM course") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0)
 {
    // looping through all results
    // products node
    $response["course"] = array();

     while ($row = mysql_fetch_array($result))
     {
        // temp user array
              $course = array();
            $course["CourseID"] = $row["CourseID"];
            $course["Code"] = $row["Code"];
            $course["Name"] = $row["Name"];
            $course["OfficeHours"] = $row["OfficeHours"];
            $course["CreditHours"] = $row["CreditHours"];
            $course["Description"] =$row["Description"];
            $course["MaxAbsenceDays"]= $row["MaxAbsenceDays"];
            $course["ExamsDates"] = $row["ExamsDates"];

        // push single product into final response array
        array_push($response["course"], $course);
        // 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);
}

?>

Any thing you want i can explain.

A: Look at the example given in halloandrdoid or SPTechnolab blog
There is a good example for connecting MySql using PHP and it worked for me.


text:
Q: Relationship between Markovianity and linear response function I consider a two level system interacting with a continuum of field. The Hamiltonian in Schrodinger picture, under the rotating wave approximation is:
$$H=-\hbar \omega_0 \sigma_z + \sum_k \hbar \omega_k a^{\dagger}_k a + \sum_k \hbar g_k ( a^{\dagger}_k \sigma_- + a_k \sigma_+).$$
In Gardiner & Collet, input output theory paper: https://journals.aps.org/pra/abstract/10.1103/PhysRevA.31.3761, they use this Hamiltonian to describe the dynamic of light field interacting with a system $S$ (a qubit in my example).
At some point they need an approximation of flat coupling to proceed, i.e $g_k \approx g$. They call it the Markov approximation.
A markovian dynamic is a dynamic in which there are no memory effect. In my own word, with handwavy approach, I would say that in this example, if the light field is cut, the qubit will directly process under its free evolution. He won't be aware there had a field just before.

What I would like to know is if there is a link between this and some aspect of classical linear response theory. Basically if I have an input $e(t)$, and an output $s(t)$, those two are related, if the system is linear by:
$$s(t) = \int_{-\infty}^{t} \chi(t-t') e(t') dt'.$$
On my basic understanding, if the system has no memory, I would expect the function $\chi(t-t')=\chi_0 \delta(t-t')$ (if I cut the input, the output is instantaneously cut).
It implies that $\chi(\omega)=\chi_0$: flat in frequency.
My questions:
Am I correct if I say that classically a system will be markovian if the linear responce function is a delta dirac as I wrote? If no, why isn't it true? It would mean the system will have some memory effect?
Is the Markov approximation made in Gardiner & Collet (and in many other places actually) physically related to this intuition?

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP - loop through messages in array I have weird problem with my PHP code. I decoded an elasticsearch json, and I got this array:
Array ( [took] => 1 [timed_out] => [_shards] => Array ( [total] => 6 [successful] => 6 [skipped] => 0 [failed] => 0 ) [hits] => Array ( [total] => 7336 [max_score] => 0.8790647 [hits] => Array ( [0] => Array ( [_index] => logstash-2019.02.25 [_type] => doc [_id] => 5T8GJWkBAZbF3w3t4NF2 [_score] => 0.8790647 [_source] => Array ( [@version] => 1 [log-level] => ERROR [port] => 50906 [host] => 6b14cd1f183d.mynetwork [@timestamp] => 2019-02-25T14:20:01.367Z [Timestamp] => 2019-02-25T13:57:40+0000 [message] => Array ( [0] => 2019-02-25T13:57:40+0000 ERROR something happened in this execution. [1] => something happened in this execution. ) ) ) [1] => Array ( [_index] => logstash-2019.02.25 [_type] => doc [_id] => 7z8GJWkBAZbF3w3t4NF2 [_score] => 0.8790647 [_source] => Array ( [@version] => 1 [log-level] => INFO [port] => 50906 [host] => 6b14cd1f183d.mynetwork [@timestamp] => 2019-02-25T14:20:01.369Z [Timestamp] => 2019-02-25T14:00:13+0000 [message] => Array ( [0] => 2019-02-25T14:00:13+0000 INFO takes the value and converts it to string. [1] => takes the value and converts it to string. ) ) ) ) ) )

What I want is only to print the "messages".
If I run this code:
$echo json_decoded['hits']['hits']['0']['_source']['message']['0']
It echo "2019-02-25T13:57:40+0000 ERROR something happened in this execution."
And if I run this code:
$echo json_decoded['hits']['hits']['1']['_source']['message']['0']
It echo "2019-02-25T14:00:13+0000 INFO takes the value and converts it to string."
ALL GOOD SO FAR, but now I want to run it as loop, to print the messages. I made the following loop:
foreach($json_decoded['hits']['hits'] as $host) {
    echo $host[$index]['_source']['message']['0'];
    $index++;
}

I don't get any output. What is the problem?

A: When you foreach over ['hits']['hits'] this will iterate over the next level of the array (so the ['0'] and ['1'] elements).  So you don't need to add in the [$index] part of your echo or the $index value...
foreach($json_decoded['hits']['hits'] as $host) {
    echo $host['_source']['message']['0'];
}


text:
Q: MUI-DataTables does not sort my formatted date I have a data set recieved as response from a API call in which I have the dates in the format of "2020-06-10" which is (YYYY-MM-DD), but I need this to be displayed as "10 June 2020" for which I am using a utility as:
const SPACED_DATE_FORMAT = "DD MMM YYYY";

export const getHyphenatedDate = (dateString) =>
  moment(dateString, "YYYY-MM-DD").format(SPACED_DATE_FORMAT);

But now when I pass this data to MUI Datatable implementation and the sort does not work as expected (neither in asc nor in desc), it just get shuffled randomly.
Please suggest how can I achieve both points of display the expected format and the correct sorting on top of it.
Library version used:
"moment": "2.24.0",
"mui-datatables": "2.14.0",
"react": "16.13.1",
"react-dom": "16.10.2"
NOTE: If I do not format the dates, the sorting works fine.
Sandbox with replicated issues : https://codesandbox.io/s/objective-golick-8qvzf

A: I have solved thism by converting the gridData date value using toDate() and getTime() through momentand using customBodyRender on date objects in columns definition as
customBodyRender: value =>
      moment(new Date(value)).format(SPACED_DATE_FORMAT)
Below Sandbox has the fix to it
https://codesandbox.io/s/hopeful-butterfly-isdjb?file=/src/App.js:2402-2497


text:
Q: condition specific differentially expressed genes I have log2 transformed gene expression data set.
        Condition1-A Condition1-B Condition1-A Condition1-B Condition1-A  Condition2-B Condition2-B  Condition2-A   Condition2-A  Condition2-A
    G1  7.208092    6.750469    8.075674    7.013972    7.449042    7.171538    6.978883    6.952459    7.151522    7.279471
    G2  3.0738758   1.9639700   2.5514604   2.5976361   1.9519020   2.9587819   0.9509838   1.3255526   3.2792520   2.4635816
    G3  -3.292569   -3.144790   1.540046    -3.596165   -3.584326   -3.204754   -3.293944   1.372275    -3.421160   -3.022793
    G4  5.935161    5.486081    5.441551    5.629999    5.265330    5.526397    5.353094    5.236713    5.404589    5.780409
    G5  5.105139    5.219205    4.789138    5.304543    5.033632    5.236399    5.367262    5.017811    4.819554    4.609520
    G6  2.610378    2.390324    3.307976    2.589459    2.670613    1.651612    2.806704    -3.319884   1.309417    2.552799

There are two groups A and B from two different conditions Condition1 and Condition2.
I want to identify those genes that are differentially expressed between A and B in condition1 but these genes should not be differentially expressed in condition2 or should be oppositely regulated in condition2 compared to condition1.
I tried different contrasts like : Condition1(A-B) - Condition2(A-B) using limma package in R. But this constrast is not working and instead giving me those genes that are differentially expressed between two groups (A-B) in both the conditions.
Is there a method by which I can achieve the problem mentioned above?
Any help is very much appreciated.
Thanks.
Edited : I used the model : Condition + Group + Group*Condition
Group : A and B
Condition : 1 and 2
The contrast that I was using was :
Condition1.GroupA-Condition1.GroupB - Condition2.GroupA-Condition2.GroupB
The contrast :
(Intercept)
0
GroupB
0
Condition2
-1
GroupB:Condition2
0

Code :
library(limma)
des <- model.matrix(0 ~ Condition*Group)
fit<-lmFit(data,des)
fit2<-contrasts.fit(fit,contrasts = c(0,0,-1,0))
fit2<-eBayes(fit2)

topgenes <- topTable(fit2, coef=c(1:2), adjust="fdr", sort.by="B", number=Inf)

A: I'm not sure that any single contrast will accomplish what you want. Why not just address directly the requirements that you specify?
First, determine all the genes differentially expressed, under condition 1, between groups A and B. Call that group GeneSet1. Then determine which of those genes are differentially expressed, in the same directions between groups A and B, under condition 2. Call that GeneSet2. Remove from GeneSet1 all the genes in GeneSet2. You are then left with the genes that meet your specification: differentially expressed in condition 1 but not differentially expressed or differential in the opposite direction under condition 2.
You should in any event double-check how you specify the model matrix and the contrasts in the limma package, following examples in the vignettes or other references. It's been several years since I've tried to use that package, but at first glance it seems that your "contrast" doesn't do anything besides provide the negative of gene-expression values under condition 2 versus condition 1. It doesn't seem to take the Groups into account at all.


text:
Q: Неправильная запись при сохранении QJson Не могу найти чего то подобного на просторах Инета. Проблема в следующем: Читаю json файл, после просто сохраняю. Но значения получаются следующие(слева считанный , справа сохраненный)
Так же прикладываю код который сохраняет файл.
void JsonSetings::saveJson(SetupSettings setting, QString nameJson)
{
   QString val;
   QFile file;
   file.setFileName("test1.json");
   file.open(QIODevice::WriteOnly | QIODevice::Text);
   QJsonObject textObject;
   QJsonObject textObject2;
   textObject2[namesjson.mType] = setting.mType;
   textObject2[namesjson.mCounter] = setting.mCounter;
   textObject2[namesjson.mAlgorithm] = setting.mAlgorithm;
   textObject2[namesjson.mWork] = setting.mWork;
   textObject2[namesjson.mRoll] = setting.mRoll;
   textObject2[namesjson.mPitch] = setting.mPitch;
   textObject2[namesjson.mYaw] = setting.mYaw;
   textObject2[namesjson.mOwnSpeed] = setting.mOwnSpeed;
   textObject2[namesjson.mInstantSpeed] = setting.mInstantSpeed;
   textObject2[namesjson.mMask] = setting.mMask;
   textObject2[namesjson.mProtocol] = setting.mProtocol;
   textObject2[namesjson.mDriveSpeed] = setting.mDriveSpeed;
   textObject2[namesjson.mDriveDirection] = setting.mDriveDirection;
   textObject.insert("presets",textObject2);
   file.write(QJsonDocument(textObject).toJson());
}

Пожалуйста подскажите. Задача решена но мой Перфекционизм внутри не дает покоя.

A: Округляйте перед сохранением либо храните в строковом представлении.


text:
Q: Error while hosting a asp.net site on Go Daddy My website runs fine locally but when I host it on Go Daddy I get an error:

Cannot execute a program. The command being executed was G:\PleskVhosts\website\httpdocs\bin\roslyn\csc.exe /shared /keepalive:10 /noconfig /fullpaths @C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\50de3e74\54b1af4e\o0tsqc2f.cmdline.

When I looked into Google for suggestions I found out a solution
A simple solution for this issue is that removing Roslyn compiler plugin from your project and using old compiler. In order to remove Roslyn:
Follow Tools > NuGet Package Manager > Manage NuGet Packages for Solution in Visual Studio
Find DotNetCompilerPlatform and uninstall it
After executing above steps when I try to run the project I get the below error:

Severity  Code    Description Project File    Line    Suppression State
  Error   Copying file bin\roslyn\csc.exe to obj\Debug\Package\PackageTmp\bin\roslyn\csc.exe failed. Could not find a part of the path 'bin\roslyn\csc.exe'.

When I reinstall the DotNetCompilerPlatform the error disappears but I get the previous error on godaddy site.
What should I do???


text:
Q: Regarding SIgnals in C I understand with the help of Signals, we can pass interrupts to the executing C programs, and direct them to behave according to the Handlers assigned. When ctrl+c is pressed, SIGINT is executed.
Currently I am running a setup, where in  I have 2 systems. Both have servers(DiscoveryServers) capable of multicast extension(mDNS). I have made use of Signals like SIGHUP and SIGKILL.
I am trying to understand what SIGKILL and SIGHUP actually does here.
So in one of the systems, I have an extra server which registers to the local discovery server. This server is advertised throughout the network with the help of mDNS.
Now, through SIGHUP, i can see that the terminal close of the server is detected amd the corresponding handler is executed.
But when I shut the system down, both the server and the Discovery server of that system, should go off. But that is detected inconsistently( not always) through SIGHUP. I tried with SIGKILL and still the response is the same. It is very unclear as to why it is happening?
Is it because the mDNS is using UDP and the UDP is unreliable?
Eg: Consider A and B as two systemss. Both A and B have discoveryservers running (capable of mDNS: meaning they can advertise the server records throughout the network) which contains the list of servers running on their system respectively. An extra server (server E) running on A, registers to discovery server of A. Now  the registered server records are also advertised. Because of mDNS, the discovery server in B also updates its cache with all the advertiesments from system A. B can be seen as a client, runs a particular API, to get the list of servers running on the netowrk.  All of this works fine.
If i close the terminal of the extra server on purpose, SIGHUP handler works smoothly. I can see from logs of both the discovery servers that the extra server has been removed.
Now if i shutdown the system A unexpectedly, the terminals running the server applications should close. That can be achieved with SIGHUP handler. What i observe from the log of system B is that, sometimes there are clean removal of the servers, sometimes partial.
There is no clarity as to why it is happening.


text:
Q: Prove that the hydrogen continuum spectrum wavefunctions are distributions This is a truly difficult question, because the answer I am looking for is strictly mathematical. In the textbook by L. Landau & E. Lifschitz, "Quantum Mechanics", the Schrödinger wavefunction generically denoted by $R_{kl}$ of the H-atom corresponding to the continuous $E\in[0,\infty)$ spectrum of the dummy particle is given by formula (36.18), where F is a Kummer (confluent) hypergeometric function.
The question: Identify the proper space of distributions and prove that $R_{kl}$ are vectors in it.
I know a bit about distribution spaces, and found this discussion here Do tempered distributions form a topological subspace of the space of distributions? both illuminating and dissapointing (in the sense that I was truly hoping for a proof that the inclusion $\mathcal{S}'(\Omega)\subset \mathcal{D}'(\Omega)(\Omega\subset\mathbb{R}^n, \text{open}$) was also topological), and I cannot say for sure that the TVS sought in the question is $\mathcal{D}'\left(\left(0,\infty),~dr\right)\right)$ or a particular subset of it under the right topology.
So can you help me with the answer and a rigorous proof?


text:
Q: How can i make that the backgroundworker will report the progress items only once? foreach (string file in filePathList)
{
    try
    {
        _busy.WaitOne();
        if (worker.CancellationPending == true)
        {
            e.Cancel = true;
            return;
        }

        for (int i = 0; i < textToSearch.Length; i++)
        {
            List<MyProgress> prog = new List<MyProgress>();
            if (File.ReadAllText(file).IndexOf(textToSearch[i], StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                resultsoftextfound.Add(file + "  " + textToSearch[i]);
                numberoffiles++;
                prog.Add(new MyProgress { Report1 = file, Report2 = numberoffiles.ToString(), Report3 = textToSearch[i] });
                backgroundWorker1.ReportProgress(0, prog);
            }
        }
            numberofdirs++;
            label1.Invoke((MethodInvoker)delegate
            {
                label1.Text = numberofdirs.ToString();
                label1.Visible = true;
            });
        }
     catch (Exception)
     {
         restrictedFiles.Add(file);
         continue;
     }
}

The class MyProgress
public class MyProgress
{
    public string Report1 { get; set; }
    public string Report2 { get; set; }
    public string Report3 { get; set; }
}

In the inner loop when textToSearch contain more then one item for example:

hi hello world

If more then two words exist in the same file it will report the same file twice or three times according to how many words/text found in the file.
How can i keep the loop to find the text in the file more then once but reportprogress the file only once?
This line to report only once.
If in a file it found 2 or 3 results report only once. In many cases it's reporting twice or three times the same file.
backgroundWorker1.ReportProgress(0, prog);

Later on progresschanged i'm adding the files as strings to a listView
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    List<MyProgress> mypro = e.UserState as List<MyProgress>;
    ListViewCostumControl.lvnf.Items.Add(mypro[0].Report1);
    label15.Text = mypro[0].Report2;
    label15.Visible = true;
    if (ListViewCostumControl.lvnf.Items.Count > 9)
        textBox4.Enabled = true;
}

This line add the files results to the listView
ListViewCostumControl.lvnf.Items.Add(mypro[0].Report1);

I don't want to change the loop only to make it to report each file after it finish to search to be reported once.

A: Without a good Minimal, Complete, and Verifiable code example that shows clearly what your code does now, and a precise description of what you want it to do instead, it's difficult if not impossible to know for sure what it is you want.
But if I understand the question correctly, the solution is as simple as maintaining a flag that indicates whether you've reported the current file or not, and only report the file if the flag hasn't been set yet. E.g.:
foreach (string file in filePathList)
{
    try
    {
        _busy.WaitOne();
        if (worker.CancellationPending == true)
        {
            e.Cancel = true;
            return;
        }

        bool reportedFile = false;

        for (int i = 0; i < textToSearch.Length; i++)
        {
            List<MyProgress> prog = new List<MyProgress>();
            if (File.ReadAllText(file).IndexOf(textToSearch[i], StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                resultsoftextfound.Add(file + "  " + textToSearch[i]);

                if (!reportedFile)
                {
                    numberoffiles++;
                    prog.Add(new MyProgress { Report1 = file, Report2 = numberoffiles.ToString(), Report3 = textToSearch[i] });
                    backgroundWorker1.ReportProgress(0, prog);
                    reportedFile = true;
                }
            }
        }

        numberofdirs++;
        label1.Invoke((MethodInvoker)delegate
        {
            label1.Text = numberofdirs.ToString();
            label1.Visible = true;
        });
    }
    catch (Exception)
    {
        restrictedFiles.Add(file);
        continue;
    }
}

I will also point out that you seem to be using a List<MyProgress> to pass information for the ReportProgress() method for no good reason. The list only ever has one element in it, so you might as well just pass the MyProgress value itself, rather than a list containing that value.
If the above does not address your question, please improve the question so that it is more understandable.


text:
Q: Can a com surrogate be largeaddressaware? I am using the 'COM Surrogate' method to host a 32 bit dll, so that it can be called from a 64-bit C# exe.
This uses the 'DllSurrogate' method described in  Hosting a .NET DLL as an Out-Of-Process COM Server (EXE) .
This works well, but I now have a need for the 32-bit process to allow more than 2GB of address space.  It seems that for a normal exe you can use editbin to make the exe largeaddressaware.  For example: How to make a .NET application "large address aware"?.
My question is how to make that work when the dll will be hosted in the system COM Surrogate?


text:
Q: iOS Capturing Video I want to make an app for the iPhone with the ability to record video. One thing I want to do with the video once it's recorded, is to take the audio from it and alter it, such as make it sound feminine or masculine etc. I've never done this before but is it better to use AVFoundation or UIImagePickerController. I've read that the UIImagePickerController is easier to use but will it allow be to extract and edit the audio of the recorded video and put it back in?
Any help or suggestions as to how to approach this are appreciated.
Thanks

A: It is easiest to capture with UIImagePickerController if you do not need to alter it live. Once the video is captured and you have altered the audio track somehow, write it again using AVFoundation's AVMutableComposition and an audio mix.


text:
Q: Storyboard, NavigationController, Landscape Orientation and Scrollview Coordinate I'm facing an issue which is caused by orientation magic I don't understand.
First, I'm using a NavigationController which loads a ViewController. In this ViewController is a ScrollView. When I ask for the position of the ScrollView, I get wrong data. For example: The x coordinate of the ScrollView is 90 in the interface builder. If I get the frame of the ScrollView programmatically it returns 280.
Everything in the App is set to landscape. In the Info.plist, in the summary, in the implementation of the ViewControllers, in the interface builder.
I made some screenshots. Maybe are they helping finding the mistake.

And every ViewController has this:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

If I remove the NavigationController from the Storyboard and leave the simulated metrics to inferred, then the first ViewController swaps to portrait in the Storyboard.
When I log the size of the view from the NavigationController is it in portrait
NSLog(@"frame %@", NSStringFromCGRect(self.view.frame));

The output is 768x1024

A: I thought you usually had to take orientation into account when you calculated x off of a frame, which is why they have transforms? iPhone SDK: Orientation (Landscape and Portrait views)
Simply querying the frame for an X value wont always give you accurate results.

A: The problem is the method used ie the viewDidLoad: method. At that time no subviews are yet drawn and no frames are initialized yet, so the problem is accord.
Instead of using the viewDidLoad: use viewWillAppear:animated: or viewDidAppear:animated: will solve the problem for you.
Happy Coding :)


text:
Q: Flutter Unhandled Exception: type 'Null' is not a subtype of type 'List' in type cast I need to assign a model to a list in the application, but I am getting the error I mentioned in the title.
Although I get this error on the android side, I do not have a problem, but when I try it on the ios side, my application crashes.
List<MessageModel> messageList = [];
String? message;
bool success = false;

@override
MessageService decode(dynamic data) {
messageList = (data as List).map((e) => MessageModel.fromJsonData(e)).toList(); ----> Unhandled Exception: type 'Null' is not a subtype of type 'List<dynamic>' in type cast
return this;
}

A: You can declare it as nullable:
List<MessageModel> ?messageList = [];

A: The reason you get the error is data is null.
Try my solution:
List<MessageModel> messageList = [];
String? message;
bool success = false;

@override
MessageService decode(dynamic data) {
  messageList = data?.map((e) => MessageModel.fromJsonData(e))?.toList() ?? [];
  return this;
}


text:
Q: Simple question about superposition-theorem Which one is correct? (first one is my solution, second one is how my teacher solved it in class as an example when he was teaching superposition theorem).
Red rectangles are where the difference is.

A: In your calculation the problem is with \$V_2\$. You have a voltage divider, so it should be
$$V_2=3\cdot\frac{9}{6+9}=\frac{9}{5}$$
So the total voltage \$V\$ becomes
$$V=V_1+V_2=\frac{36+9}{5}=9$$
And \$i_x\$ is given by
$$i_x=\frac{V}{9}=1$$
as it should be.
EDIT:
To make it even a bit clearer: you can also directly compute the contributions of the two sources to the current \$i_x\$. Let \$i_{x,1}\$ be the contribution of the current source:
$$i_{x,1}=2\cdot\frac{6\cdot 9}{6+9}\cdot 9=\frac{12}{15}$$
The contribution of the voltage source is \$i_{x,2}\$:
$$i_{x,2}=\frac{3}{6+9}=\frac{3}{15}$$
So the total current is
$$i_x=i_{x,1}+i_{x,2}=\frac{12}{15}+\frac{3}{15}=\frac{15}{15}=1$$
which is of course the same result as obtained above.


text:
Q: Mat Table Not Sorting After View Change I have an ngIf that changes the view on click on the products screen. The starting view is the data in a mat table, but once you click the add product button and [cancel / add product / edit product] go back to the table view, it no longer sorts.
I've tried adding the view child to see if I can renderrows after an add, but no dice.
CODE: https://stackblitz.com/edit/angular-wez8lh
(Please excuse the horrendous CSS)
Is there a way to get it to sort again after [add / edit / cancel] without putting the form in another path or always showing it?

A: HERE IS A WORKING STACKBLITZ
The problem you have is the *ngIf in the mat-table selector. If you check this.sort you'll see it's undefined. This works :
@ViewChild(MatSort) set content(content: ElementRef) {
  this.sort = content;
  if (this.sort){
     this.dataSource.sort = this.sort;

  }
}


text:
Q: How do I bind a number and prevent scientific notation? I would like to bind a number to an input box and make sure that it is never displayed in scientific notation.
<input type="text" class="form-control text-right"
       data-bind="value: myData, valueUpdate: 'afterkeydown'" />

The input box should accept a decimal number of up to 8 places and I should be able to modify myData from my viewModel and have it shown as a number such as .00000001.  I'd like myData to be a number because I perform arithmetic on it within the viewModel.
The example numeric extender doesn't work for me because if you start trying to type .00001, it starts to update the value from underneath the user.  I've tried using ratelimiting, but that setting is finicky as it eventually changes the value from under the user as well.
Is there a way to code an extender such that the display binding to the input box is always toFixed(8) while some underlying data is always numeric?   The opposite would be okay where the underlying data is text but can be accessed somehow as numeric when needed.
Thank you

A: To separate the value in your viewmodel from the value displayed, you can use a computed observable.
For example, you can have a viewmodel like this:
function ViewModel() {
    var self = this;
    this.myValue = ko.observable(0);
    this.displayedValue = ko.computed({
        read: return self.myValue().toFixed(8),
        write: function (value) {
            self.myValue(value); //maybe do something to ensure you save a number
        }
    });
}

When you need to do a calculation, use myValue, but use displayedValue for your html:
<input type="text" class="form-control text-right"
       data-bind="value: displayedValue, valueUpdate: 'afterkeydown'" />

A: The reason the value is being updated from underneath the user is because you are using valueUpdate: 'afterkeydown'. This will be a problem for anything that will change the text, as it will confuse the user if the text changes as they type. If you don't use valueUpdate: 'afterkeydown' then the text can be changed when they tab out of the field. The extenders work fine for that case.


text:
Q: How can I strip down the Qt libraries to remove stuff not used by my application? I'm shipping a stand-alone Linux application with Qt libraries compiled-in.
Is there a tool which would scan my source code, see which classes/methods my app uses, then it would pluck the unnecessary/unused stuff out of the Qt source code and compile Qt libraries tailor-made for my application without any extra bloat? This is the best case scenario, of course.
But what is the closest existing solution that would allow me to make my Linux stand-alone app with compiled-in qt libs as slim as possible?

A:
Is there a tool which would scan my source code, see which classes/methods my app uses, then it would pluck the unnecessary/unused stuff out of the Qt source code and compile Qt libraries tailor-made for my application without any extra bloat?

The linker already does this for you. If you're statically linking to the Qt libraries, then only the code for the functions that you're calling will be embedded into the executable.
You don't need an external piece of software to do this. It doesn't matter how big the Qt libraries are on your development machine.

A: for additional size reduction of your program try UPX - it will make your application even smaller.

A:
what is the closest existing solution […] to make my Linux stand-alone app with compiled-in Qt libs as slim as possible?

Specifically for Qt, since early 2019 there is the build process configuration option -ltcg to enable link-time code generation. According to the Qt company blog, it allows 15% size reduction for statically linked Qt and a smaller but still noticable effect for dynamically linked Qt libraries.


text:
Q: Skipping rows starting with specific values while importing a CSV file into R using FREAD I am trying to import a CSV file from an URL in R. The file contains rows randomly starting with specific strings - either '<<<<<<< HEAD', '=======' or '>>>>>>> master'. The rows containing these characters are at random row locations.  I want to avoid these rows and import rest of the document. Is there a way to do? I prefer to use FREAD for importing the data. Appreciate inputs.
The data is not loading by default. It is throwing an error at the first instance (line 347 of the CSV) of encountering the aforesaid string. The URL from which I am trying to download the data is "https://raw.githubusercontent.com/RamiKrispin/coronavirus/master/csv/coronavirus.csv" and the error it is throwing is as follows:
[0%] Downloaded 0 bytes...
Warning message:
In data.table::fread("https://raw.githubusercontent.com/RamiKrispin/coronavirus/master/csv/coronavirus.csv",  :
  Stopped early on line 347. Expected 7 fields but found 1. Consider fill=TRUE and comment.char=. First discarded non-empty line: <<<<<<<<< HEAD>>

The the code statement that I am using to download the data is:
covid_ds <- data.table::fread('https://raw.githubusercontent.com/RamiKrispin/coronavirus/master/csv/coronavirus.csv')

A: You can read the data with read.csv with fill = TRUE, keep only those rows that have data in date format in date column so values like '<<<<<<< HEAD' or '=======' are removed and use type_convert to change them in respective types.
data <- read.csv('https://raw.githubusercontent.com/RamiKrispin/coronavirus/master/csv/coronavirus.csv', fill = TRUE)
data <- data[grepl('\\d+-\\d+-\\d+', data$date), ]
data <- readr::type_convert(data)
data

#    date       province country       lat  long type      cases
#   <date>     <chr>    <chr>       <dbl> <dbl> <chr>     <int>
# 1 2020-01-22 NA       Afghanistan  33.9  67.7 confirmed     0
# 2 2020-01-23 NA       Afghanistan  33.9  67.7 confirmed     0
# 3 2020-01-24 NA       Afghanistan  33.9  67.7 confirmed     0
# 4 2020-01-25 NA       Afghanistan  33.9  67.7 confirmed     0
# 5 2020-01-26 NA       Afghanistan  33.9  67.7 confirmed     0
# 6 2020-01-27 NA       Afghanistan  33.9  67.7 confirmed     0
# 7 2020-01-28 NA       Afghanistan  33.9  67.7 confirmed     0
# 8 2020-01-29 NA       Afghanistan  33.9  67.7 confirmed     0
# 9 2020-01-30 NA       Afghanistan  33.9  67.7 confirmed     0
#10 2020-01-31 NA       Afghanistan  33.9  67.7 confirmed     0
# … with 287,772 more rows

and with data.table::fread you can use blank.lines.skip=TRUE.
data <- data.table::fread('https://raw.githubusercontent.com/RamiKrispin/coronavirus/master/csv/coronavirus.csv', blank.lines.skip=TRUE)


text:
Q: Entity Framework metadata artifact not embeded when using xbuild and mono When I try and use EntityFramework and MySQL on a Linux or Windows environment I run into the following problem:
Project 1: Contains EntityFramework edmx and logic to insert update data using the dbcontext class
Project 2: References Project 1.
When I build the solution using msbuild the EntityFramework metadata files are embeded in Project1.dll

When I do a clean build with xbuild in a Linux environment or in a Windows environment the EntityFramework metadata files are missing

When you run the application you get the following error:

Unable to load the specified metadata resource.

I am using mono version 4.2.2
Does anybody know a solution for embedding the EntityFramework metadata files when using xbuild?

A: I have implemented the following workaround until mono embeds the Entity Framework metadata artifacts

*

*Step1 - Update your EntityFramework Model's Metadata  Artifact Processing property from "Embed in Output Assembly" to "Copy to Output Directory"

This copies the metadata artifact files to the bin folder of the project containing the .edmx(Project1)

*Step2 - Add the following post build events to the referencing project(Project2) to copy the metadata artifact files to its bin. You can add them to the end of the .csproj project file. Replace Project1 with the name of your project.
<PropertyGroup>
   <PostBuildEvent Condition=" '$(OS)' != 'Unix' ">copy /Y   "$(ProjectDir)..\Project1\bin\Debug\Models\*" "$(ProjectDir)\bin\Debug\"  </PostBuildEvent>
   <PostBuildEvent Condition=" '$(OS)' == 'Unix' ">cp -a "$(ProjectDir)../Project1/bin/Debug/Models/." "$(ProjectDir)bin/Debug/"  </PostBuildEvent>
</PropertyGroup>

*Step3 - Update your connection string
from
<add name="EntityframeworkTestEntities" connectionString="metadata=res://*/EntityFrameworkTestModel.csdl|res://*/EntityFrameworkTestModel.ssdl|res://*/EntityFrameworkTestModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=EntityframeworkTest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

to
<add name="EntityframeworkTestEntities" connectionString="metadata=EntityFrameworkTestModel.csdl|EntityFrameworkTestModel.ssdl|EntityFrameworkTestModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=EntityframeworkTest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />


text:
Q: How to set up basic authentication for some subdomains but not others using envif Thanks to some wonderful people here at stack overflow I got my authentication working to demand a password at dev.website.com using this script:
SetEnvIfNoCase Host ^.*dev\.website\.com$ require_auth=true
AuthUserFile /var/www/vhosts/website.com/.htpasswd
AuthName "Password Protected"
AuthType Basic
Order Deny,Allow
Deny from all
Satisfy any
Require valid-user
Allow from env=!require_auth

I also want it to demand a password on: myname.website.com mynamedev.website.com & devmyname.website.com. Basically on anything but "www.website.com" and "website.com".
What is the simplest way to do that?

A: I would have thought you could do the following
SetEnv require_auth=true
SetEnvIfNoCase Host ^www\.website\.com$ require_auth=false
SetEnvIfNoCase Host ^website\.com$ require_auth=false
AuthUserFile /var/www/vhosts/website.com/.htpasswd
AuthName "Password Protected"
AuthType Basic
Order Deny,Allow
Deny from all
Satisfy any
Require valid-user
Allow from env=!require_auth

The first line setting the default case to be authentication is required, the second two lines being the specific cases where authentication is not required.

A: Try :
#set env "auth" only for subdomains
SetEnvIfNoCase host ^((?!www\.).+)\.website\.com$ auth=1
 #auth
 AuthUserFile /var/www/vhosts/website.com/.htpasswd
 AuthName "Password Protected"
AuthType Basic

 #Here is where we allow/deny
Order Deny,Allow
Satisfy any
Deny from all
Require user valid-user
Allow from env=!auth


text:
Q: Postgresql: How can I verify a constraint after several update queries? I'm building a database with postgresql.

I have 3 tables linked together by a many to many relation.  The join table uiComponent_cat_subcat defines a unique constraint with subcategoryId, categoryId and position (red on the picture).
In my workflow I must make 2 queries update in a row. The first one breaks the constraint whereas the second one sets it back.
I would like this constraint to be verified after the 2 queries.
ALTER TABLE "uiComponent_cat_subcat" ALTER CONSTRAINT "unique_constraint_categoryId_subcategoryId_position" DEFERRABLE INITIALLY DEFERRED;

I tried to use the DEFERRABLE property on the constraint and to wrap my queries inside one transaction. However this can only be applied on constraints set to foreign keys.
How can I verify the unique constraint after the two update queries were made?
Edit: Here are the object definitions:
1 -  CREATE TABLE
CREATE TABLE IF NOT EXISTS "uiComponent"
(
  "id"           uuid NOT NULL,
  "name"         varchar(255),
  "preview"      json,
  "symbolID"     varchar(255),
  "libraryID"    varchar(255),
  "type"         "public"."enum_uiComponent_type" DEFAULT 'basic',
  "content"      json,
  "created_at"   timestamp WITH time ZONE NOT NULL DEFAULT now(),
  "updated_at"   timestamp WITH time ZONE NOT NULL DEFAULT now(),
  PRIMARY KEY ("id")
);

CREATE TABLE IF NOT EXISTS "category"
(
  "id"            uuid NOT NULL,
  "name"          varchar(255),
  "immuable"      boolean,
  "description"   varchar(255),
  "section"       "public"."enum_category_section" NOT NULL DEFAULT 'Components',
  "created_at"    timestamp WITH time ZONE NOT NULL DEFAULT now(),
  "updated_at"    timestamp WITH time ZONE NOT NULL DEFAULT now(),
  PRIMARY KEY ("id")
);

CREATE TABLE IF NOT EXISTS "subcategory"
(
  "id"           uuid NOT NULL,
  "name"         varchar(255),
  "position"     integer NOT NULL,
  "created_at"   timestamp WITH time ZONE NOT NULL DEFAULT now(),
  "updated_at"   timestamp WITH time ZONE NOT NULL DEFAULT now(),
  PRIMARY KEY ("id")
);

CREATE TABLE IF NOT EXISTS "uiComponent_cat_subcat"
(
  "id"              uuid,
  "uiComponentId"   uuid NOT NULL REFERENCES "uiComponent" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
  "categoryId"      uuid NOT NULL REFERENCES "category" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
  "subcategoryId"   uuid REFERENCES "subcategory" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
  "position"        integer NOT NULL,
  PRIMARY KEY ("id")
);

2 - CREATE CONSTRAINT
ALTER TABLE "uiComponent_cat_subcat"
   ADD CONSTRAINT "unique_constraint_categoryId_subcategoryId_position" UNIQUE ("categoryId", "subcategoryId", "position")
   DEFERRABLE INITIALLY DEFERRED;

3 - UPDATE QUERIES
START TRANSACTION;

UPDATE "uiComponent_cat_subcat"
  SET "position"="position"+ 1
WHERE "position" BETWEEN 1 AND 1
AND "categoryId" = '10e4621e-f52d-4fe2-a408-139841718fd5'
AND "subcategoryId" = 'a7770326-35be-45ae-ba26-4635cfb6f4dc';

UPDATE "uiComponent_cat_subcat"
  SET "position"=1
WHERE "id" = '50022f87-8fe9-4f21-a622-d5f51c16d9fc'

COMMIT;

The problem is solved but I don't know why
Does wrapping queries in a transaction allows me to check the constraint after the commit.

A: 1 -  CREATE TABLE
CREATE TABLE IF NOT EXISTS "uiComponent"
(
  "id"           uuid NOT NULL,
  "name"         varchar(255),
  "preview"      json,
  "symbolID"     varchar(255),
  "libraryID"    varchar(255),
  "type"         "public"."enum_uiComponent_type" DEFAULT 'basic',
  "content"      json,
  "created_at"   timestamp WITH time ZONE NOT NULL DEFAULT now(),
  "updated_at"   timestamp WITH time ZONE NOT NULL DEFAULT now(),
  PRIMARY KEY ("id")
);

CREATE TABLE IF NOT EXISTS "category"
(
  "id"            uuid NOT NULL,
  "name"          varchar(255),
  "immuable"      boolean,
  "description"   varchar(255),
  "section"       "public"."enum_category_section" NOT NULL DEFAULT 'Components',
  "created_at"    timestamp WITH time ZONE NOT NULL DEFAULT now(),
  "updated_at"    timestamp WITH time ZONE NOT NULL DEFAULT now(),
  PRIMARY KEY ("id")
);

CREATE TABLE IF NOT EXISTS "subcategory"
(
  "id"           uuid NOT NULL,
  "name"         varchar(255),
  "position"     integer NOT NULL,
  "created_at"   timestamp WITH time ZONE NOT NULL DEFAULT now(),
  "updated_at"   timestamp WITH time ZONE NOT NULL DEFAULT now(),
  PRIMARY KEY ("id")
);

CREATE TABLE IF NOT EXISTS "uiComponent_cat_subcat"
(
  "id"              uuid,
  "uiComponentId"   uuid NOT NULL REFERENCES "uiComponent" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
  "categoryId"      uuid NOT NULL REFERENCES "category" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
  "subcategoryId"   uuid REFERENCES "subcategory" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
  "position"        integer NOT NULL,
  PRIMARY KEY ("id")
);

2 - CREATE CONSTRAINT
ALTER TABLE "uiComponent_cat_subcat"
   ADD CONSTRAINT "unique_constraint_categoryId_subcategoryId_position" UNIQUE ("categoryId", "subcategoryId", "position")
   DEFERRABLE INITIALLY DEFERRED;

3 - UPDATE QUERIES
START TRANSACTION;

UPDATE "uiComponent_cat_subcat"
  SET "position"="position"+ 1
WHERE "position" BETWEEN 1 AND 1
AND "categoryId" = '10e4621e-f52d-4fe2-a408-139841718fd5'
AND "subcategoryId" = 'a7770326-35be-45ae-ba26-4635cfb6f4dc';

UPDATE "uiComponent_cat_subcat"
  SET "position"=1
WHERE "id" = '50022f87-8fe9-4f21-a622-d5f51c16d9fc'

COMMIT;

The problem is solved but I don't know why
Does wrapping queries in a transaction allows me to check the constraint after the commit.


text:
Q: RingGeometry rotate in three.js I followed a example to create a planet ring with the following code.
    createRing(){
        const TEXTURE_PATH = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/123879/';

        let loader = new THREE.TextureLoader();
        loader.setCrossOrigin( 'https://s.codepen.io' );
        var ringTexture = loader.load( TEXTURE_PATH + 'saturnrings.png' );
        let saturnRadius = 0.98;
        var ringGeometry = new THREE.RingGeometry(1.4 * saturnRadius, 2.5 * saturnRadius, 2 * 32, 5, 0, Math.PI * 2);
        var ringMaterial = new THREE.MeshBasicMaterial({
            map: ringTexture,
            side: THREE.DoubleSide,
            transparent: true,
            opacity: 0.7,
        });

        var ring = new THREE.Mesh( ringGeometry, ringMaterial );
        scene.add(ring);
   }

the code works to show a planet and planet ring as shown in the image below.

then I tried to rotate the ring with the code,
ring.rotation.set(new THREE.Vector3(  Math.PI / 2, 0, 0 ));

however the ring just disappear with only the planet left.
what goes wrong with it


text:
Q: Annual compounding and how it changes during the year I was reading from a book that if we compound annually at $40\%$ the rate of growth at any instant, such as $P$ in the following graphs (AL represents $1$ year) will be $40\%$ of the value at the beginning of the year. If we compound semi-annually the rate will be $40\%$ of the value at the beginning of the half-year in which $P$ lies etc

At this point I am confused because my understanding of annual compounding is that there is $1$ change in the original amount at the end of the year i.e. the graph (assuming $\$100$ at the start) should be:

I.e. no change until $L$ and a sudden jump in the graph at $L$
What am I misunderstanding here? I think it will be $\$140$ only at $L$ so $P$ should be $40\%$ of the beginning value only at $M$ and not earlier


text:
Q: Proof for Mean value theorem for integrals I have the proof in my book for the mean value theorem for integrals $$\int_a^b f(x)g(x)dx = f(c)\int_a^b g(x) dx$$
However, I don't understand the proof especially at the beginning where the proof starts with $$F(x) = \int_a^x f(t) g(t) dt - \frac{A}{B} \int_a^x g(t) dt$$
$$A = \int_a^b f(x)g(x) dx$$
$$B = \int_a^b g(x) dx$$
Where this formula come from?

A: The formula did not come from any where, it is a definition of a new function $F(x)$ that will help during the proof. To avoid confusion i will denote this function as $H(x)$.
First of all The definition of the function $H(x)$ is
$$
H(x)=\intop_a^xf(t)g(t)dt-\frac{A}{B}\intop_a^xg(t)dt
$$
Where $A=\intop_a^bf(t)g(t)dt$ and $B=\intop_a^bg(t)dt$.
Because $g(x)>0$ and is continuous, then $\intop_a^bg(x)dx>0$, so $H(x)$ is well defined.
Assuming that $g(x),f(x)$ are continuous functions, from the Fundamental theorem of calculus it follows that $H(x)$ is a differentiable function. Notice that
$$
\begin{align}
H(a)=&\intop_a^af(x)g(x)dx-\frac{A}{B}\intop_a^ag(x)dx=0\\
H(b)=&\intop_a^bf(x)g(x)dx-\frac{\intop_a^bf(x)g(x)dx}{\intop_a^bg(x)dx}\intop_a^bg(x)dx=\\
=&\intop_a^bf(x)g(x)dx-\intop_a^bf(x)g(x)dx=0
\end{align}
$$
So by Rolle's theorem there exists $c\in (a,b)$ such that $H'(c)=0$. From the Fundamental theorem of calculus the derivative is
$$
0=H'(c)=f(c)g(c)-\frac{A}{B}g(c)
$$
And with a little arithmetic and because $g(c)\neq0$ we will get
$$
A=f(c)\cdot B\,\Rightarrow\,\intop_a^bf(x)g(x)dx=f(c)\intop_a^bg(x)dx
$$


text:
Q: Possible to register static only protocols? Unfortunately, some libraries only have static methods to them. Is it possible to make Swinject register a type to return a type instead of an instance of a type? Makes it hard to stub out static only libraries for testing.

A: In the current state of the Swinject this is unfortunately not possible. One of the ways you could work around this would be creating a custom type provider:
protocol LibraryProtocol {}
class Library: LibraryProtocol {}

class LibraryProvider {
    let library: LibraryProtocol.Type
    init(_ library: LibraryProtocol.Type) { self.library = library }
}

container.register(LibraryProvider.self) { _ in LibraryProvider(Library.self) }


text:
Q: Can I avoid making a synchronous callback, if I want a click to only *sometimes* open a new window? In this scenario:

*

*User enters some information into a textbox

*User clicks a button

*Server-side processing of the entered information takes place

*Depending on the result of that server-side processing, either a new window is to be opened, or a message is to be displayed on the current page (and no popup)

I cannot come up with an approach other than to use async: false in the jQuery ajax call, which is strongly discouraged:

Setting this option to false (and thus making the call no longer
  asynchronous) is strongly discouraged, as it can cause the browser to
  become unresponsive.

I've tried:

*

*having the call be async and in the callback handler, depending on what the server said, sometimes opening a new window - this gets blocked by popup blockers

*another idea, which I've not even bothered with due to its unpleasantness, is to always open a window, and it is this new window that calls the server, and sometimes closes itself (somehow updating text in the parent on its way out)

What I've settled on is what I've described above: in the click handler, do a synchronous server call, and if the server says to do so, open a new window. Popup blockers are happy with this, because the window opening is done in the click handler. But...

Similar (but not duplicate, as I don't always want to open a new window) questions that have not provided a nice solution:

*

*How can I open a new window using a URL that is generated inside the getScript callback function, and avoid pop-up blockers?

*(How) can I open the result of a form submission in a new window?

A: what you can do is ,
try to have a hidden field on your page which will be set by a value like true or false at server side , that you can check later on in jquery document .ready function
if the value is false just show a msg else popup a new window
as simple as that

A: I tried out my 'unpleasant' idea: to always open a new window, and have that new window make the server call, closing itself if the results of the server call dictated that it was not required.
But that was pretty horrible, so I stuck with the synchronous call.
So for me, the answer to this question is no, you can't avoid being synchronous in this situation.


text:
Q: drawLayer not called when subclassing CALayer I have a simple CALayer subclass (BoxLayer) with this drawLayer method:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    NSLog(@"drawLayer");
    NSGraphicsContext *nsGraphicsContext;
    nsGraphicsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx
                                                                   flipped:NO];
    [NSGraphicsContext saveGraphicsState];
    [NSGraphicsContext setCurrentContext:nsGraphicsContext];

    // ...Draw content using NS APIs...
    NSPoint origin = { 21,21 };

    NSRect rect;
    rect.origin = origin;
    rect.size.width  = 128;
    rect.size.height = 128;

    NSBezierPath * path;
    path = [NSBezierPath bezierPathWithRect:rect];

    [path setLineWidth:4];

    [[NSColor whiteColor] set];
    [path fill];

    [[NSColor grayColor] set];
    [path stroke];

    [NSGraphicsContext restoreGraphicsState];
}
I then have this awakeFromNib in my NSView subclass:
- (void)awakeFromNib {
    CALayer* rootLayer = [CALayer layer];
    [self setLayer:rootLayer];
    [self setWantsLayer:YES];

    box1 = [CALayer layer];
    box1.bounds = CGRectMake(0, 0, 70, 30);
    box1.position = CGPointMake(80, 80);
    box1.cornerRadius = 10;
    box1.borderColor = CGColorCreateGenericRGB(255, 0, 0, 1);
    box1.borderWidth = 1.5;
    [rootLayer addSublayer:box1];

    box2 = [BoxLayer layer];
    [box2 setDelegate:box2];
    [box2 setNeedsDisplay];
    [rootLayer addSublayer:box2];
}
My drawLayer is never called though, but why not?
Thank you

A: Possibly because the frame of your layer seems to be equal to CGRectZero, so the OS might think it's invisible so it doesn't need to draw it.
On a side note, why are going the complicated way of setting the layer's delegate to itself and implementing drawLayer:inContext: instead of using drawInContext: directly?


text:
Q: How to colorize Minitest output by default? After a recent Ruby upgrade from 2.6 to 2.7, I no longer get colorized Minitest output as I used to in Windows 10. I can still get colorized output with minitest-reporters or minitest-color, but these do not apply by default—they need a require or a command-line argument. It would be nice to have colors by default.
I'm fairly certain this feature came from a gem that I had installed, but due to my careless upgrade I seem to have lost it, and I've had no success finding it again even after hours of searching.
I have installed win32console, but that didn't make any difference. I also tried using Ruby 2.6 again, to no avail.


text:
Q: How can i delete between these tags  I have asked this question and didn't come right. I want to delete the output between the value tags but am falling to do so. i only want to delete the value tag that is within the data which is my table. can you please help me delete those values. keep it in mind that those output are not hard-coded,the user just entered those values, so every time i load the form i want to delete those output between the tags.
 <data name="CurrentSelectedUser_Label" xml:space="preserve">
   <value>Current selected record:</value>
   <comment>[Font]Bold[/Font][DateStamp]2015/01/01 00:00:00[/DateStamp][Comment] this is a comment.!![/Comment]</comment>
 </data>
 <data name="FinEnrolment_Exit_Button" xml:space="preserve">
   <value>Exit Finger Enrolment</value>
   <comment>[Font]Regular[/Font][DateStamp]2014/012/01 00:00:00[/DateStamp]  [Comment] this is a comment.!![/Comment]</comment>
  </data>

i tried this, but am failing to specify the value tags that are within the data which is my table. see my coding below;
    string text = File.ReadAllText(outputFilePath);
    text = DeleteBetween1(text, "<value>", "</value>");

     public string DeleteBetween1(string STR, string FirstString, string LastString)
    {
        string regularExpressionPattern1 = "<value(.*?)</value>";
        Regex regex = new Regex(regularExpressionPattern1, RegexOptions.Singleline);
        MatchCollection collection = regex.Matches(STR.ToString());
        var val = string.Empty;
        foreach (Match m in collection)
        {
            val = m.Groups[1].Value;
            STR = STR.Replace(val, "");
        }
        STR = STR.Replace(val, "");
        return STR;
    }

A: Appologies for the previous answer I've knocked up a test program in linqpad which acheives what you want.
Hopefully this approach should work for you.
I've had to insert a root node or the XML will not parse, I called this root.
void Main()
{
    string xml = @"
    <root>
    <data name=""CurrentSelectedUser_Label"" xml:space=""preserve"">
       <value>Current selected record:</value>
       <comment>[Font]Bold[/Font][DateStamp]2015/01/01 00:00:00[/DateStamp][Comment] this is a comment.!![/Comment]</comment>
     </data>
     <data name=""FinEnrolment_Exit_Button"" xml:space=""preserve"">
       <value>Exit Finger Enrolment</value>
       <comment>[Font]Regular[/Font][DateStamp]2014/012/01 00:00:00[/DateStamp]  [Comment] this is a comment.!![/Comment]</comment>
      </data></root>";

    var doc = XDocument.Load(new StringReader(xml));

    var nodes = doc.XPathSelectElements("/root/data/value");

    foreach (var node in nodes)
    {
        ((XElement)node).Value = string.Empty;
    }

    ... output the doc here.
}

A: With Linq to XML
class Program
{
    static void Main(string[] args)
    {
        XDocument doc = XDocument.Load("XMLFile1.xml");

        foreach(var valueNode in doc.Descendants("data").SelectMany(n=> n.Elements("value")))
        {
            valueNode.Value = string.Empty;
        }
    }
}


text:
Q: Compare cells to delete rows, value is true but not deleting rows I'm trying to compare 2 cells and if its true that row will be deleted, i tried using msgbox to return the value and it shows its true, but row is not deleting.
The first cell is derived using formula in 1 sheet and the other is just numbers, does that make a difference?
Dim r, s, i, t As Long
Dim com, cc, bl, acc As Long
Dim rDB, rInput As Range
Dim shDB, shInput As Worksheet

Set shDB = ActiveWorkbook.Sheets("Database")
Set rDB = shDB.Range("A1", "T1000")

Set shInput = ActiveWorkbook.Sheets("Data Input")
Set rInput = shInput.Range("A1", "R1000")

r = 2
Do While Len(shDB.Cells(r, 1).Formula) > 0
    com = shInput.Cells(7, 5).Value
    cc = shInput.Cells(5, 5).Value
    bl = shInput.Cells(9, 5).Value
    acc = shInput.Cells(5, 10).Value
    MsgBox (com & " " & shDB.Cells(r, 1).Value & " " & cc & " " & rDB.Cells(r, 2).Value & " " & rDB.Cells(r, 3).Value & " " & bl & " " & rDB.Cells(r, 4).Value & " " & acc)
    If shDB.Cells(r, 1).Value = com And rDB.Cells(r, 2).Value = cc And rDB.Cells(r, 3).Value = bl And rDB.Cells(r, 4).Value = acc Then
    shDB.Rows(r).EntireRow.Delete
    MsgBox ("deleting rows")
    Else
        r = r + 1
    End If
Loop

A: When deleting alway go from the last index to the first.  This applies to listboxes, comboboxes, ranges, ...etc.
If you delete from first to last then you will skip every other row


text:
Q: API to get latest browser and Flash versions? I'm looking for an web service that would provide me with the latest version numbers for the major web browsers as well as Adobe Flash?
fresh-browsers.com seemed to be the go to place for this before but has been abandoned.
Note that I am not doing this for feature detection but so that I can tell my users to upgrade their Flash or web browser, so Modernizr will not solve my problems.


text:
Q: How to get stride and Y plane alignment values for MediaCodec encoder There's a few related questions and discussions on this subject:

*

*Mediacodec and camera, color space incorrect

*Getting QualComm encoders to work via MediaCodec API

*https://groups.google.com/d/msg/android-platform/awaNwgb6EbY/a-YiIOwaL0QJ

*https://code.google.com/p/android/issues/detail?id=37769
I am feeding camera preview frames (NV21 converted to NV12) to MediaCodec encoder (NV12 aka COLOR_FormatYUV420SemiPlanar). It looks like that on some devices with QualComm encoder which are running Android versions less than 4.3 I have to do some input frames processing in order to receive back frame with correct color.
On Sony Xperia ZR running Android 4.2.2 I have to add Y plane alignment in order to make it working on almost all resolutions. Code above adds 1024 bytes alignment for widths which can not be divided by 32 and 2048 bytes alignment for other resolutions. It makes MediaCodec to encode frames properly for all resolutions which can be divided by 16 (except 176x144 for which UV plane looks misaligned).
int getYPadding() {
    if (mediaCodecInfo.getName().contains("OMX.qcom") && android.os.Build.VERSION.SDK_INT < 18) {
        if ((getWidth() % 32) != 0) {
            return (getWidth()*getHeight()) % 1024;
        } else {
            return (getWidth()*getHeight()) % 2048;
        }
    }
    return 0;
}

I've tried to test this alignment on LG G2 which is running same Android 4.2.2 and has QualComm encoder, and it looks like it does not working on it correctly. UV plane is misaligned (a green stripe at the bottom of the frame). I was not able to calculate the padding which will work for both phones.
I also have access to Sony Xperia Z1 running Android 4.3 with QualComm chipset and it looks like it does not have such problems. Video on every resolution looks fine and Y plane does not needs to be aligned anyhow.
I understand that it's hardware-related and might be complicated, but since I have to support users running Android prior to 4.3 I have a question. Is it possible to programmatically determine Y plane alignment and vertical / horizontal stride values which encoder is expecting for the given color format?

A: The problem in a nutshell: there were no CTS tests for video encoding until Android 4.3 (API 18).
As a result, the behavior of MediaCodec across different devices was inconsistent, and a few bugs went unnoticed.  The EncodeDecodeTest tests exercise the functions you're asking about, and as a result you can reliably feed YUV data to a 4.3+ device (though you still have to runtime-detect whether it wants planar or semi-planar).
For your specific question, the Y plane on older Qualcomm devices needs to be aligned at a 2K boundary, which isn't quite what your code is doing.  For 720p video this happens naturally (720*1280 == 450 * 2048), for 176x144 you'd adjust by 1280 to start the UV plane at 26624 instead of 25344.  You need to set the absolute alignment within the buffer, not a fixed amount of padding -- use uvoffset = (width*height + 2047) & ~2047.
You will need to detect the codec vendor and Android software version, and if it's Qualcomm on pre-4.3 you need to make this adjustment.  If your requirements change, and you can target API 18+, these issues go away.  (And you can use Surface input to MediaCodec, which avoids the U/V swap issue, though depending on your needs that may not be useful.)


text:
Q: Overriding DataBind on User Control, caveats? I've a custom property on a user control which has multiple state/modes. If this property is set in the parent page: I would like for my control to update automatically. Using the property in the page load does not work because it is not initiated.
I can imagine 3 methods to do this:

*

*On the property, I could add a code block that would call this.DataBind().

*I could add the code by overriding the virtual method DataBind.

*I could create a public proprietary Update method.

I would like any input into what is the best practice in general. More to the point, I've chosen to override the virtual method DataBind. My pseudo code is as such:
    public override void DataBind()
{
      if (SpecialMode)
       {
        .. load from database

       }
      base.DataBind()
    }

I'm interested in the ordering of the base.DataBind(). I've seen it typically placed first but after I load the data from the database: I will need to databind to get the data to display.
Any input into these considerations will be greatly appreciated.
To be clear:
This control is a Poll widget. It will typically search and load the poll to display from the Page_Load event. But, it also has a reports mode which allows the page in which the control is embedded to change the Id of the poll to display. This property will not be initiated in Page_Load. Okay, part of this mess is that I've a property for an object, and I've also a duplicated property for the ViewState but only the Id.

A: Your control should not depend, in any way, on the page in which it is embedded. Instead, have an "AutoUpdate" property on the control, and have the page set it. The page should also set properties telling the control how to update when the AutoUpdate property is set.

A: You could have your user control handle the automatic databinding in its PreRender event.  When the Id property is changed (or whatever property it is that triggers the automatic databinding) you could set a flag within the control that is later checked in PreRender to indicate that data needs to be loaded.
Alternatively, instead of setting a flag you could possibly clear any data that you've already loaded from ViewState and implement logic in PreRender to say "If there is no data, then load it".
This avoids potentially loading data multiple times within a single request due situations where there happens to be code that sets the Id property multiple times.


text:
Q: Overloaded Addition assignment operator in C++ for two /more than two objects? I have overloaded the + operator like this
class sample
{
private :
  int x;
public :
  sample(int x1 =0)
  {
    x = x1;
  }

  sample operator+(sample s);
};

sample sample::operator+(sample s)
{
  x = x + s.x;
  return *this;
}

int  main()
{
  sample s1(10);
  sample s2;
  s2 = s2 + s1;
  return 0;
}

Is this correct?
My question is If I want to add two different sample objects how will I overloaded the opeartor; e.g for s = s1 + s2;
I feel like doing s = s + s1 + s2 with the existing implementation.

A: Using friend operator overload should do the trick for you and is a common way to define binary operators, just add:
friend sample operator+(const sample& a, const sample& b); //in class

sample operator+(const sample& a, const sample& b) { //outside the class
    return sample(a.x + b.x);
}

If you want it to remain a member, (which has downsides in some rare scenarios, and no upsides), you have to make the operator a const function:
sample operator+(sample s) const; //in class

sample sample::operator+(const sample& b) const { //outside the class
    return sample(this->x + b.x);
}

Either of these will allow operator chaining.  The reason your previous s = s + s1 + s2 was failing, is that the s + s1 would execute and return a temporary sample object.  Then, it would attempt to add s2 to that sample.  However, temporaries can only be const references[1], and as such, can only use const member functions.  Since your operator+ member function is not a const function, you cannot use that function on the const temporary.  Note that to make it const, I had to rewrite it, since your version modifies the object on the left side of the +.
[1]with exceptions aren't particularly relevant here, namely rvalues


text:
Q: How to draw a non uniformly scaled 3D sphere(ellipsoid) using point sprite in modern GLSL? I'm trying to render a non uniformly scaled sphere(ellipsoid) using point sprite in GLSL 440 or GLSL version higher than 330.
As we know, the point sprite in GLSL, can easily draw a unit sphere, but it's difficult to draw a ellipsoid with special requirements.
My thoughts are as follows:

*

*Firstly, I have a point(center of the sphere);

*Then, render a unit sphere using the point sprite;

*Suppose that the sphere is transformed by a rotate-scale matrix(non uniformly scaled);

*Then the transformed ellipsoid is rendered on the screen. reference: Line-ellipsoid intersection
In old OpenGL version, the function glutSloidSphere() in GLUT lib can easily realize this, but how can I code in the modern OpenGL 4.x using fragment shader?
Thanks a lot!
The final effect I want is similar to the one shown below.


text:
Q: Only one checkbox can be checked I am building a mobile webapp with jquery mobile. Now what I want 2 things to do. One thing is  that only one checkbox can be checked. Another thing is that when there comes another checkbox  I don't want to modify my javascript.
My html
<input type="checkbox" name="checkbox-zaal1" id="checkbox-1" onClick="CountChecks('checkbox-1')"/>
                    Zaal 1

                    <input type="checkbox" name="checkbox-zaal2" id="checkbox-2" onClick="CountChecks('checkbox-2')"/>
                      Zaal 2

                    <input type="checkbox" name="checkbox-zaal3" id="checkbox-3" onClick="CountChecks('checkbox-3')"/>
                    Zaal 3

And my javascript
function CountChecks(which) {
        var maxchecked = 1;
        var count = 0;
        for (i=0;i<=3;i++){
            if(eval('document.getElementById("checkbox-"+ i).checked == true')) { count++; }
        }
        if(count > maxchecked) {
            eval('document.getElementById("' + which + '").checked = false');
            alert('Sorry je kan enkel maar 1 meeting room reserveren');
        }
    }

So as you can see in my javascript. I want to change the 3 in the for loop in the amount off checkboxes on my pages. There is also something wrong with my first eval function. But I can't figure it out.
Could you help me ?
Thank you

A: Use Radio Buttons, with the same Name attribute
http://www.w3schools.com/jsref/dom_obj_radio.asp

A: Use radio buttons instead of check boxes and give them all the same name.  And then don't use javascript at all.

A: You are using the wrong thing for the job, use radio buttons, this how you use them in a group:
<input type="radio" name="group1" value="Zaal1"> Zaal 1

<input type="radio" name="group1" value="Zaal2"> Zaal 2

<input type="radio" name="group1" value="Zaal3"> Zaal 3

Hope this was helpful.


text:
Q: How to create a 360 panorama image in Gatsby/React? I am trying to understand how to create a basic 360 Panorama image in react/gatsbyjs where the user is able to infinite scroll the image horizontally. Here is the result I'm trying to achieve:
sample site
I could easily achieve this result with the help of a jquery plugin in normal html/css/js, however, I couldn't figure out how to properly do it the "react way". I've tried using react-vr, however, when I try to import all the needed modules from react-vr, the browser throws me the following error:

I'm still learning React,
So any pointers or suggestion would be much appreciated!
here's my component code:
import React, { Component } from 'react'
import { View, Pano } from 'react-vr'
import { Link } from 'gatsby'
import FooterMenu from '../../components/footer-menu/footer-menu'
import Content from '../../components/content-container/content'

import './upper.sass'

const UpperPage = () => {
  return (
    <Content>
      <div id="view-1" class="view-content">
        <Link to="/views" className="back-btn">
          ← back
        </Link>
        <View>
          <Pano source={{ uri: '../../images/views/high.jpg' }} />
        </View>
      </div>
      <FooterMenu />
    </Content>
  )
}

export default UpperPage

A: I'm not familiar with the legacy React VR project, but this documentation suggests that it's not intended to be included within an existing React component but instead built as its own project.
This documentation offers two ways you can integrate a 360 project into an existing application, one of which is to use an iframe. To do this inside of Gatsby, you would set your React 360 project to build to a folder in the static folder of your Gatsby project (e.g: your-gatsby-site/static/vr-experience/index.html), and build/deploy it before you run gatsby build. This will copy your React 360 project over to your public folder on-build, making it available for HTTP requests.

A: I'd suggest to use aframe-react instead of react-360 (rebranded react-vr). I simply integrated it with Gatsby project:

*

*Follow installation guide for aframe-react to add required dependencies to Gatsby project:
npm install --save aframe aframe-react

*Create Gatsby component/page (for example: src/pages/virtual-reality.tsx) with content below, and use it:
import 'aframe';
import 'aframe-particle-system-component';

import React from 'react';
import { Entity, Scene } from 'aframe-react';

const VRScene: React.FunctionComponent = () => {
  return (
    <Scene>
      <Entity
        geometry={{ primitive: 'box' }}
        material={{ color: 'red' }}
        position={{ x: 0, y: 0, z: -5 }}
      />
      <Entity particle-system={{ preset: 'snow' }} />
      <Entity light={{ type: 'point' }} />
      <Entity gltf-model={{ src: 'virtualcity.gltf' }} />
      <Entity text={{ value: 'Hello, WebVR!' }} />
    </Scene>
  );
};

export default VRScene;

*Run your Gatsby project by npm start:

How is React 360 Different from A-Frame?

A-Frame is a framework for building VR worlds using declarative HTML-like components. It has a rich collection of available components from a vibrant community, and is great for creating intricate 3D scenes that can be viewed in VR. We believe that React 360 serves a different use case optimized around applications that rely on user interfaces, or are event-driven in nature. Look through our examples to see the types of things you can easily build with React 360.
Trying to figure out which framework is right for you? Here's a quick test. If your application is driven by user interaction, and has many 2D or 3D UI elements, React 360 will provide the tools you need. If your application consists of many 3D objects, or relies on complex effects like shaders and post-processing, you'll get better support from A-Frame. Either way, you'll be building great immersive experiences that are VR-ready!


text:
Q: LWUIT TextArea issue I have created LWUIT TextArea. I want to reduce my TextArea's font size. I have used the code below:
public class TextAreaMidlet extends MIDlet {

public void startApp() {
    Display.init(this);
    Form mForm = new Form("Text Area");
    mForm.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
    Button button = new Button("Click here to open new Form");
    mForm.addComponent(button);
    TextArea textArea = new TextArea();
    textArea.setEditable(false);
    textArea.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL));
    textArea.setText("The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog");
    mForm.addComponent(textArea);
    mForm.show();
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

But the TextArea display issue, look like this:
 ----------------------------------
|The quick brown fox               |
|jumps over the lazy               |
|dog, The quick brown              |
|fox jumps over the lazy           |
|dog, The quick brown fox          |
|jumps over the lazy dog           |
 ----------------------------------

I want it display normally, like this
 ----------------------------------
|The quick brown fox jumps over the|
|lazy dog, The quick brown fox     |
|jumps over the lazy dog, The quick|
|brown fox jumps over the lazy dog |
 ----------------------------------

I uploaded picture here
Please help me!

A: The start method is invoked in the MIDP thread not the EDT. You should wrap your code in a callSerially call (everything after init) as such:
public class TextAreaMidlet extends MIDlet implements Runnable {

public void startApp() {
    Display.init(this);
    Display.getInstance().callSerially(this);
}

public void run() {
    Form mForm = new Form("Text Area");
    mForm.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
    Button button = new Button("Click here to open new Form");
    mForm.addComponent(button);
    TextArea textArea = new TextArea();
    textArea.setEditable(false);
    textArea.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL));
    textArea.setText("The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog");
    mForm.addComponent(textArea);
    mForm.show();
}

As a sidenote Codename One simplified this whole pain start() is just invoked on the EDT and you are rarely exposed to the device threads, another good reason to migrate.


text:
Q: UIScrollView - dynamic loading the images, how can I reload more images in scrollview? UIScrollView with dynamic loading the images, when scroll
 the end page, how can I reload UIScrollView and load more new images into this scrollView?

A: I use GMGridView https://github.com/gmoledina/GMGridView
GMGridView is subclass of UIScrollView, and can dynamic loading the images like UITableView reload.


text:
Q: Does MetaBase provide drill-down functionality? I want to implement drilling in metabase dashboards.
I discovered 'Custom Destinations' option which navigates user to any link upon clicking on a chart, but it does not carry forward the filter for selected dimension.
Is there any way we can implement drill-down functionality in MetaBase?
I linked a chart to another dashboard but it didn't filter by the selected dimension.


text:
Q: Java else if statement within selenium webdriver- negative test So I'm testing adding an item to a cart, but realistically I want to pick the 1st Item if present and else if select the second but there's no list on https://www.prana.com/men/tops/shirts.html for the items. So I went the css selector for each of the images. To also still have the ability to have multiple items I wanted to use if- else if statements to decide between the Items. I have:
if (driver.findElement(By.cssSelector("a[title='Weathered Blu22e']")).isDisplayed())
{
    driver.findElement(By.cssSelector("a[title='Weathered Blue']")).click();
}
else if (driver.findElement(By.cssSelector("a[title='Equinox Blue']")).isDisplayed )
{
    driver.findElement(By.cssSelector("a[title='Weathered Blue']")).click();
}

the first line that has "Blu22e" is not a correct CSS title but Blue is... when I have "blue" it selects the item correctly but When I put in Blu22e ( to do a negative test and go to the else if statement I see this error:
no such element: unable to locate such an element.
Any ideas how I can negative test the first line? I want it to skip that and move on to the next statement
Sorry for lack of knowledge I am an intern and going to school still so my Java isn't up to par.

A: As I understand your usecase you want to click on the element cssSelector("a[title=''Weathered Blu22e'']") and incase it is not available within the HTML DOM you want to click on the element cssSelector("a[title='Weathered Blue']")
In this case, you need to wrap up the logic in a try-catch{} block as follows:
try {
    driver.findElement(By.cssSelector("a[title='Weathered Blu22e']")).click();
} catch (NoSuchElementException e) {
    driver.findElement(By.cssSelector("a[title='Weathered Blue']")).click();
}

A: If you look in javadocs for WebDriver you will see: findElement should not be used to look for non-present elements, use findElements(By) assert zero length response instead. So it could be as like:
if (driver.findElements(By.cssSelector("a[title='Weathered Blu22e']")).size() > 0)
{
    driver.findElement(By.cssSelector("a[title='Weathered Blue']")).click();
}
else if (driver.findElements(By.cssSelector("a[title='Equinox Blue']")).size() > 0)
{
    driver.findElement(By.cssSelector("a[title='Weathered Blue']")).click();
}


text:
Q: Microsoft Bot Framework (Node.js- SDK4) + Microsoft Graph API Is it possible that the Microsoft Bot Framework Node.js - SDK4 automatically identify a logged in user from a Microsoft account (like a user that is logged in Sharepoint) so that I can use Microsoft Graph services directly on the bot without needing to ask user login and password?
I'm asking that because I have a bot running on a sharepoint page, and in theory, the user already will be logged in on a microsoft account when he starts talking to the bot.

A: Check this code.
                { ResponseIds.Greeting, (context, data) => {
                var greetings = JsonConvert.DeserializeObject<Greetings>
                (MainStrings.GREETING);

                Random r = new Random( );
                int index = r.Next( greetings.messages.Count );

                return greetings.messages[index].message.Replace("
                {username}",context.Activity.From.Name);

                 }

Else I have seen an authentication dialog that probably does a similar operation


text:
Q: Оптимизация MySQL Мне нужно, чтобы на каждой странице сайта выводилось количество новых сообщений для пользователя (например, 30 новых сообщений). Для этого мне каждый раз из таблицы нужно будет извлекать count(*) количество сообщений для данного пользователя (а если в таблице всего тысяч 50 сообщений для всех пользователей, то это делать накладно). Как в этой ситуации поступить, может нужно кэшированием запроса воспользоваться?
A: Т.к. сообщения лучше обновлять чаще раза в час, предлагаю сделать таблицу со спец.данными (сообщения, обновления другого рода) и обновлять ее при соответствующих действиях.
function addMessage($from, $to, $msg) {
  /* code */
  mysql_query('UPDATE upd_table SET total_in_messages=total_in_messages+1 WHERE userid='.$to.';');
  mysql_query('UPDATE upd_table SET total_out_messages=total_out_messages+1 WHERE userid='.$from.';');
  }

Там же можно сделать счетчик new_messages_counter, например.
A: А можно сделать "ORDER BY date_added DESC LIMIT 30", не сильно затратно )
A: count(*) - оптимизированная мускулем функция, и не тратится время на data transfer. так что действительно не сильно затратно.
A: Немного разовью идею @Sh4dow, создайте дополнительную таблицу с {userID, privateMessageCount} обновление privateMessageCount происходит через триггер на вставку в таблицу приватных сообщений пользователей записи о новом сообщении для данного пользователя (не стоит это делать через доп. запросы как это предлогает @Sh4dow - бессмысленная нагрузка для mysql, пусть и небольшая).
Да, и при необходимости получить count(*), просто получаем данные из описанной мною выше новоиспеченной таблицы.


text:
Q: Auto Scroll To A each div or element I need some help regarding auto scroll to each div or element when the user will use the scroll button in the mouse. Here goes the scenario
Suppose this is my structure of the page..

here goes my content 1

here goes my content 2

here goes my content 3

-Now suppose my each div has got enough content to make the page long. Suppose the user is on my-div-1 and when the viewer uses the scroll button to scroll down, instead of scrolling through the whole div, i want it to scroll automatically to the my-div-2.
I hope my explanation make sense here.
Is there any way to sort it out by using javascript and jquery?
I will appreciate any response..Thanks in advance.

A: Here's a fiddle with what you want: http://jsfiddle.net/3qxhY/9/
Source of plugin used in code (debounce/throttle plugin): http://benalman.com/projects/jquery-throttle-debounce-plugin/
Code
// debounce/throttle plugin
(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);

//elements you want to scroll to go here
divs = [$(".my-div-1"),$(".my-div-2"),$(".my-div-3")];

var lastScrollTop = 0; //we'll update this on every scroll and compare it to the last scroll to determine the scroll direction
var run = true;

$(window).scroll($.debounce(250, true, function () { //debounce so it only runs once per scroll
  var st = $(window).scrollTop();
  if (st > lastScrollTop) { // if the scrollTop when the scroll event fires is larger than the last scroll, we can assume the scroll was in a downward direction
    $.each(divs, function (i, v) {
      ((v.offset().top - $(window).scrollTop()) < 0) && (next = i + 1); //compare each elements offset to the windows offset to determine which element we're currently scrolling through
    });
    run = (next != divs.length) ? true : false; //dont run if we are at the last div
  } else {
    $.each(divs, function (i, v) {
      ((v.offset().top - $(window).scrollTop()) < 0) && (next = i);
    });
    run = true;
  }
  if (run) {
    $('html, body').animate({
      scrollTop: divs[next].offset().top
    }, 1000,'linear', function() {
      lastScrollTop = $(window).scrollTop();
    });
  } else { lastScrollTop = $(window).scrollTop(); }
}));


text:
Q: React native invariant violation element type is invalid I am following a tutorial and i am facing with this error.

Invariant Violation:Element type is invalid expected a string but got
  object:
  Check the render method of 'Home'
  This error is located at:
in Home(at index.js:12)

This is my file structure:

index.js:
import React from 'react';
import EStyleSheet from 'react-native-extended-stylesheet';
import Home from './screens/Home';

EStyleSheet.build({
    $primaryBlue:'#4F6D7A',
    $white:'#fff'
});

export default ()=> <Home/>;

home.js:
import React,{Component} from 'react';
import {View,StatusBar} from 'react-native';
import Container from '../components/Container';
import Logo from '../components/Logo';
import InputWithButton from '../components/TextInput';

class Home extends Component {
    render(){
       return (
          <Container>
             <StatusBar translucent={false} barStyle="light-content">
             </StatusBar>
             <Logo/>
             <InputWithButton/>
             <InputWithButton/>
          </Container>
        );
    }
}

export default Home;

Container.js:
import React from 'react';
import PropTypes from 'prop-types';
import {View} from 'react-native';
import styles from './styles';

const Container = ({children})=>(
   <View style = {styles.Container}>
      {children}
   </View>
);

Container.propTypes={
   children:PropTypes.any,
};
export default Container;