text:
Q: Sending a String from Raspberry Pi to Arduino via XBee modules [SOLVED] the problem was with the USB-TTL PL2303 chip I was using to interface the XBee module with the Pi. It was creating the problem. It's drivers were not properly supported by the RPi2.
I am trying to send a string (possibly a number) from a python script on my Raspberry Pi2 through a XBee module connected to it, to an Arduino Uno. The data sent is being misinterpreted at the Arduino end. When I use the terminal on X-CTU and send strings through that it shows up correctly on the serial monitor of Arduino IDE.
Here is the Python Code I am using
import time
import serial
ser = serial.Serial("/dev/ttyUSB0",9600)
ser.isOpen()
x= '4'
ser.write(bytes(x, "ascii")) #writing as bytes
time.sleep(2)
ser.close()

Here is the Arduino code I used
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
// Open serial communications
Serial.begin(9600);

// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
}

void loop() // run over and over
{
 int x;
 if (mySerial.available())
  {

    x = char(mySerial.read()) - '0';
   //reading data value from Software Serial port
   //converting ASCII to int
   //and storing it as x
   Serial.print(x);

   }

A: My guess, if you are already typecasting to char, you don't need to subtract '0', because then Serial.print() will interpret that value as an ascii code and print the corrosponding character. So just try, char(Serial.read()) and print it.

A: Well, you know the code on the receiving end is working correctly because you can test it by sending data with the X-CTU terminal.  How are you sending from X-CTU?  Just typing the number 4 in the window, or sending it as a hex value (0x04)?
What happens when you have the Python script send to the X-CTU terminal?  What do you see?  What if you just dump the value of the byte read on the Arduino side before doing any conversions to it?  Compare what X-CTU sends to what Python sends.
Instead of using bytes() to convert your Python string, you could just assign x = b'4' and see what that does.


text:
Q: Convert Linq to SqlCommand What is the equivalent of this Linq query in SQL Server query?
IEnumerable<Profile> profiles = am.Profile.Where(a => articles.Select(b => b.ProfileId).Distinct().Contains(a.ProfileID));

where articles is:
IEnumerable<Article> articles = (from a in am.Article
                                 orderby a.AddedDate descending
                                 select a).ToList();

A: Use EXISTS:
SELECT * FROM Profile P
WHERE EXISTS(
    SELECT 1 FROM Article A
    WHERE A.ProfileId = P.ProfileId
)

Apart from that, your linq query is inefficient. Why do you use Distinct before Contains? It's not necessary to remove duplicates before you use Contains.
This is more readable and efficient:
IEnumerable<Profile> profiles = am.Profile
    .Where(p => articles.Any(a => a.ProfileID == p.ProfileID));

A: SELECT * FROM Profile
WHERE
EXISTS(SELECT DISTINCT ProfileId FROM Article WHERE ProfileId in (SELECT ProfileID FROM  Profile))

A: Select p.*
From [Profile] p
Where p.profileID In (
    Select Distinct ProfileId
    From [Article]
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Edit Text not allowing to enter value when the value entered is within the range Below is the code which i use in my edit text to take value only within a certain range
 EditText.setFilters(new InputFilter[]{ new InputFilterMinMax(Min, Max)});

this is my fuction:
 public class InputFilterMinMax implements InputFilter {

    private int min, max;

    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }

    public InputFilterMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int input = 0;
        try {
            input = Integer.parseInt(dest.toString() + source.toString());
            if (isInRange(min, max, input))
                return null;
        } catch (NumberFormatException nfe) {
        }
        return "";
    }

    private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}

This code works when min is 1 and max is 10, but it is not working when min is 20 and max is 30
please help,thanks in advance

A: This is because when you start typing '20', the first number is 2, and 2 is not between 20 and 30.
I suggest you to use TextWatcher instead :
TextWatcher textWatcher = new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if(s.length() > 0) {
            int num = Integer.parseInt(s);
            if (num >= Min && num <= Max)
            {
                // Place your logic here. EG : save the number.
            }
            else{
                // Your are not in the desired range.
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
};

EditText.addTextChangedListener(textWatcher);

A: public class InputFilterMinMax implements InputFilter {

    private int min, max;

    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }

    public InputFilterMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int input = 0;
        try {
            **if(end==1){
               min = Integer.parseInt(source.toString());
            }**
            input = Integer.parseInt(dest.toString() + source.toString());
            if (isInRange(min, max, input))
                return null;
            } catch (NumberFormatException nfe) {
        }
        return "";
    }

    private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}

Appending if (end==1) { min = Integer.parseInt(source.toString()); } works fine for me.
However, a better approach for what you are trying to implement is to use TextWatcher as mentioned by Thomas


text:
Q: Aggregation using MongoDB java driver with multiple $project I am trying to convert Mongo Aggregation query into Java and I am kind of stuck on the second $project statement
db.ValidationResults.aggregate([

        {
            $match: {
                "_id.settlementInstanceId" : "715e66c7-92ff-4619-9324-2c708489fe27",
                "Versions.scope" : "INPUT_QUALITY"

            }
        },
    {
        $project: {
            Versions: 1,
            MaxVersion: { $max: "$Versions.version" }
        }
    },
    {
        $project: {
            Versions: {
                $filter: {
                    input: "$Versions",
                    as: "x",
                    cond: { $eq: [ "$$x.version", "$MaxVersion" ] }
                }
            }
        }
    },
    {
        $unwind: "$Versions"
    }
])

Any help is really appreciated. TIA
Java Code -
    AggregationOutput agg1 = db.getCollection("ValidationResults").aggregate(
            new BasicDBObject().append("$match",
                    new BasicDBObject().append("_id.settlementInstanceId", "715e66c7-92ff-4619-9324-2c708489fe27").append("Versions.scope","INPUT_QUALITY")),
            new BasicDBObject().append(
                    "$project",
                    new BasicDBObject().append("Versions", 1).append("MaxVersion",
                            new BasicDBObject().append("$max", "$Versions.version"))),
            new BasicDBObject().append(
                    "$project",
                    new BasicDBObject().append("Versions",new BasicDBObject().append("$filter", new BasicDBObject().append("input", "$Versions").append("cond",
                            new BasicDBObject().append("$eq", new BasicDBObject().append("$$x.version", "$MaxVersion")))))),
            new BasicDBObject().append("$unwind", "$Versions")
                    );

I am getting error on "$$x.version" such as -
Unrecognized expression '$$x.version'. The full response is { "ok" : 0.0, "errmsg" : "Unrecognized expression '$$x.version'", "code" : 168, "codeName" : "InvalidPipelineOperator" }


text:
Q: Laravel 7 - Spatie Permissions: Assign User with different role per team Well I am trying to do the following:

*

*A user can have a specific role (user, elevated user, admin)

*Most people will be registered as users, but some will be granted the elevated user role

*Elevated users will be able to make their own teams

*In each team, elevated users will be able to invite ANY user registered to my Laravel application

*If a user is invited to a team, he will be given a specific task to do (aka a team role)

I made the following roles:
    $role = Role::create(['name' => 'Elevated User']);
    $role = Role::create(['name' => 'User']);
    $role = Role::create(['name' => 'Admin']);

How can I achieve such a thing?
Is it possible to do that by using Spatie?

*

*I thought of assigning my user with a specific role for the whole
application, but grand a specific role just for each team he belongs
to.

*A user may belong to different teams and have different roles in each team

Example:
User Chris has the User role

*

*Chris belongs to team A and his role on the team is "editor"

*Chris also belongs to team B and his role on that team is "leader"

Each role that Chris has in those two different teams, grand him different permissions for team A or B

A: *

*Requires a user and teams connection.

*Role and permission must be linked to it.

*You can do the required condition there.

For example, like this
Models/User.php

public function hasAuthorized($team_id, $role) {
   return $this->userTeams()->where('team_id', $team_id)->first()->hasRole($role);
}


text:
Q: XPAGES - add a file in a rich text with getDocumentByUNID I try to create a pdf with itext and adding this in a rich text.
I create the pdf it's ok but when i want to put the file in the rich text, i have an error : "null" in my document Notes.
I don't understand.
This is my code :
// recupere l'id du document ouvert dans l'url
            String idDocument = XSPContext.getXSPContext(FacesContext.getCurrentInstance())
                    .getUrl().getParameter("documentId");

            // recupere le document
            Session session = Factory.fromLotus(Utils.getSession(), Session.class, null);
            Database db = session.getCurrentDatabase();
            Document docRepeat = db.getDocumentByUNID(idDocument);

pieceJointe.copieFichierDansRichText(docRepeat, nomChampSauvegarderPdf, tempDocPdf,
                    nomPdf, REPERTOIRE);

I create my pdf'file (it's ok) and =>
public void copieFichierDansRichText(Document monDoc, String nomRti, File file,
        String nameFichier, String chemin) {  RichTextItem rtiNew = (RichTextItem) monDoc.createRichTextItem(nomRti);
    PieceJointe pieceJointe = new PieceJointe();
    pieceJointe = buildPieceJointe(file, nameFichier, chemin);

    rtiNew.embedObject(EmbeddedObject.EMBED_ATTACHMENT, null, pieceJointe.getChemin(),
            pieceJointe.getNomPiece());
    monDoc.computeWithForm(true, false);
    monDoc.save();}

The problem i have

But when i use this to create my pdf it's ok i have the informations ????
it's only when i want to create the rich text that it says null exception !
In the console i have "org.openntf.domino.utils.DominoUtils$4 run"
Could you help me ?
EDIT
it seems that docRepeat is the problem
Document docRepeat = db.getDocumentByUNID(idDocument);

I try docRepeat is not null, there is an exception toArray....

