text:
Q: Checking every element in an array for a specific requirement I need to check every element in an array to see if it can be divided by 5 or more different numbers, if not - drop it into a different array.
For example, I have an array [3,32,6,8,0,16,3,45] and I have to get a result of [3,5,8,0,3]
I tried going for a simple while loop inside a for loop:
for i in array:
    n = 0
    div = 1
    while n <= 4 and div <= i:
        if i % div == 0:
            n += 1
        div += 1

    if n <= 4:
        sub_array.append(i)

return sub_array

It works just fine, but I need to make it so it will check the division with elements and not indexes. The moment I change all 'i' to 'array[i]': "list index out of range". Is there any way to solve this issue?
The reason why I'm trying to improve this code is because the tester I am using to check it returns errors from time to time.

A: When you do for i in array it means the 'i' is the element in the array.
If you want to iterate with using array[i] you should use for i in range(len(array))
The modified code is as follows:
for i in range(len(array)):
    n = 0
    div = 1
    while n <= 4 and div <= array[i]:
        if array[i] % div == 0:
            n += 1
        div += 1

    if n <= 4:
        sub_array.append(array[i])

return sub_array

A: I've written this code for you (if any of the numbers from an array is not divisible by 5, they will be put into a different array):
array = [3,32,6,8,0,16,3,45]
subarray = []
for i in array:
    if i%5==0:
        continue
    else:
        subarray.append(i)

print(subarray)


text:
Q: Arduino button on and off function I need help for a button in Arduino to turn on and off. I am trying to make my own Arduino car for my classes in my tech lesson.
It is a transistor circuit in a connected to 2 motors, an Arduino board and an Arduino sensor shield v5.0. The code I typed in worked for an on/off function but it wouldn't turn off it only stayed on forever.
Code for the first one:
//variables
int led = 13; //led on indicator
int motor1 = 12; //right motor
int motor2 = 11; //left motor
int button = A0; //on and off button
int val = 0; //value for on press button

void setup() {
  //setting up code to definition of pins
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  pinMode(motor1, OUTPUT);
  pinMode(motor2, OUTPUT);
  pinMode(button, INPUT);
}

void loop() {
  //looping the code to execute
  //button code for on and off
  val = digitalRead(button);
  if (val == LOW) {
    digitalWrite(led, HIGH);
    start_driving();
    Serial.println("Turned on!");
    Serial.println("It is driving!");
  } else {
    Serial.println("Not turned on!");
  }
}

//functions
void start_driving() {
  //The driving function
  digitalWrite(motor1, HIGH);
  digitalWrite(motor2, HIGH);
  delay(500);
  turn_left();
  digitalWrite(motor1, HIGH);
  digitalWrite(motor2, HIGH);
  delay(500);
  turn_right();
  digitalWrite(motor1, HIGH);
  digitalWrite(motor2, HIGH);
  delay(1000);
}

//turn right
void turn_right() {
  //turning right at 90 degrees
  digitalWrite(motor1, LOW);
  digitalWrite(motor2, HIGH);
  delay(500);
  digitalWrite(motor1, LOW);
  digitalWrite(motor2, LOW);
  delay(78);
}

//turn left
void turn_left() {
  //turning left a 90 degrees
  digitalWrite(motor1, HIGH);
  digitalWrite(motor2, LOW);
  delay(500);
  digitalWrite(motor1, LOW);
  digitalWrite(motor2, LOW);
  delay(78);
}

And now I am making a new .ino file to start again (I have still kept the first one still), but I am trying to make a button on and off function to turn on the led and also activate a void function called
void start_driving() {
}

So I hope you get what I mean and I hoped that I made sense. Oh and you can help me solve the driving function if you want to as well, like help me with the turning right or left or go forward or backwards function. So can you please help me please?

A: The reason why it doesn't stop is easy: You never told them to stop. In the case that you turn off the Button it will finish the start_driving() function and the last commands are HIGH for the Motors. The rest of the time it will stay in the else-part of the loop() function and is never told to be LOW.
So add some digitalWrite(motor1/2, LOW); to the start_driving() function in the end, or in the else part of the loop() else.
I made some changes to your code and added the needed parts (LED has the same problems like your Motors):
#define LEDPIN          13        // Use defines, because the values won't change anyway
                                  // For the same reason they are Uppercase like LOW, HIGH, INPUT ...
                                  // It is an indicator for non changeing values
#define RIGHTMOTORPIN   11        // Changed to PWM capable Pins, so you can
#define LEFTMOTORPIN    10        // have a variable speed later on
#define BUTTONPIN       A0

#define RIGHT           0         // For more readability in the makeTurn function
#define LEFT            1

void setup() {
  Serial.begin(9600);

  pinMode(LEDPIN, OUTPUT);
  pinMode(RIGHTMOTORPIN, OUTPUT);
  pinMode(LEFTMOTORPIN, OUTPUT);

  pinMode(BUTTONPIN, INPUT);
}

void loop() {
  if(digitalRead(BUTTONPIN) == LOW){
    digitalWrite(LEDPIN, HIGH);
    Serial.println("Turned on!");             // Put it in front, so it isn't shown after the drive
    Serial.println("It is driving!");
    startDriving();
  }else{
    Serial.println("Not turned on!");
    digitalWrite(LEDPIN, LOW);                // I guess the led should be turned off too.
    parallelMotorControl(LOW);                // THIS is the reason, why it continued driving!
                                              // You never stopped the Motors
  }
}

void startDriving() {
  parallelMotorControl(HIGH);
  delay(500);
  makeTurn(RIGHT);
  parallelMotorControl(HIGH);
  delay(500);
  makeTurn(LEFT);
  parallelMotorControl(HIGH);
  delay(1000);
}

// Reuse more code, that is similar.
void makeTurn(bool turnDirection){
  if(turnDirection){                          // Right turn
    digitalWrite(RIGHTMOTORPIN, LOW);
    digitalWrite(LEFTMOTORPIN, HIGH);
  }else{                                      // Left turn
    digitalWrite(RIGHTMOTORPIN, HIGH);
    digitalWrite(LEFTMOTORPIN, LOW);
  }
  delay(500);
  parallelMotorControl(LOW);
  delay(78);
}

