text:
Q: Image Pixel Array without first drawing into main Canvas? Do you have to first draw any source images into the canvas before you can obtain the pixel array data? or is there a better way? such as having a second hidden canvas?
I am using several images that I will mash together, and draw into the main canvas. What is the best way to obtain to say backgroundData, objectsData, effectsData, from bg.png, obj.png, fx.png? without first showing them in the main canvas.

A: I believe (99%, not 100%) you have to draw them to Canvas to get any of the data properties.
That said, you could draw them to a temporary, hidden canvas that you create on the fly and kill when you're done.


text:
Q: How to import Azure Storage Blob JSON into Azure SQL Server {
    "Events":
        [
            {
            "dataOne":7.5555555555555555,
            "dataTwo":7.5555555555555555,
            "dataFive":1025,
            "dataSix":0,
            "dataSeven":1025,
            "dateTimeLocal":1234567890,
            "dateTimeUTC":1234567890
            }
        ],
    "infoType":"type1",
    "deviceID":"00000000000000000",
    "dateTimeLocal":1234567890,
    "dateTimeUTC":1234567890,
    "EventProcessedUtcTime":"20xx-0x-xxT0x:0x:x.4781329Z",
    "PartitionId":1,
    "EventEnqueuedUtcTime":"20xx-0x-xxT0x:0x:x.3850000Z"
}

Here is a JSON record of my data, how do I define my sql table according to it, and how do I import the JSON data in to Azure SQL Server : (

A: You could use Azure Data Factory Copy Activity to transfer your blob data into sql server directly. Please configure the input as Azure Blob Storage Connector and output as Azure SQL Database Connector.
About the column mapping, please refer to this link:https://learn.microsoft.com/en-us/azure/data-factory/copy-activity-schema-and-type-mapping. The array property could be stored as string in your sql database column.

A: Please look at this doucment:Import JSON documents into SQL Server(Azure SQL Database)
It shows how to import Azure Storage Blob JSON into Azure SQL Server. And provides the demos:

*

*Import a JSON document into a single column

*Import multiple JSON documents

*Import JSON documents from Azure File Storage

*Import JSON documents from Azure Blob Storage

*Parse JSON documents into rows and columns
Demo SQL:
CREATE EXTERNAL DATA SOURCE MyAzureBlobStorage
 WITH ( TYPE = BLOB_STORAGE,
        LOCATION = 'https://myazureblobstorage.blob.core.windows.net',
        CREDENTIAL= MyAzureBlobStorageCredential);
BULK INSERT Product
FROM 'data/product.dat'
WITH ( DATA_SOURCE = 'MyAzureBlobStorage');

You just need to follow the tutorial.
Hope this helps.

A: In ADF, you can create a 'Copy Activity' to transfer your blob data into the SQL server directly. Please configure the source dataset as CSV 'DelimitedText' (Think JSON file content as csv data with 1 row and 1 column) and Sink dataset as Azure SQL Database Connector. You can load hundreds of JSON from Azure blob to a Azure SQL table having a field with size NVARCHAR(MAX).
Define the mapping for 1 source (i.e. JSON) column. You can also add custom fields in Copy activity Source and do it mapping here too.
Create another 'Stored Procedure Activity' to parse JSON stored in SQL table.
Source:

Source Dataset:

Sink:

Mapping:

'stg' table to save should look like this.
CREATE TABLE [dbo].[stgSalesInvoice](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [JsonData] [nvarchar](max) NULL
) ON [PRIMARY]
GO

The stored procedure to parse JSON in Target Azure Sql table will look like this for a sample nested json. Not attaching the json file but below shows how easily you can parse nested json.
CREATE  PROCEDURE [dbo].[pLoadSalesInvoice]
AS
BEGIN
    DECLARE @Jsons nVARCHAR(MAX);
    DECLARE @mPartitionKey VARCHAR(20) ;
    DECLARE @mFileName VARCHAR(1000) ;
    DECLARE @JsonTotalFilesCount INT = (SELECT COUNT(*) FROM [dbo].[stgSalesInvoice]);
    DECLARE @JsonLoopCount INT = 1;

    TRUNCATE TABLE  [dbo].[SalesInvoice]

    WHILE @JsonLoopCount <= @JsonTotalFilesCount
    BEGIN
        SELECT @Jsons = JsonData FROM [dbo].[stgSalesInvoice] WHERE id = @JsonLoopCount;

        --Target Azure Sql Table
        INSERT INTO [dbo].[SalesInvoice]
               ([SalesInvoiceId]
               ,[invoiceNo]
               ,[transactionId]
               ,[supplierId]
               ,[vendorSupplierId]
               ,[vendorNoExt]
               ,[vendorDate]
               ,[biddingId]
               ,[description]
               ,[biddingDimensionId]
               ,[biddingItemDimensionValueId]
                )
        SELECT  [SalesInvoiceId]
               ,[invoiceNo]
               ,[transactionId]
               ,[supplierId]
               ,[vendorSupplierId]
               ,[vendorNoExt]
               ,[vendorDate]
               ,[biddingId]
               ,[description]
               ,[biddingDimensionId]
               ,[biddingItemDimensionValueId]

        FROM OPENJSON(@Jsons) WITH (
                SalesInvoice NVARCHAR(MAX) '$.SalesInvoice' AS JSON
                ,supplier NVARCHAR(MAX) '$.supplier' AS JSON
                ,vendor NVARCHAR(MAX) '$.vendor' AS JSON
                ,bidding NVARCHAR(MAX) '$.bidding' AS JSON
                )
        OUTER APPLY OPENJSON(SalesInvoice) WITH (
                [SalesInvoiceId] NVARCHAR(100) '$.id'
                ,[invoiceNo] NVARCHAR(100) '$.invoiceNo'
                ,[transactionId] NVARCHAR(100) '$.transactionId'
                )
        OUTER APPLY OPENJSON(supplier) WITH (
                [supplierId] NVARCHAR(100) '$.id'
                ,[vendorSupplierId] NVARCHAR(100) '$.vendorSupplierId'
                )
        OUTER APPLY OPENJSON(vendor) WITH (
                [vendorNoExt] NVARCHAR(100) '$.vendorNoExt'
                ,[vendorDate] datetime2(7) '$.vendorDate'
                )
        OUTER APPLY OPENJSON(bidding) WITH (items NVARCHAR(MAX) '$.items' AS JSON)
        OUTER APPLY OPENJSON(items) WITH (
                [biddingId] NVARCHAR(100) '$.biddingId',
                [description] NVARCHAR(250) '$.description',
                biddingItemDimensionValues NVARCHAR(MAX) '$.biddingItemDimensionValues' AS JSON
                )
        OUTER APPLY OPENJSON(biddingItemDimensionValues) WITH (
                [biddingDimensionId] NVARCHAR(100) '$.biddingDimensionId'
                ,[biddingItemDimensionValueId] NVARCHAR(100) '$.biddingItemDimensionValueId'
                );
        SET @JsonLoopCount = @JsonLoopCount + 1
    END
    SELECT 1;
END

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deploying latest docker containers with ansible I have been trying to get ansible to deploy my containers, and I have been successful with the following config, but the problem I am running into is that it will not start the most recent version of my container.
- name: Deploy
  hosts: staging
  tasks:
    - name: Install docker-py
      pip: name=docker-py
    - name: Pull latest container
      raw: docker pull org/proj:latest
    - name: Stop container
      docker:
        image="org/proj:latest"
        name=proj-rails
        state=stopped
    - name: Deploy container
      docker:
        image="org/proj:latest"
        name=proj-rails
        ports=80:80
        state=running

I can build and push new containers to docker hub and try to pull them down. On the server docker images lists the latest containers:
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
org/proj            latest              9f0de94df28c        2 hours ago         675.5 MB
<none>              <none>              15f4bbbeebca        2 days ago          670.6 MB
<none>              <none>              f7958247ed52        2 days ago          670.3 MB

My problem is that ansible keeps starting 15f4bbbeebca (which is not the latest container). Can anyone help me figure out what is wrong?

A: Shot in the dark, but that syntax looks odd to me.  Shouldn't it be
- name: Stop container
  docker:
    image: org/proj:latest
    name: proj-rails
    state: stopped

?
Also, why are you using raw rather than command (or shell)?

A: Is it possible that the issue arises from the misunderstood latesttag? see this https://medium.com/@mccode/the-misunderstood-docker-tag-latest-af3babfd6375#.hlzfep7mn

A: I fixed my issues by writing my own deployment solution and then open sourced it, https://github.com/mrinterweb/freighter
I designed freighter to be easily configurable and flexible at the same time. I hope someone finds it to be helpful. I am not finished with freighter yet, but it is usable at this point.
I realize that this does not answer the question about how to deploy docker with ansible, but I gave up on trying to deploy containers with ansible. I just did not find the ansible docker module to be mature enough, documented enough, or configurable to my needs.


text:
Q: Debugging JS in Safari For apps that were running in simulator, I was able to debug Javascript on Safari till yesterday night. However, something happened today and I am not able to do it.
I tried it on 2 other laptops as well and it is not working on them as well.

*

*I have tied resetting simulator, restarting Mac, updating everything

*I have tried getting other projects from github to ensure there is nothing wrong in my current project - did not work

*Below is how it looks in Safari

Is there something else that I can try to get it working again?


text:
Q: Custom Attribute in c# to give Custom data-attribute in html I'd like to be able to make a data attribute in c# for an object in my model. When this is displayed. I'd like the html to render the value in a data attribute within the html itself.
In my head, the code looks similar to this.
public class AffectsAttribute:Attribute
{
    public string[] Departments { get; set; }

}

[EmailAddress]
[Required(ErrorMessage = "Email is required")]
[Affects(Departments = new string[]{"Coaches"})]
public string Email {get; set;}

Then in the html, after being called with razor it would look something like this
@Html.EditorFor(model => model.Email)

<input class="text-box single-line" data-affects="Coaches" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="Email is required" id="Email" name="Email" type="email"  value="">

I have no clue how to specify that I would like the additional data attribute to be added when the item is rendered on a page. Can anyone help?

A: It can be done through the ValidationAttribute. If you inherit this:
public class MyCustomAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
    }
}