A: I find !
It's openntf which don't works.
I must use lotus.domino.document =>
public void copieFichierDansRichText(String idDocument, String nomRti, File file,
        String nameFichier, String chemin) throws NotesException {

    lotus.domino.Session session = Utils.getSession();
    lotus.domino.Database db = session.getCurrentDatabase();
    lotus.domino.Document monDoc = db.getDocumentByUNID(idDocument);

    try {
        if (monDoc != null) {
            lotus.domino.RichTextItem rtiNew = (lotus.domino.RichTextItem) monDoc
                    .getFirstItem(nomRti);
            PieceJointe pieceJointe = new PieceJointe();
            pieceJointe = buildPieceJointe(file, nameFichier, chemin);

            rtiNew.embedObject(EmbeddedObject.EMBED_ATTACHMENT, "", pieceJointe.getChemin()
                    + pieceJointe.getNomPiece(), pieceJointe.getNomPiece());
            monDoc.computeWithForm(true, true);
            monDoc.save(true);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}


text:
Q: vertical bars not aligned with the x-axis label and last bar rendered outside the x-axis range - D3 js - simple bar with fixed width I'm having challenges in setting the bar (fixed width) position aligned correctly width the x-axis label.
The bars and the x-ticks are not aligned correctly and also the last bar is rendered after the max xscale range.
Appreciate any help in fixing this issue.
Please check the sample here - https://jsfiddle.net/sjselvan/wsy5frh2/29/ - updated and fixed version

function generateChart(){
  const data = [{
   label: 100,
   value: 10
},
{
   label: 200,
   value: 20
},
{
   label: 300,
   value: 30
},
{
   label: 400,
   value: 40
},
{
   label: 500,
   value: 50
}];

let margin = {top: 20, right: 20, bottom: 70, left: 40},
    width = 600 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

const xScale = d3.scaleLinear().domain([0,500]).range([0,width]);
const yScale = d3.scaleLinear().domain([0,50]).range([height,0]);

const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);

console.log(d3.select('#chart'));
let svg = d3.select('#chart')
               .append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
         .append("g")
          .attr("transform",
               "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .selectAll("text")
      .style("text-anchor", "end")
      .attr("dx", "-.8em")
      .attr("dy", "-.55em")
      .attr("transform", "rotate(-90)" );

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Value ($)");

  svg.selectAll("bar")
      .data(data)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", function(d) { return xScale(d.label); })
      .attr("width", 15)
      .attr("y", function(d) { return yScale(d.value); })
      .attr("height", function(d) { return height - yScale(d.value); });
}

generateChart();

A: You're setting the x value of the bars, which sets the left-hand edge of the bars, using the same scale as the x axis. So, it makes sense that the left-hand edge of the bar representing 100 is lined up with the 100 tick in the axis.
In order to line up the bars, you need to move them to the left by half of their width. You would need to make the bar width an even number so that the bars fit nicely.
const barWidth = 16;

svg.selectAll("bar")
  .data(data)
.enter().append("rect")
  .style("fill", "steelblue")
  .attr("x", function(d) { return xScale(d.label) - (barWidth / 2); })
  .attr("width", barWidth)
  .attr("y", function(d) { return yScale(d.value); })
  .attr("height", function(d) { return height - yScale(d.value); });

However, I would say that it doesn't really make sense for this chart to be a bar chart. Bars usually represent nominal (Banana, Apple, Pear), or ordinal values. Whereas your chart seems to more suit a line, or a scattergraph.
But if you do mean to use the numbers as labels, you will be better off using a band scale which will line up the bars above the labels nicely.


text:
Q: Solving "unable to connect to the specified server" error in Diadem DataFileHeaderAccess I am currently using Diadem to process a large amount of data.
There is a specific treatment that I must do on a large number of files. Therefore, I have a script loading each file one by one to do this every time.
The thing is, after several hours of computation, I get an error : Incorrect instruction or user command. In <DataFileHeaderAccess.VBC> (line:1328, column:5): Unable to conect to the specified server.
By this time, it will have successfully passed the portion of code where it happens several times, and if I launch it back on the file that has issues, it will not fail (not for this file at least).
Even more strange is that nothing is done remotely there, so I have no idea which server it might be talking about. And the file is ot opened elsewhere. Most of the time, it happens when I'm not even in the office.
And finally, I managed to find nothing anywhere regarding this issue, And I'm growing quite desperate to manage to solve it.
So ... Simple question ... "Help ?".
Well, let's develop it a little :

*

*What might be the cause of this issue ?

*How can I solve it ?

Here is the portion of code incriminated if it might help :
Function TryLoadGroup(sPath, sFileName, sGroupName, sNewGroupName)
  Dim oDataFileHeader, oImportedGroup
  Set oDataFileHeader = DataFileHeaderAccess(sPath & sFileName, "TDM", True)

  Dim iLoop, bRet
  For iLoop = 1 To oDataFileHeader.GroupCount
    If oDataFileHeader.GroupNameGet(iLoop) = sGroupName Then
      bret = True
    End If
  Next
  oDataFileHeader.Close(False)

  If bRet Then
    Set oImportedGroup = DatafileLoadSel(sPath & sFileName,"TDM", sGroupName & "/*")
    oImportedGroup.Item(1).Name = sNewGroupName
    Set TryLoadGroup = oImportedGroup
  Else
    Set TryLoadGroup = Data.CreateElementList
  End If

End Function

A: Set oDataFileHeader = DataFileHeaderAccess(sPath & sFileName, "TDM", True)

The error message just means that it is not capable to open the file.
There are some things I can think of

*

*The file is corrupt (but this seems not to be true because you can open it)

*The file is opened by DIAdem or a group of it is already loaded into DIAdem

*DIAdem has run out of memory

Potentially you should put an error handler arround your inner loop
on error goto 0
' call a method
if 0 <> err.number then
  LogFileWrite "Unable to insert file '" & filename & "': " & err.description
end if
on error goto 0

This will allow you to go on processing and see the error in the DIAdem Logfile later on.


text:
Q: What's the name of film where aliens make earth better then blow it up I'm sure it was a 2 or 3 part film with Tom Cruise in it but I may be wrong. Aliens made the planet better with no war or hunger. The children born were more advanced, able to do telepathy etc. The aliens took the children off Earth to a better more advanced planet then, when everyone on Earth died, they blew it up.

A: Reminiscent of the miniseries Childhood's End.
It was in three parts. No Tom Cruise though.

Aliens made the planet better with no war or hunger.

Wikipedia says of part 2: In 2035, life on Earth resembles a pastoral idyll.

The aliens took the children off Earth to a better more advanced
  planet then, when everyone on Earth died, they blew it up.

Wikipedia says of part 3: The Earth is destroyed as the children join the Overmind.


text:
Q: In DynamoDB ,given a table, can I programmatically find the primary keys( both hash key and sort key) I am new to this and using python and boto3. I get a table in dynamodb as follows
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MyTabe')

Now I want to execute a Query for which I need the primary key. Is it possible to find these keys programmatically? ( PS I know the keys or I can even find it from AWS interactively)

A: You can find keys by .scan() method, like:
response = client.scan(
    TableName='your_table_name')

for item in response['Items']:
     print(item.get('your_primary_keys'))


text:
Q: Remove item from category collection in Magento 1.9 I have a category collection in Magento 1.9
This is my code :-
    $categories = Mage::getModel('catalog/category')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('parent_id', array('eq' => 4))
    ->addIsActiveFilter()
    ->addAttributeToSort('name', 'ASC');
    foreach ($categories as $cat) {

       $category = Mage::getModel('catalog/category')->load($cat->getId());

       $categories->removeItemByKey($cat->getId);
       echo '
';
       //echo $cat->getIsActive();
       print_r($categories->getData());
       exit;
    }

I need to remove the element corresponding to the current categoryId from the collection in the current loop so that when I use the same collection anywhere after the first loop I do not get the same category again.
But when I do $categories->removeItemByKey($cat->getId) it does not work. It does not remove the corresponding id element from the categories collection.
Am I doing something wrong or does removeItemByKey() not work for category collection and I have to do something else.
I am trying to find this for 5 hours but to no avail.

A: Try this:
$categories = Mage::getModel('catalog/category')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('parent_id', array('eq' => 4))
    ->addAttributeToFilter('entity_id', array('neq' => {set you category id here}))
    ->addIsActiveFilter()
    ->addAttributeToSort('name', 'ASC');
echo $categories->getSelect();
foreach ($categories as $cat) {

    echo '
';
    //echo $cat->getIsActive();
    print_r($categories->getData());
    exit;
}

OR you can exclude that by particular category ID
$categories = Mage::getModel('catalog/category')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('parent_id', array('eq' => {set you category id here}))
    ->addIsActiveFilter()
    ->addAttributeToSort('name', 'ASC');
echo $categories->getSelect();
foreach ($categories as $cat) {

    if($cat->getId() != 5)
    echo '
';
    //echo $cat->getIsActive();
    print_r($categories->getData());
    exit;
}

Here is the clone feature.
$categories = Mage::getModel('catalog/category');

$categoriesCollection = clone $categories;

$categoriesCollectionFilter = $categoriesCollection
        ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('parent_id', array('eq' => 3))
    ->addIsActiveFilter()
    ->addAttributeToSort('name', 'ASC')
->addAttributeToFilter('entity_id', array('neq' => 5));
echo "
";
    print_r($categoriesCollectionFilter->getData());
echo "

";
$categoriesOther = $categories->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('parent_id', array('eq' => 3))
    ->addIsActiveFilter()
    ->addAttributeToSort('name', 'ASC');
    print_r($categoriesOther->getData());
exit;


text:
Q: Add Dynamic content in {% schema %} section for Shopify Theme According to Shopify theme tutorial https://help.shopify.com/themes/development/theme-editor/settings-schema
files, we can define theme setting through set {% schema %} part like the following example:
{% schema %}
{
  "name": "Line",
  "class": "index-section",
  "settings": [
    {
      "type": "radio",
      "id": "small_line",
      "label": "Correct Gap",
      "options": [
        {
          "value": "none",
          "label": "None"
        },
        {
          "value": "gap1",
          "label": "Different Gap"
        }
      ],
      "default": "none"
    }
  ],
  "presets": [
    {
      "name": "Line",
      "category": "Design",
      "settings": {
      }
    }
  ]
}
{% endschema %}

My question if there is a way we can set this settings to be dynamic in the schema part like define "small_line" options as a variable in the above example, something similar to the following
{% schema %}
{
  "name": "Line",
  "class": "index-section",
  "settings": [
    {
      "type": "radio",
      "id": "small_line",
      "label": "Correct Gap",
      "options": MY_OPTIONS_VAR,
      "default": "none"
    }
  ],
  "presets": [
    {
      "name": "Line",
      "category": "Design",
      "settings": {
      }
    }
  ]
}
{% endschema %}

A: No you can't add any liquid code in your schema object.
Everything there needs to be entered as static information.


text:
Q: Would we consider a quadratic expression having an irrational and a rational root a polynomial? Would we classify a quadratic expression as the following as a polynomial?
$$2s^2-(1+2\sqrt2)s+\sqrt2$$
Shouldn't the roots of a quadratic expression always occur in pairs of either rational or irrational expressions?

A: The expression you wrote is a polynomial in the variable $s$ over the real numbers $\mathbb{R}$.
It is an expression of this type:
\begin{equation}
a_0+a_1x+a_2x^2+\dots+a_nx^n
\end{equation} where $a_i \in \mathbb{R} $ for all $i, 0 \le i \le n$.
Of course you can choose to consider polynomials over the rational numbers, or over the integers; in those cases, the expression you wrote is not a polynomial over the rationals or the integers because not all the coefficients are in $\mathbb{Q}$ or in $\mathbb{Z}$.
Let's now talk about your last question: the root of a quadratic polynomial over the real numbers (we can include the rationals and the integers as special cases of real numbers) are either both imaginary or both real, but nothing is said a priori without knowing the coefficients about them. You can have a quadratic polynomial over the real numbers whose roots are an integer and an irrational number:
\begin{equation}
x^2-(1+\sqrt{2})x+\sqrt{2}=(x-1)(x-\sqrt{2}).
\end{equation}

A: If the coefficients $a,b,c$ in the equation $ax^2+bx+c=0$ are rational and $a\ne0,$ then the roots are $$\left( \dfrac{-b}{2a} \pm (\text{a number that may be rational or irrational}) \right).$$
In that case either both roots are rational or both are irrational. But if some of $a,b,c$ are not rational, then that conclusion does not hold.
And if $a,b,c$ are real then either both roots are real or both have a nonzero imaginary part, and the two imaginary parts cancel each other out if added. But if the quadratic equation is $x^2 -(5+4i)x +(11+7i)=0,$ then the roots are not complex conjugates of each other. (For that equation, the discriminant $b^2-4ac$ is $-35+12i$ and $\displaystyle \pm\sqrt{b^2-4ac\,\,} = \pm(1+6i).$)


text:
Q: Merging shapefiles and creating unique feature wherever shapefiles' features overlap using ArcGIS Desktop? I am using ArcGIS Desktop 10.5.
I have a shapefile for impervious surfaces and a shapefile for tree canopy. I need to separate the tree canopy features into tree canopy that overlaps (is assumed to be above) impervious surfaces vs. tree canopy that does not overlap any impervious surface, and specifically I need to be able to calculate the area of each. Ideally I'd also merge these layers together to get a single shapefile that shows tree canopy over pervious cover, tree canopy over impervious cover, and impervious cover with no tree canopy above it, with the ability to calculate area for each class.
Here's a screenshot of what I have so far:

How can these shapefiles be merged so to create a unique feature or attribute wherever the original shapefiles' features overlap?

A: The geoprocessing tool that does this is union. It will merge both geometries and split them wherever they overlap.
You get unique features for each type of overlapping or not. The attribute table hold all columns from both layers. In the attribute table you can then select all features that are either tree or surface or both. Have a look at the tool help if it fits your task.


text:
Q: Chrome timer extension. How to keep timer running when extension is closed? I'm working on timer extension. I already have working timer app. But the problem is that after closing extension or changing tab  my extension is closing and all data will be erased. How to keep timer running when extension is closed?
Here is code of my app
manifest.json
{
    "manifest_version": 2,
    "name": "Timer",
    "version": "1.0",

    "description": "Just a simple timer",

    "icons": {
        "48": "icons/time-icon-48.png"
    },

    "browser_action": {
        "default_icon": "icons/time-icon-48.png",
        "default_popup": "popup.html"
    }
}

app.js
let HOURS = document.getElementById("hours");
let MINUTES = document.getElementById("minutes");
let SECONDS = document.getElementById("seconds");
let START = document.getElementById("start");
let RESET = document.getElementById("reset");

let startTimer = null;

START.addEventListener('click', function(){
    function startInterval(){
        startTimer = setInterval(function() {
            timer();
        }, 1000);
    }
    startInterval();
})

RESET.addEventListener('click', function(){
    HOURS.value = 0;
    MINUTES.value = 0;
    SECONDS.value = 0;

    clearInterval(startTimer);
})

function timer(){
    if(HOURS.value == 0 && MINUTES.value == 0 && SECONDS.value == 0){
        HOURS.value = 0;
        MINUTES.value = 0;
        SECONDS.value = 0;
    } else if(SECONDS.value != 0){
        SECONDS.value--;
    } else if(MINUTES.value != 0 && SECONDS.value == 0){
        SECONDS.value = 59;
        MINUTES.value--;
    } else if(HOURS.value != 0 && MINUTES.value == 0){
        MINUTES.value = 60;
        HOURS.value--;
    }
    return;
}


text:
Q: Given 2 numbers N and Q followed by N numbers.Now Q inputs of 2 Numbers U and V are given. U indicates the starting index and V indicates the ending Given 2 numbers N and Q followed by N numbers. Now Q inputs of 2 Numbers U and V are given. U indicates the starting index and V indicates the ending index. So for each U,V find the minimum of all values of the array from the index U to V(1 based indexing) Input Size: N<=100000
example
INPUT
5 3
1 1 1 1 1
1 3
2 4
3 4
OUTPUT
1
1
1

A: You can do something like this:
const N = 5;
const Q = 3;
const Numbers = [1, 1, 1, 1, 1];
const UVInputs = [[1, 3], [2, 4], [3, 4]];
const result = [];
for(let i = 0;i < Q;i++)
   result.push(Math.min(...Numbers.slice(UVInputs[i][0], UVInputs[i][1])));
console.log(result);


text:
Q: how to create dynamic database table using csv file in django or DRF I am going to create a database table using csv file without model in django. Steps are:
after sending csv file by post request, one database table will be created according to csv headers (name, university, score, total_score etc). And it will be populated using csv file data. Database table name should be derived from csv file name.
I searched but couldn't find good solution.
Any help is appreciated.
Below is my code to read csv file
class UploadProductApiView(generics.CreateAPIView):
serializer_class = FileUploadSerializer
def post(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    file = serializer.validated_data['file']
    decoded_file = file.read().decode()
    # upload_products_csv.delay(decoded_file, request.user.pk)
    io_string = io.StringIO(decoded_file)
    reader = csv.reader(io_string)
    for row in reader:
        print(row)

A: You could always create a dynamic Django model: https://code.djangoproject.com/wiki/DynamicModels
With this approach you could create models on the fly and by running this snippet
from django.core.management import call_command
call_command('makemigrations')
call_command('migrate')

you could migrate the model to the database and use it for accessing and storing the csv data. After that you should create the model code with inspectdb:
python manage.py inspectdb TableName > output.py

Set the path to the where you want your model file to be generated. I'm not certain if this command would overwrite or append to the current file, so you can try to append to current file, if it doesn't work make a temp file and write the output to it and append it to your desired models.py file: https://www.geeksforgeeks.org/python-append-content-of-one-text-file-to-another/
After the whole process you will have migrations generated, executed and the model in models.py for use on server restart.


text:
Q: Proper network configuration on Windows Server 2008 R2 without internet access I have a new Winwdows Sever 2008 R2 machine with two network cards. The situation is as follows:

*

*One network card is connected to CompanyLAN_1 (10.0.0.0/24)

*Through this card the machine can reach 10.0.0.254

*Through 10.0.0.254 the machine can reach 10.0.0.0/16

*The other network card is connected to CompanyBackup_1 (192.168.0.0/24)

*Through this card the machine can reach 192.168.0.254

*Through 192.168.0.254 the machine can reach 192.168.0.0/16

*The machine should NOT be able to access any networks beyond 10.0.0.0/16 and 192.168.0.0/16 (the machine should have no internet access at all)

What is the proper/recommended way of setting this up in Win2k8R2?
A) set up the network cards with the proper netmasks and put default gateways to each one
B) set up the network cards with the proper netmasks and put a default gateway to the normal one and add a static route to the backup one
C) set up the network cards with the proper netmasks and add two static routes, one for each?
Any link to official Microsoft references detailing recommendations would be welcome as well.