void parallelMotorControl(bool motorState){
  digitalWrite(RIGHTMOTORPIN, motorState);
  digitalWrite(LEFTMOTORPIN, motorState);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connect two tables in msql Ok, so I at the moment, I have one table "project" with Id and other stuff. I need another table that will hold subprojects of the first table. How would I be able to connect these two tables so that when the information from the first table is accessed, it will also bring the subproject from the other table with it.
Example:
 ______
|1|John|
|2|Bob |
Project Table
 ___________
|1|DO WORK  |
|2|DONT WORK|
SubProject Table

When I click view info button the table should print out all the info from project as well as his subproject b/c of the same ID

A: Just add a foreign key to the second table and name it project_id, for example:
 ___________ ___
|1|DO WORK  | 1 |
|2|DONT WORK| 1 |
SubProject Table

In this example, both subprojects will be associated to the project with id = 1.
Then query the tables with a query similar to this:
select p.id, p.name, sp.id, sp.name
from projects p
inner join subprojects sp on p.id = sp.project_id
where p.id = 1

This is the very basic. You should read about FOREIGN KEYS, and how to define them in your database, so it can help you validate the relationship between records.


text:
Q: How to get list of available wireless networks without being root I would like to get a list of all the wireless networks.
iwlist wlan0 scan | grep ESSID

This will only show me the wireless network I am currently connected to. When I run the command as root, it shows me all the available networks. If I run the command without sudo quickly after this, all the networks will show up, but after a while they are all gone except the network I am currently connected to.
Is there a way to get all the available networks when I am not root?

A: You could (or do?) probably use wpa_supplicant; using its ctrl_interface configuration key, you can allow non-root users (e.g. those with group wheel) access via wpa_cli (i.e. /sbin/wpa_cli scan_results [1])
# allow frontend (e.g., wpa_cli) to be used by all users in 'wheel' group
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=wheel

There's also a command-line switch to wpa_suppliant,
-u     Enabled  DBus  control  interface. If enabled, interface defini‐
       tions may be omitted.

giving you a DBus interface and thus another possibility for non-root access (I think NetworkManager uses this interface).
[1] Once connected, this only shows the wireless LAN you are connected to...I don't know if this is any different with NetworkManager.


text:
Q: Powershell script check the status of the stopped services and send mail I am pretty new  to Powershell scripting and i have a requirement to check the status of the services, if the services are stopped ,capture the status into a separate text file and send the  email status to the users that services got stopped. In my environment services runs on two different machines . How to achieve it using Get -service
Please help me.

A: Since it looks like you haven't started, I'll give you a few things to kick you off.
Get-Service | Where-Object {$_.status -eq "stopped"}

This is a way to retrieve all the stopped services. Get-Service gets all the services, Where-Object is like an if statement in programming, and the part in parenthesis is the condition to meet.
Here's a link where you can read more about that: https://technet.microsoft.com/en-us/library/ee176858.aspx
This is a line of code that will write processes to a text file:
Get-Process | Out-File c:\scripts\test.txt

You can see how combining different commands will get you the result you want. Search around the internet if you get stuck. PowerShell is pretty well documented.
Here's a link for some more research on writing to a file: https://technet.microsoft.com/en-us/library/ee176924.aspx


text:
Q: Retrive data from database and display in table using php I have two table named ITEM and Price. These are the fields and data of both table
Table : ITEM
item_id | item_name
  1     | ABC
  2     | XYZ,JKL,QWE

Table : Price
  id    | item_price | item_id
  1     | 50         |  1
  2     | 60         |  2
  3     | 100        |  1

Where item_id is reference of ITEM table. I need to create table in php to display all the data from ITEM table. item_name have multiple value seperated with coma. So we need to explode them and use as a drop-down(select) in table.My expected outputt will look like given below.
item_id | item_name | item_price

Note : item_name must have select option (dropdown)

A: use below query to get records from database
select a.item,b.item_price from table1 a,table2 b where a.item_id=b.id;
and then on your  front end(php), try the below
$results=mysqli_query($db,"select a.item,b.item_price from table1 a,table2 b where a.item_id=b.id");

if(mysqi_num_rows($result) > 1 )
{

  echo "

item_id 	item_name	item_price

";
  while($row=mysqli_fetch_array($result))
  {

    echo "
";
    echo "".$row['item_id']."	";

    $arry=explode(',',$row['item_name']);
     echo "<select>";
     foreach($arry as $value)
      {
        echo "<option>".$value."</option>";
       }
      echo "</select>	";
     $array=array();
   echo "".$row['item_price']."
";

 }
     echo "
";
  }

A: Create a file function.php and add following code
function result_to_array($result)
{
    $array =array();
    $count = 0;
    while($row = mysql_fetch_array($result))
    {
        $array[$count]= $row;
        $count++;
    }
    return $array;
}

function GetData(){

    $sql="SELECT * from ITEM,Price where ITEM.item_id=Price.item_id";

    $query=mysql_query($sql);

    $result=result_to_array($query);

    return $result;

}

Create a file data.php and include following
<?php
include "functions.php";
$data=GetData();
?>

item_id	item_name	item_price

<?php foreach($data as $d): ?>

<?php echo $d['item_id']; ?>	<?php echo $d['item_name']; ?>	<?php echo $d['item_price']; ?>

<?php endforeach;?>


text:
Q: Show that $\arctan\left({1\over A}\right)=\arctan\left({1\over B}\right)+\arctan\left({1\over C}\right)$ $1,1,2,3,5,8,...$ for $n=1,2,3,4,5,...$ ;It is the n-th Fibonacci numbers.
Show that,
$\arctan\left({1\over xF_{2n-1}+F_{2n}}\right)=\arctan\left({1\over xF_{2n-1}+F_{2n+1}}\right)+\arctan\left({1\over x^2F_{2n-1}+xF_{2n+2}+F_{2n+2}}\right)$
I try:
Using
$$\arctan\left({1\over a}\right)-\arctan\left({1\over b}\right)=\arctan\left({b-a\over ab+1}\right)$$
Just ignore the arctan for the sake of space.
$$\arctan{1\over xF_{2n-1}+F_{2n}}-\arctan{1\over xF_{2n-1}+F_{2n+1}}=\arctan{1\over x^2F_{2n-1}+xF_{2n+2}+F_{2n+2}}=T$$
$$\arctan{F_{2n+1}-F_{2n}\over x^2F_{2n-1}^2+xF_{2n-1}(F_{2n}+F_{2n+1})+F_{2n}F_{2n+1}+1}=T$$
$$\arctan{F_{2n+1}-F_{2n}\over x^2F_{2n-1}^2+xF_{2n-1}F_{2n+2}+F_{2n}F_{2n+1}+1}=T$$
$$\arctan{F_{2n-1}\over x^2F_{2n-1}^2+xF_{2n-1}F_{2n+2}+F_{2n}F_{2n+1}+1}=T$$
Any hints on how to simplify this further?

A: We make use of the identity:$$F_{2n-1}^2 -F_{2n}^2 + F_{2n}F_{2n-1} = 1...(1)$$ We can rewrite this as: $$2F_{2n}F_{2n-1} + F_{2n-1}^2 = F_{2n}^2 + F_{2n}F_{2n-1} + 1$$ $$\implies F_{2n-1}[2F_{2n} + F_{2n-1}] = F_{2n}[F_{2n} + F_{2n-1}] + 1...(2)$$ Now, we use the identity: $$F_{n+m} = F_nF_{m+1} + F_{n-1}F_m$$ to change the bracketed terms of $(2)$ into: $$F_{2n-1}F_{2n+2} = F_{2n}F_{2n+1} + 1$$ This is the same condition that is obtained by equating the $\arctan \frac{F_{2n-1}}{x^2F_{2n-1}^2 + xF_{2n-1}F_{2n+2} + F_{2n}F_{2n+1} + 1}$ and $\arctan \frac{1}{x^2F_{2n-1} + xF_{2n+2} +F_{2n+2}}$.
Hope it helps.


text:
Q: jquery from external file not loading So I know this question has been asked many times but I can't seem to get this working, even though it looks correct to me.  My jquery functions from an external file aren't loading properly.
My tableMethods.js external file looks like
$(function(){

// Write FITS
function writeFits(){
    var data = $('.sastable').bootstrapTable('getData');
    var name = $('#fitsname').val();
    $.getJSON($SCRIPT_ROOT + '/writeFits', {'data':JSON.stringify(data),'name':name},
        function(data){
            $('#fitsout').text(data.result);
        });
}

// Delete rows from data table
function deleteRows(){
    var $table = $('.sastable');
    var $delete = $('#delete');

    var ids = $.map($table.bootstrapTable('getSelections'), function (row) {
            return row.id
    });

    $table.bootstrapTable('remove', {
            field: 'id',
            values: ids
    });
}

})

My html header looks like
<script type="text/javascript" src="/static/js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap-table.js"></script>
<script type='text/javascript' src="/static/js/tableMethods.js"></script>

When I check the inspector, it says the file has loaded yet when I click my button that looks like
<button id="delete" class="btn btn-danger" type='button' onClick='deleteRows()'>Delete Rows</button>

I get the error
Uncaught ReferenceError: deleteRows is not defined

A: This is a scoping problem. You have to move your functions outside of $(function() { ... })
In JavaScript, anything exclusively defined within a function, generally stays within a function:
var x = 3;

(function() {
    var y = 1;
})();

console.log(x); // 3
console.log(y); // error

So if you're defining a function within a function, you can only invoke it from that function you have defined it in. When trying to invoke it from anywhere else, the inner function will seem undefined.
In your case, you can simply remove the wrapper function:
$(function() { // Delete this...

    ...

}); // And this

For more information, read You Don't Know JS: Scope & Closures


text:
Q: Azure DevOps get Deployment Agent status during release I'm trying to get the status of agents in a deployment pool at release time.
The use case is I have 2 servers with shared disk, I want the release to run on one server only. I have two Deployment groups that run based on a custom condition:
eq(variables['DeployGroupSelector'], '1')

With a job that runs prior to those that will determine the value of the DeployGroupSelector var, essentially a case statement.
In the job that sets the var, I'm trying to reach out to the Azure DevOps REST API:
$headers = @{
    Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}

$url = "https://dev.azure.com/$($organization)/_apis/distributedtask/pools/$($poolId)/agents?api-version=5.1"
$response = Invoke-RestMethod $url -Headers $headers -Verbose
write-host "Output: $response"
$status = ($response.value | where {$_.name -eq $($env:primaryPoolName)}).status
if($status -eq "online")
{
    Write-Output("##vso[task.setvariable variable=DeployGroupSelector;]1")
}
else
{
    Write-Output("##vso[task.setvariable variable=DeployGroupSelector;]2")
}

For the group containing the script above the "Allow scripts access to the OAuth token" box is checked.
When I run this powershell locally using a PAT it returns data. When I run the release in ADO, it hits the service, but returns an empty data set:
2019-10-07T14:16:18.8942915Z VERBOSE: GET https://dev.azure.com/xxxxxx/_apis/distributedtask/pools/13/agents?api-version=5.1 with 0-byte payload
2019-10-07T14:16:19.3235204Z VERBOSE: received 22-byte response of content type application/json
2019-10-07T14:16:19.9626359Z VERBOSE: Content encoding: utf-8
2019-10-07T14:16:19.9835101Z Output: @{count=0; value=System.Object[]}

I have tried giving the "Project Collection Build Service Accounts" group read access to pools and groups, I even tried bumping it up to user. I tried adding the build service accounts group to release administrators. I even tried using the old url format just in case.
Added picture of data returned from powershell:

UPDATE: Just to further rule out an issue with how I was using the token, I added a second powershell task to the task group in question. This script hits a different segment of the AzDO Rest API (below). This successfully gets a response. So the OAuth token is working, it just doesn't seem to have access to the entire API.
$headers = @{
    Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
$url = "https://dev.azure.com/$($organization)/$($project)/_apis/git/repositories?api-version=5.1"
$response = Invoke-RestMethod $url -Headers $headers -Verbose
write-host "Output: $($response)"

Response: Output: @{value=System.Object[]; count=10}

A: Since you're using the System_AccessToken variable, did you also enable the "Allow scripts to access OAuth token" checkbox in the agent job? https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=classic#systemaccesstoken This link shows where it is in build but you'll find it at the bottom of the Agent Job panel in release. If that's not checked, that may be why you're getting an empty response.

A: Had exactly the same issue. Were considered two options, the same as you have been trying.

*

*System.AccessToken

*PAT

Problem was solved by putting PAT into a KeyVault and using it as a basic auth token for REST API call in a pipeline.
My suggestion is that it seems expected and right behavior. Why do I think so? From Azure DevOps point of view there are two levels in our case Organization's level and Project's level. You can notice the difference by URI that were used:
$url = "https://dev.azure.com/$($organization)/_apis/distributedtask/pools/$($poolId)/agents?api-version=5.1"

$url = "https://dev.azure.com/$($organization)/$($project)/_apis/git/repositories?api-version=5.1

From security point of view it's a bad practice, let entities from lower layers, which is project in our case, access and manipulate on the higher layer, which is organization in our case.
As a conclusion I would say that SystemToken and PAT in essence have slightly different nature, one is devoted for agent, and another for one's personal profile.


text:
Q: Mongo $geoWithin Radians Struggling to calculate radians of a circle use mongoose/mongodb geoWithin query.  I have the user's location, and I the result furthest away from that user.  From those two points I need to calculate radians so I can search in a full circle around that user reaching out to furthest result.  Hopefully that makes sense. :)
    //get closest item to user (just because)
    var closestLon = vendorPosts[0].location.long;
    var closestLat = vendorPosts[0].location.lat;

    //get furthest item from user
    var furthestLon = vendorPosts[vendorPosts.length - 1].location.long;
    var furthestLat = vendorPosts[vendorPosts.length - 1].location.lat;

    //User is located here
    var userLat = req.query.lat;
    var userLon = req.query.long;

    //Number of kilometers furthest item is from user
    var maxDistanceKm = getDistanceFromLatLonInKm(userLat, userLon, furthestLat, furthestLon);

    //Attempting to convert to rads but results never appear, is this correct calculation?
    var maxDistanceRadians = maxDistanceKm/6371;

    Model.find({
        $text: { $search: searchterm, $language: 'english' },
        coordinates :
             { $geoWithin :
                 {
                     $center : [ [ userLon, userLat ] , maxDistanceRadians ]
                 }
             }
        } , { score: {
                $meta: "textScore"
            }
        }, function (err, results) {
            ....
        });

Using these famous haversine formulas/utils
    function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
        var R = 6371; // Radius of the earth in miles
        var dLat = deg2rad(lat2-lat1);  // deg2rad below
        var dLon = deg2rad(lon2-lon1);
        var a =
              Math.sin(dLat/2) * Math.sin(dLat/2) +
              Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
              Math.sin(dLon/2) * Math.sin(dLon/2)
            ;
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c; // Distance in km
        return d;
    }

    function deg2rad(deg) {
        return deg * (Math.PI/180)
    }

A: Look like I drastically overcomplicated my answer.  I already had the center point of a circle (user location) and I already had the item furthest away from the user.  From these two points I needed to calculate radius and plug into mongo.
    var furthestitem = vendorPosts[vendorPosts.length - 1];

    var radius = Math.sqrt( Math.pow((userLat-furthestitem.location.lat), 2) + Math.pow((userLong-furthestitem.location.long), 2) )

    PostModel.find({
        $text: { $search: heading, $language: 'english' },
        $or: mongoCategories,
        coordinates :
             { $geoWithin :
                 {
                     $center : [ [ userLong, userLat ] , radius ]
                 }
             }
        } , { score: {
                $meta: "textScore"
            }
        }, function (err, results) {  ...... });


text:
Q: Submit form with php WordPress Hello I work with WordPress , and I create a custom Modal with form to add a Group called 'abonnement' I added the table in Database and this is my issue:
Form
<form name="abonnementCreate" action="create.php" method="POST">

    Nom de l'abonnemnt
    <input type="text" class="form-control" id="nomA" name="nomA">

    Durée
    <input type="number" class="form-control" id="dureeA">
    En jours

    Nombre de produit autorisé
    <input type="number" class="form-control" id="nbProdA">

    Frais d'abonnement (€)
    <input type="number" class="form-control" id="fraisA">

  <button type="submit" name="create" class="btn btn-primary">Valider</button>
</form>

and this is the action of the creation :
create.php
<?php
  include'admin.php';
  global $wpdb;

  if(isset( $_POST["create"]))
   {
     $wpdb->insert('abonnement', array(
     'nom' => '.$_POST["nomA"].',
     'duree' => '.$_POST["dureeA"].',
     'nbProd' => '.$_POST["nbProdA"].',
     'frais' => '.$_POST["fraisA"].'
      ));
    }
 ?>

I have $_POST["create"] and the condition is true but $_POST[" any field"] is always null,
Someone please can help me ?

A: you can never catch the post value from id of the form input field.only way that you can get value using $_POST[] is using the "name" attribute of the input field.
    <input type="text" class="form-control" id="nomA" name="name1">

this input field value can be accessed from form action php file using $_POST["name1"]


text:
Q: LINQ to SQL ,Join tables to get distinct result? I am trying to write a LINQ query that will get me some distinct values from two SQL Server data tables.
I have two tables named, Facility_Cost_TBL and Tenant_Bills_TBL.
I then have a column that is named Nursing_Home_Name which I am trying to get the distinct data from.
This is my effort in LINQ , however it does not work,
var name = (from f in dataContext.Facility_Cost_TBLs
                join t in dataContext.Tenant_Bills_TBLs on f.Tenant_Code equals t.Tenant_Code
                where f.Tenant_Code == code && f.Date_Month == date.Month && f.Date_Year == date.Year
                select new {Facility_Cost_TBL = f, Tenant_Bills_TBL = t}).Distinct();

And this is a working SQL statement I made that does what I want via T-SQL.
SELECT DISTINCT Nursing_Home_Name
         FROM (SELECT Nursing_Home_Name
         FROM Facility_Cost_TBL
         WHERE Date_Year = 2016 AND Date_Month = 10 AND Tenant_Code = 664250
         UNION SELECT Nursing_Home_Name
         FROM Tenant_Bills_TBL
         WHERE Year_Data = 2016 AND Month_Data = 10 AND Tenant_Code = 664250)
         a

Could someone show me what LINQ sytax AND what LINQ extension method query would look like?

A: Please try following
var names = ((from f in dataContext.Facility_Cost_TBLs
                                          where f.Tenant_Code == "664250" && f.Date_Month == "10" && f.Date_Year == "2016"
                                          select new { Nursing_Home_Name = f.Nursing_Home_Name }).
                                          Union(
                                          from t in dataContext.Tenant_Bills_TBLs
                                          where t.Tenant_Code == "664250" && t.Date_Month == "10" && t.Date_Year == "2016"
                                          select new { Nursing_Home_Name = t.Nursing_Home_Name })).ToList();

Hope this will help you

A: Try this to see if this works. LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?
var name = (from f in dataContext.Facility_Cost_TBLs
                join t in dataContext.Tenant_Bills_TBLs  equals on new { f.Tenant_Code, f.Date_Month, f.Date_Year } equals new { t.Tenant_Code, t.Date_Month, t.Date_Year }
                where f.Tenant_Code == code && f.Date_Month == date.Month && f.Date_Year == date.Year
                select new {Facility_Cost_TBL = f, Tenant_Bills_TBL = t}).Distinct();


text:
Q: stop all video players when starting an other to play? I have a wordpress-page where many videos are posted. Some are embedded Vimeo or YouTube Videos, some are hosted on the server and played with wordpress-JW-Player Plugin.
The thing is, on some pages there are up to 10 videos and in "worst" case, three different players. When the user watches a video, and then starts a second one, the first video should stop automatically.
My question is: is there a Wordpress-compatible-JavaScript/WP-Plugin/etc. which provides such a behavior, when the user starts a second video the first one shell stop (and if he starts a third, then the second one shell also stop, and so on).
Or do I have to configure the WP-Plugin of JQ Player in an other way?
UPDATE
I found this script, but it seems no to do anything in my case ... (I don't get any errors - it seems just to do nothing)


text:
Q: To get complete logs of 2 devices using adb I am testing an app with 2 devices communicating using sockets and monitoring the timestamp values. I select the required device name from the DDMS perspective. But some initial logs are missing(as I have many Log.d statements in the code). I want to store the whole log file after I stop apps in both the phones. Can someone tell me how this can be done in command line using adb? I couldn't find any example for 2 devices.
Thanks

A: You can try with two console and get logcat separately for two devices
Get serial no for each devices using adb devices
and save logcat as text files
console  1: adb -s <device1serialNO> logcat  -d > logcat1.txt
console  2: adb -s <device2serialNO> logcat  -d > logcat2.txt
You can filter result for your given tag if needed

A: Before launching your application you can start the following command in your terminal:
adb logcat <your_application_log_tag>:V *:S > file.txt

<your_application_log_tag> is a log tag that you use in your application. *:S means that you suppress all log outputs from other components. > file.txt redirects the output of the command to file.txt.
The cause of the problem is that for logging Android has a buffer in RAM and if it becomes full it rewrites the most old entries (FIFO). The command I've provided will store the log on your computer.


text:
Q: Find And Replace Items In A Json file I'm trying to update items stored in a JSON file in a Express App. Basically I'm reading the contents of the JSON file updating the item fetched by Id and writing to the file the updated item.Problem?
It's appending the updated item so I get a duplicated. I can't see where is the error?
posts.json:
[
    {
        "name": "first name",
        "description": "test first description",
        "slug": "first-name",
        "id": "2f065d59"
    },
   {
        "name": "second name",
        "description": "test second description",
        "slug": "second-name",
        "id": "0071b034"
    }
]

create-update-delete.js:
var express = require('express');
var Creatordb = require('./database/posts.json');
var fs = require('fs');
var uuid = require('node-uuid');
var _ = require('lodash');

 //Create The Item
var add = function (item) {
  var id = uuid.v4();
  item.id = id;
  Creatordb[item.id] = item;
  var outputFilename = './database/posts.json';

  function appendObject(obj){
    var configFile = fs.readFileSync(outputFilename);
    var config = JSON.parse(configFile);

    config.push(obj);

    var configJSON = JSON.stringify(config, null, 4);

    fs.writeFileSync(outputFilename, configJSON);

  }
  appendObject(item);
};

//Get The Item by Id
var getById = function (id) {
  for(var i=0;i<Creatordb.length;i++) {
    var id = Creatordb[i].id;
  }
  return id;
};

//Update The Item
var update = function (item) {
  var outputFilename = './database/posts.json';
  var configFile = fs.readFileSync(outputFilename);

  var config = JSON.parse(configFile);

  //using lodash??
 var index = _.indexOf(config, _.find(config, item));

 config.splice(index, 1, item);

  var configJSON = JSON.stringify(config, null, 4);

  fs.writeFileSync(outputFilename, configJSON);

};

If I update an item the posts.json will look like this:
 [
        {
            "name": "first name",
            "description": "test first description",
            "slug": "first-name",
            "id": "2f065d59"
        },

        {
            "name": "second name edited",
            "description": "test second description edited",
            "slug": "second-name-edited",
            //this id disappeared "id": "0071b034"//
        }
    ]

Now with lodash the Id in the updated item is gone away?
Can anyone explain? - Thanks

A: There is two problems:

*

*You use push what is insert a new item into your list, this is the reason of the 'duplication'

*config[item.id] = item; is not a valid reference. Your config is not like this:
["0071b034": { name: "Foo"}]
So the keys in config are 0,1,2 and not the item.id
I suggest to use lodash. There are a lots of useful functions, but if you stick this implementation, use this:
function findIndex(collection, id) {
  for(var i=0; i<collection.length; i++) {
    if (collection[i].id === id) {
      return i;
    }
  }
}

// In your update function
var index = findIndex(config, item.id);
config[index] = item;

A: I don't understand, why do you use splice function in the update? In JavaScript, when you deal with objects or arrays, you work with their references, not copies. So, you can replace splice with this one:
var obj = _.find(config, ['id', item.id]);
_.assign(obj, item);

In this case, you don't care, if item has all necessary fields, since assign method will update only those fields, that were specified.
At the same time, if you 100% sure that new item will always have all fields specified, then Festo's solution is better, since it just replaces a reference of the old item on the new one, which is much faster.

var config = [
    {
        "name": "first name",
        "description": "test first description",
        "slug": "first-name",
        "id": "2f065d59"
    },
   {
        "name": "second name",
        "description": "test second description",
        "slug": "second-name",
        "id": "0071b034"
    }
];

function update(item) {
  // Your read file logic.

  var obj = _.find(config, ['id', item.id]);
  _.assign(obj, item);

  // Your write file logic.
}

console.log('config befor update:', config);
update({
  "name": "third name",
  "id": "0071b034"
});
console.log('config after update:', config);
<script src="https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js"></script>


text:
Q: linux syntax error-unexpected token near "r" I am writing a couple of bash scripts which I wish to call within another bash script but I can't seem to get these two examples online to work. It keeps telling me that there is an unexpected error near "r" and one near "mychoice" though it doesn't get resolved when I make the changes. The two classes are to generate a prime numbers test which if it works, I hope to be able to stress a cpu. the other class is just to dynamically select how long to run sar rather than having to hard code in sar 1 30 for example. Does anyone know what is wrong with these classes? Thanks in advance.
primetest class

  #!/bin/bash

#
# primes.sh - find all prime numbers up to a certain number
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

factorial ()  {
 local factorial_count=$1
 if [ "$factorial_count" -eq 0 ]
 then
  factorial_count=1
 fi
 for (( factor=$((factorial_count -1)); $factor >= 1; --factor ))
 do
  factorial_count=$(($factorial_count * $factor))
 done
 echo $factorial_count
}

prime_number ()  {
 local prime=$1
 p_minus_1=$(($prime - 1))
 fact_p_minus_1=`factorial "$p_minus_1"`
 fact_plus_1=$(($fact_p_minus_1 + 1))
 echo $fact_plus_1
}

highest_number=$1

if [ -z $highest_number ]
then
 echo
 echo "Usage: $0 highestNumber"
 echo
 exit 1
fi

if [ $highest_number -eq 0 ]
then
 echo
 echo "Sorry.  0 is not a prime number"
 echo
 exit 0
elif [ $highest_number -eq 1 ]
then
 echo
 echo "Sorry.  0 and 1 are not prime numbers"
 echo
 exit 0
fi

echo "Generating Prime Numbers Up To $highest_number"
if [ $highest_number -eq 2 ]
then
 echo
 echo -n "2"
else
 echo
 echo -n "2 3 "
fi

count=4
while [ $count -le $highest_number ]
do
 prime_return=`prime_number "$count"`
 prime_test=$(($prime_return % count))
 if [ $prime_test -eq 0 ]
 then
  echo -n "$count "
 fi
 count=$(($count + 1))
done

echo
echo
echo "All Set!"
echo

exit 0


text:
Q: Appending data from another row to an above or below row entry in R? I am a research biologist who is relatively new at coding. I am working on cleaning up a dataset and automating a process to then be used in ArcGIS. I have a dataset from 2015 of about 10 birds that I am using as a sample year for right now. The end result I am looking for is a csv file for each bird, with a one to one join for each 15 minute GPS point to the spatial location I have. Where I run into issues is that the data loggers also have a dive logger for when the bird dives, but there is not specific GPS coordinates for dives.
Now I am a bit stuck. I need to combine the dive duration entries to the lat and long to the most taken GPS point to create a 1:1 join in ArcGIS (either the point above or below depending on timing). I would love to be able to create a code that results in the following (with potentially another column that has information for number of dives):
BIRD 1 TIME DATE LATITUDE LONGITUDE    DIVE DURATION  NUMBER OF DIVES
Is there a feature in dplyr that can help with this?
Any help would be much appreciated!
EDIT: My current code:
# Start by connecting to 2015 data
data2015 <- read.csv("GPS data 2015\\GPS2015Birds.csv")

# select out individual logger.ID
i <- "GRE12"

# Now this starts to filter only the information wanted in the final CSV file

birdo <- data2015 %>%
  filter(LoggerID== i)

birdie <- birdo %>%
  filter(!is.na(Latitude)|Divingduration %in% c(4:120))

This is a sample of some of the data:
head(birdie)

   LoggerID Year Month Day Hour Minute Second Latitude Longitude Divingduration
1     GRE12 2015     6  19   23     38      0 51.03007 -39.78358             NA
2     GRE12 2015     6  21   12     18      0 55.02958 -39.79267             NA
3     GRE12 2015     6  21   12     19      0 45.02962 -39.79262             NA
4     GRE12 2015     6  21   12     19      0 65.02960 -39.79275             NA
5     GRE12 2015     6  21   12     23      0 62.02960 -39.79272             NA
6     GRE12 2015     6  21   12     24      0 23.02960 -39.79257             NA
7     GRE12 2015     6  21   12     24      0 34.02955 -39.79247             NA
8     GRE12 2015     6  21   12     31      0 76.02958 -39.79275             NA
9     GRE12 2015     6  21   12     31      0 61.02960 -39.79267             NA
10    GRE12 2015     6  21   12     32      0 67.02958 -39.79270             NA
11    GRE12 2015     6  21   12     32      0 54.02960 -39.79277             NA
12    GRE12 2015     6  21   12     33      0 98.02963 -39.79272             NA
13    GRE12 2015     6  21   12     37     16       NA        NA             24
14    GRE12 2015     6  21   12     48      0 12.03137 -39.79330             NA
15    GRE12 2015     6  21   13      3      0 41.03152 -39.79270             NA
16    GRE12 2015     6  21   13     18      0 98.03187 -39.79252             NA
17    GRE12 2015     6  21   13     33      0 43.03185 -39.79258             NA
18    GRE12 2015     6  21   13     49      0 59.03187 -39.79262             NA
19    GRE12 2015     6  21   14      4      0 38.03245 -39.79222             NA
20    GRE12 2015     6  21   14     19      0 93.03245 -39.79250             NA
21    GRE12 2015     6  21   14     35      0 69.03245 -39.79237             NA
22    GRE12 2015     6  21   14     50      0 32.04337 -39.80202             NA
23    GRE12 2015     6  21   15      5      0 54.05958 -39.88438             NA
24    GRE12 2015     6  21   15     20      0 76.05950 -39.88617             NA
25    GRE12 2015     6  21   15     35      0 23.05945 -39.88620             NA
26    GRE12 2015     6  21   15     51      0 43.05943 -39.88617             NA
27    GRE12 2015     6  21   16      3     16       NA        NA              4
28    GRE12 2015     6  21   16      6      0 99.05950 -39.88662             NA
29    GRE12 2015     6  21   16     21      0 63.05517 -39.89503             NA
30    GRE12 2015     6  21   16     33     46       NA        NA              4
31    GRE12 2015     6  21   16     34     48       NA        NA              6
32    GRE12 2015     6  21   16     37      0 78.04935 -39.90928             NA
33    GRE12 2015     6  21   16     37     42       NA        NA              7

A: Here's an approach with the fuzzyjoin package:
First, let's combine the various time components into one datetime column:
library(lurbidate)
library(dplyr)
birdie <- birdie %>%
  mutate(Time = mdy_hms(paste(Month,Day,Year,Hour, Minute, Second))) %>%
  select(LoggerID, Latitude, Longitude, Divingduration, Time)

Now, we will separate the birdie data into to sets, rows with Lat/Long data, and those rows with Divingduration data.
Then we can use a difference_join, to join on the times within a certain distance, in the clase, I used 15 minutes (60*15).
After the join is complete, we can group by LoggerID.x and make sure the LoggerIDs are the same, and then filter for rows where the time difference is minimum.
Lastly, we can select the columns we're interested in.
library(fuzzyjoin)
birdie %>%
  filter(!is.na(Latitude)) %>%
  difference_inner_join(birdie %>% filter(!is.na(Divingduration)),
                        by = "Time", max_dist = 60*15) %>%
  group_by(LoggerID.x,Time.y) %>%
  filter(LoggerID.x == LoggerID.y &
           abs(Time.x - Time.y) == min(abs(Time.x - Time.y))) %>%
  select(LoggerID.x,Latitude.x,Longitude.x, Time.x, Divingduration.y,Time.y)

# A tibble: 5 x 6
# Groups:   LoggerID.x, Time.y [5]
  LoggerID.x Latitude.x Longitude.x Time.x              Divingduration.y Time.y
  <fct>           <dbl>       <dbl> <dttm>                         <int> <dttm>
1 GRE12            98.0       -39.8 2015-06-21 12:33:00               24 2015-06-21 12:37:16
2 GRE12            99.1       -39.9 2015-06-21 16:06:00                4 2015-06-21 16:03:16
3 GRE12            78.0       -39.9 2015-06-21 16:37:00                4 2015-06-21 16:33:46
4 GRE12            78.0       -39.9 2015-06-21 16:37:00                6 2015-06-21 16:34:48
5 GRE12            78.0       -39.9 2015-06-21 16:37:00                7 2015-06-21 16:37:42


text:
Q: How to open the chrome browser with gulp-open? I am using gulp-open with gulp in windows 7:
gulp.task('op', function(){
    var options = {
        uri: 'localhost:8080',
        app: 'chrome'
    };
    gulp.src(__filename)
        .pipe(open(options));
});

The index.html file opens with the app when I use app:'Firefox' but when I use the chrome option it opens an empty index.html? How can I fix this?

A: Depending on the OS you need to refer to the chrome app differently in options:
'google-chrome' // Linux

'chrome' // Windows

'google chrome' or 'Google Chrome' // OSX

Refer to section Options.app in the NPM documentation about gulp-open.

A: I only added http:// to the uri and it worked for me.
gulp.task('op', function(){
    var options = {
        uri: 'http://localhost:8080',
        app: 'chrome'
    };
    gulp.src(__filename)
    .pipe(open(options));
});

A: This is a snippet of my code that solves the issue for me, you can use it to modify yours accordingly:
var gulp = require('gulp');
var liveServer = require('gulp-live-server');
var browserSync = require('browser-sync');

gulp.task('live-server', function(done){
    var server = new liveServer('server/main.js');
    server.start();
    done();
})

gulp.task('serve', gulp.series('live-server', function(done){
    browserSync.init(null,{
        proxy:"http://localhost:7777",
        port:9001,
        open: true
    })
    done();
}));


text:
Q: What is best source to learn about Single Page Application development? I am new to Javascript and have started watching some Backbone.js tutorial on youtube. I have a background of working on Backend where I developed web-services.
I want to learn to develop websites using framework like backbone.js/angular.js

A: To start with, you should know how these framework helping you to create the Single Page Application. Take for example angularjs,

*

*ng-view

*Routing Concept.

*Ajax Support like $http service.

*Your back-end APIs

Creating sample Single Page Application here. Some concerns with single page application are mentioned in these two blogs.

*

*Memory Management in Single Page Application

*Designing Model
for Single Page Application


text:
Q: React Native Init Hanging I am unable to create a new React Native project via react-native init <ProjectName>.
This is the first time I've tried since upgrading to macOS Sierra, but I don't know if that's related.
If I run the command with the --verbose flag, it runs through all the npm packages, but then eventually outputs the following:
├── UNMET PEER DEPENDENCY react@~15.3.1
<List of other packages including react-native 0.34.1>

npm WARN react-native@0.34.1 requires a peer of react@~15.3.1 but none was installed.
npm verb
npm verb If you need help, you may report this error at:
npm verb     <https://github.com/npm/npm/issues>
npm verb exit [ 0, true ]
npm info ok

It then just sits there indefinitely. Last time I created a react native project it would take maybe 20-30 seconds max, but now it never completes (after say 10-15 minutes).
If I kill the process, all I have is a package.json with just the following in:
{
  "name": "TestApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "dependencies": {
    "react-native": "0.34.1"
  }
}

...and the node_modules folder containig react-native and its dependencies. None of the required XCode/Android folders are there, or the index entry points, configs etc.
I have tried reinstalling all the required dependencies (node, homebrew) and I have also reinstalled git via homebrew.
I've seen other threads that suggest manually installing React, but I don't buy it. This used to work and React used to get installed as part of the process, but now I get this warning and it's game over.
Anyone else seen this issue?
EDIT
I just tried this on my other Mac, also running macOS Sierra and it worked fine. I followed the same steps on that to ensure all my dependencies were up to date first. I did a verbose init and still got the warning about React 15.3.1 being missing, but it then carried on and install Reacrt 15.3.2 and then set up all the XCode/Android project files.
Very odd/annoying as I really need to start putting something together on this Mac.
SECOND EDIT
If I create a new user account on my Mac and log in as that, I can create a project, so it seems to be user-specific. Although annoying, I don't mind setting a new account up, but before I do would like to see if anyone can offer any suggestions. Thanks.

A: So the issue turned about to be watchman, as outlined here: https://github.com/facebook/react-native/issues/9943
If I ran watchman version the terminal hung, so as per the instructions I did:
rm -rf /usr/local/var/run/watchman/ && brew uninstall watchman && brew install watchman
...and it worked a treat!


text:
Q: Creating a list from input using while loop Im new to python and trying to convert input to a list and I am required to use a while loop but I keep getting an EOF error.
def get_grades():
    value = float(input('Enter grade:\n'))
    grades = []
    while value > 0:
        grades.append(value)
        value = float(input('Enter grade:\n'))
    return(get_grades)

A: I think you want to return the list of grades from that function, so you could change return(get_grades) to return grades (no need for the parentheses). When you have return(get_grades) you're actually returning the address that the get_grades function is stored at in memory.
So with that change the code looks like:
def get_grades():
    value = float(input('Enter grade:\n'))
    grades = []
    while value > 0:
        grades.append(value)
        value = float(input('Enter grade:\n'))
    return grades

print(get_grades())

You can run it with the following inputs and see those printed out to the console:
Enter grade:
30
Enter grade:
40
Enter grade:
50
Enter grade:
0
[30.0, 40.0, 50.0]


text:
Q: birt increment values in a report based on unique key I've managed to get the following output from a simple select statement:
SELECT DAILY.KEY,DAILY.TIMESTAMP,DAILY.LOG
FROM DAILY
ORDER BY DAILY.SEQUENCE

    KEY      ,TIMESTAMP           , LOG
    index_230,Oct 2, 2013 11:02 AM, MAIN_4
    index_230,Oct 2, 2013 11:02 AM, MENU_C
    index_230,Oct 2, 2013 11:02 AM, SUBMENU_9
    index_230,Oct 2, 2013 11:02 AM, OPTION_20
    index_235,Oct 2, 2013 11:02 AM, MAIN_6
    index_235,Oct 2, 2013 11:02 AM, MENU_A
    index_235,Oct 2, 2013 11:02 AM, SUBMENU_6
    index_235,Oct 2, 2013 11:02 AM, OPTION_10
    index_233,Oct 2, 2013 11:02 AM, MAIN_7
    index_233,Oct 2, 2013 11:02 AM, MENU_A
    index_233,Oct 2, 2013 11:02 AM, SUBMENU_7
    index_231,Oct 2, 2013 11:02 AM, MAIN_4
    index_231,Oct 2, 2013 11:02 AM, MENU_C
    index_231,Oct 2, 2013 11:02 AM, SUBMENU_8
    index_232,Oct 2, 2013 11:02 AM, MAIN_4
    index_232,Oct 2, 2013 11:02 AM, MENU_C
    index_232,Oct 2, 2013 11:02 AM, SUBMENU_9

However, am not sure how to process this data before creating my report.
I basically need to create counts for each unique sequence.
but am having trouble correlating each option..
ie for the KEY
    KEY      ,TIMESTAMP           , LOG
    index_230,Oct 2, 2013 11:02 AM, MAIN_4
    index_230,Oct 2, 2013 11:02 AM, MENU_C
    index_230,Oct 2, 2013 11:02 AM, SUBMENU_9
    index_230,Oct 2, 2013 11:02 AM, OPTION_20

Should increment these values in a report:
MAIN_4(+1) +- MENU_C(+1) +-- SUBMENU_9(+1) +-- OPTION_20 (+1)

Where the entire report would end up as follows:
MAIN_1  +- MENU_A(13)+-  SUBMENU_1(6)+- OPTION_1  (1)
        |            |               +- OPTION_2  (0)
        |            |               +- OPTION_3  (5)
        |            +-  SUBMENU_2(7)+- OPTION_1  (4)
        |                            +- OPTION_2  (3)
        |                            +- OPTION_3  (0)
        +- MENU_B(1) +-  SUBMENU_1(1)+- OPTION_1 (1)
                                     +- OPTION_2 (0)
         .                           +- OPTION_3 (0)
         .
         .

MAIN_2  +- MENU_A(1) +-  SUBMENU_1(1)+- OPTION_1  (1)
        |
etc...

Any pointers or recommendations on how to do this are appreciated..

A: Use a computed column to give a value of 1 to eaqch of your rows of data.  You can do math on the values, pretty much any place you want to get the best results for your report.
I this image I am giving the value of 1 to a new field "All" for every row in the data set.


text:
Q: iMX6: MSI-X not working in Linux PCIe device driver I'm trying to get MSI-X working on an iMX6 (Freescale/NXP/Qualcomm) CPU in Linux v4.1 for a PCIe character device driver. Whenever I call either pci_enable_msix() or pci_enable_msix_range() or pci_enable_msix_exact() I get an EINVAL value returned. I do have the CONFIG_PCI_MSI option selected in the kernel configuration and I am also able to get single MSI working with pci_enable_msi(), but I cannot get multiple MSI working either.
I have tested my driver code on an Intel i7 running kernel v3 with the same PCIe hardware attached and I was able to get MSI-X working without any problems so I know my code is correctly written and the hardware is correctly functioning.
When running on the iMX6 I can use lspci -v to view that the hardware has MSI-X capabilities and see the number of IRQs it allows. I can even get the same correct number in my driver when calling pci_msix_vec_count().Questions

*

*Are there any other kernel configuration flags I need to set?

*Is there anything specific to the iMX6 CPU I need to consider?

*Does anyone have any experience with the iMX6 and either MSI-X or
multiple MSI?


text:
Q: Solution to do submit-for-validation to W3C Validator in PHP? To use the W3C Validator your (i.e. beta-) website normally has to be online which I'd rather avoid. Or use the direct input method. Say hello to continuous copy & paste.
My Idea:
The "direct input methods" submits the input as a form (no surprise here).
In other words: The actual validation-page receives a POST request.
So: Could I make a link (i.e. in my standard page footer) that leads to a local submitForValidation.php (rather than the regular linking to validator.w3.org)
Within that php file I shall...

*

*grab the Referer-URL it just came from (yes, within PHP 'curling' the localhost server...)

*submit that as the body of a POST request to the W3C page: http://validator.w3.org/check
Is that feasible? Someone has done this solution?
Frank

A: I still don't clearly understand what you're trying to do. If you want to do a direct input validation by manipulating POST data, you could install w3c markup validator on localhost and then modify it as you want. refer to installation documentation here.

A: If you want to validate an XHTML or HTML page you can use

*

*DOMDocument::validate —  Validates the document based on its DTD

If you want to make sure it is valid, you can also run it through the ob_tidyhandler but note that this will incur some performance penalties due to the buffer being inspected and repaired on every serving.

A: If what the Web Developer Toolbar has to offer (It essentially does the same thing you are planning to do) won't work for you, what you suggest yourself sounds like the best solution to me. Use CURL to POST the contents of the current, generated PHP file to W3C's service.
You could even make use of output buffering to grab the current page's contents, run them through the validator, and if any errors occur, paste the information into a placeholder in the generated HTML. (All this in "debug mode" or if a cookie is set or a GET parameter present, or something like that.)
The tough job will be to parse the results page, though. I think a local validation package returning messages in a array or XML structure would be easier to deal with. However, DOMDocument's Validate has the downside that it doesn't give any details about problems, so it would have to be something else.


text:
Q: Application Insights to azure webjob .Net Core 2.0 How to add application insights telemetry (Application Insights) to azure webjob ?

A: With recently released WebJob SDK 3.0, you can add ApplicationInsights in the ConfigureLogging method
public static async Task Main(string[] args)
{
     var builder = new HostBuilder()
        .ConfigureWebJobs(b =>
        {
            b.AddAzureStorageCoreServices().AddAzureStorage();
        })
        .ConfigureAppConfiguration(b =>
        {
            // Adding command line as a configuration source
            b.AddCommandLine(args);
        })
        .ConfigureLogging((context, b) =>
        {
            b.SetMinimumLevel(LogLevel.Debug);
            b.AddConsole();

            // If this key exists in any config, use it to enable App Insights
            string appInsightsKey = context.Configuration["ApplicationInsights:InstrumentationKey"];
            if (!string.IsNullOrEmpty(appInsightsKey))
            {
                b.AddApplicationInsights(o => o.InstrumentationKey = appInsightsKey);
            }
        });

     var host = builder.Build();
     using (host)
     {
         await host.RunAsync();
     }
}

A: You can add AI to Web Jobs during the development time as a Nuget Package.
AI .NET Core Nuget is here. Package name is a bit misleading (Microsoft.ApplicationInsights.AspNetCore) but it's supposed to work with all .Net core apps.
AI .NET Core GitHub page is here (with some customization options explained in Wiki).
Getting started guide is on GitHub and learn.microsoft.com as well. It's a bit lengthy guide, so I hope links are OK (although not in full accordance with SO guidelines) and I won't need to post it as part of the reply.


text:
Q: How do I handle foreign key relationships in my fixtures for unit testing with SimpleTest in CakePHP? I'm trying to create some fixture data for my unit tests in CakePHP (via SimpleTest) and I have no idea how to handle my foreign key relationships. Here's a sample of the fixture code:
<?php
class SpecialtyFixture extends CakeTestFixture {
    var $name = "Specialty";
    var $import = "Specialty";

    var $records = array(
            array(
               'id' => '1',
               'event_id' => '1',
               'code' => 'endocrin-1',
               'name' => 'Endocrinology'),
            array(
               'id' => '2',
               'event_id' => '1',
               'code' => 'ent-1',
               'name' => 'Ear, Nose and Throat')
    );
}
?>

So, as you can guess Specialty has a foreign key to event (my Event model looks like this):
<?php
class Event extends AppModel {
    var $name = "Event";
    var $primaryKey = "id";

    var $hasMany = array(
            'EventLocation' => array('className' => 'EventLocation'),
            'Faculty' => array('className' => 'Faculty'),
            'Agenda' => array('className' => 'Agenda'),
            'Role' => array('className' => 'Role'),
            'Specialty' => array('className' => 'Specialty'),
    );

    var $hasAndBelongsToMany = array('User');
}
?>

The error I'm getting is this:
Unexpected PHP error [SQL Error: 1054: Unknown column 'event_id' in 'field list'] severity [E_USER_WARNING] in [/dev/trunk/cake/libs/model/datasources/dbo_source.php line 525]
/dev/trunk/app/tests/cases/models/event.test.php -> EventTestCase -> endCase
I'll admit my understanding of CakePHP fixture data is minimal (documentation is kinda scarce, and examples on the web all rehash somewhat trivial examples) so any ideas on what I can/should do?

A: Take a look at the Fixturize shell by the good folks at Debuggable. Once you have data in your database, you can use this shell to extract it into fixtures automatically. Saves an awful lot of headache.
Like you, my knowledge of fixtures is limited, but I think you'd be able to avoid this kind of pain by getting something solid in your database and just extracting that to fixtures.


text:
Q: Accounts and Related Contacts in Picklist I would like to show Accounts and Related Contacts in a Picklist.
public class mappingaccount1 {
  public List<SelectOption> mapcon { get; set; }
  public List<Contact> mapcon { get; set; }
  public Map<Account, List<Contact>> mapconn { get; set; }

  public mappingaccount1(){
    mapconn = new Map<Account, List<Contact>>();
    List<Account> lstacc= [SELECT Id, Name, (SELECT Id, Name FROM Contact) FROM Account];

    for(Account a : lstacc) {
      List<SelectOption> mapcon = [SELECT id,name FROM Contact WHERE AccountId =:a.id];

      mapcon.put(a,lstcon);
    }
  }
}

A: An org might have 10,000 Accounts and 10,000,000 Contacts. Unless you can guarantee that there will only ever be a few hundred of each object in your target org you should re-think your design.


text:
Q: Log all errors for a value into error log if a single row fails I am trying to maintain data integrity and logging errors to an error table. I've got 3 tables with unique constraints and 1 error table:
create table tbl_one (
pass_no number,
constraint tbl_one_u01 unique (pass_no) );
insert into tbl_one values(10);
insert into tbl_one values(20);

create table tbl_two (
cus_no number,
cus_name varchar2(50),
pass_no number,
constraint tbl_two_u01 unique (cus_no) );
insert into tbl_two values( 101, 'NameX',10);
insert into tbl_two values( 102, 'NameY',10);
insert into tbl_two values( 103, 'NameZ',20);

create table tbl_target (
cus_no number,
pass_no number,
constraint tbl_target_u01 unique (cus_no),
constraint tbl_target_u02 unique (pass_no));

exec dbms_errlog.create_error_log('tbl_target','tbl_target_err');

I am trying to log all ORA-00001 errors to the error table tbl_target_err like this:
begin
    insert into tbl_target
    select a.pass_no, b.cus_no
      from tbl_one a
     inner join tbl_two b on b.pass_no = a.pass_no
       log errors into tbl_target_err reject limit 10;
end;

The result is:
select * from tbl_target;
-------------------
CUS_NO    PASS_NO
101    10
103    20

and the error table:
CUS_NO    PASS_NO
102    10

I need all the violated errors to go into the error table. If the value of pass_no 10 is violated then all 10 values should inserted into the error table; not, one into target and one to error table. I don't want to use exists statements because I won't able to log all violated values.
How could I go about doing this?

A: You can't use the error logging mechanism for this as it isn't designed to support it. It errors at the point it tries to create the duplicate in the table - the first value it tries to insert for pass_no 10 is valid on its own - so it would have to distinguish between data that already existed and multiple values coming from the insert, to start with. So you'd need to roll your own.
One option is to create your own table to hold the duplicates, and use an insert all to decide which values belong in each table:
create table tbl_target_dup (
cus_no number,
pass_no number
);

insert all
when cus_count = 1 and pass_count = 1 then
  into tbl_target values (cus_no, pass_no)
else
  into tbl_target_dup values (cus_no, pass_no)
select a.pass_no, b.cus_no,
  count(*) over (partition by a.pass_no) as pass_count,
  count(*) over (partition by b.cus_no) as cus_count
from tbl_one a
join tbl_two b on b.pass_no = a.pass_no;

This allows you to have more columns than those affected by the PK/UK, and insert them only into the real table if you prefer, or a subset into the 'error' table. With just those two columns in each table you get:
select * from tbl_target;

    CUS_NO    PASS_NO
---------- ----------
       103         20

select * from tbl_target_dup;

    CUS_NO    PASS_NO
---------- ----------
       101         10
       102         10

SQL Fiddle demo.
You could do the same thing with two inserts based on the same select, one with a subquery checking that both counts are 1, other checking that at least one is not, but this might perform better.


text:
Q: Why am I getting a DatabaseObjectNotClosedException with OrmLite under Android? I get a android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here when starting a new Activity using OrmLite.
I'm not using any Cursors myself, so it must be the low level code that ORMLite uses. Not sure what the relevant code would be here, but basically I'm using Query/DeleteBuilders with 2 Dao objects usually inside a transaction manager. Minimal example that leads to the problem (exception handling removed):
return new TransactionManager(connectionSource).callInTransaction(new Callable<List<ConversionData>>() {
    public List<ConversionData> call() throws Exception {
        QueryBuilder<ConversionData, Date> builder = getDataDao().queryBuilder();
        builder.orderBy("date", /* desc */ true);
        return builder.query();
    }
});

Since neither the Dao nor the Builders have any close methods I'm not sure where exactly I should actually close.
There's a close method in my Activity that extends OrmLiteBaseActivity, but then how would I open it again when I return from the other activity?

A: So after some back and forth, this turned out to be a problem with a data iterator on a lazy collection that was not being closed.  @Voo was doing something like the following:
for (ConversionRate rate : conversionRates) {
    if (rate.getCurrency().equals(curr))
        // you can't do this because otherwise the iterator won't be closed
        return rate;
}

This problem happens once and a while.  The documentation for iterators is explicit about it.  To quote:

NOTE: you must page through all items for the iterator to close the underlying SQL object. If you don't go all of the way, the garbage collector will close the SQL statement some time later which is considered bad form. See the wrapped iterable below.

The issue with lazy collections is also documented:

WARNING: Most likely for(;;) loops should not be used here since we need to be careful about closing the iterator.

To debug this problem, we first turned the lazy loaded collection into an eager one with @ForeignCollection(eager = true).  That removed the problem indicating that it probably was a improper break out of a for loop or some other bad pattern.
Good lesson for others.


text:
Q: Npm install failed on semantic-ui due to gulp I'm trying to install the dependencies for this react app. I have the packages in my package.json and am running npm install. The output is:
> semantic-ui@2.3.3 install /srv/org/reactsgo/app/front_end/node_modules/semantic-ui
> gulp install

gulp[10488]: ../src/node_contextify.cc:637:static void node::contextify::ContextifyScript::New(const v8::FunctionCallbackInfo<v8::Value>&): Assertion `args[1]->IsString()' failed.
 1: 0x8b8210 node::Abort() [gulp]
 2: 0x8b82e5  [gulp]
 3: 0x8eb237 node::contextify::ContextifyScript::New(v8::FunctionCallbackInfo<v8::Value> const&) [gulp]
 4: 0xb4daa8  [gulp]
 5: 0xb4fa12 v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [gulp]
 6: 0x1a851fd841bd
Aborted

I've tried to clean my cache with npm clean cache --force. I've built and rebuilt. I always get the same problem when I do the semantic-ui install even when I simply try to npm install semantic-ui on its own.
Am I hitting a versioning issue? My node is v10.8.0 and my npm is 6.2.0.
Anyone have a similar issue and a fix?
EDIT: On Debian 8 jessie

A: fixed running npm install natives then rerunning npm install


text:
Q: Wordpress 404 page when using /%category%/%postname%, works when using just /%postname% When I set my permalinks to use /%category%/%postname% i get a 404 page, but if i set it to just /%postname% it works fine.
htaccess is set to mod rewrites etc, here is a broken post example:
http://s23771.p717.sites.pressdns.com/blog/sales/amazong-will
The site only has 2 categories and 1 post created as its a test to see if the structure is possible.
Thanks!

A: I have faced this issue before.
Only setting mod rewrites is not enough.
I found from this link.
go to/etc/apache2/sites-available/ and make following changes in default file
<Directory /var/www/>
    Options +ExecCGI
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
</Directory>
<Directory /var/www/blog/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
</Directory>


text:
Q: Riesz Lemma with $\alpha=1$ and Linear Bounded Functional Show that on a normed linear space $X$, Riesz lemma with $\alpha=1 $ holds implies that every bounded linear functional attains its norm on the unit sphere of $X$.
This is not a homework question and I have tried a huge amount of approaches (too much to describe my attempts in here), so excuse me for not showing my work. A good hint would be appreciated.


text:
Q: Is there any way of inheriting Bootstrap classes in layouts? I am adapting a website to use Bootstrap. I was wondering if there was any way of using it so that my HTML elements don't get littered with classes.
I'd like to replace the code below:

        Text

With something like:

        Text

Where myClass would inherit the hidden-xs, col-sm-12, col-md-4 and col-md-offset-1 classes.
I've been looking around online seeing if there was any way that I could make my own custom classes "inherit" the bootstrap classes so I can keep the styling in CSS as much as possible, but I can't find anything. I wouldn't be surprised if it's not possible to do, but has anyone got any recommendations or anything on how to make the end result look as clean as it can be?
Thanks

A: Directly in CSS it's not possible (as far as I know), but it should be possible if you switch to sass (scss).
That being said, I advise against doing so, just repeat the classes and be done with it, that way everyone can tell at first glance what the block will look like.
When you install SASS, you need to download the source files of bootstrap from their download page and extract the scss dir to some directory, e.g. bootstrap.
After that create your own stylesheets, let's call it style.scss (notice the scss extension).
Now in your style.scss:
@import "bootstrap/bootstrap";
@import "bootstrap/bootstrap-grid";

.myClass {
  @extend .col-sm-12;
  @extend .col-md-4;
  // extend any other classes here
}

Then you compile your scss file (read sass documentation) and your myClass will have all the attributes of classes it extends.
If you never heard of sass before read the documentation first to understand how it works.


text:
Q: Merging commits in git I have a git repository with hundreds of commits. When I clone it, I get a lot of output like this:
...
got ac6d99d2762efe0fcf2b78656e336c25ca8428d5
got ef98d4e93c680384f8174b95e431627b29a56580
got 4d6e1231e0f6265458a8e6ab47a44bfcd357486b
got 7e3d3a2fc10d0dfe00e87e8eed4a3fc1efa5eaed
walk b43c1e0062b72d3ab416ad209e94e13a6c71815d
...
This corresponds to every single commit, which is annoying. Is there a way of "merging" the commits (don't need them anymore) besides the (obvious) import of HEAD into a new repository?
Edit: The clone cmd is done with the http method.

A: If you only have issues with git clone, you could try using the -q flag to tell it to be more quiet.
If you want to merge commits, use git rebase -i.  In git parlance, merging one commit into another is known as "squashing".  Keep in mind that this only affects the current branch.  If the commits exist on other branches, they will still exist on other branches.

A:
don't need them anymore

What do you mean by this? For better or for worse, the HEAD commit of any given repository points to its parent, which points to its parent, all the way back to the very first commit ever made.

*

*Is the output of git-clone cluttering up the screen? You can avoid this by using the -q flag to make it quieter. You could also upgrade — in version 1.7.1, I do not get the long list of commits unless I ask for extra verbosity (with -vv).
The chatty output only happens in the unsophisticated HTTP protocol. Using the git or ssh protocols is more efficient, and GitHub supports all of them. Also, read about the new Smart HTTP Transport.

*Are you used to centralized VCS, where a working copy only has the latest version? The best equivalent is probably a shallow clone, created with git clone --depth=n, where n is how much history you want. It has some limitations which you should read about, but it lets you clone only the recent history and still make changes that can be pushed back.
You don't save as much space as you might expect with a shallow clone, by the way — I picked a random project, and the 2.2MB of history shrank to 1.2MB when I only grabbed the latest commit. Git's pack is very space efficient.

*Do you really want to throw away all that history? An important lesson in git is that any modifications to history make your repository incompatible with its origin — if you rebase to squash them all, or else throw away all the history and start over, you will not be able to communicate with the origin repository.


text:
Q: *ngFor inside *ngFor I have an array that holds a user's orders, and inside of it there is another array that holds his ordered items:

My question is: how do I loop through his orders[] -> orderItems[]
For now, I did it manually just to make sure it works
HTML file:

                    {{order.orderItems[0].product_Name}}
                    {{order.orderItems[0].product_Price | currency: '$'}}
                    {{order.orderItems[0].product_Quantity}}
                    {{order.orderItems[0].product_Price* order.orderItems[0].product_Quantity | currency: '$'}}

TS file:

export class ProfileOrdersComponent implements OnInit {

  myOrders: OrderDetails[];
  constructor(private userService : UserService) { }

  ngOnInit() {
    this.userService.getProfileOrders().subscribe((data:OrderDetails[]) =>{
      this.myOrders = data
      console.log("My Orders:", this.myOrders);
    })
  }

}

Appreciated!

A: Here is how to render html

          {{orderItem.product_Name}}
          {{orderItem.product_Price | currency: '$'}}
          {{orderItem.product_Quantity}}
          {{orderItem.product_Price* orderItem.product_Quantity | currency: '$'}}


text:
Q: CRTP C++ Pattern and interfaces I am a beginner in C++ templates and stumbled upon following definition,
In general, CRTP is useful to factor out implementations of interfaces that can only be member functions (for example, constructor, destructors, and subscript operators).
And I am trying hard to understand what this means ?
Can anyone help me with a simple program...


text:
Q: Web Method accepting huge xml string I have a web service with just 1 Web method which will accept xml as string.
This web method is a function which will loop through data received and insert into sql server database in relevant tables.
When I try to consume this webservice which is on my machine from another vb.net application if the XMLstring is too huge I am getting a network error.
Is there a limit on the length of the string?

A: Set the httpRuntime maxRequestLength to a higher max.


text:
Q: Scalatest runner results in VerifyError: Cannot inherit from final class I am trying to run all the tests (all of them extend FlatSpec) in a jar using the ScalaTest Runner, but get a message for VerifyError. However, I am able to individually run the tests.
The jar was compiled using sbt test:assembly. I am trying to run the tests in another environment where sbt is not available. The tests are available in the jar in com/tfs/test path, as shown in the output below:
samik@samik-lap:~/git/proj$ jar tf test-2018.2.jar | grep MyTest
com/tfs/test/MyTest$$anonfun$1$$anonfun$apply$mcV$sp$1.class
com/tfs/test/MyTest$$anonfun$4.class
com/tfs/test/MyTest$$anonfun$5.class
com/tfs/test/MyTest$$typecreator4$1.class
com/tfs/test/MyTest$$typecreator5$1.class
com/tfs/test/MyTest$$typecreator9$1.class
com/tfs/test/MyTest.class

The following command runs the specific test just fine:
samik@samik-lap:~/git/proj$ scala -J-Xmx2g -cp "scalatest_2.11-3.0.5.jar:scalactic_2.11-3.0.5.jar:test-2018.2.jar" org.scalatest.run com.tfs.test.MyTest
0    [ScalaTest-main] INFO  com.tfs.test.MyTest  - Starting MyTest test application
Start Time: 0 sec
...

However, when I use Runner to run all the tests (there are ~7 similar tests in the jar available at the same path), it doesn't work.
samik@samik-lap:~/git/proj$ scala -J-Xmx2g -cp "scalatest_2.11-3.0.5.jar:scalactic_2.11-3.0.5.jar" org.scalatest.tools.Runner -o -R test-2018.2.jar
Discovery starting.
*** RUN ABORTED ***
java.lang.VerifyError: Cannot inherit from final class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)

How do I get all the tests to run through Runner? How do I get to know what is happening inside and where the issue is? Thanks for any pointer.


text:
Q: Turn off screenshots in Rails system tests I'm using system tests in Rails 5.1, and I'd like to turn off the automated screenshots for failure cases. Usually the failure message is plenty for me to figure out what's going on — and notably, the webdriver browser window always takes focus in order to take a screenshot, which is annoying when I'm working on the code (or trying to do anything else).
Is there a built in way in Capybara configuration to turn off screenshots? I looked through the docs and couldn't find anything stated explicitly, but since this is a new-ish addition to mainstream Rails, I figure that doesn't necessarily mean it doesn't exist.

A: In Rails 5.1 ActionDispatch::SystemTestCase (from which ApplicationSystemTestCase derives) has a default after_teardown method of
def after_teardown
  take_failed_screenshot
  Capybara.reset_sessions!
  super
end

To stop this from taking a screenshot, the easiest method is to override take_failed_screenshot in your ApplicationSystemTestCase class
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by ...

  # Add this method
  def take_failed_screenshot
    false
  end
end

A: I think it is more elegant to override supports_screenshot? method, In my case I wanted to disable screenshots on Heroku CI
 class ApplicationSystemTestCase < ActionDispatch::SystemTestCase

   private

   # disable only on CI, i.e: HEROKU CI
   def supports_screenshot?
    return false if ENV['CI']
    super
   end

   # to disable screenshots completely on every test invironment (local, CI)
   def supports_screenshot?
    false
   end

end

A: Capybara::Screenshot.autosave_on_failure = false

I think that will solve your problem.
Try to find file where you are importing this library. Or find capybara-screenshot/lib/capybara-screenshot.rb and change self.autosave_on_failure = true to false


text:
Q: C# - Paste multiline cells to excel from a string I was trying copying a string to an excel line using "\r" to separate the cells. I want only 2 cells to be multiline but using "\n" will switch the text over to the next line in the spreadsheet instead of making a new line in the cell. (The program automaticly copies the text to the Clipboard)
Is there any way to achieve this?
For example if you have a string:
    string s = "cell1 \t cell2 \t cell3 \n stillcell3 \t cell4";

It will result in (cell(contents)):
A1(cell1) A2(cell2) A3(cell3 newline stillcell3) A4(cell4)
I hope it made sense and it would be great if you could help me!
Solution:
Make sure you have enclosed the multiline section in \"\".

A: Try this:
String s = "cell1\tcell2\t\"cell3\nstillcell3\"\tcell4\r\n";
Clipboard.SetText(s);

Now go to Excel and Paste
(Control + V)


text:
Q: How to make some selected countries in the same color? Here is a good example of world map. I want to divide it into some regions, like Asia, Europe and so onn to make the countries in one region in the same color. How to make it? http://techslides.com/demos/d3/d3-world-map-colors-tooltips.html
I also want to add some values in every region, like the region name. How to do it?


text:
Q: SQL - Check and Update table for new rows? I have two tables, for example:
Table firstfile                      Table secondfile
===============                      ================

Emplid   | Color                     Emplid       | Color   |status
----------------------               -------------|---------|------
123      | red                       123          | red     |
456      | green                     456          | Green   |
789      | black                     000          | red     |
                                     789          | black   |
                                     999          | white   |

Table firstfile is my source table and secondfile is the destination table. Now I need a query which finds all the different (additional) rows in table secondfile. So I need a query which finds me the following:
Table secondfile
================

Emplid       | Color   | Status
-------------------------------
123          | red     |
456          | Green   |
000          | red     | added
789          | black   |
999          | white   | added

What is a good approach for such a query?
i tried this but its not working
UPDATE secondfile
INNER JOIN firstfile
   ON secondfile.Emplid = firstfile.Emplid
SET status = (CASE  WHEN secondfile.Emplid != firstfile.Emplid THEN 'Added' END)

A: Try this
    UPDATE secondfile
    SET status = 'Added'
    WHERE secondfile.Emplid NOT IN( select  Emplid  from firstfile)

sample to apply case
UPDATE secondfile
SET status =      CASE
                        WHEN Emplid= 10 THEN 'JustAdded'
                        WHEN Emplid= 20  THEN 'NewlyAdded'
                        WHEN Emplid= 30 THEN 'Old'
                        ELSE 'Added'
                    END
WHERE secondfile.Emplid not in ( select  Emplid  from firstfile)

A: TRY THIS In the following way using LEFT JOIN and IS NULL you can check the records that is not exist in the firstfile but in the second and it will update the same resultset
UPDATE secondfile
LEFT JOIN firstfile ON secondfile.Emplid = firstfile.Emplid
SET status = 'Added'
WHERE firstfile.Emplid IS NULL

In your code you are using secondfile.Emplid != firstfile.Emplid which will never be satisfied with INNER JOIN, this join always returns matching data only and in your case it will return data that exists in both the tables.
You can make tiny change in your query as below:
UPDATE secondfile
LEFT JOIN firstfile ON secondfile.Emplid = firstfile.Emplid
SET status = CASE WHEN secondfile.Emplid != firstfile.Emplid THEN 'Added' ELSE status END

A: You can use NOT EXISTS() and do something like this:
UPDATE secondfile
SET status = 'Added'
WHERE  NOT EXITS(
                  select  1
                  from firstfile
                  where Emplid= secondfile.Emplid
                                                   )


text:
Q: CometD / jQuery Client Error 402::Unknown Client I'm trying to get started with CometD as I need some empirical background for a technical comparision between various push technologies.
I finally managed to get an example code running in my Tomcat (v7.0).
Now I'm having strange behavior and I'm desperately trying to find out what I did wrong.
Here are my observations:

*

*Connection Loops:
I'm running in an endless connection loop with the client.
Request:
[{"channel":"/meta/connect","connectionType":"long-polling","id":"19","clientId":"f1le33y91f6pa71f39z52km87yp"}]

Response:
[{"id":"19","successful":true,"advice":{"interval":2000,"reconnect":"retry","multiple-clients":true,"timeout":60000},"channel":"/meta/connect"}]

The interesting thing about this is, that the Listener-callback event actually occures
 cometd.addListener('/meta/handshake', _metaHandshake);

*Client connection request stucks
This mostly occurs after a fresh restart of my Tomcat server. I can see a successful subscription to 2 channels:
Request
[{"version":"1.0","minimumVersion":"0.9","channel":"/meta/handshake","supportedConnectionTypes":["long-polling","callback-polling"],"advice":{"timeout":60000,"interval":0},"id":"1"}]

Response
[{"id":"1","minimumVersion":"1.0","supportedConnectionTypes":["callback-polling","long-polling"],"successful":true,"channel":"/meta/handshake","clientId":"11tnpjnmkqo3tf64zcvufuqbtv","version":"1.0"}]

Request
[{"channel":"/meta/subscribe","subscription":"/hello","id":"2","clientId":"11tnpjnmkqo3tf64zcvufuqbtv"},{"channel":"/service/hello","data":{"name":"World"},"id":"3","clientId":"11tnpjnmkqo3tf64zcvufuqbtv"}]

Response
[{"id":"2","subscription":"/hello","successful":true,"channel":"/meta/subscribe"},{"id":"3","successful":true,"channel":"/service/hello"}]

The call after this one stucks and takes forever.
... abd here is my Code

*

*Client
(function($)
 {
   var cometd = $.cometd;

$(document).ready(function()
{
    function _connectionEstablished()
    {
        $('#body').append('
CometD Connection Established
');
    }

    function _connectionBroken()
    {
        $('#body').append('
CometD Connection Broken
');
    }

    function _connectionClosed()
    {
        $('#body').append('
CometD Connection Closed
');
    }

    // Function that manages the connection status with the Bayeux server
    var _connected = false;
    function _metaConnect(message)
    {
        if (cometd.isDisconnected())
        {
            _connected = false;
            _connectionClosed();
            return;
        }

        var wasConnected = _connected;
        _connected = message.successful === true;
        if (!wasConnected && _connected)
        {
            _connectionEstablished();
        }
        else if (wasConnected && !_connected)
        {
            _connectionBroken();
        }
    }

    // Function invoked when first contacting the server and
    // when the server has lost the state of this client
    function _metaHandshake(handshake)
    {
        if (handshake.successful === true)
        {
           // interesting enough: that event is triggered
            alert('event occured');
            cometd.batch(function()
            {
                // that function is called and produces a corresponding request to the server
                cometd.subscribe('/hello', function(message)
                {
                    // that one never happens...
                    $('#body').append('
Server Says: ' + message.data.greeting + '
');
                });
                // Publish on a service channel since the message is for the server only
                cometd.publish('/service/hello', { name: 'World' });
            });
        }
    }

    // Disconnect when the page unloads
    $(window).unload(function()
    {
        cometd.disconnect(true);
    });

    var cometURL = location.protocol + "//" + location.host + config.contextPath + "/cometd";
    cometd.configure({
        url: cometURL,
        logLevel: 'debug'
    });

    cometd.addListener('/meta/handshake', _metaHandshake);
    cometd.addListener('/meta/connect', _metaConnect);

    cometd.handshake();
});
})(jQuery);

*Server
Notice that this is almost 1:1 from the example from the distribution package!
public class HelloService extends AbstractService
{
public HelloService(BayeuxServer bayeux)
{
    super(bayeux, "hello");
    addService("/service/hello", "processHello");
}

public void processHello(ServerSession remote, Message message)
{
    Map<String, Object> input = message.getDataAsMap();
    String name = (String)input.get("name");

    Map<String, Object> output = new HashMap<String, Object>();
    output.put("greeting", "Hello, " + name);
    remote.deliver(getServerSession(), "/hello", output, null);
}

}

*Web.xml File

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
<servlet>
    <servlet-name>cometd</servlet-name>
    <servlet-class>org.cometd.server.CometdServlet</servlet-class>
    <async-supported>true</async-supported>
    <init-param>
        <param-name>timeout</param-name>
        <param-value>60000</param-value>
    </init-param>
    <init-param>
        <param-name>logLevel</param-name>
        <param-value>3</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>cometd</servlet-name>
    <url-pattern>/cometd/*</url-pattern>
</servlet-mapping>

Maybe I'm just doing something completely wrong, but I'm starting to get a bit desperate on this. Help would be highly appreciated.


text:
Q: BitmapFactory Not working in Android This line of code always returns null after cropping:
this.bmp = BitmapFactory.decodeFile(this.imageFileUri.getPath());

This is my crop method:
 private void performCrop() {
      this.imageFileUri = Uri.fromFile(this.file);
      Intent var1 = new Intent("com.android.camera.action.CROP");
      var1.setDataAndType(this.imageFileUri, "image/*");
      System.out.println(this.imageFileUri.getPath());
      var1.putExtra("crop", "true");
      var1.putExtra("scale", true);
      var1.putExtra("return-data", true);
     // var1.putExtra("output", this.imageFileUri);
      intent.putExtra(MediaStore.EXTRA_OUTPUT, this.imageFileUri);
      this.startActivityForResult(var1, 1);
   }

I have tried by using a custom method to return the Bitmap it still returns null. This is the method
public static Bitmap decodeFile(String path) {
       int orientation;
       try {
           if (path == null) {
               return null;
           }
           // decode image size
           BitmapFactory.Options o = new BitmapFactory.Options();
           o.inJustDecodeBounds = true;
           // Find the correct scale value. It should be the power of 2.
           final int REQUIRED_SIZE = 70;
           int width_tmp = o.outWidth, height_tmp = o.outHeight;
           int scale = 1;

           BitmapFactory.Options o2 = new BitmapFactory.Options();
           o2.inSampleSize = scale;
           Bitmap bm = BitmapFactory.decodeFile(path, o2);
           Bitmap bitmap = bm;

           ExifInterface exif = new ExifInterface(path);

           orientation = exif
                   .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

           Log.e("ExifInteface .........", "rotation =" + orientation);

           // exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);

           Log.e("orientation", "" + orientation);
           Matrix m = new Matrix();

           if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
               m.postRotate(180);
               // m.postScale((float) bm.getWidth(), (float) bm.getHeight());
               // if(m.preRotate(90)){
               Log.e("in orientation", "" + orientation);
               bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                       bm.getHeight(), m, true);
               return bitmap;
           } else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
               m.postRotate(90);
               Log.e("in orientation", "" + orientation);
               bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                       bm.getHeight(), m, true);
               return bitmap;
           } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
               m.postRotate(270);
               Log.e("in orientation", "" + orientation);
               bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                       bm.getHeight(), m, true);
               return bitmap;
           }
           return bitmap;
       } catch (Exception e) {
           return null;
       }

   }

And calling the above method this way:
this.bmp = MyClass.decodeFile(this.imageFileUri.getPath());

Kindly assist!


text:
Q: The eigenvalues and corresponding eigenvectors for the matrix The matrix is
$$\begin{pmatrix}
0&2&2\\
2&0&2\\
2&2&0
\end{pmatrix}
$$
I have calculated the equation for eigenvalues, which is $\lambda^3-4\lambda-16=0$, but how do I solve this equation? Can this matrix be diagonalized?

A:
I have calculated the equation for eigenvalues, which is $\lambda^3-4\lambda-16=0$, but how do I solve this equation?

Your characteristic equation is wrong. You can avoid having to solve a cubic equation by first using some properties of determinants; e.g. subtracting the third column from the second and then adding the third row to the second:
$$\begin{vmatrix}
-\lambda&2&2\\
2&-\lambda&2\\
2&2&-\lambda
\end{vmatrix}
=\begin{vmatrix}
-\lambda&0&2\\
2&-\lambda-2&2\\
2&2+\lambda&-\lambda
\end{vmatrix}
=\begin{vmatrix}
-\lambda&0&2\\
4&0&2-\lambda\\
2&2+\lambda&-\lambda
\end{vmatrix}$$
Expanding along the second column now gives:
$$(2+\lambda)\left(-\lambda(2-\lambda)-8\right)=0 \iff (2+\lambda)^2(\lambda-4)=0 \iff \lambda = -2 \vee \lambda = 4$$
Now proceed with finding the corresponding eigenvectors. You should find two linearly indepedent eigenvectors for the double eigenvalue $\lambda = -2$, so yes: the matrix is diagonalizable.

A: One can quickly find the eigenvalues of a matrix of this form without forming and solving the characteristic equation. Call your matrix $A$. Observe that the matrix of all $2$'s is singular. That matrix is equal to $A+2I$, so $-2$ is an eigenvalue. It should be clear that the kernel of $A+2I$ is two-dimensional, so $-2$ is at least a double eigenvalue. Using the fact that the trace of a matrix is equal to the sum of its eigenvalues, we find that the third eigenvalue is $0-2(-2)=4$.
More generally, the same line of reasoning shows that the eigenvalues of the matrix $\small{\pmatrix{a&k&k\\k&a&k\\k&k&a}}$ are $a-k$, $a-k$ and $a+2k$. This has a straightforward generalization to $n\times n$ matrices as well.


text:
Q: Shell - aapt output into variable I use following command to get my APK versionName
PATH/aapt dump badging APK-Path | grep versionName

And it works fine if I run it on it's own but I need it in a variable so I try sth like this:
$s='PATH/aapt dump badging APK-Path | grep versionName'

but it returns

PATH/aapt dump badging APK-Path | grep versionName no such file or
  directory

error. I also tried using $() instead of ''. Any ideas how to make it work?
EDIT.: I use terminal in MacOS. if I enter PATH I can just run aapt dump badging APK-Path | grep versionName but if I don't do that I need to pass it as shown above

A: Assuming you mean bash (or the like) when you say shell, you probably want to do something like this:
s="PATH/aapt dump badging APK-Path | grep versionName" or s="$(PATH/aapt dump badging APK-Path | grep versionName)"
You can then retrieve the value of s with echo $s


text:
Q: Mautic can't add custom field, fails after upgrade to 4.4.5 I upgraded Mautic from v2 to v3 to v4.4.5 and the upgrade went well and email automations are working. But after trying to add a custom field to the Contacts I keep getting this error:
An exception occurred while executing 'ALTER TABLE leads ADD created DATE DEFAULT NULL': SQLSTATE[42S22]: Column not found: 1054 Unknown column '`mautic`.`l`.`email`' in 'GENERATED ALWAYS'

I tried running these commands in case a migrations wasn't migrated but its not working
docker-compose run app php bin/console mautic:update:apply
docker-compose run app php bin/console mautic:update:apply --finish
docker-compose run app php bin/console cache:clear

Any ideas?


text:
Q: C++ member function applied to object I want to call member function by passing it as template parameter, without using boost is possible. Here is an example off what I tried to do,
class object { void method(); }

{
object object_instance;
...
apply<object:: method>();
...

template<class F>
void apply() { F(object_instance); } // want to call object_instance.F()
}

that does not work, so question is how do I go about binding object method to an object.
Thanks
above is an example, not the real code. I have a bunch of functions differing only in name, but with many parameters, that I want to wrap around in operators.

A: Something like:
struct foo
{
    void bar(void) {}
};

template <typename R, typename C>
R apply(C& pObject, R (C::*pFunc)())
{
    return (pObject.*pFunc)();
}

int main(void)
{
    foo f;
    apply(f, &foo::bar);
}

this.

A: This is similar to your code, and will allow passing a member function as a template parameter:
class object { public: void method() {} };
object object_instance;

template<void (object::*F)()>
void apply() {
    (object_instance.*F)();
}

int main() {
    apply<&object::method>();
    return 0;
}

A: As a member function isn't a type or integral value, you can't pass it as a template parameter. You could do what you seem to want by creating a struct which calls the member function, though having object_instance in scope in the template is rather smelly.
What are you actually trying to do?

A: This example is for rvalue references in c++ox. Does not work on all compilers.
class Sample
{
public:
    void fun() { cout << "Sample::fun\n"; }
};

template<typename Function>
void FunCall( Function&& f)
{
    f();
}

void RvaluesDemo()
{
    FunCall([&]
    {
        Sample().fun();
    });
}


text:
Q: Error: Invalid character in header content ["jwt_token"] I was following this guide https://helpx.adobe.com/marketing-cloud-core/kb/adobe-io-authentication-step-by-step.html on adobe api.
After converting the v1 api call to v2 exchangeJwt.json in the guide I imported it as instructed added the appropriate keys and values hit send. It returned the error

I'm pretty sure I followed the instructions so I am not sure what went wrong.

A: In the docs, just put jwt_token in body form-data, not ["jwt_token"] in header


text:
Q: Можно ли менять \ в типе byte? replace() не работает
Мне пришлось изменить utf-8 кодировку, так как она плохо парсилась.
После этого у меня есть строка, которая на самом деле является этой самой
кодировкой.
Ну то есть text = '\u0026 \xd8b \r'. Но например в нем есть \\n.
Такой символ не парсится как перевод строки,
поэтому я делаю text = text.replace(b'\\\\', b'\\'),
но ничего не происходит.
Из чего пришло предположение - в байт нельзя заменять \? Они являются 'вспомогательными' и не отображаются как символы?

Есть ли похожий способ дебажить '\\n'?


text:
Q: Could not resolve host: github.com BeagleBoard Black wireless I am trying to clone my git repository into my BeagleBone black but i get the error

fatal: unable to access 'git url'; Could not resolve host: github.com

When I ping 8.8.8.8 there is a response however when trying to ping 'github.com' it also tells me

ping: unknown host github.com

has anyone encountered something like this?

A: As the ping to 8.8.8.8 got through, have you tried pinging the ip (192.30.253.112) directly?
If that works it would suggest a problem with the DNS look up.

A: If you have dns server on your environment, check your configuration on the server and probably problem is your dns server can not transmit your dns queries. You can check your dns forwarders and root hints.
If you do not have any dns server, you can try to change your dns to google, opendns or another. Then you can try.

A: If you're able to ping 8.8.8.8, that means that your internet might be working but the actual DNS lookup (how it translates a web address like google.com to the IP address such as 8.8.8.8) is failing.
You might be able to solve this by directly pinging the IP or setting your IP address to be static.
Try following the steps in this:
http://ofitselfso.com/Beagle/NetworkingSetupConnectingTheBeagleboneBlack.php
or
http://derekmolloy.ie/set-ip-address-to-be-static-on-the-beaglebone-black/