The GetClientValidationRules is what you are interested in. You return an IEnumerable of attributes you want the client to have.
You can check out this article on CodeProject.

A: You'll have to create a new HTML helper to do that.
http://www.asp.net/mvc/overview/older-versions-1/views/creating-custom-html-helpers-cs
It's an extension from the HtmlHelper, that creates that.
Something like:
  public static class YourExtensions
 {
      public static string YourMethodName(this HtmlHelper helper, string[] paramName)
      {
           return  String.Format("<input data-affects='{0}'>",String.Join(" ", paramName));
      }
 }


text:
Q: Clipping of sound files + Blackberry Is it somehow possible to clip a sound file i between ? In my application I have to provide the user the ability to create a ringtone out of a sound file and the user will enter the start and end time of the region within the file he wants to clip .Is this possible?

A: Parse mp3 (or other sound) binary format and do whatever you want with this file. Information on mp3 and other file formats can be found via google.


text:
Q: Parse file into list I'm parsing an file ( php ) to an list in C#, so that I can do stuff with it. I've done it before in PHP, but there it works really slow, so I'm trying to make an C# winform application of it.
This is the code that I already have in C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace g7_product_parser
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void log(String msg)
        {
            textBox1.AppendText(msg + "\r\n\r\n");
        }

        public string[] parseLine(String regel)
        {
            string[] parsed;
            parsed = new string[2];
            regel = regel.Replace("array(", "");
            regel = regel.Replace("),", "");
            regel = regel.Replace(")", "");
            string[] temp = regel.Split(',');
            foreach (string part in temp)
            {
                string[] part2 = Regex.Split(part, "=>");
                // log(String.Join(",", part2));
                if (part2[0].Replace("'", "").Trim() == "keyword_uid")
                {
                    parsed[1] = part2[1].Replace("'", "").Trim();
                }
                else if (part2[0].Replace("'", "").Trim() == "product_uid")
                {
                    parsed[0] = part2[1].Replace("'", "").Trim();
                }
            }
            return parsed;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            String startTime = DateTime.Now.ToString("HH:mm:ss tt");
            log("Begin!");
            string[] lines = System.IO.File.ReadAllLines("tx_ttproductsv2_keywords_in_products.php");
            List<string> entrys = new List<string>();
            foreach (string line in lines)
            {
               // parseLine(line);
                log(String.Join(",",parseLine(line)));

                Application.DoEvents();
            }

            String endTime = DateTime.Now.ToString("HH:mm:ss tt");
            String totalTime = (DateTime.Parse(endTime) - DateTime.Parse(startTime)).ToString();
            log("Klaar!");
            log("Start Tijd: " + startTime + "\r\nEind Tijd: " + endTime + "\r\nTotale Tijd: " + totalTime);
        }

    }
}

The file to parse looks like this:
array('uid' => '1','pid' => '2','keyword_uid' => '1','product_uid' => '1','amount' => '15','in_title' => '0'),
array('uid' => '2','pid' => '2','keyword_uid' => '2','product_uid' => '1','amount' => '12','in_title' => '0'),
array('uid' => '3','pid' => '2','keyword_uid' => '3','product_uid' => '1','amount' => '12','in_title' => '0'),
array('uid' => '4','pid' => '2','keyword_uid' => '4','product_uid' => '1','amount' => '9','in_title' => '0'),
array('uid' => '5','pid' => '2','keyword_uid' => '5','product_uid' => '1','amount' => '18','in_title' => '0'),
array('uid' => '6','pid' => '2','keyword_uid' => '6','product_uid' => '1','amount' => '6','in_title' => '0'),
array('uid' => '7','pid' => '2','keyword_uid' => '7','product_uid' => '1','amount' => '6','in_title' => '0'),
array('uid' => '8','pid' => '2','keyword_uid' => '8','product_uid' => '1','amount' => '6','in_title' => '0'),
array('uid' => '9','pid' => '2','keyword_uid' => '9','product_uid' => '1','amount' => '79','in_title' => '1'),
array('uid' => '10','pid' => '2','keyword_uid' => '10','product_uid' => '1','amount' => '6','in_title' => '0'),
array('uid' => '11','pid' => '2','keyword_uid' => '11','product_uid' => '1','amount' => '6','in_title' => '0'),
array('uid' => '12','pid' => '2','keyword_uid' => '12','product_uid' => '1','amount' => '6','in_title' => '0'),
array('uid' => '13','pid' => '2','keyword_uid' => '13','product_uid' => '1','amount' => '6','in_title' => '0'),
array('uid' => '14','pid' => '2','keyword_uid' => '14','product_uid' => '1','amount' => '6','in_title' => '0'),
array('uid' => '15','pid' => '2','keyword_uid' => '15','product_uid' => '1','amount' => '15','in_title' => '0'),
array('uid' => '16','pid' => '2','keyword_uid' => '16','product_uid' => '1','amount' => '12','in_title' => '0'),
array('uid' => '17','pid' => '2','keyword_uid' => '17','product_uid' => '1','amount' => '12','in_title' => '0'),
array('uid' => '18','pid' => '2','keyword_uid' => '18','product_uid' => '1','amount' => '6','in_title' => '0'),
array('uid' => '19','pid' => '2','keyword_uid' => '19','product_uid' => '1','amount' => '15','in_title' => '1'),
array('uid' => '20','pid' => '2','keyword_uid' => '20','product_uid' => '1','amount' => '6','in_title' => '0'),
array('uid' => '21','pid' => '2','keyword_uid' => '21','product_uid' => '1','amount' => '15','in_title' => '0'),
array('uid' => '22','pid' => '2','keyword_uid' => '22','product_uid' => '1','amount' => '21','in_title' => '0'),
array('uid' => '23','pid' => '2','keyword_uid' => '23','product_uid' => '1','amount' => '12','in_title' => '0'),

I had some PHP code like this:
require_once 'export/tx_ttproductsv2_keywords_in_products_part.php';
$sql = new Sql;
    $tagList = array();
    $counter = 0;
    $counter2 = 0;
    $counter3 = 0;

    foreach ($tx_ttproductsv2_keywords_in_products as $key => $value) {
        $keywordsList = $sql -> getKeyWords($value['keyword_uid']);
        foreach ($keywordsList as $key2 => $value2) {
            if(isset($tagList[$value['product_uid']])){
                $tagList[$value['product_uid']] .= ", " . $value2['keyword'];
            }else{
                $tagList[$value['product_uid']] = $value2['keyword'];
            }
        }
    }

In this way ( in PHP ), i check if an entry in the array already excist, and if that's true, append, or else make an new entry.
My question is: how can I do that in C#. I think that I have to use an list, but I really don't know how exactly.

A: I wrote a quick and dirty Console program to convert that into an array. See if you can modify it to your purposes... if not, please explain in more detail what exactly you need it to do.
(Note: this was a quick rush job and is not the most efficient way of handling this.)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace simplearraything
{
class myarrayitem
{
    public int uid;
    public int pid;
    public int keyword_uid;
    public int product_uid;
    public int amount;
    public int in_title;
}
class Program
{
    static void Main(string[] args)
    {
        //array('uid' => '23','pid' => '2','keyword_uid' => '23','product_uid' => '1','amount' => '12','in_title' => '0'),
        string Original = File.ReadAllText("array.txt").Replace("array('uid' => '", "").Replace(
            "','pid' => '", "/").Replace("','keyword_uid' => '", "/").Replace("','product_uid' => '", "/").Replace(
            "','amount' => '", "/").Replace("','in_title' => '", "/").Replace("'),", "").Replace("\r","");
        string[] lines = Original.Split('\n');
        List<myarrayitem> mystuff = new List<myarrayitem>();
        for (int i = 0; i < lines.Length; i++)
        {
            string[] thisitem = lines[i].Split('/');
            myarrayitem item = new myarrayitem();
            item.uid = int.Parse(thisitem[0]);
            item.pid = int.Parse(thisitem[1]);
            item.keyword_uid = int.Parse(thisitem[2]);
            item.product_uid = int.Parse(thisitem[3]);
            item.amount = int.Parse(thisitem[4]);
            item.in_title = int.Parse(thisitem[5]);
            mystuff.Add(item);
        }

        // Now, output it to prove accuracy:
        for (int i = 0; i < lines.Length; i++)
        {
            Console.WriteLine("UID:" + mystuff[i].uid.ToString() + "/PID:" + mystuff[i].pid.ToString() + "/KEYWORD_UID:" + mystuff[i].keyword_uid.ToString() +
                "/PRODUCT_UID:" + mystuff[i].product_uid.ToString() + "/amount:" + mystuff[i].amount.ToString() + "/in_title:" + mystuff[i].in_title.ToString());
        }
        Console.Read();
    }
}
}

In response to comment:
List<myarrayitem> items new List<myarrayitem>();
for (int i = 0;i < mystuff.Count;i++)
{
      if (mystuff[i].product_uid == PRODUCT_UID_HERE)
      {
            items.add(mystuff[i]);
            // Or, instead of this items List, you could just do whatever you wanted to do with the items right here.
      }
}

A: Try this:

*

*Get Newtonsoft.Json

*Add the following classes to your code:

public class DataArray {
  public string uid { get; set; }
  public string pid { get; set; }
  public string keyword_uid { get; set; }
  public string product_uid { get; set; }
  public string amount { get; set; }
  public string in_title { get; set; }
}

public class RootObject {
  public DataArray DataArray { get; set; }
}

*

*Load the file into a String called toProcess, then run the following:

    // the next 4 lines convert that data into JSON format
      toProcess = toProcess.Replace("array(", "{\"DataArray\":{");
      toProcess = toProcess.Replace(")", "}}");
      toProcess = toProcess.Replace("'", "\"");
      toProcess = "[" + toProcess.Replace("=>", ":") + "]";
List<RootObject> data = JsonConvert.DeserializeObject<List<RootObject>>(toProcess);

foreach ( RootObject d in data ) {
  // do something here like..
  if (d.DataArray.uid == "1") {
      //
  }
}