A: The simplest way to do this is not to specify any default gateway. When you do that, only the networks specified in the local routing table will be available.
You should, however, consider using a proper firewall for this machine: not only is it simpler to configure, it's also much more resilient to problems.


text:
Q: How to debug just some DLLs of an external program in VS? I have a program myProgram.exe installed in D:\myPrgram\
myProgram.exe uses some dlls which are in the same directory:
myProgram.exe

*

*myDll_1.dll

*myDll_2.dll

*myDll_3.dll

*myDll_4.dll

I have a visual studio solution in which I am able to generate only myDll_1 and myDll_2
How can I debug at least myDll_1 and myDll_2 generated from my Visual Studio Solution when I run myProgram.exe?

*

*Should I copy my dlls (with .pdb) to the ".exe" directory D:\myPrgram\ ?

*Run myProgram.exe and attach to it from Visual Studio

Remark :

*

*All source code is in C#

*I have .pdb of ALL dlls in D:\myPrgram\ : myDll_1, myDll_2, myDll_3 and myDll_4

*I have .pdb of myDll_1 and myDll_2 generated from my Visual Studio Solution


text:
Q: How to avoid spaces with stdout in python? While messing around with Python, I decided to make a random symbol generator, that would output a continuous stream of characters to the CL.
It's pretty simple, and looks like this:
from random import choice
import sys

char_ranges = [[33,48],[58,65],[91,97],[123,127]]

chars = []
for r in char_ranges:
    for i in range(r[0],r[1]):
        chars.append(chr(i))

while True:
    print choice(chars),
    sys.stdout.flush()

The only problem with it, is that the , used after printing a character causes a space to be added after stdout.flush() is called.
The way I'd usually get around this, is by concatenating a string and printing that instead, but in this case I want a continuous output flow, and therefore concatenation won't help.
So how can I get a continuous output flow in Python with no spaces?

A: Use sys.stdout.write instead of print.
print is a higher level construct for quick and dirty output. If you need more control, use something else.

A: Try this:
sys.stdout.write(choice(chars))


text:
Q: kernel panic error when trying to load bootpimage with hardware monitoring enabled when i enable hardware monitoring from makemenuconfig and try to load bootpimage i get the following error. we are doing this for an arm based processor
Kernel panic - not syncing: Attempted to kill init!


text:
Q: Bootstrap CSS not found while hosting in pythonanywhere I am trying to make an admin panel that includes some database. I have used flask-admin to automatically generate admin panel. When I ran the server locally in my PC, the bootstrap swatch is loading and works fine. However, when I hosted it in pythonanywhere and ran, it shows that the CSS is not found as shown in the image.
I have not used any templates of my own for admin panel. I used the following code to automatically generate the template.
admin = Admin(app, name='Admin Panel', template_mode='bootstrap3')

Link for the error message.

A: Same happened to me, but it turned out I used an unsupported swatch, here is the code that worked
app.config['FLASK_ADMIN_SWATCH'] = 'flatly'

# Create admin with custom base template
admin = admin.Admin(app, name='XXX', template_mode='bootstrap4')


text:
Q: Cocoapods: not loading Google SDK on xcodebuild I am using the Google SDK for SignIn in my ios 9 app. It successfully works and runs locally on my phone. and through clicking "Run" in xCode with my phone as the target.
Here is my PodFile:
use_frameworks!

    target "myApp" do
     pod 'Google/SignIn'
     pod 'Firebase'
    end

I then write import Google at the top of all my .swift files which use any delegate methods for SignIn or any other things related to authenticating with the Google SDK.
I don't use a bridging header because of use_frameworks!
I have an .xcworkspace that I am trying to make a executable of through a gitlab runner.
When I run the following in my runner
xcodebuild test -workspace myApp.xcworkspace -scheme myApp -destination 'platform=iOS Simulator,name=iPhone 6s,OS=9.3' | xcpretty -s

I get the following error:
AppDelegate.swift:17:56: use of undeclared type 'GIDSignInDelegate'

and basically every single usage of a Google dependent function or variable name throws in error.
It could be because it is xcodebuild test and somehow I am not properly linking my pods correctly for the test case of a build? Any help appreciated!

A: If you want to use the Google Sign In SDK on it's own without any other google services then I would recommend the following approach:
Podfile
In your Podfile, declare the Sign In library directly like so
use_frameworks!

target "myApp" do
    pod 'GoogleSignIn', '4.0.0'
end

Note: I'm specifying an explicit version number here because as of Cocoapods 1.0, the pod spec repo is no longer updated on every pod install call.
Module support wasn't introduced in the Google Sign In SDK until the latest version (4.0.0) on 18th May 2016 so if you haven't run pod repo update since then from the code example in your question you would actually be installing an older version of the SDK that doesn't support what you are trying to do.
If you receive an error when trying to run pod install with the above Podfile then running pod repo update should fix your issues.
Usage
In your .swift files where you use the SDK, import the library like so:
import GoogleSignIn


text:
Q: Why is colspan not a known native attribute in Angular 2? If we attempt code like this:
Column

or this:
Column

We soon find out that "colspan is not a known native attribute."
From the A2 docs we learn that:

the  element does not have a colspan property. It has the "colspan" attribute, but interpolation and property binding can set only properties, not attributes.

We must instead do this:
Column

Which is fair enough.
Question:
My question is, why is colspan not an attribute of the DOM, and if it is missing, how can the browser possibly render tables, since the browser renders the DOM and not the HTML?
Also, if I open my Chrome inspector, and go to the properties tab, why can I see colspan as a property of the Element?
Why does the DOM exhibit this inconsistency?

A:
My question is, why is colspan not an attribute of the DOM, and if it
  is missing, how can the browser possibly render tables, since the
  browser renders the DOM and not the HTML?

Colspan is an attribute of the DOM but it's not a property, so it's read only and browser renders it because it's an attribute.

Also, if I open my Chrome inspector, and go to the properties tab, why can I see colspan as a property of the Element?

The chrome shows both attributes and properties when you inspect it.
If you consider following,

A	A

B

document.getElementById('xyz').colspan results in undefined
Since it's not a property
but document.getElementById('xyz').id results in xyz
Since it's a property

A: Attributes & properties in Angular:
When the browser parses the HTML it will create an in memory DOM representation of the parsed HTML. What the data from the attributes often will become initial values for properties which are present in the DOM.
Since colspan isn't a DOM property of an  but colSpan (capital letter S) is one you will have to use the colSpan property. Here is an  element shown in chrome devtools:

We can see that the html attributes are saved in the attribute DOM property. It is important to realise that the current colspan is reflecting in the DOM colSpan property which can be observed below in the image.
When you are using property binding in Angular you are binding literaly 1 to 1 with these DOM properties. So in order to bind to the colSpan property we would need the following syntax:
Column

We can also bind directly to attributes in Angular, as you pointed out with the following syntax:
Column

Why does the DOM exhibit this inconsistency?

*

*For consistency reasons all DOM properties are lower camel cased

*Not all attributes can be transformed into DOM properties in a 1 to 1 fashion. Take for example the class attribute, we can see in the example image that the class attribute in our HTML results in 2 DOM properties (classList, className).

A: **Similar example
Property and attribute aren't always 1:1. An often encountered example is the label tag

In Angular

fails with the same error and you'd need to bind like

or

but

would also work because in this case htmlFor is the property that is reflected to the DOM for attribute.
See also https://developer.mozilla.org/de/docs/Web/API/HTMLLabelElement for the htmlFor property (in the Properties section)
See also What is the difference between attribute and property?
colSpan the actual property name
According to https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement colSpan is the property that is reflected to the colspan attribute therefore (uppercase S)
Column

See also https://plnkr.co/edit/BZelYOraELdprw5GMKPr?p=preview
works just fine.
Why does Angular bind to properties by default
Angular binds to the property by default for performance reasons. Binding to an attribute is expensive because attributes are reflected in the DOM and a change in the DOM can causes reevaluation of CSS styles that might match after the change, while properties are just a value in a JavaScript object that changed.
With attr. you opt in explicitely to the expensive behavior.


text:
Q: jqGrid inline delete/edit for local data shows URL not specified I am pretty new in JQuery and I am developing my first page using jqGrid. I need to fill a grid of some data from a from and in grid I need to delete row one by one and edit row by sending them to the source form and change them next send them back to grid at same row.
the problem is, while the data is local and I don't send any request to server, the delete and edit buttons asks me the URL. my code is as bellow:
jQuery("#grid1").jqGrid({
datatype: 'local',
colNames: [...,'Action'],
colModel: [...,{name: 'act', index: 'act', editable: false, formatter: 'actions',
        formatoptions: {
            keys: true,
            editbutton: true,
            delbutton: true,

            reloadAfterSubmit: false,

            delOptions: {
                onclickSubmit: function (options, rowid) {
                    $(this).delRowData(rowid);
                }
            }
        }
    }],
processing:true,
loadonce: true,
cellsubmit: 'clientArray'
});

I want to know is there any option, attribute or any trick to fix this.

A: You have to set editUrl property to 'clientArray'.


text:
Q: Convert lambda with method reference to function in Java 7 I'm working on an application which is working on Java 1.7. I need to rewrite some code which has been writing with Java 1.8 with SpringFramework. Unfortunately, I'm not familiar with a newer version and I don't know how to rewrite this code to work with Java 7...
Below part of the code.
ConfigRepo:
public class ConfigRepo extends RepositoryRestConfigurerAdapter {

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repoRestConfig) {
    repoRestConfig.withEntityLookup().forRepository(IConfigRepo.class, (Config config) -> {
        ConfigPK pk = new ConfigPK();
        pk.setScope(config.getId().getScope());
        pk.setKey(config.getId().getKey());
        return pk;
    }, IConfigRepo::findOne);
}

IConfigRepo:
public interface IConfigRepo extends CrudRepository<Config, ConfigPK> {}