text:
Q: How to stop my date from selecting one extra date? I want to select the first 14 days report_date(s) after a specified date release_date that I have set up in separate table. These tables are joined and I can select both release_date and report_date to show, however when I perform my date function for some reason it is printing back out report_date(s) that start one day before my release_date (when there is data available to bring out).
This is my current code, which returns me the first 14 days, and additionally sometimes the day before my release date. I can't figure out how to rid it of the previous day.
Where
report_date < date_ADD(release_date, interval +14 day)
Any help would be very appreciated!
Image show casing my report_date pulling one day before my stated release date

A: I think You can just update your condition to -
...report_date < date_ADD(release_date, interval +14 day)
AND report_date >=   release_date


text:
Q: Calling fortran from R via C does not link I have a routine in fortran, which I wish to use in R via a C implementation. Suppose my fortran file is bivnt.f. Now, R CMD SHLIB C_Binary.c and R CMD SHLIB bivnt.f do not give any problem but when it comes to linking I obtain
> dyn.load("bivnt.so")
> dyn.load("C_Binary.so")
Errore in dyn.load("C_Binary.so") :
  unable to load shared object '/Users/erlisruli/Dropbox/WPapers/ABC-cs/Rcode/CorBinData/C_Binary.so':
  dlopen(/Users/erlisruli/Dropbox/WPapers/ABC-cs/Rcode/CorBinData/C_Binary.so, 6): Symbol not found: _smvbvt_
  Referenced from: /Users/erlisruli/Dropbox/WPapers/ABC-cs/Rcode/CorBinData/C_Binary.so
  Expected in: flat namespace
 in /Users/erlisruli/Dropbox/WPapers/ABC-cs/Rcode/CorBinData/C_Binary.so

this seems pretty strange to me, since from nm I obtain
$ nm bivnt.so
0000000000003940 s _a.1868
                 U _asin
                 U _atan
                 U _atan2
                 U _exp
0000000000003540 T _mvbvn_
00000000000027a0 T _mvbvt_
0000000000002610 T _mvbvtc_
0000000000002040 T _mvbvtl_
0000000000002d10 T _mvbvu_
0000000000001f20 T _mvphi_
0000000000002b80 T _mvstdt_
                 U _sin
00000000000038a0 T _smvbvt_
0000000000003ba0 s _w.1368
0000000000003aa0 s _x.1369
                 U dyld_stub_binder

Any clue?
P.S. the C_Binary.c is
#include<R.h>
/* Calcolo ripartizione normale bivariata */
void F77_SUB(smvbvt)( double* , int* , double*, double* , int* , double* ) ;

void biv_pmnorm( double *prob , int *nu, double *lower , double *upper , int *flag , double *corr )
{
  F77_CALL(smvbvt)( prob , nu , lower , upper , flag , corr ) ;
}
//pairwise log-likelihood-->output: units
void bin_pairwise_llik( double *res , double *data , double *cov, double *theta , int *n , int *nc  ) /* n = #righe ; nc = #colonne*/
{
    register int k, i, j, ite=0;
    int nu=0, flag[2];
    double res2=0.0 , res3=0.0, corr=theta[2], lower[2], upper[2];

    for( k=0; k<*n; k++ )
    {
        for( i=0; i<(*nc-1); i++ )
        {
            for( j=(i+1); j<*nc; j++ )
            {
                 if(*(data + i + k**nc)==1)
                 {
                     lower[0] = -*(theta+0)-*(theta+1)**(cov + i + k**nc);
                     upper[0] = 0.0;
                     flag[0]  = 1;
                 }
                 else
                 {
                     lower[0] = 0.0;
                     upper[0] = -*(theta+0)-*(theta+1)**(cov + i + k**nc);
                     flag[0]  = 0;

                 }

                 if(*(data + j + k**nc)==1)
                 {
                     lower[1] = -*(theta+0)-*(theta+1)**(cov + j + k**nc);
                     upper[1] = 0.0;
                     flag[1]  = 1;
                 }
                 else
                 {
                     lower[1] = 0.0;
                     upper[1] = -*(theta+0)-*(theta+1)**(cov + j + k**nc);
                     flag[1]  = 0;
                 }

                 biv_pmnorm( &res2, &nu, lower, upper, flag, &corr ) ;
                 res3+=log(res2);
                 ite += 1;
            }
        }
         res[k]=res3;
         res3=0.0;
    }
}

//pairwise log-likelihood-->output: one value
void bin_pairwise_llik_sum( double *res , double *data , double *cov, double *theta , int *n , int *nc  ) /* n = #righe ; nc = #colonne*/
{
    register int k, i, j, ite=0;
    int nu=0, flag[2];
    double res2=0.0 , corr=theta[2], lower[2], upper[2];
    *res=0.0;

    for( k=0; k<*n; k++ )
    {
        for( i=0; i<(*nc-1); i++ )
        {
            for( j=(i+1); j<*nc; j++ )
            {
                 if(*(data + i + k**nc)==1)
                 {
                     lower[0] = -*(theta+0)-*(theta+1)**(cov + i + k**nc);
                     upper[0] = 0.0;
                     flag[0]  = 1;
                 }
                 else
                 {
                     lower[0] = 0.0;
                     upper[0] = -*(theta+0)-*(theta+1)**(cov + i + k**nc);
                     flag[0]  = 0;

                 }

                 if(*(data + j + k**nc)==1)
                 {
                     lower[1] = -*(theta+0)-*(theta+1)**(cov + j + k**nc);
                     upper[1] = 0.0;
                     flag[1]  = 1;
                 }
                 else
                 {
                     lower[1] = 0.0;
                     upper[1] = -*(theta+0)-*(theta+1)**(cov + j + k**nc);
                     flag[1]  = 0;
                 }

                 biv_pmnorm( &res2, &nu, lower, upper, flag, &corr ) ;
                 *res+=log(res2);

                 ite += 1;
            }
        }
    }
}


text:
Q: How to hide a static variable in Java I have three classes with same methods and only constants are different. So what I wanted is to create one base class, which contains all the methods and to add three child classes which contain only constant variables. It looks like it is not possible to do so because of the dynamic binding. Please look at the example:
public class Parent {
    static String MY_CONSTANT = "bla bla";
    public void printSomething() {
        System.out.println(MY_CONSTANT);
    }
}

public class Child extends Parent {
    static String MY_CONSTANT = "hello world";
}

public class Greetings {
    public static void main(String[] args) {
        Child hey = new Child();
        hey.printSomething();
    }
}

The output is "bla bla", but I want the output to be "hello world".
Is there some solution for this problem?

A: You'll have to override the printSomething() method:
public class Child extends Parent {
    static String MY_CONSTANT = "hello world";

    @Override
    public void printSomething() {
        System.out.println(MY_CONSTANT);
    }
}

It might be cleaner, though, to have a method that returns the value of the static variable. Then you can override that method, and call it from the base class:
public class Parent {
    static String MY_CONSTANT = "bla bla";

    public String getConstant() {
        return Parent.MY_CONSTANT;
    }
    public void printSomething() {
        System.out.println(getConstant());
    }
}

public class Child extends Parent {
    static String MY_CONSTANT = "hello world";

    @Override
    public String getConstant() {
        return Child.MY_CONSTANT;
    }
}

public class Greetings {
    public static void main(String[] args) {
        Child hey = new Child();
        hey.printSomething();
    }
}

A:
How to hide a static variable in Java?

This is all you can do for variables: hide them. Although variables can be inherited, they cannot be overridden.
As actual values are class-specific and static, the only way to reuse a method in this scenario, is by making it take parameters:
public class Parent {
    static String MY_CONSTANT = "bla bla";

    public void printSomething(String something) {
        System.out.println(something);
    }

    //Essentially, Parent.MY_CONSTANT becomes just the default
    public void printSomething() {
        System.out.println(MY_CONSTANT);
    }
}

And the child can choose what it sends (overriding is basically to reuse the API):
public class Child extends Parent{
    static String MY_CONSTANT = "hello world";

    @Override
    public void printSomething() {
        //MY_CONSTANT is hidden and has "hello world"
        super.printSomething(MY_CONSTANT);
    }
}

The above design allows calls from the test class to behave predictably (or, rather, intuitively):
Child hey = new Child();
//Behaves as Child.
hey.printSomething();

EDIT: Since the getter is an instance method (understandable as you depend on the instance type to read the correct value), you can expose to children the field, or a setter, and all sorts of hiding would be suppressed completely:
public class Parent {
    protected String myConstant = "bla bla";

    public void printSomething() {
        System.out.println(this.myConstant);
    }
}

And children would just have to set the value in an initialization block:
public class Child extends Parent{
    public Child() {
        myConstant = "hello world";
    }
}

A: public class Parent {

    static String MY_CONSTANT = "bla bla";

    public void printSomething() {
        System.out.println(Child.MY_CONSTANT);
    }
}

public class Child extends Parent{
        static String MY_CONSTANT = "hello world";

        @Override
        public void printSomething() {
            super.printSomething(); // definition define in parent class
        }
    }
public class LeapTEST {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

            Child child = new Child();
            child.printSomething();
    }

}

A: If you want to use a constant you should combine the static modifier with the final one. The final modifier indicates that the value of this field cannot change (have a look to this link, in the related section). (A static variable is common for all instances of the class. A final variable can not change after it has been set the first time).
If you have a look the Java Language Specification:

A hidden field can be accessed by using a qualified name if it is
  static, or by using a field access expression that contains the
  keyword super or a cast to a superclass type.

So you can refer a static variable outside the class using ClassName.myStaticVariable:
And since you should access them in this way, there is also no need to worry about hiding them.

A: I reached the same problem and my solution instead of extending the parent class was by using an enum like this:
public enum MyEnum {
    PARENT("Parent constant"),
    CHILD("Child constant");
    private String myConstant;
    MyEnum(String s) {
        myConstant = s;
    }

    public void printConstant(){
        System.out.println(myConstant);
    }
}

And then, call the printConstant method of the desired enum like:
MyEnum.CHILD.printConstant();

Of course, this is limited but it suites my case so i hope it will help someone too.


text:
Q: How to validate an ID token signature with apple as an alternative to google oauth2 Hello all i have created with google oauth api an easy way to validate an ID token signature for debugging by using  the tokeninfo endpoint.
To validate an ID token using the tokeninfo endpoint, i make an HTTPS POST or GET request to the endpoint, and pass my ID token in the id_token parameter. For example, to validate the token "XYZ123", make the following GET request:
https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123
If the token is properly signed and has the appropriate values I got an HTTP 200 response (i follow this guide https://developers.google.com/identity/sign-in/web/backend-auth)
What is the alternative choice within apple? Any recommendations on how to fix the exact same thing for apple?
Here is an example of my code:
$curl = curl_init();

            curl_setopt_array($curl, array(
              CURLOPT_URL => 'https://oauth2.googleapis.com/tokeninfo?id_token=' . $request->input('token'),
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'GET',
            ));

            $response = curl_exec($curl);
            curl_close($curl);
            $responseDecoded = json_decode($response);

            if (isset($responseDecoded->error)) //FAILED TO GOOGLE AUTHENTICATED
            {
                if ($responseDecoded->error=='invalid_token')
                {
                    return response()->json(['status' => 'fail', 'message'=>'invalid_token']);
                }
            }

A: A key thing to understand here:

*

*There are a myriad of ways for users to sign in - one of them is Apple - they come and go - see the Curity Authenticators Page to get a feel for this.

*Protecting your data should work the same in all cases.
So if you base your data protection around Apple it will just not work for people who do not use Apple to sign in and you are restricting your possibilities.
Here is how the solution should work:

*

*Your UIs and APIs talk to an Authorization Server (AS)

*The AS manages the connection to Apple and the 25 other possible authentication methods

*Every time you add a new authentication option, zero code needs to change in any of your UIs and APIs

*Your UI and API code remains simple and portable over time

To summarize, I would recommend your apps talk to Google OAuth2 - which helps to protect your data, whereas Apple should play a smaller role of being an authentication method - Google should talk to Apple for you.
At Curity we provide a Sign in with Apple capability. Our main mission is around protecting data though ...
ID TOKEN VALIDATION
If this is received in a browser response it should be validated by the app. This usually involves downloading token signing public keys from the Authorization Server. Some providers may give you an endpoint that does this as in the Google case.
Apple provide some (non standard) behavior as in this link to do an equivalent thing.
But coding this in your app is likely to lead to further problems later, when you try to implement authorization. Note also that an ID token should not be used to protect data in APIs - use access tokens instead.


text:
Q: projectVector results not between -1 and 1 (three.js) Note: code below updated with WestLangley's fix.
I've tried several examples of projecting from 3D to 2D.  However, when I try to use projectVector the result is not between -1 and 1, and so when I multiply by my window's width/height I get extravagantly large numbers (much larger than my screen resolution).  Hoping that my problem is something simple.  I'm using three.min.js r56, and my inner window dimensions are 1366x418.
The code below yields a projected (x,y) of: (-7.874704599380493,-13.403168320655823) for the 3D point (1200,625,100).  I know I still need to multiple this result by something like half my window height and width, but the resulting (x,y) in pixels is way off the screen.
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

<script type="text/javascript" src="three.min.js"></script>
</head>
<body>
<canvas id='container'></canvas>

<script>

    /// GLOBAL VARIABLES
    var camera, scene, renderer, container, projector;

    init();

    function toXYCoord (object) {
        var vector = projector.projectVector(object.position.clone(), camera);
        return vector;
    }

    /// INIT
    function init() {

        scene = new THREE.Scene();

        camera = new THREE.PerspectiveCamera(  50, window.innerWidth / window.innerHeight, 0.1, 20000 );
        scene.add(camera);
        camera.position.set(0,-1500,1500);
        camera.lookAt(scene.position);
        camera.updateMatrixWorld();     ///////////////// THIS IS THE FIX
        projector = new THREE.Projector();

        // sphere
        var sphere = new THREE.Mesh( new THREE.SphereGeometry( 200, 32, 16 ), new THREE.MeshBasicMaterial({ color: 0x000000 }) );
        sphere.position.set(1200,625,100);
        scene.add(sphere);

        container = document.getElementById('container');
        renderer = new THREE.WebGLRenderer( { canvas: container, antialias:true } );
        renderer.setSize( window.innerWidth, window.innerHeight );

        var testVector = toXYCoord(sphere);

        console.log(window.innerWidth + "x" + window.innerHeight);
        console.log("Got: (" + testVector.x + "," + testVector.y + ")");

        renderer.render( scene, camera );
    }

</script>

</body>
</html>

A: The renderer does some calculations for you that are normally done in the render loop.
They are not being done in your case because you have placed your single call to render() as the last line of your script.
You need to place the following line after camera.lookAt():
camera.updateMatrixWorld();

Alternatively, you can move your
renderer.render( scene, camera );

call so it occurs before your call to your toXYCoord() function.


text:
Q: Does an exception use move semantics when thrown in C++11? http://www.drdobbs.com/cpp/practical-c-error-handling-in-hybrid-env/197003350?pgno=4
In this article Herb Sutter explains that throwing an exception requires a copy of the exception as it's created as a temporary and therefore uses an std::auto_ptr to get round the copy overhead. In light of move semantics being made available in C++11 is this still necessary?

A: Move from exception objects is not mandatory now.
It's a defect of C++11. See CWG1493 .

A: I have just checked, and the Standard allows

*

*omitting the copy or move of an object specified by the operand of a throw expression into the exception object

*omitting the copy or move of the exception object into the catch clause variable of the same type as the exception object if you don't otherwise change the meaning of the program (i.e if you would rethrow and subsequent catches would suddenly see a changed exception object changed by the previous catch block).

Since these omissions are allowed, the spec requires to first regard the source of the copy or move as an rvalue. So this means that the respective objects will be moved if possible. Of course copy and move elision are still allowed as the first choice.

Update
I was notified that the consideration of the exception object initializer of a catch clause parameter as an rvalue initializer will probably be dropped from the Standard (because in general it is not possible for all cases to detect when the behavior of the program is unchanged when omitting a copy/move), so I recommend to not rely on this (second bullet above).
What you can still rely about is the move of a local variable into the exception object, as in throw x; (first bullet above).

A: *
*Upon throw expression, a copy of the exception object always needs to be created as the original object goes out of the scope during the stack unwinding process.
*During that initialization, we may expect copy elision (see this) – omits copy or move constructors (object constructed directly into the storage of the target object).
*But even though copy elision may or may not be applied you should provide proper copy constructor and/or move constructor which is what C++ standard mandates(see 15.1). See below compilation error for reference.

But modern C++ provides more feature: "Moving safely with move semantics & exception"
struct demo
{
    demo() = default;
    demo(const demo &) { cout << "Copying\n"; }
    // Exception safe move constructor
    demo(demo &&) noexcept { cout << "Moving\n"; }
private:
    std::vector<int>    m_v;
};
int main()
{
    demo obj1;
    if (noexcept(demo(std::declval<demo>()))){  // if moving safe
        demo obj2(std::move(obj1));             // then move it
    }
    else{
        demo obj2(obj1);                        // otherwise copy it
    }
    demo obj3(std::move_if_noexcept(obj1));     // Alternatively you can do this----------------
    return 0;
}

*
*We can use noexcept(T(std::declval<T>())) to check if T's move constructor exists and is noexcept in order to decide if we want to create an instance of T by moving another instance of T (using std::move).
*Alternatively, we can use std::move_if_noexcept, which uses noexcept operator and casts to either rvalue or lvalue. Such checks are used in std::vector and other containers.
*This will be useful while you are processing critical data which you don't want to lose. For example, we have critical data received from the server that we do not want to lose it at any cost while processing.  In such a case, we should use std::move_if_noexcept which will move ownership of critical data only and only if move constructor is exception-safe.

From: 7 best practices for exception handling in C++


text:
Q: Turn results of a raw SQL query to JSON (and CSV) I need to pull data from a legacy SQL Server database and turn it into JSON.  I have SQL queries already written (for legacy versions of reports, that I'm replacing) that extracts exactly what I need.
It is of course easy to turn ActiveRecord objects to JSON (and CSV), but I don't see any good way to do what I need to do, since all the ActiveRecord methods involving raw SQL seem to be aimed at returning ActiveRecord objects, and this data doesn't necessarily logically correspond to a class, and I don't need to persist it anywhere additional.  I just want to perform the SQL query and return JSON and CSV and be done with it.

A: in your controller, you could add:
render json: @result

or
render :json => @result

and that would render something like this:
 {id: 1, name: "user name", color: "red"}

A: I'd recommend sequel.
From Querying with Sequel:
require 'sequel'

DB = Sequel.connect # database information goes here

class Thing < Sequel::Model
end

result_objects = DB["SELECT * FROM things"].all

Then simply parse the result_objects into JSON:
require 'json'

hashes = result_objects.collect { |ro|
  ro.to_hash
}

JSON.generate(hashes)


text:
Q: Enable Google API OAuth Scope For one of the application created using Google Apps Script, some scopes are automatically added as follows in my app:
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/script.external_request
https://www.googleapis.com/auth/script.send_mail
https://www.googleapis.com/auth/spreadsheets
I've followed all the steps for OAuth Client Verification according to this documentation. But still, my verification process is pending and support team said that I need to add https://www.googleapis.com/auth/drive.file scope to my project.
Anybody know how to add/enable https://www.googleapis.com/auth/drive.file scope in the existing project.

A: When you authenticate your application you should request the additional scope

*

*Open the script project in the Apps Script editor.

*In the menu, select File > Project properties.

*Select the Scopes tab.

*Review the scopes your script currently requires and determine what changes need to be made. Click Cancel when finished.

*If the manifest file appsscript.json isn't visible in the left nav bar, select the View > Show manifest file menu item.

*Select the appsscript.json file in the left nav to open it.

*Locate the top-level field labeled oauthScopes. If it is not present, you can add it.

*The oauthScopes field specifies an array of strings.

example
{
  ...
  "oauthScopes": [
    " https://www.googleapis.com/auth/drive.file",
    "https://www.googleapis.com/auth/userinfo.email"
  ],
}

check the documentation here


text:
Q: How to get the sibling of an xml node I have an xml file as below
<Games>
   <Game>
      <name>Tzoker</name>
      <file>tzoker1</file>
   </Game>
   <Game>
      <file>lotto770</file>
   </Game>
   <Game>
      <name>Proto</name>
      <file>proto220</file>
   </Game>
</Games>

I want to get the values of name and file items for every Game node.
It is easy by using this query.
string query = String.Format("//Games/Game");
 XmlNodeList elements1 = xml.SelectNodes(query);
 foreach (XmlNode xn in elements1)
 {
   s1 = xn["name"].InnerText;
   s2 = xn["file"].InnerText;
 }

The problem is that there are some nodes that they don't have the name item. So the code above doesn't work.
I have solved the problem by using the following code
string query = String.Format("//Games/Game/name");
XmlNodeList elements1 = xml.SelectNodes(query);
foreach (XmlNode xn in elements1)
{
  s1 = xn.InnerText;
  string query1 = String.Format("//Games/Game[name='{0}']/file", s1);
  XmlNodeList elements2 = xml.SelectNodes(query1);
  foreach (XmlNode xn2 in elements2)
  {
    s2 = xn2.InnerText;
  }
}

The problem is that there is a case that two or more nodes have the same name value. So, the s2 variable will get the file value of the last node that the loop finds. So, I would like to find a way to get the sibling file value of the current name item. How could I do it? I try do move to the parent node of the current node and then to move to the file item but without success by using the following code.
string query = String.Format("//Games/Game/name");
XmlNodeList elements1 = xml.SelectNodes(query);
foreach (XmlNode xn in elements1)
{
   s1 = xn.InnerText;
   string query1 = String.Format("../file");
   XmlNodeList elements2 = xml.SelectNodes(query1);
   foreach (XmlNode xn2 in elements2)
   {
     s2 = xn2.InnerText;
   }
}

I hope there is a solution.

A: If I understand you correctly you want to find all games that have a name. You can do that using XPath. Here is a solution that uses LINQ to XML. I find that easier to work with than XmlDocument:
var xDocument = XDocument.Parse(xml);
var games = xDocument
  .Root
  .XPathSelectElements("Game[child::name]")
  .Select(
    gameElement => new {
      Name = gameElement.Element("name").Value,
      File = gameElement.Element("file").Value
    }
  );

The XPath to select all <Game> elements that have a <name> child element is Game[child::name].

A: You can use Game[name] to filter Game elements to those with child element name. This is possible because child:: is the default axes which will be implied when no explicit axes mentioned. Extending this further to check for child element file as well, would be as simple as Game[name and file] :
string query = String.Format("//Games/Game[name]");
XmlNodeList elements1 = xml.SelectNodes(query);
foreach (XmlNode xn in elements1)
{
   s1 = xn["name"].InnerText;
   s2 = xn["file"].InnerText;
}

Now to answer your question literally, you can use following-sibling:: axes to get sibling element that follows current context element. So, given the context element is name, you can do following-sibling::file to return the sibling file element.

Your attempt which uses ../file should also work. The only problem was, that your code executes that XPath on xml, the XmlDocument, instead of executing it on current name element :
XmlNodeList elements2 = xn.SelectNodes("../file");


text:
Q: Informal Proof for tautology I proved the following tautology formally using a truth table:
$$((A \to B) \land (A \to C)) \to (A \to (B \land C)).$$

What would an Informal proof (non-symbolic) in the English Language to show this is a tautology look like ?

A: General comment: If I had a pound for every exam answer I've marked over the years where someone has "proved" that $X$ is/isn't a tautology or is/isn't valid, when a moment's informal argumentation would have shown them that their answer can't be right, then ... well, I'd not be rich, but at least could have bought a few more drinks along the way!
So, yes, faced with a claim that so-and-so is or isn't a tautology (or that such-and-such is or isn't a tautologically valid inference), it is often a very good instinct to ask yourself "what's an informal argument for this?"

Specific response: In this case something as informal as the following is enough to make it clear that the proposition given should indeed come out as  a tautology:

Suppose we get B if A is true, and also get C if A is true; then if A
  is true we get both B and C.

Of course, this sort of very informal reasoning can only take us so far, and can sometimes lead us astray. But that's why we have formal logical systems, to regiment and systematize argumentation!

A: Well, I am not sure if this is what you are looking for but here is another way to express it:
If we use the fact that $X \implies Y = \lnot X \lor Y$ here, we have:
$$((A \implies B) \land (A \implies C)) \implies (A \implies (B \land C))$$ $$= ((\lnot A \lor B) \land (\lnot A \lor C)) \implies (\lnot A \lor (B \land C))$$ $$= ((\lnot A \lor B) \land (\lnot A \lor C)) \implies ((\lnot A \lor B) \land (\lnot A \lor C))$$
which is $1$ because the expression before the $\implies$ is same as the expression after $\implies$. So we can write it as $D \implies D = 1$ where $D =(\lnot A \lor B) \land (\lnot A \lor C) $.

A: If $A$ implies $B$, and $A$ implies $C$, then $A$ implies both $B$ and $C$.


text:
Q: Walmart Seller API POST not working I am attempting to POST to the Walmart Seller API using CURL i PHP to acknowledge orders.
https://developer.walmartapis.com/#acknowledging-purchase-orders
for some reason it will not accept my method or it returns "Bad Request".
anyone with experience in this?
$apiheaders = array(
'WM_SVC.NAME: Walmart Marketplace',
'WM_QOS.CORRELATION_ID: 1466113345',
'WM_SEC.TIMESTAMP:1466113345447',
'WM_SEC.AUTH_SIGNATURE: XXXXXXXXXXX'
'WM_CONSUMER.ID: XXXXXXXXXXX',
'Content-Type: application/xml',
'Accept: application/xml',
 );

$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, $apiheaders);
curl_setopt($curl, CURLOPT_URL,$return_api_host);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
$response = curl_exec($curl);
curl_close($curl);