EDIT:
Added my code.
I'm not sure if this what I've done part of it correctly. I don't know how this Config config should be passed. Also I don't know what I should do with this method reference...
My version:
public class ConfigRepo extends RepositoryRestConfigurerAdapter {

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repoRestConfig) {
    repoRestConfig.withEntityLookup().forRepository(IConfigRepo.class, new Config() {
        public ConfigPK prepareConfigPK(Config config) {
            ConfigPK pk = new ConfigPK();
            pk.setScope(config.getId().getScope());
            pk.setKey(config.getId().getKey());
            return pk;
        }, IConfigRepo::findOne);
}

A: The function forRepository seems to accept three arguments:

*

*A Class<IConfigRepo>

*An instance of the interface Converter<Config, ConfigPK>:
public interface Converter<Config, ConfigPK> {
    ConfigPK convert(Config config);
}

It's actually a generic interface but I inserted the types you use there.

*An instance of another functional interface Lookup<IConfigRepo, ID>
public interface Lookup {
    Object lookup(IConfigRepo repository, ID identifier)
}

Again a generic interface, but I inserted the types you use (except ID).
So the both functional interface arguments can be rewritten as instances of anonymous classes:
// Java 8
(Config config) -> {
    ConfigPK pk = new ConfigPK();
    pk.setScope(config.getId().getScope());
    pk.setKey(config.getId().getKey());
    return pk;
}

//Java 7
new Converter<Config, ConfigPK>() {
    @Override
    public ConfigPK convert(Config config) {
        ConfigPK pk = new ConfigPK();
        pk.setScope(config.getId().getScope());
        pk.setKey(config.getId().getKey());
        return pk;
    }
}

and
// Java 8
IConfigRepo::findOne

// Java 7
// ??? because I don't know your type for ID
new Lookup<IConfigRepo, ???>() {
     @Override
     public Object lookup(IConfigRepo repository, ??? identifier) {
          return repo.findOne();
     }
}

In your code you can replace the Java8 style lambda and method reference as parameters with what I wrote there


text:
Q: how to create Delphi 4 structure to map column names in XLS to column names in SQL I have an EXCEL sheet.it has various form-fields that are named as
 "smrBgm133GallonsGross/ smrBgm167GallonsGross "

and
 "smrEgm133GallonsGross/ smrEgm167GallonsGross "

I added to the XCEL sheets 2 new form fields named
smrBgm167GrosGalnsDA/smrEgm167GrosGalnsDA
The above additons I made in EXCEL should ACTUALLy be named as
`smrBgm229GallonsGross/smrEgm229GallonsGross` because. This is a  MUST  for the Delphi application to function properly.

This Delphi-4 application extracts , and vewrifys the form DATA in tandem with the DB.
My Delphi-4 application works (checks/inserts/retrieves)  so that current  months beginning gallon of milk "bgm229"  is equal to last months ending  gallon of milk "egm229"  , and then throw an exception if they are different.
Excel sheets:-  Bgm167GrosGalnsDA/  Egm160GrosGalnsDA
Delphi Code (DB- input/ DB- output/validation):-     bgm229/ egm229
SQL 2005 DB:- bgm167DA/ egm167DA
Actually the columns I ADDED should have been named asa "smrEgm133GallonsGross/ smrEgm167GallonsGross "...I messed up in naming them and they are on the production now....
In the Delphi procedure,for  the beginning  inventory, the code  it is
  ExtractFormBgmInfo(smrMilkAvMilk,  'smrBgm133');
  ExtractFormBgmInfo(smrMilkDe,           'smrBgm167');

For ending   inventory  the  code  it is
  ExtractFormEgmInfo(smrMilkAvMilk,  'smrEgm133');
  ExtractFormEgmInfo(smrMilkDe,           'smrEgm167');

I am adding "smrBgm229GrosGalns/smrEgm229GrosGalns" to the list
But the issue is that they are named erroneously as "smrBgm167GrosGalnsDA/ smrEgm167GrosGalnsDA" IN THE EXCEL sheets, while they are to be named as 'smrBgm229/'smrEgm229''(as is the case in the Delphi code). Hence. I added ...to the above
  ExtractFormBgmInfo(smrMilkAvMilk,    'smrBgm133');
  ExtractFormBgmInfo(smrMilkDe,           'smrBgm167');
  ExtractFormBgmInfo(smrMilkDyedDe,       'smrBgm229');

  ExtractFormEgmInfo(smrMilkAvMilk,      'smrEgm133');
  ExtractFormEgmInfo(smrMilkDe,           'smrEgm167');
  ExtractFormEgmInfo(smrMilkDyedDe,       'smrEgm229');

This throws an error  , as smrBgm229GallonsGross /smrEgm229GallonsGross  are not defined in the EXCEL sheets .So the issue is how do I convert "smrBgm167GrosGalnsDA" from Excel sheets into "smrBgm229GallonsGross" and then make my "ExtractForm" statement correct?
Please help there is an release scheduled today and got to discuss this with my superirors

A: What you want to do is map one string to another. You can use a simple string list for that.
// Declare the variable somewhere, such as at unit scope or as a field
// of your form class
var
  ColumnNameMap: TStrings;

// Somewhere else, such as unit initialization or a class constructor,
// initialize the data structure with the column-name mappings.
ColumnNameMap := TStringList.Create;
ColumnNameMap.Values['Bgm167 GrosGalns DA'] := 'bgm229/ egm229';

// In yet a third place in your code, use something like this to map
// the column name in your input to the real column name in your output.
i := ColumnNameMap.IndexOfName(ColumnName);
if i >= 0 then
  RealColumnName := ColumnNameMap.Values[ColumnName]
else
  RealColumnName := ColumnName;

Later versions of Delphi have the generic TDictionary class. Use TDictionary<string, string>. The TStrings solution I outlined above will have problems if any of the column names can have equals signs in them, but you can mitigate that by changing the NameValueSeparator property.
var
  ColumnNameMap: TDictionary<string, string>;

ColumnNameMap := TDictionary<string, string>.Create;
ColumnNameMap.Add('Bgm167 GrosGalns DA', 'bgm229/ egm229');

if not ColumnNameMap.TryGetValue(ColumnName, RealColumnName) then
  RealColumnName := ColumnName;


text:
Q: Importing a very large tab delimited file into MySQL WITHOUT first creating a table I have a very large tab delimited file. It's about 500 columns wide, and perhaps a million records long. It's a mix of text, dates and numbers. I'm actually only interested in a few columns from inside that - the rest will get deleted.
I want to import it into MySQL, but it's a one-off (perhaps 2- or 3-off) task and I can't really be bothered to create an empty table for a LOAD DATA INFILE command.
What is the lowest-effort method of achieving this? Can LOAD DATA INFILE be made to create a table on-the-fly with VARCHAR/TEXT columns or similar?

A: You have to create a table. But if you only need certain columns, you can select them.
Create a table of the desired columns.
the you can run the LOAD DATA like this.
LOAD DATA LOCAL INFILE 'import.csv' INTO TABLE yournewtable
FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'
(@col1,@col2) set Colum1=@col1,Column2=@col2;

@col1,@col2 are variables from the CSV. Colum1,Column2 represents the columns in the table you created.

A: LOAD DATA INFILE http://dev.mysql.com/doc/refman/5.5/en/load-data.html allows you to specify that only certain columns will be imported.


text:
Q: How to remove upper gap from svg text So there's a gap above my svg that no matter the height this still persist. I did think of solutions to fix this such as setting y="22" and then setting a margin-top: 10px;. But, I more just want to find out what's wrong exactly and what's the proper way to fix this.

<!DOCTYPE html>

<svg width="70px" height="50px">
    <text x="0" y="50" font-family="arial" font-size="25">
        Home
    </text>
</svg>

A: You just need to change the y value to 20 instead of 50

<svg width="70px" height="50px">
    <text x="0" y="20" font-family="arial" font-size="25">
        Home
    </text>
</svg>

A: I suggest to change y="20" by dy="25"
more info see: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dy
Why 25? because its the font-size that you choose.

<svg width="70px" height="50px" preserveAspectRatio="xMinYMin">
 <text x="0" dy="25" font-family="arial" font-size="25">
    Home
 </text>
</svg>

I also add the property preserveAspectRatio that could be useful for you too.

A: your way is correct instead of 50 for the Y you can put 20 for the Y then it will be fixed

<svg width="70px" height="50px">
    <text x="0" y="20" font-family="arial" font-size="25">
        Home
    </text>
</svg>


text:
Q: react-dom/test-utils, TypeError: Cannot read property 'children' of undefined I use react-dom/test-utils to test my react component.
But the return value of scryRenderedDOMComponentsWithClass has no props
and props.children property. Did I do something wrong or what?
here is my test code:
it('renders item count correctly', () => {
    const $$searchList  = TestUtils.renderIntoDocument(<SearchList items={datas}/>)
    const list = TestUtils.scryRenderedDOMComponentsWithClass($$searchList, 'list');

    expect(list.props.children).toHaveLength(4);
    expect(items).toHaveLength(4);

  });

here is the test result:
● component - SearchList test suites › renders item count correctly

    TypeError: Cannot read property 'children' of undefined

      at Object.<anonymous> (src/components/List/__tests__/SearchList.test.jsx:17:26)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
      at process._tickCallback (internal/process/next_tick.js:109:7)

  component - SearchList test suites
    ✓ loads without error (43ms)
    ✕ renders item count correctly (18ms)

-- update --
Here is my component render:
return (
      <div className="list">
        {
          items.map((item: Book, idx: number): React.ReactElement<IListProps<Book>> => {
            return (
              <ListItem onClick={() => this.onItemClick(item, idx)} key={item.id} item={item}/>
            );
          })
        }
      </div>
    );

A: scryRenderedDOMComponentsWithClass does not allow you to assert props on found components, while scryRenderedComponentsWithType does. More on that can be found here
Before to React 0.14, scry/find...WithClass would have returned the DOM component. With the release of 0.14, these methods return the DOM node itself. In neither of these cases would the props of a composite component be accessible.
You can also decide to use enzyme which has much more simple syntax for shallow rendering and finding your sub-components and their props then the syntax of react test utils (scryRenderedDOMComponentsWithClass, scryRenderedDOMComponentsWithTag and scryRenderedComponentsWithType).
You can read why and more about it here


text:
Q: Convert error codes to text in iOS I have a wrapper for encrypting and decrypting using CommonCryptor. Occasionally the decryption process will fail, in which case I fill an error like so:
if (result == kCCSuccess) {
    cipherData.length = outLength;
} else {
    if (error) {
        *error = [NSError errorWithDomain:kBridgeEncryptorErrorDomain
                                     code:result
                                 userInfo:nil];
    }

    return nil;
}

And then I log the error like this:
if (error != nil) {
    DDLogError(@"Decrypt fail %i, %@", [error code], [error localizedDescription]);
}

However, this ends up generating strings like:
2013-01-09 09:15:19.753 [BridgeEncrypter decryptDataFromData:] [Line 83] E: Decrypt fail -4304, The operation couldn't be completed. (com.***.bridgecrypt error -4304.)

Where the -4304 could be any of the error codes in CommonCryptor.h (-4300 to -4305). Is there a good way to map the error codes to their string values, or do I need to have a switch statement that adjusts the string by hand? If I do have to depend on a switch, would best practice be to put it where the issue is logged or where the error is generated?

A: I'm not sure what you're looking for here. I'm not familiar with CommonCryptor or how error messages are handled in it.
I can recommend that you lean on NSError and it's userInfo and NSLocalized*Key feature.
For example, if you set a NSLocalizedDescriptionKey in the userInfo dictionary, error:
NSDictionary userInfo = @{
    NSLocalizedDescriptionKey : @"This is the error message I want users to see"
};
*error = [NSError errorWithDomain:kBridgeEncryptorErrorDomain
                             code:result
                         userInfo:userInfo];

Then This is the error message I want users to see is the string returned by -localizedDescription. Then the calling code can use the string to display a message to the user without needing to reinterpret it.
As to the question of how to link error codes to messages you want users to see, there could be a CommonCryptor function that converts error codes to human readable string. If not, then you could write your own. I would recommend using a switch.
NSString *MyCodeToLocalizedDescription(CCCryptorStatus cryptorStatus)
{
    switch(cryptorStatus) {
    case kCCDecodeError: return @"This is the error message I want users to see";
    …
    default: return @"Oh noes, unknown error";
    }
}

At that point setting the error is:
NSDictionary userInfo = @{
    NSLocalizedDescriptionKey : MyCodeToLocalizedDescription(result)
};
*error = [NSError errorWithDomain:kBridgeEncryptorErrorDomain
                             code:result
                         userInfo:userInfo];


text:
Q: How to change +0800 to +0000 in Java? How to change 2018-12-24 12:00:00 +0800 to 2018-12-23 16:00:00 +0000 in Java?
private String currentDateandTime = new Date();

final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
final DateFormat fullFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss XX", Locale.CHINA);
//dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//fullFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

Date dateTest = dateFormat.parse(currentDateandTime);
currentDateandTime = fullFormat.format(dateTest);

currentDateanTime Result
2018-12-24 12:00:00 +0800

A: need to set "GMT" timezone (+0000) for fullFormat in order to convert Default Timezone to use GMT Timezone :
Date currentDateandTime = new Date();

final DateFormat fullFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss XX", Locale.CHINA);
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
fullFormat.setTimeZone(gmtTime);
String currentDateandTimeInGMTFullFormat = fullFormat.format(currentDateandTime);

A: Well, your code starts with an issue.
private String currentDateandTime = new Date();

Assuming Date() is imported from here java.util.Date
This line should show compiler error
Anyways I assume you want to convert your LocalTimezone DateTime to GMT Date Time
Date currentDate = new Date();
System.out.println(currentDate);

final DateFormat gmtFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
gmtFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
String convertedDate = gmtFormatter.format(currentDate);
System.out.println(convertedDate);

OUTPUT:
Mon Dec 24 09:52:14 IST 2018
2018-12-24 04:22:14

A: If you only want to get the same instance in different time zones, you can do it this way:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss Z");
OffsetDateTime offsetDateTime = OffsetDateTime.parse("2018-12-24 12:00:00 +0800", formatter);
ZonedDateTime dateTimeInDesiredZoned = offsetDateTime.atZoneSameInstant(ZoneId.of("UTC"));
// 2018-12-24 04:00:00 +0000
System.out.println(formatter.format(dateTimeInDesiredZoned));

However, 2018-12-24 12:00:00 +0800 and 2018-12-23 16:00:00 +0000 is not the same instant. There are 12 hours interval between them, you need minus these 12 hours.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss Z");
OffsetDateTime offsetDateTime = OffsetDateTime.parse("2018-12-24 12:00:00 +0800", formatter);
offsetDateTime = offsetDateTime.minusHours(12);
ZonedDateTime dateTimeInDesiredZoned = offsetDateTime.atZoneSameInstant(ZoneId.of("UTC"));
// 2018-12-23 16:00:00 +0000
System.out.println(formatter.format(dateTimeInDesiredZoned));


text:
Q: How to add keep asking for user input and save all input to file I have a certain problem with my code: Whenever I want to add a new patient, something fishy happens. If I write one patient at a time and then quit the registration, the patient I have typed in will be found in the file. But if I write more than one patient at a time, it's only the last patient input that will be saved and the rest isn't saved. I believe it has something to do with my array, but I can't put my finger on it. Any advice?
Here is the code:
    FILE *patientfile;
    char answer;

    patientfile= fopen("test.txt", "a");
    if (!patientfile)
        {
        printf(" Failed to open file.\n");
        }

    do
    {
        int i=0;

        printf(" Enter details of patient %d\n\n", i+1);

        printf(" Patients first name: ");
            scanf("%s",arr_patient[i].fname);
        printf(" Last name: ");
            scanf("%s",arr_patient[i].lname);
        printf(" Personnummer: ");
            scanf("%d", &arr_patient[i].birthdate);
        printf(" Bildref: ");
            scanf("%d", &arr_patient[i].bildref);

        printf(" Do you want to add someone else?: (y/n):");
            scanf(" %c",&answer);

        i++;

    }while(answer != 'n');

    int i = 0;

    fprintf(patientfile," %s\t%s \n ", arr_patient[i].fnamn,arr_patient[i].lnamn);
    fprintf(patientfile," %d \n",arr_patient[i].birthdate);
    fprintf(patientfile," %d \n",arr_patient[i].bildref);

    fclose(patientfile);

    }

EDIT: Problem fixed! Thanks everyone!