A: In my case the issue was from my header signature. Not shown here. Don't forget to create the signature for the correct type of transmission. Eg post,get etc. I had it set as get on my previous calls and did not make it a variable as it should have been.
Feel free to post your example so we can see.

A: <?php
$consumer_id='xxxxxxxxxx';
$private_key='xxxxxxxxxx';
$timestamp='xxxxxxxx';
$correlation_id='xxxxxxxxxxx';
$channel_id='xxxxxxxxxx';

$endPoint = "v3/orders/".$purchaseOrderId."/acknowledge";
$requestUrl = "https://marketplace.walmartapis.com/$endPoint";
$requestMethod = 'POST';
$signature = new Signature($consumer_id, $private_key, $requestUrl,$requestMethod);
$actual_signature = $signature->getSignature($timestamp);

$headers = [];
$headers[] = "WM_SVC.NAME: Walmart Marketplace";
$headers[] = "WM_QOS.CORRELATION_ID: ".$correlation_id;
$headers[] = "WM_SEC.TIMESTAMP: ".$timestamp;
$headers[] = "WM_SEC.AUTH_SIGNATURE: ".$actual_signature;
$headers[] = "WM_CONSUMER.ID: " .$consumer_id;
$headers[] = "Content-Type: multipart/form-data";
$headers[] = "Accept: application/xml";
$headers[] = "WM_CONSUMER.CHANNEL.TYPE: ".$channel_id;
$headers[] = "HOST: marketplace.walmartapis.com";

$body['data'] = array();

$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $requestUrl );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_HEADER, 1 );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $body );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
$server_output = curl_exec ( $ch );
?>


text:
Q: Ruby build .where over two classes I'm in trouble building my .where to retrieve specific Values.
I have this hierarchy:
-Customer
--has_many Projects
---has_many Tickets
I want to retrieve all Tickets by a customer ID as an ActiveRecord::Relation.
My idea was this loop (c is the customer from whom I want the tickets):
customer_projects = Project.where(:customer_id => c.id)
  tickets = ActiveRecord::Relation.new(Ticket, anything)
  customer_projects.each do |cp|
    project_tickets = Ticket.where(:project_id => cp.id).where("DATE(created_at) >= ?", report.start_time).where("DATE(created_at) <= ?", report.end_time)
    tickets.insert(project_tickets)
  end

I am neither sure where to write for "anything" as table argument, nor if this even works.  I'd prefer a "simple" .where that could retrieve all tickets.

A: You don't need all this hassle. You have the through method to do it for you.
# customer.rb
has_many :tickets, through: projects

# ticket.rb
has_many :customers, through: projects

This way, you can do:
@customer.tickets
@ticket.customers


text:
Q: Calculating daily max and min temperature data from GLDAS over several years using Google Earth Engine I am still new to the Google Earth Engine and try to calculate the daily max and min temperature based on the GLDAS.
Could you advise me on how I correct this code to calculate daily max and min temperature?
var startDate = ee.Date('2018-01-01');
var endDate = ee.Date('2021-01-01');

// Specify Country names
var worldcountries = ee.FeatureCollection('FAO/GAUL/2015/level2');

var filterCountry = ee.Filter.eq('ADM2_NAME', 'Kurgantepa district');

var country = worldcountries.filter(filterCountry);

Map.addLayer(country);
Map.centerObject(country, 10);

var dataset = ee.ImageCollection("NASA/GLDAS/V021/NOAH/G025/T3H")
  .select('Tair_f_inst')
  .filterDate(startDate, endDate);

var list_dataset = dataset.toList(dataset.size());

print(list_dataset);

var getTemperature = function(image) {

  var value_temperat = ee.Image(image)
    .reduceRegion(ee.Reducer.first(), country)
    .get('Tair_f_inst');

var temperat_K = ee.Number(value_temperat);

  return temperat_K;
};

var count = dataset.size();

var temperat_list = dataset.toList(count).map(getTemperature);

print("Tair_f_inst list", temperat_list);

var allDates = ee.List(dataset.aggregate_array('system:time_start'));

var allDatesSimple = allDates.map(function(date){
  return ee.Date(date).format().slice(0,10);
  });

print(allDatesSimple);

var len = temperat_list.size();

print(len);

var paired = allDatesSimple.zip(temperat_list);

print (paired);

var title = {
  title: 'Daily Temperature',
  hAxis: {title: 'Time'},
  vAxis: {title: 'Temperature (K)'},
};

var chartDaily = ui.Chart.image.seriesByRegion({
  imageCollection: dataset,
  regions: country,
  reducer: ee.Reducer.mean(),
  band: 'Tair_f_inst',
  scale: 5000,
  xProperty: 'system:time_start',
  seriesProperty: 'SITE'
}).setOptions(title)
  .setChartType('ColumnChart');

print(chartDaily);

var myFeatures = ee.FeatureCollection(paired.map(function(el){
  el = ee.List(el); // cast every element of the list
  var geom = country;
  return ee.Feature(null, {
    'date': ee.String(el.get(0)),
    'value':ee.Number(el.get(1))
  });
}));

//print(myFeatures);

// Export features, specifying corresponding names.
Export.table.toDrive(myFeatures,
"Temperature", //my task
"GEE_Folder", //my export folder
"daily_temperat",  //file name
"CSV");

A: GLDAS products have images with climatic elements for each three hours so, you will have 8 values per day of temperatures. In this case, you need to map your temperatures list for slicing each eight values. In these slices, you can apply a min reducer for minimum temperatures and a max reducer for maximum temperatures. However, produced temperatures list must be paired with distinct dates list (not with original dates list with 8 times values). Following script works as expected.
var startDate = ee.Date('2018-01-01');
var endDate = ee.Date('2021-01-01');

// Specify Country names
var worldcountries = ee.FeatureCollection('FAO/GAUL/2015/level2');

var filterCountry = ee.Filter.eq('ADM2_NAME', 'Kurgantepa district');

var country = worldcountries.filter(filterCountry);

Map.addLayer(country);
Map.centerObject(country, 10);

var dataset = ee.ImageCollection("NASA/GLDAS/V021/NOAH/G025/T3H")
  .select('Tair_f_inst')
  .filterDate(startDate, endDate);

var list_dataset = dataset.toList(dataset.size());

print(list_dataset);

var getTemperature = function(image) {

  var value_temperat = ee.Image(image)
    .reduceRegion(ee.Reducer.mean(), country)
    .get('Tair_f_inst');

  return value_temperat;

};

var count = dataset.size();

var temperat_list = dataset.toList(count).map(getTemperature);

//print("Tair_f_inst list", temperat_list);

var len = temperat_list.size();

var list = ee.List.sequence(0, len.subtract(1), 8);

var temp_list = list.map(function(ele){

  var start = ee.Number(ele).int();
  var end = ee.Number(ele).add(8).int();

  var new_list = ee.List([]);
  var element = ee.List(temperat_list.slice(start, end)).reduce(ee.Reducer.min());

  new_list = new_list.add(element);

  var element2 = ee.List(temperat_list.slice(start, end)).reduce(ee.Reducer.max());

  new_list = new_list.add(element2);

  return new_list;

});

print("temp_list", temp_list);

var allDates = ee.List(dataset.aggregate_array('system:time_start'));

var allDatesSimple = allDates.map(function(date){
  return ee.Date(date).format().slice(0,10);
  }).distinct();

print("distinct dates list", allDatesSimple);

var len = temperat_list.size();

//print(len);

var paired = allDatesSimple.zip(temp_list);

print ("paired list", paired);

var title = {
  title: 'Daily Temperature',
  hAxis: {title: 'Time'},
  vAxis: {title: 'Temperature (K)'},
};

var chartDaily = ui.Chart.image.seriesByRegion({
  imageCollection: dataset,
  regions: country,
  reducer: ee.Reducer.mean(),
  band: 'Tair_f_inst',
  scale: 5000,
  xProperty: 'system:time_start',
  seriesProperty: 'SITE'
}).setOptions(title)
  .setChartType('ColumnChart');

//print(chartDaily);

var myFeatures = ee.FeatureCollection(paired.map(function(el){
  el = ee.List(el); // cast every element of the list
  var geom = country;
  return ee.Feature(null, {
    'date': ee.String(el.get(0)),
    'Tmin':ee.Number(ee.List(el.get(1)).get(0)),
    'Tmax':ee.Number(ee.List(el.get(1)).get(1))
  });
}));

//print(myFeatures);

// Export features, specifying corresponding names.
Export.table.toDrive(myFeatures,
"Temperature", //my task
"GEE_Folder", //my export folder
"daily_temperat",  //file name
"CSV");

After running above script in GEE console editor, you can see an extract of obtained CSV as follows:
system:index,Tmax,Tmin,date,.geo
0,283.12159660270623,274.85638262774495,2018-01-01,
1,283.22070862366274,274.42199638297967,2018-01-02,
2,283.75842133943024,275.1772416948198,2018-01-03,
3,281.7471648894989,275.3844425785649,2018-01-04,
4,280.8100086933858,274.43567458144184,2018-01-05,
5,282.165957064242,273.98338400351037,2018-01-06,
6,282.7080238960885,275.0355672750387,2018-01-07,
7,281.14597712336354,274.04015618401604,2018-01-08,
8,280.4689321432028,273.21697956806906,2018-01-09,
9,281.3570821951102,273.7503255208333,2018-01-10,
10,275.70246337340757,273.3154177279086,2018-01-11,
.
.
.


text: Q: ExpressionEngine custom extension to change date format I am trying to create an Extension to change my entries formatting in the way I want , I can create my custom extension and change the date format using hooks , but I don't know where to use my custom hooks to change entries date format. I hope that I was clear enough! Thanks a lot in advance.


text:
Q: Read each word in text file separately I have text file (words.text) includes lines each line have characters and equivalent words like this:
A = 1
B = 2
C = 3
D = 4

I used following code to read text file
     System.IO.StreamReader file =
    new System.IO.StreamReader(@"c:\words.txt");
    while((line = file.ReadLine()) != null)
    {
       System.Console.WriteLine (line);
       counter++;
    }

I need to change the value of each character (number)  by counter and saved it again in way to be like this
A = 3
B = 4
C = 1
D = 2

I thought about makes each word and = to be "first" and number is "second", and loop the second one
First = "A = ", Second = "1"

I have no idea how to make program to read each line and identified first and second one

A: You can simply split each line value by = character to get first and second value:
  System.IO.StreamReader file =
    new System.IO.StreamReader(@"c:\words.txt");
    while((line = file.ReadLine()) != null)
    {
       string[] split = line.Split('=');
       string First = split[0] + " = ";
       string Second = split[1];
       //actually you can use split[0] and split[1], the two above llines are for demo
       counter++;
    }

A: How about this...
// Getting content of the file.
string contents = File.ReadAllText(@"C:\test.txt");

// Separating content
string[] contentArr  = contents.Split('\n');

List<string> characterList = new List<string>();
List<int> valueList = new List<int>();

foreach (string value in contentArr)
{
    characterList.Add(string.Join("", value.ToCharArray().Where(Char.IsLetter)).Trim());
    valueList.Add(Int32.Parse(string.Join("", value.ToCharArray().Where(Char.IsDigit))));
}

All the characters will be stored in the characterList as a string and all the value will be stored in the valueList as integers (int).
If you need to read or change values, you can do it like this using a forloop (or a foreach).
for (int i = 0; i < contentArr.Length; i++)
{
    //valueList[i] = 5
    Console.WriteLine(characterList[i] + " = " + valueList[i]);
}

//// characters
//foreach(string value in characterList)
//{
//  Console.WriteLine(value);
//}

//// Values
//foreach(int value in valueList)
//{
//  Console.WriteLine(value);
//}

Or, you can change value individually...
valueList[0] = 3;
valueList[1] = 4;
valueList[2] = 1;
valueList[3] = 2;

After making changes, you can write back to the file.
string output = "";

for (int i = 0; i < contentArr.Length; i++)
{
    output += characterList[i] + " = " + valueList[i] + Environment.NewLine;
}

File.WriteAllText(@"C:\test.txt", output);

Online Sample 01: http://rextester.com/TIVM24779
Online Sample 02: http://rextester.com/KAUG79928


text:
Q: Windows Phone 7 Development - Do I need a Service Provider With the upcoming WP7 release, I am wanting to develop against the framework.  I have an iPhone and don't want to get away from using that service.  I know Visual Studio has tools to emulate the WP7 device for testing one's apps but this is not a true test.  I was wondering if it is possible to get a WP7 without a service, e.g. AT&T, and do development?
Are there many drawbacks?
Thanks!

A: You can access the net fine using wifi or connected to the pc via it's lan.

A: Not entirely sure what your question is but, you can get devices on Pay-As-You-Go tarrifs and network unlocked. What is available and how much it will cost will depend on which country you are in and who you buy it from.
Once you have an account with the marketplace, you can unlock any phone for development.
There are limits on the number of phones you can unlock though.


text:
Q: How to cache Rails API actions What is the best and correct approach to do caching for actions?

*

*Am I forced to ActionController::Base?

*Is there another way (keeping ActionController::API present)?

*Do I have to push caching down to Model layer?

I saw that Rails 6 (maybe prior) does not support action caching out of the box anymore. The caching was extracted to a gem: actionpack-action_caching https://github.com/rails/actionpack-action_caching. I installed it, but it seems not working with ActionController::API, it only works with ActionController::Base.
class ApplicationController < ActionController::API
must be changed to
class ApplicationController < ActionController::Base
Then, and only then I can cache an action like so:
    class CategoryController < ApplicationController
      caches_action :index
      def index
        @root_categories = Category.roots
      end
    end

Thank you in advance

A: The gem adds these methods to your controllers by including ActionController::Caching in ActionController::Base (see here). To add this behaviour to controllers that don't extend from ActionController::Base, simply include ActionController::Caching.
e.g.
class ApplicationController < ActionController::API
  include ActionController::Caching
end


text:
Q: wxPython - lines drawn with Device Context disappear when focus changes I've written this small app that draws lines between two points selected by the user and it works but how do I keep the lines I draw from disappearing whenever the window is minimized or gets covered by another open window?
class SimpleDraw(wx.Frame):
  def __init__(self, parent, id, title, size=(640, 480)):
    self.points = []
    wx.Frame.__init__(self, parent, id, title, size)

    self.Bind(wx.EVT_LEFT_DOWN, self.DrawDot)

    self.SetBackgroundColour("WHITE")
    self.Centre()
    self.Show(True)

  def DrawDot(self, event):
    self.points.append(event.GetPosition())
    if len(self.points) == 2:
        dc = wx.ClientDC(self)
        dc.SetPen(wx.Pen("#000000", 10, wx.SOLID))
        x1, y1 = self.points[0]
        x2, y2 = self.points[1]
        dc.DrawLine(x1, y1, x2, y2)
        # reset the list to empty
        self.points = []