A: This is how it should be done (I embedded notes about the problems in the code)
char answer;
// NOTE: this must be outside the loop
int i=0;
do
{
    printf(" Enter details of patient %d\n\n", i+1);

    printf(" Patients first name: ");
    scanf("%s",arr_patient[i].fname);
    printf(" Last name: ");
    scanf("%s",arr_patient[i].lname);
    printf(" Personnummer: ");
    scanf("%d", &arr_patient[i].birthdate);
    printf(" Bildref: ");
    scanf("%d", &arr_patient[i].bildref);

    printf(" Do you want to add someone else?: (y/n):");
        scanf(" %c",&answer);

    i++;

}while(answer != 'n');

FILE *patientfile = fopen("test.txt", "a");
if (!patientfile) printf(" Failed to open file.\n");

// NOTE: You need to loop over the array and write all the patients to the file
for(int j=0; j<i; j++)
{
    fprintf(patientfile," %s\t%s \n ", arr_patient[j].fnamn,arr_patient[j].lnamn);
    fprintf(patientfile," %d \n",arr_patient[j].birthdate);
    fprintf(patientfile," %d \n",arr_patient[j].bildref);
}
fclose(patientfile);

But you don't actually need the array. You can write the patients to the file directly like this:
FILE *patientfile = fopen("test.txt", "a");
if (!patientfile) printf(" Failed to open file.\n");
char answer;
int i=0;
do
{
    // change patient_struct to your structure name
    patient_struct patient;
    printf(" Enter details of patient %d\n\n", i+1);

    printf(" Patients first name: ");
    scanf("%s",patient.fname);
    printf(" Last name: ");
    scanf("%s",patient.lname);
    printf(" Personnummer: ");
    scanf("%d", &patient.birthdate);
    printf(" Bildref: ");
    scanf("%d", &patient.bildref);

    fprintf(patientfile," %s\t%s \n ", patient.fnamn, patient.lnamn);
    fprintf(patientfile," %d \n", patient.birthdate);
    fprintf(patientfile," %d \n", patient.bildref);

    printf(" Do you want to add someone else?: (y/n):");
        scanf(" %c",&answer);

    i++;

}while(answer != 'n');
fclose(patientfile);

A: I see two problems:
You are setting i to zero in every loop:
do
{
    int i=0;

so all reading goes to array index zero. Move the initialization out of the loop:
int i=0;
do
{

so that the first record will be stored at array index 0, the second record at array index 1 and so on.
Further, you need a loop when writing to the file. Currently you only write one record. To write all records do something like:
for (int j = 0; j<i; ++j)
{
    fprintf(patientfile," %s\t%s \n ", arr_patient[j].fnamn,arr_patient[j].lnamn);
    fprintf(patientfile," %d \n",arr_patient[j].birthdate);
    fprintf(patientfile," %d \n",arr_patient[j].bildref);
}


text:
Q: How to understand the output of objdump, about indirect jmp? When objdump -S my_program, usually I can see the following indirect jmp instruction, which is typically used for switch/case jump table:
ffffffff802e04d3:       ff 24 d5 38 2e 10 81    jmpq   *-0x7eefd1c8(,%rdx,8)
How to understand the address -0x7eefd1c8? It means the table's base address is 0xffffffff802e04d3 - 0x7eefd1c8?
Also, how can I get -0x7eefd1c8 from ff 24 d5 38 2e 10 81?

A:
decoding issue

Than you have to look at Intel Development Manuals

*

*ff is JMP opcode (Jump near, absolute indirect) [1]

*24 is a ModR/M byte [2] which means that SIB byte goes after it (JMP opcode has only one operand, so register field is ignored)

*d5 is a SIB byte [2] which means that disp32 goes after that, Scale = 8 and Index = %rdx (in 32-bit mode, Index should be %edx) with no base.

*38 2e 10 81 is a 4-byte disp32 operand. If you encode it as double word, you will get 0x81102e38 note that highest bit is set to 1. It is a sign bit meaning that value is encoded in Two's Complement Encoding [3].

Converting from two's complement gives us expected number:
>>> print hex(0x81102e38 - (1 << 32))
-0x7eefd1c8

When processor executes that instruction in 64-bit mode, it reads 8 bytes from 0xffffffff81102e38 + (%rdx * 8) (original number is sign-extended) and puts that quad word into %rip [4].
References to manuals:

*

*Vol.2A, section 3.2 INSTRUCTIONS (A-M), page 3-440

*Vol 2, section 2.1.5 Addressing-Mode Encoding of ModR/M and SIB Bytes, pages 2-6..2-7

*Vol 1, section 4.2.1.2 Signed Integers, page 4-4

*Vol 2, section 2.2.1.3 Displacement, page 2-11


text:
Q: SQLite error: 'could not convert text value to numeric value.' I've found a work-around, but I am completely perplexed by an issue I ran into with Adobe Air and SQLite. An UPDATE query that I believe worked correctly earlier in the development process suddenly started failing with the error details:'could not convert text value to numeric value.', operation:'execute', detailID:'2300'. Several hours later I found that if I included a pretty irrelevant column in the query, setting it to an arbitrary value, the problem went away. As luck would have it, this did not affect the business logic in any meaningful way, so I'm going to leave it as is. However, I detest mysteries like this. Can anyone think of what might have happened?
(Edit: Sorry, I made a mistake in my code. The last two queries were identical in my original post. In fact, the UPDATE query only worked when I also added locked = null or locked = 0 to the query. If I didn't set this value, the query would fail. I did just about everything I could to get around this, including rebuilding the database file.)
Here's the table definition:
CREATE TABLE cars (
    car_id INTEGER  PRIMARY KEY AUTOINCREMENT DEFAULT NULL,
    cargroup_id NUMERIC,
    starting_ordinal NUMERIC,
    ending_ordinal NUMERIC,
    locked NUMERIC
);

This query has always worked:
var query = new Query(
    "UPDATE cars SET locked = (car_id = ?) WHERE cargroup_id = ?",
    [intCarId,intCargroupId],
    success,failure
);

This query failed with the above error ([edit]):
var query = new Query(
    "UPDATE cars SET starting_ordinal = ?, ending_ordinal = ?, cargroup_id = ? WHERE car_id = ?",
    [
        parseInt(objPayout.starting_ordinal,10),
        parseInt(objPayout.ending_ordinal,10),
        parseInt(objPayout.cargroup_id,10),
        parseInt(objPayout.car_id,10)
    ],
    success,failure
);

I solved the problem by changing the query to this:
var query = new Query(
    "UPDATE cars SET starting_ordinal = ?, ending_ordinal = ?, cargroup_id = ?, locked = null WHERE car_id = ?",
    [
        parseInt(objPayout.starting_ordinal,10),
        parseInt(objPayout.ending_ordinal,10),
        parseInt(objPayout.cargroup_id,10),
        parseInt(objPayout.car_id,10)
    ],
    success,failure
);


text:
Q: Install DBI-mysql for Perl 5.18.xx I am using perl 5.18.1.1800 with ppm 4.19 in a Windows 7 64 bit machine.
I need to use DBD-mysql to be able to access mysql from perl. But I get below error message:
use DBI();
my $dbh = DBI->connect("DBI:mysql:database=mydbname;host=localhost","myuser", "mypass",{'RaiseError' => 1})

install_driver(mysql) failed: Can't locate DBD/mysql.pm in @INC (you
  may need to install the DBD::mysql module)

So i tried to install DBD-mysql, but i don't have that listed in my PPM. In command line, when I tried to install, i get below error
ppm install DBD-mysql

ppm install failed: Can't find any package that provides DBD-mysql

I tried to download and install it, but it requires a C compiler which I don't have.
From DBD-mysql info page, there is no mentioning of Perl 5.18 support for the module.
So, should I revert back to 5.16.xx or the problem is something else?
Thanks,

A: DBD-mysql is available for ActivePerl-5.16.3.1604. Reverting back to that version is probably simpler than installing a compiler to build the package yourself.
Activestate used Visual Studio to build DBD-mysql: http://ppm4.activestate.com/MSWin32-x86/5.16/1600/C/CA/CAPTTOFU/DBD-mysql-4.022.d/log-20120830T032945.txt

C:\>ppm install DBD-mysql
Downloading ActiveState Package Repository packlist...done
Updating ActiveState Package Repository database...done
Syncing site PPM database with .packlists...done
Downloading DBD-mysql-4.022...done
Unpacking DBD-mysql-4.022...done
Generating HTML for DBD-mysql-4.022...done
Updating files in site area...done
  12 files installed

A: The name of the module is DBI. Try using:
ppm install DBI

*Disclaimer: I haven't used Perl on Windows, rather Perl on Linux, so I assumed the syntax for using ppm is "ppm install modulename".
also, the correct syntax hereafter would be:
my $dbh = DBI->connect(DBI:mysql:DBNAME, $username, $pass, {RaiseError => 1, AutoCommit
=> 1}) or die "Could not Connect to DB";


text:
Q: redirect mydomain.com to openshift app without www I am trying to deploy my app on Openshift.
I've added www.mydomain.com, and mydomain.com as aliases on Openshift and changed the cname record 'www' to myapp-mydomain.rhcloud.com
when I try to access the app these are the results,
myapp-mydomain.rhcloud.com  - Opens myapp
www.mydomain.com - redirects to myapp
mydomain.com - opens a blank page (the source of the blank page links to a godaddy's parking
looks like this http://mcc.godaddy.com/park/xxxxxxxxxxxxxx
how can I make my mydomain.com point to the application at myapp-mydomain.rhcloud.com
I have tried to change the 'A' record of the domain that pointed to 184.168.221.xx but it needs to be an IP address not the app address.
thank you so much for any help.

A: Not sure if you've seen this Openshift Article or not https://www.openshift.com/blogs/custom-url-names-for-your-paas-applications-host-forwarding-and-cnames-the-openshift-way but it will walk you through step by step on how to acheive exactly what your asking.
The important part to pay attention to is:

If you want to forward over your whole domain, such as mycompany.com
  and not www.mycompany.com, then you either need to use Domain
  Forwarding or find a DNS provider that allows "Naked" CName records.
  Domain forwarding uses a web server to do a redirect.

Also be sure to check out https://www.openshift.com/forums/openshift/domain-with-no-www-dns-question-is-that-possible.

A: CloudFlare allows you to create naked domains as CNAME records for free. Add CNAME records for both mydomain.com and www.mydomain.com which aliases myapp-mydomain.rhcloud.com.


text:
Q: Reading JSON file using java My issue is that I don't how to find that I have read the first JSON object of the JSON array leave_applicants. This I need to find using java.
{
    "leave_applicants":[
        {
            "applicant_name" : "Jhon",
            "supervisor_name" : "Mark",
            "org" : "UNDP",
            "index_no" : 1,
            "leave_details": {
                "leave_type" : "annual",
                "from" : "12-07-2018",
                "to" : "15-07-2018"
            }
        },
        {
            "applicant_name" : "Ravi",
            "supervisor_name" : "Mark",
            "org" : "UNDP",
            "index_no" : 2,
            "leave_details": {
                "leave_type" : "sick_leave_cert",
                "from" : "20-07-2018",
                "to" : "25-07-2018"
            }
        }
    ]
}

A: Assuming the JSON is in a text file stored on your computer. See the following code and at the end of each iteration of the for loop the end of first JSON object of the JSON array will occur (as you wanted).
import java.io.FileReader;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class ReadingJSONFromFile {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();

        try {

            Object obj = parser.parse(new FileReader(
                    "Path/To/JSON/File/json_file.txt"));

            JSONObject jsonObject = (JSONObject) obj;
            JSONArray leaveApplicants = (JSONArray) jsonObject.get("leave_applicants");

            for(Object applicants: leaveApplicants) {
                JSONObject app = (JSONJObject)applicants;
                String name = (String) app.get("applicant_name"); // Get the applicant name
                // You can get the other keys of the object similarly and display them as you want
                // This will be the end of the first object of the JSON Array
            }

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


text:
Q: Create global variables Bit of a newbie to VBA, sorry
I need to create some variables that are available throughout my workbook, but I can't seem to figure it out. I've read in previous questions where some people have suggested create a separate dim for this?
When the workbook opens I need to set some variables equal to certain cells in a worksheet, these variables need to be called from dims in others worksheets.
So far I have tried to use
Workbook_Open()
In the 'ThisWorkbook' code area but to no avail.
Any tips?
Reagards
EDIT ----
I have tried with the following:
In 'ThisWorkbook'
Public wsDrawings As String
Public Sub Workbook_Open()
     wsDrawings = "Hello"
End Sub

And in Sheet1
Private Sub CommandButton1_Click()
    MsgBox wsDrawings
End Sub

I do not get an error, but the message box is empty.

A: You can create global variable with code like this
Public testVar As String
you need to place it outside function or sub and then this variable has value till you close workbook. But i think it have scope only in current module.
So you can have something like this
Public testVar As String

Private Sub Workbook_Open()

testVar = "test"
End Sub

Sub testEcho()

MsgBox testVar
End Sub

for shared variable between multiple modules look here
edit:
So now i found, that you can use public variable from ThisWorkbook using this
Sub testSub()

    MsgBox ThisWorkbook.wsDrawings
End Sub

A: Just declare the variables you need wherever they are first used (ThisWorkbook is a fine place to do it) and replace the typical Dim with Public.  It will then be accessable in all your code

A: you can use module for creating global variable.


text: Q: Load data into ExtJS app at loadtime I have a database of users and their security credentials. I'm using passport (node authentication middleware) to authenticate users before serving my main ExtJS app.js. Is there a way to configure my app.js with the user's security credentials as I'm serving app.js? I.e, if Bob is authenticated with security clearance 4, how can I configure my Ext JS app to reflect this security level? I'm quite unfamiliar with web programming..(but learning!)


text:
Q: Video and audio playback not working on iOS I'm trying to incorporate video and audio file attachment to forum posts in an app, and the playback isn't working on iOS. On Android it works fine. The code looks like this (for audio, and similar for video):
String localAudiofilePath = FileSystemStorage.getInstance().getAppHomePath() + (String) fileInfo.get("path");
InputStream is = null;
Media m = null;
try{
    is = FileSystemStorage.getInstance().openInputStream(localAudiofilePath);
    m = MediaManager.createMedia(is, "audio/" + extractFileExtension((String) fileInfo.get("path")));
}catch(Exception ex){
    ex.printStackTrace();
}

m.play();

final Media mm = m;

Display.getInstance().scheduleBackgroundTask(new Runnable() {
    @Override
    public void run() {
      while(mm.isPlaying()){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
        }
      }
      mm.cleanup();
    }
});

I don't see any errors in the console, and when debugging I see the catch block is not entered. However, no sound comes out of the device when I try to play the audio, and the video player remains blank, giving me this message in the console:

2018-01-18 04:22:20.213822 MyApplication[24425:2262915] [Playback] ❗Playback failed with error: Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSUnderlyingError=0x61000024c2d0 {Error Domain=NSOSStatusErrorDomain Code=-12893 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-12893), NSLocalizedDescription=The operation could not be completed}, not resolving (canResolve: YES, errorResolver: (null))

What am I missing?

A: You are using the audio recording mime type to playback a video. I guess Android ignores it which is fine. The iOS port sees an audio format for the stream data and assumes this is an audio file. You need to specify the mime file type of the video you are playing.

A: The problem was not at all media playback.  The file wasn't actually present on the device, even though no exception was reported by iOS nor was the catch clause ever entered.  My incorrect assumptions were 1. that I could use try/catch around the input stream instantiation as a means of checking if the file exists (it worked on Android but not iOS), and 2. that the operating system would necessarily throw an exception if the file wasn't present (not the same as 1., but tied into it).
My new, working code looks like this:
String localAudiofilePath = FileSystemStorage.getInstance().getAppHomePath() + MyApplication.DIRECTORY_APP_DOWNLOADS + "/" + (String) fileInfo.get("path");
if(!FileSystemStorage.getInstance().exists(localAudiofilePath)){
    Cn1FileUtils.downloadRemoteFile("https://medonline.co.il/uploads/" + (String) fileInfo.get("path"), (String) fileInfo.get("path"), true);
}
InputStream is = null;
media = null;
try{
    is = FileSystemStorage.getInstance().openInputStream(localAudiofilePath);
    media = MediaManager.createMedia(is, "audio/" + Cn1FileUtils.extractFileExtension((String) fileInfo.get("path")));
}catch(Exception ex){
    ex.printStackTrace();
 ToastBar.showErrorMessage(MyApplication.getInstance().getString("error_loading_file"));
    return;
}
media.play();


text:
Q: Android Thumbnail Size Practice
I implemented a ListView with a AsyncTask for image loading and resizing. My question is about the image size of thumbnails for different Android Screen sizes.
If I shrink my thumbnails to 100px width and height, all my images have best sizes in every screen size. This means all my thumbnails have the same size. Does Android scale images internal?
I want to display a placeholder for all my list items if they have no own image.
I know this question is a little bit confusing but what i mean is:
Should i shrink my images to only one size and bring no placeholder for each screen size to have no different thumbnail sizes or scale my images by individual screen sizes and use a fallback from my ldpi, mdpi, hdpi or xhdpi? I hope it is understandable.

A: Ok so your question is if you should provide an placeholder in all densitys? You can, but its not necessary. Coincidentally  we just discussed that on tze android chat site here on stackoverflow. A user tested it out weather its necessary to provide images lower than hdpi. He tested it out and he noticed that Android resized all drawables just perfect so you wouldn't see a different. I hope I could answer your question.


text:
Q: React-native  component's "elevation" style is causing ugly shadows The elevation style attribute enables box-shadows for Android 5.0+.
Am I doing something unusual with 'elevation' here to cause the ugliness that can be seen in the screenshot below?  Also, is there any way to define a shadow-offset?
The emulator is running 6.0 (> 5.0), so that's not the problem.  I'm running react-native 25.1.
  "dependencies": {
    "react": "^0.14.8",
    "react-native": "^0.25.1",
    "react-native-gcm-android": "^0.2.0",
    "react-native-material-design": "^0.3.5",
    "react-native-system-notification": "^0.1.10",
    "react-redux": "^4.4.5",
    "redux": "^3.5.2"
  }

Here's react-native's documentation for View component styling
Here's my render method:
  render() {
    return (
      <ListView
        dataSource={alertData}
        renderRow={(rowData) =>
          <View style={style.cardContainer}>
            <Text>{rowData.blah}</Text>
            <Text>{"#" + rowData.foo}</Text>
            <Text>{rowData.blah}</Text>
            <Text>{rowData.foo}</Text>
            <Text>{rowData.baz}</Text>
          </View>
        }
      />
    );
  }

And the style declaration:
var style = StyleSheet.create({
  cardContainer : {
    elevation   : 3,
    flex        : 1,
    margin      : 10,
    padding     : 10,
    borderWidth : 2,
    borderColor : beeStyles.colors.lightGray
  }
});

Which somehow it results in this ...

A: The missing piece is backgroundColor.  Adding backgroundColor : '<anything>' style to the View container makes those weird inner shadows disappear.

A: You can add background color: backgroundColor : '#000';
A nice handy component :
import React from 'react'
import { View, StyleSheet, ViewPropTypes } from 'react-native'
import PropTypes from 'prop-types'

const SingleSidedShadowCard = ({ children, style }) => (
    <View style={[ styles.container, style ]}>
        { children }
    </View>
);

const styles = StyleSheet.create({
    container:{
        overflow: 'hidden',
        paddingBottom: 5,
    }
});

SingleSidedShadowCard.propTypes = {
    children: PropTypes.element,
    style: ViewPropTypes.style,
};

export default SingleSidedShadowCard;


text:
Q: Why does backbone filter collection fails when passing to view I have two methods to filter a collection:
Method 1: Using this method fails when I pass it to the view.
byCategory = @projects.byCategory(data)

Method 2: This method works very well.
byCategory = new App.Collections.Projects(@projects.byCategory(data))

Both methods works when I map byCategory and get the title:
byCategory.map (project) ->
  console.log project.get('title')

The second method works when I pass it to the view. But the first method fails:
view = new App.Views.ProjectsCarousel(collection: byCategory)
$('.slides').html(view.render().el);

My question is: Why? Why does the first fails when I pass it to the view, and why the second works?  The first one produces a error log: TypeError: _ref is undefined

Full code here:
Router
class App.Routers.PortfolioRouter extends Backbone.Router
  routes:
    '': 'index'

  index: ->
    controls = new App.Views.ProjectsControls({el: '#list', projects: new App.Collections.Projects()});

Collection
class App.Collections.Projects extends Backbone.Collection
  url: '/de/projects'

  byCategory: (cat) ->
    return @where category: cat

Views
class App.Views.ProjectsControls extends Backbone.View

  events:
    'click a': 'selectCategory'

  initialize: (options) ->
    @projects = options.projects
    @projects.fetch()

  selectCategory: (event) ->
    event.preventDefault()

    data = $(event.currentTarget).attr('data-category')
    # This method fails when I pass it to the view
    # byCategory = @projects.byCategory(data)
    # This method works very well, why does it work and the previous no?
    byCategory = new App.Collections.Projects(@projects.byCategory(data))

    # it works with both methods
    byCategory.map (project) ->
      console.log project.get('title')

    view = new App.Views.ProjectsCarousel(collection: @projects)
    $('.slides').html(view.render().el);

class App.Views.ProjectsCarousel extends Backbone.View
  template: JST['projects/carousel']

  render: ->
    @$el.html(@template(projects: @collection))
    this

Template
<% for project in @projects.models: %>
  <%= project.get('title') %>
<% end %>

A: TL;DR
I assume that @projects.byCategory(data) returns an array of Backbone.model, while the view expects an instance of Backbone.Collection. In your view you're probably using this.collection.models for an iteration* and .models is a property that you certainly won't find in a plain array of Backbone.model.

* The argument holds true if you're calling collection.fetch() or maybe even .set(), or any other Backbone.Collection, method

My intuition here (unless you say otherwise) is that
App.Collections.Projects.byCategory()

returns an array of Backnone.model, probably through a .map() or .pluck(). This assumption would answer your question and satisfy your .map() test.
Question 1: Why does passing byCategory = @projects.byCategory(data) fail?
So if my assumption is correct, then the byCategory variable is nothing but a JavaScript Array of Backbone.model. This is not what Backbone expects when it uses the Backbone.View.collection property, for example when you do a fetch, or set or simply try to iterate through collection.models (and a simple array of model does not carry a .models prop).
Question 2: Why does .map() always work?
The answer to this isn't obvious. Clearly Backbone.collection.map is going to work smoothly since _.map() is mixed into Backbone.Collection by default.
The reason .map() works on byCategory === @projects.byCategory(data) depends on two things.
1. byCategory is an array, therefore, and I'm assuming you're using an ECMASCRIPT 5 compliant browser, Array.prototype.map() works. And it accepts the same chaining convention as does the mixed in _.map() and takes the same Array parameter as _.map(). So in effect, you could easily be fooled into thinking that you're using Backbone.collection.map(), while in fact you were using Array.prototype.map().
The question remains, why did the .get('title') method in
console.log project.get('title')

work? Give the above, that's simple. Since you passed in an array of Backone.model to Array.prototype.map(), the argument in each iteration is Backone.model, which will happily accept Backone.model.get().


text:
Q: How do I sync my desktop Simplenote with that on my mobile phone?
*

*I have Simplenote on my android phone.

*I have installed Simplenote on my Ubuntu 20.04 pc (from 'Ubuntu Software').

*Now, how do I sync the Simplenote on my pc with that on my mobile (Android phone / cell phone)?
Thank you.
DB

A: Generally in Ubuntu: set up a google account in Ubuntu to use features from google. Link syncing bookmarks between systems and gmail.
On the simplenote site they explain how to share notes, so logically I would assume if you tag it with your own mail address it will be shown everywhere you use simplenote with that mail address:
I would assume you use your mail address as a tag:

How can I share a note or collaborate with others?
If you'd like others to view and edit one of your notes, add their email address as a tag. The shared note will then pop up in their list of notes. They'll need to have their own Simplenote account first. Similarly, if you'd like to work on a note together, have them add your email address as a tag to collaborate. In the iOS app, instead of adding your email address as a tag, you can tap the Info panel icon when viewing a note, then tap Collaborate.


text:
Q: Validating input in a form in Java using a Validate class. I am trying to get the code to use the Validate class into my program I have written a Validate class using Java and I want to use it to validate input on a form. The form itself is written and works. the following is an example of the code from my Validate class:
public static boolean validateID( String ID){

     return ID.matches("\\d{5}");
}

then I try to put the corresponding code into the form code
if(!Validate.validateID(ID)){
 System.out.println("Please enter a 5 digit number for the ID");

}
I keep getting the following error message and can't figure out how to fix it.
incompatible types: JTextField cannot be  converted to a String.

A: It looks like the type of ID that you are passing in is a variable of JTextField and not String. You didn't provide us with the declaration or initialization of ID so can't really pinpoint it.


text:
Q: Add page content dynamically MVC 5 I need to build a manage environment for my users so they could create new views (to give a title, a category, and the main content) or edit the content of the views that already have been created. I need to store this information in a database and have it appear in my site. I search through the internet but I didn't find a solution. I need this because I would like my site to have searchable content and because I have to many pages. Is that possible to achieve with MVC?

A: *

*first step

Save view content as string using a wysiwyg editor, I recomend
http://summernote.org/

*You need show your html using Html.raw() :

Exemple:  Html.Raw("<div class=\"resource-row\">")
that way you will show your string as HTML.
I hope it is useful


text:
Q: How to use Editfor in jquery datatable using ASP.net MVC I am using Jquery Datatable in asp.net MVC. I bind the sql query in datatable and the datatable i am using one Editfor, here i am using datetime picker. i attached my code on below. please help me.

        @foreach (var item in Model)
        {

                    @Html.DisplayFor(modelItem => item.RMAKey)

                    @Html.DisplayFor(modelItem => item.SalesPerson)

                    @Html.DisplayFor(modelItem => item.SalesRep)

                    @Html.DisplayFor(modelItem => item.Datecreated)

                    @Html.EditorFor(model => model.First().FollowupDate)
                    @Html.ValidationMessageFor(model => model.First().FollowupDate)

                    @Ajax.ActionLink("Followup", "FollowupUpdate", new { RMAKey = item.RMAKey,  FollowupDate=item.FollowupDate }, new AjaxOptions { UpdateTargetId = "modal", InsertionMode = InsertionMode.Replace, HttpMethod = "GET", OnSuccess = "onModalLoad" }, new { @class = "icon-secondary note" })

        }

The above code i am using   @Html.EditorFor(model => model.First().FollowupDate). This is my problem occur here i get the date and send the date to partial view. How to generate the date dinamically?


text:
Q: 2nd generation Google cloud SQL - App Engine Delighted to see that you have rolled out 2nd generation cloud SQL in Beta. However, I see that it is not available yet to GAE projects. Can you estimate when this link will be enabled please? We are making some big infrastructural changes in our fancy system necessitated by the slowness of Generation 1 SQL, but will stick with cloud SQL if the change is not far off.

A: As of April 27, 2016 Second Generation connectivity to App Engine is supported.

OLD content:
The Cloud SQL team is actively working on adding App Engine support for Second Generation instances. Unfortunately I can't speak about specific dates, but we hope to make it available as soon as possible.

A: You can now connect to second generation Google Cloud SQL instances from App Engine apps. The connection string is slightly different from first generation instances (docs).

*

*Open your SQL instance in the cloud console.

*Under properties copy the "Instance connection name". Note that this is different to the 'name' of your instance and will probably follow the format project:region:instance.

*It is normal for the UI to say "None" for authorized applications - you will still be able to connect from GAE. Note: the SQL instance and GAE app must be part of the same project.
Update: Don't have to be in the same project, you need to grant access if they are not in the same project. Ref: https://cloud.google.com/sql/docs/dev-access#gaev1-csqlv2-access

Example PHP connection code:
$con = "mysql:unix_socket=/cloudsql/CONNECTION_STRING_FROM_CONSOLE;dbname=some_db";
$this->db = new pdo($con, "root", "");
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


text:
Q: What are some heuristics for choosing a diff algorithm? The Myers diff algorithm performs well when the differences between the two texts are small, because most simple implementations have complexity O((N+M) * D). However when differences are large, it takes a very long time to run. For example, if one of the texts is large and the other is the empty string, many implementations take several minutes to run.
If you knew the differences were large, then you could choose a different algorithm. How do diff tools make this determination in practice?


text:
Q: Twilio function event parameter does not contain value. Example: Event.name object is undefined I'm facing an issue where when my twilio funciton is called, when i pass in two function parameters as shown below, they cannot be accessed from within the twilio function. The error says that event.name is undefined. but im passing a parameter called name through the funciton like shown below. So after passing a paremeter like this (edit: here im passing test but its the same output for test as well) :

I get this output
my code is as below :

FIXED! Sorry it was totally a problem on my end, I had configured the SMS and the Call for the same number, that was creating a bit of a issue.

A: What do you get back when you log out the entire event object stringified like so; console.log(JSON.stringify(event))


text:
Q: Summarize database values of the last 12 hours for each hour I've got a table with the columns id, type, value, created_at and I want to sum up the last 12 hours with one query. The result should be in an array for each hour ago.
At the moment I use this query to fetch the data for an hour:
select sum(`value`) as aggregate from `clan_values` where `type` = '2' and `created_at` between '2016-04-12 10:00:00' and '2016-04-12 10:59:59'

I dont have any clue how to solve this with just one query.
Thank you.

A: You can try group by DATE_FORMAT %H
select sum(`value`) as aggregate
from `clan_values`
where `type` = '2' and `created_at` between '2016-04-12 10:00:00' and '2016-04-12 10:59:59'
group by DATE_FORMAT( `created_at`,'%H');

A: you can try using this query, it'll return sum(value) for last 12 hours including the hour of current_timestamp().  If there are no rows for a certain hour you'll get a zero for the aggregate of that hour.
SELECT sum(IFNULL(`value`,0)) as aggregate,
       MyTime.MyHour,
       DATE_ADD(DATE(created_at),
                  INTERVAL HOUR(created_at) hour) as ActualHour
FROM
  (SELECT DATE_ADD(DATE(CURRENT_TIMESTAMP()),
                  INTERVAL HOUR(CURRENT_TIMESTAMP())-hour.count hour) as MyHour
  FROM
  (SELECT 0 as count
  UNION SELECT 1
  UNION SELECT 2
  UNION SELECT 3
  UNION SELECT 4
  UNION SELECT 5
  UNION SELECT 6
  UNION SELECT 7
  UNION SELECT 8
  UNION SELECT 9
  UNION SELECT 10
  UNION SELECT 11)AS Hour
   )as MyTime LEFT JOIN
   `clan_values` ON DATE_ADD(DATE(created_at),INTERVAL HOUR(created_at) hour) = MyTime.MyHour
AND `type` = '2'
GROUP BY MyTime.MyHour,ActualHour
ORDER BY MyTime.MyHour ASC

sqlfiddle


text:
Q: RUN puppeteer in a Node Dockerfile I have a Node JS Backend, which should use puppeteer for screenshoting my pdfs.
On my local System (MAC OS) everything works fine.
Now I want to publish this as a docker container in an Azure App Service.
The app starts well, but when I trigger puppeteer, the following error occurs:

Error: Could not find Chromium (rev. 1069273). This can occur if
either

*

*you did not perform an
installation before running the script (e.g. npm install) or

*your cache path is incorrectly
configured (which is: /root/.cache/puppeteer).
For (2), check out our guide on
configuring puppeteer at https://pptr.dev/guides/configuration.

Dockerfile:
FROM node:slim

ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true

# INSTALL PUPPETEER DEPENDENCIES
RUN apt-get update && apt-get install gnupg wget chromium -y && \
  wget --quiet --output-document=- https://dl-ssl.google.com/linux/linux_signing_key.pub | gpg --dearmor > /etc/apt/trusted.gpg.d/google-archive.gpg && \
  sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' && \
  apt-get update && \
  apt-get install google-chrome-stable -y --no-install-recommends && \
  rm -rf /var/lib/apt/lists/*

COPY ./backend/ .

RUN npm install

CMD ["npm", "start"]

The code of the route:
import puppeteer from 'puppeteer';
...
const browser = await puppeteer.launch({
    headless: true,
    ignoreHTTPSErrors: true,
    executablePath: '/usr/bin/google-chrome'
})

package.json:
"dependencies": {
    ...
    "puppeteer": "^19.4.1",
}

I followed this guide for my code: https://dev.to/cloudx/how-to-use-puppeteer-inside-a-docker-container-568c
What I'm doing wrong?