if __name__ == "__main__":
  app = wx.App()
  SimpleDraw(None, -1, "Title Here!")
  app.MainLoop()

A: Your issue is that you are only drawing when the user clicks. The resize/erase (when another window covers yours) problems are because your window doesn't maintain a "buffer" which it can redraw.
Here, I've modified your sample, it seems to be working okay.
import wx

class SimpleDraw(wx.Frame):
    def __init__(self, parent, id, title, size=(640, 480)):
        self.points = []
        wx.Frame.__init__(self, parent, id, title, size)

        self.Bind(wx.EVT_LEFT_DOWN, self.DrawDot)
        self.Bind(wx.EVT_PAINT, self.Paint)

        self.SetBackgroundColour("WHITE")
        self.Centre()
        self.Show(True)
        self.buffer = wx.EmptyBitmap(640, 480)  # draw to this
        dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)
        dc.Clear()  # black window otherwise

    def DrawDot(self, event):
        self.points.append(event.GetPosition())
        if len(self.points) == 2:
            dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)
            dc.Clear()
            dc.SetPen(wx.Pen("#000000", 10, wx.SOLID))
            x1, y1 = self.points[0]
            x2, y2 = self.points[1]
            dc.DrawLine(x1, y1, x2, y2)
            # reset the list to empty
            self.points = []

    def Paint(self, event):
        wx.BufferedPaintDC(self, self.buffer)

if __name__ == "__main__":
    app = wx.App(0)
    SimpleDraw(None, -1, "Title Here!")
    app.MainLoop()

A: You have to structure your program differently in a GUI environment.  Typically, you maintain a data structure called your model.  In your case, you already have a start of one, self.points.  Then you only draw on the window in response to a paint event.  The windowing system will send you paint events when the window needs painting, including when it is first displayed, when it is maximized, and when it is revealed from beneath another window.
In your program, you'd bind the LeftDown event to a function that modifies self.points and invalidates the window, which would usually cause the windowing system to send you paint events.  You'd bind the Paint event to a function that draws on the window.


text:
Q: Parse second XML element in Python I have an XML file in the following format:
<item id="xxxxxx">
    <Category>xxxxx</Category>
    <EmpEmail>xxxxxx</EmpEmail>
    <EmployeeName>xxxxxxx</EmployeeName>
    <InteractionType>xxxxxx</InteractionType>
    <pxCreateOpName>xxxxxx</pxCreateOpName>
    <pyID>xxxxx</pyID>
    <WorkerInfo>
        <Country>xxxxx</Country>
        <JobTitle>xxxxxx</JobTitle>
        <Region>xxxxx</Region>
    </WorkerInfo>
    <InsKey>xxxxx</InsKey>
</item>

I am able to parse tags in the item element using
for item in root.findall('item'):
    row = []
    if item.find('Category') is not None:
        category = item.find('Category').text
    else:
        category = ''
    row.append(category)

But I cannot retrieve the tags under WorkerInfo using for item in root.findall('WorkerInfo').  What would be best way to get to this element?

A: Just add another loop like below. Also my indenting might be off.
for item in root.findall('item'):
row = []
if item.find('Category') is not None:
    category = item.find('Category').text
else:
     for itemsecond in root.findall('WorkerInfo'):
         if item.find('WorkerInfo') is not None:
             category2= item.find('Category').text
             if category2 is not None:
                row.append(category2)
row.append(category)

A: It look like WorkerInfo contains nested elements, and your first line for item in foot.findall('item'): will only loop over top level elements. So, at some point item will be set to WorkerInfo, but that is not the same as being set to its sub-elements. You will need a nested loop to loop over those. Try this:
for item in root.findall('item'):
    for workerItem in item.findall('WorkerInfo'):
        // Do whatever you want with the elements of WorkerInfo here

A: To get to WorkerInfo and retrieve its tags, you can use a similar structure. Just call findall() passing in 'WorkerInfo' and loop through its children.
for item in root.findall('item'):
    for worker in root.findall('WorkerInfo'):
        row = []
        for child in worker:
            row.append(child.tag)

With your example, row becomes ['Country', 'JobTitle', 'Region']


text:
Q: inserting trigger on same table after insert CREATE TABLE STUDENTS_1
(
NAME VARCHAR2(50)NOT NULL,
DIV VARCHAR2(5) CHECK (DIV IN ('E','F','G')),
MARKS NUMBER CHECK (MARKS <= 600),
GRADE VARCHAR2(5) CHECK (GRADE IN ('A','B','C'))
)

CREATE OR REPLACE TRIGGER MARKS
BEFORE INSERT OR UPDATE ON STUDENTS_1
FOR EACH ROW

BEGIN

IF (:NEW.MARKS>500)THEN
INSERT INTO STUDENTS_1(MARKS,GRADE)VALUES(:NEW.MARKS,'A');

ELSIF (:NEW.MARKS>400 AND:NEW.MARKS<500) THEN
INSERT INTO STUDENTS_1(MARKS,GRADE)VALUES(:NEW.MARKS,'B');

ELSE (:NEW.MARKS <400 )
INSERT INTO STUDENTS_1(MARKS,GRADE)VALUES(:NEW.MARKS,'C');

END IF ;
END;/

I would insert marks into this table and i want trigger to trigger grade accordingly into the same table with respect to what marks i'm entering and  i'm getting not enough values error when i'm doing this
So i wanted to know that what i'm doing is it possible or there's another way ??

A: There are several problems with this approach.  First of all, if you could insert into students_1 in an insert trigger on students_1, you'd create an infinite loop. You'd do an insert, firing the trigger, which would do an insert, which would fire the trigger, which would do an insert, which would fire the trigger...  Second, you presumably want to set the grade value for the current row, not create a new row.  The grade presumably relates to the mark of the row you are in the process of inserting.
You probably just want to update the grade in the :new pseudorecord
FOR EACH ROW
BEGIN
  case when :new.marks < 400
       then :new.grade := 'C';
       when :new.marks between 400 and 500
       then :new.grade := 'B';
       when :new.marks > 500
       then :new.grade := 'A';
   end case;
END;

If this is a real problem rather than a homework assignment that requires a trigger, you probably want a virtual column for grade that includes the calculation rather than writing a trigger to maintain a computed column.


text:
Q: typeahead.js prefetch doesn't work I can't get the prefetch function in typeahead.js to work, it works just fine with the local data though. I first tried linking to a servlet returning json objects or lists, but after a while I gave up on that and started checking the provided examples. So their examples links to pages that look like this:
http://twitter.github.io/typeahead.js/data/countries.json
However, my script doesn't even work when I link it to that page even if I do exactly the same thing as they do. I tried copying that file over to my local workspace and linking to it there to no avail. To check if it even were making any calls I made my servlet crash every time it got a get request, and sure enough it crashed when I ran my autocomplete example page so it isn't a cache problem. I tried downgrading jquery to 1.9.1, but that didn't work either(currently using 1.10). I tried using different versions of typeahead.js. I tried using internet explorer as well as google chrome to see if the error was there.
There must be something vital that I am missing, as I have exhausted every source of errors I could think of. Others don't seem to have any problems getting this to work.
Here is the code I use:
<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Demo</title>
    <link rel="stylesheet" type="text/css" href="typeahead.js-bootstrap.css">

</head>

<body>

    <script src="jquery.js"></script>
    <script src="typeahead.js"></script>

<input type="text" class="typeahead" placeholder="test" />
    <script>
    $(document).ready(function() {$('.typeahead').typeahead({
        name: "Auto"  ,
        ttl_ms: 10000,
        prefetch: 'http://twitter.github.io/typeahead.js/data/countries.json',
        //local: ['abc', 'acd', 'ade', 'bcd]
});});
    </script>
</body>
</html>

A: It seems the issue is related to caching of the data in the browser storage.

*

*You can clean your browser storage (not the browser cache).

*You can change the dataset name in typeahead config to another one.

*You can lower the ttl in prefetch. You can increase the ttl later, of course. See below:
prefetch: {
    url: 'http://twitter.github.io/typeahead.js/data/countries.json',
    ttl: 1 // in milliseconds
},

It will be more clear if you browse the code here: http://goo.gl/TN3Gv


text:
Q: I am trying to launch Firefox using geckodriver for selenium webDriver in Ubuntu 22.04.1 LTS and got error msg as - rg.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: LINUX
Build info: version: '4.0.0', revision: '3a21814679'
System info: host: 'rashed-hp', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '5.15.0-43-generic', java.version: '18.0.2'
Driver info: driver.version: FirefoxDriver
at org.openqa.selenium.firefox.FirefoxBinary.<init>(FirefoxBinary.java:95)
at java.base/java.util.Optional.orElseGet(Optional.java:364)
at org.openqa.selenium.firefox.FirefoxOptions.getBinary(FirefoxOptions.java:189)
at org.openqa.selenium.firefox.GeckoDriverService$Builder.withOptions(GeckoDriverService.java:179)
at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:232)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:186)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:164)
at BrowserTest.firefoxSession(BrowserTest.java:18)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

Process finished with exit code 255
enter code here

A: Make sure that Firefox must install on the default place like ->
(c:/Program Files (x86)/Mozilla Firefox

OR
c:/Program Files/Mozilla Firefox, note: at the time of Firefox installation do not change the path so let it installing in default path)
If Firefox is installed on some other place then selenium show those error.
If you have set your Firefox in Systems(Windows) environment variable then either remove it or update it with new Firefox version path.
If you want to use Firefox in any other place then use below code:-
Full Working code:
System.setProperty("webdriver.gecko.driver","D:\\Workspace\\demoproject\\src\\lib\\geckodriver.exe");
File pathBinary = new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
DesiredCapabilities desired = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
desired.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options.setBinary(firefoxBinary));
WebDriver driver = new FirefoxDriver(options);
driver.get("https://www.google.co.in/");


text:
Q: Powershell return different results running the same script from c# I am trying to run a simple script for getting file attributes.
string script = @"$path = 'C:\Temp\Indexing\Asm1.asm'
                            $shell = New-Object -COMObject Shell.Application
                            $folder = Split-Path $path
                            $file = Split-Path $path -Leaf
                            $shellfolder = $shell.Namespace($folder)
                            $shellfile = $shellfolder.ParseName($file)
                            0..500 | Foreach-Object { '{0} = {1}' -f $shellfolder.GetDetailsOf($null, $_), $shellfolder.GetDetailsOf($shellfile, $_).toString()}";

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(script);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();

When running within powershell I get more attribute results which are empty when running it through the code.
It seems like an access issue.
any help will be much appreciated!

A: Try adding #!/usr/bin/env pwsh as first line of the script.


text:
Q: How to make this loop (in which one iteration depends on the previous) faster? I need to make the following loop faster. My only two requirements are:

*

*it has to be called from a Python script;

*it cannot use Numba;

I am sorry for such a generic title, but I was not sure how to post a specific performance problem. Thank you for the input.
import numpy as np

def sig(a):
    return 1 / (1 + np.exp(-a))

N = 1000
xt = np.random.rand(N, 1).astype(np.float32)    # input
w1 = np.random.rand(64, 64).astype(np.float32)  # weight 1
w2 = np.random.rand(1, 64).astype(np.float32)   # weight 2
ht = np.zeros((N, 64), dtype=np.float32)        # output

h = ht[N - 1:N]
for i in range(N):
    h = sig(h @ w1 + xt[i:i + 1] @ w2)  # 1x64 = sig(1x64 @ 64x64 + 1x1 @ 1x64)
    ht[i] = h


text:
Q: Missing romance dialog option in Greedfall I'm playing Greedfall (via Steam, no DLC), and have just completed Vasco's first personal quest "A Name For the Family." I have gained experience points and Vasco's relationship with me increased as well.
According to the guides, the next thing I should do to romance him is select the "Ask him if he has any happy memories." dialog option.
I don't see that option available, however:

Ask him ...

*

*Whether he is mad at you

*Whether he wished he was never given to the Nauts

Both this guide and this other guide both indicate that I should be asking about the happy memories, and the second guide also confirms that the gender of the main character doesn't matter (unlike with some of the other companions.)
The second guide sounds like I should be asking about the happy memories while in the process of completing the quest (eg. when I return to him after stealing his personnel file), but there are no dialog options available during that sequence -- it's fully scripted.
Is there something else I need to do to have this option appear?


text:
Q: Searching a two dimensional array c++ Total newbie here, having problems searching a 2 dimensional array.  I have a 3x3 char array that holds '1' thru '9' like a tic tac toe board.  For testing, I hard coded it to search for a '5', hoping it would return '1' for the row.  It returns '3' no matter what.  There are other posts similar, but they are all too advanced for what minuscule amount I know about c++.  Here is my array:
char board[3][3] =
{
    { '1', '2', '3', }, // row 0
    { '4', '5', '6', }, // row 1
    { '7', '8', '9' } // row 2
};

And here's my function:
int searchBoard()
{
    char board[3][3];
    for (int r = 0; r < 3; r++)
    {
        for (int c = 0; c < 3; c++)
        {
            if (board[r][c] == '5')
            {
                return r;
            }
        }
    }
}

I would really appreciate some help!

A: You should not declare a local, uninitialized board in searchBoard() which masked the global board.

A: Try changing your function searchBoard to
int searchBoard()
{
    char board[3][3] =
    {
        { '1', '2', '3', }, // row 0
        { '4', '5', '6', }, // row 1
        { '7', '8', '9' } // row 2
    };
    for (int r = 0; r < 3; r++)
    {
        for (int c = 0; c < 3; c++)
        {
            if (board[r][c] == '5')
            {
                return r;
            }
        }
    }
}


text:
Q: 1-D numerical gradient for a 3-D array in matlab I have a 3-D array (an image) of size (nrows x cols x ndivs), and I wish to calculate the 1-D numerical gradient along the 3rd dimension with a spacing of 0.01, and obtain (nrows x ncols) of sets of gradients.
I have thought of a way to do this by looping over every pixel:
grad_F = zeros(nrows,ncols,ndivs);

for irow = 1:nrows
    for icol = 1:ncols
        grad_F(irow,icol,:) = gradient(F(irow,icol,:),0.01);
    end
end

I would like to ask if there is an array operation for gradient to do the above without looping over every pixel? And if there is such a way, is it faster or will it take the same amount of time?

A: If I understand you correctly, this should work.
[~,~,FZ] = gradient(F,0.01)

FZ is your gradient in 3rd dimension.


text:
Q: Moving colorbox's captions to top of box? I'm using colorbox to open modal windows on my project.
There is 5 style to use colorbox. I'm using Example 5 on this url: http://www.jacklmoore.com/colorbox/example5/
I am trying to move colorbox.js's caption row (title attribute text, background and close icon) to the top of the box - it defaults to the bottom. How can I do it?
This is normal view of Colorbox window on Example 5:

This is what I REALLY WANT:

A: Simply copy the below mentioned code in the bottom of your colorbox.css
#colorbox #cboxClose
    {
    top: 0;
    right: 0;
    }
    #cboxLoadedContent{
    margin-top:28px;
    margin-bottom:0;
    }

A: You have to do two things:  The first is easy; you'll have to edit the CSS file (colorbox.css) and change the position rule for the following elements:
#cboxTitle, #cboxCurrent, #cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow

so that their absolute positioning is based on the 'top' property not the 'bottom' property. Here is an example, before and after an edit (the before version is commented out):
/*#cboxCurrent{position:absolute; bottom:-25px; left:58px; font-weight:bold; color:#7C7C7C;} */
  #cboxCurrent{position:absolute; top: 0; left:58px; font-weight:bold; color:#7C7C7C;}

You'll have to experiment to get the proper values for the 'top' property.
The second thing to do may be more difficult. The plugin uses an image 'sprite' (a composite of many images) called controls.png.  Looking at it, it does not have the images necessary to do what you want.
If you are competent with an image editor, you could modify this image and add the necessary images, then determine the X-Y co-ordinates necessary to use the new image content according to typical sprite use in CSS.  Don't know if you are up for this.
Ah, but you thought it was a simple change, eh? Best of luck!

A: Edit colorbox.css
Make following changes

1. Replace
#cboxLoadedContent{margin-bottom:28px;}
with
#cboxLoadedContent{margin-top:28px;}

2. Replace
#cboxClose{position:absolute; bottom:0;
with
#cboxClose{position:absolute; top:0;

A: Found an easier way to change the close to an image,
change word "close" to your image in jquery.colorbox.js
current: "image {current} of {total}",
previous: "previous",
next: "next",
close: "", //was "close"
xhrError: "This content failed to load.",
imgError: "This image failed to load.",

A: Replace this
       $content = $tag(div, "Content").append(
            $title = $tag(div, "Title"),
            $current = $tag(div, "Current"),
            $prev = $('<button type="button"/>').attr({id:prefix+'Previous'}),
            $next = $('<button type="button"/>').attr({id:prefix+'Next'}),
            $slideshow = $('<button type="button"/>').attr({id:prefix+'Slideshow'}),
            $loadingOverlay
        );

        $close = $('<button type="button"/>').attr({id:prefix+'Close'});

With
$content = $tag(div, "Content").append(
        //$title = $tag(div, "Title"),   // comment this line
        $current = $tag(div, "Current"),
        $prev = $('<button type="button"/>').attr({id:prefix+'Previous'}),
        $next = $('<button type="button"/>').attr({id:prefix+'Next'}),
        $slideshow = $('<button type="button"/>').attr({id:prefix+'Slideshow'}),
        $loadingOverlay
    );

    $close = $('<button type="button"/>').attr({id:prefix+'Close'});
    // add this new code
    $wrap  = $tag(div, "Wrapper").append(
            $title = $tag(div, "Title")
    );


text:
Q: security tunnel with SSL or VPN? In the point of view of security, what are the difference between a "cipher tunnel" by ssl or by vpn?
The scenario is: One server web that provides a service to few (known) people. Now the authentication is based on iis' basic authentication (over ssl), and a kerberos system.
It will possible use a VPN to authenticate on a web service, and use it instead ssl+kerberos?
it will a gain on the security point of view?

A: Cryptic version: it depends. ;)
There are some very insecure ways to deploy both SSL (v2, md5, renegotiation exploits) and VPN (some VPN solutions use deeply flawed crypto algorithms such as RC4).
The security level of modern, well-configured implementations of both technologies is roughly comparable (and quite good).
To the other aspect of your question - SSL is probably the best solution for you; being connected to VPN and hitting an unencrypted page will lose some of the advantages of SSL (notably, server authentication) and will leave your requests in plaintext in between where the VPN terminates and the web server.

A: If the service is limited to a known set of users then VPN and a firewall set is going to be easy enough to set up.
You could even just use fire-walling here if you know the users IP addresses are static (internal corporate network). All you do is add rules to allow the known hosts and then deny all other.
If the users are coming from outside on dynamic addresses then a VPN plus a firewall will work well here.
You can employ SSL on top of all this too to add another layer of security which will not be inconvenient to your users as it is transparent and doesn't require anything from them.


text:
Q: Extract All Values using HTMLAligity Pack Following is the HTML of webpage and I am willing to extract values of All data-user-id field

can any one pls provide help is c# or vb.net I tried following code but its not working
Dim UrlRegister1 As String = "C:/Users/Shripad/Desktop/result.htm"
   Dim document = New HtmlDocument()
    document.Load("C:/Users/Shripad/Desktop/result.htm")
    Dim node As HtmlNode = document.DocumentNode.SelectSingleNode("//class='account   js-actionable-user js-profile-popup-actionable'/data-user-id=")
    Dim useridd As String = node.Attributes("Value").Value

A: For selecting elements that has 'account' class - use XPath contains selector like this:
[contains(@class, 'account')]

The whole result should be:
var node = doc.DocumentNode.SelectSingleNode(@"//div[contains(@class, 'account')]");
var useridd = node.Attributes["data-user-id"].Value;

Here more information about selecting element by classes : XPath for CSS classes