Q: Why is my shellscript execution of a gradle build behaving differently on jenkins than on cli? When I perform ./gradlew build on command line, gradle downloads and unzips the correct wrapper dist version and continues to download dependencies and build the project.
However when I perform the same within a shellscript on jenkins, it only downloads the gradle wrapper dist zip and tells me there are no dependencies.
How come no dependencies are seen this time ?
------------------------------------------------------------
Root project
------------------------------------------------------------

classpath
No dependencies

BUILD SUCCESSFUL in 9s

I have already (first) tried using the gradle plugin on jenkins, same result.                 ANDROID_HOME is the same and set, I am using the same user on the cli.
Java version 8, Gradle 4.1, Android 25, Android build-tools 26.0.2
When i let jenkins invoke a script holding this build command it does work, but not directly. (current quickfix)
Does anyone have an idea what is going wrong ?

A: It now works, I am not sure what changed to fix this other than the fact i have placed the commands in a function this time, but it is all working as desired.


Q: Using Python to backup ArcSDE geodatabase on SQL Server Express? Is it possible to use Python to do a backup of ArcSDE databases stored in SQL Server Express?  I have been using a custom executable that uses Arcobjects
IDataServerManagerAdmin.BackupGeodatabase()

but, I would prefer to use Python. The executable makes our IT staff a bit nervous.

A: Backup of a geodatabase on a database server, can be done using ArcCatalog and Arcobjects (IDataServerManagerAdmin.BackupGeodatabase()). Unfortunately it is not exposed to python or Arcpy.
So to automate the process of backup you have to create a stored procedure in MS SQL Server and then create a batch file to call the stored procedure. Finally, schedule the batch file.
Stored Procedure
USE [master]
GO
/****** Object:  StoredProcedure [dbo].[sp_BackupDatabases] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sp_BackupDatabases]
            @databaseName sysname = null,
            @backupType CHAR(1),
            @backupLocation nvarchar(200)
AS

       SET NOCOUNT ON;

            DECLARE @DBs TABLE
            (
                  ID int IDENTITY PRIMARY KEY,
                  DBNAME nvarchar(500)
            )

             -- Pick out only databases which are online in case ALL databases are chosen to be backed up
             -- If specific database is chosen to be backed up only pick that out from @DBs
            INSERT INTO @DBs (DBNAME)
            SELECT Name FROM master.sys.databases
            where state=0
            AND name=@DatabaseName
            OR @DatabaseName IS NULL
            ORDER BY Name

            -- Filter out databases which do not need to backed up
            IF @backupType='F'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')
                  END
            ELSE IF @backupType='D'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
                  END
            ELSE IF @backupType='L'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
                  END
            ELSE
                  BEGIN
                  RETURN
                  END

            -- Declare variables
            DECLARE @BackupName varchar(100)
            DECLARE @BackupFile varchar(100)
            DECLARE @DBNAME varchar(300)
            DECLARE @sqlCommand NVARCHAR(1000)
        DECLARE @dateTime NVARCHAR(20)
            DECLARE @Loop int

            -- Loop through the databases one by one
            SELECT @Loop = min(ID) FROM @DBs

      WHILE @Loop IS NOT NULL
      BEGIN

-- Database Names have to be in [dbname] format since some have - or _ in their name
      SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'

-- Set the current date and time n yyyyhhmmss format
      SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' +  REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')

-- Create backup filename in path\filename.extension format for full,diff and log backups
      IF @backupType = 'F'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
      ELSE IF @backupType = 'D'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'
      ELSE IF @backupType = 'L'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'

-- Provide the backup a name for storing in the media
      IF @backupType = 'F'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime
      IF @backupType = 'D'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime
      IF @backupType = 'L'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime

-- Generate the dynamic SQL command to be executed

       IF @backupType = 'F'
                  BEGIN
               SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
                  END
       IF @backupType = 'D'
                  BEGIN
               SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
                  END
       IF @backupType = 'L'
                  BEGIN
               SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
                  END

-- Execute the generated SQL command
       EXEC(@sqlCommand)

-- Goto the next database
SELECT @Loop = min(ID) FROM @DBs where ID>@Loop

END

Batch File

*

*for Full backups of all databases in the local named instance of SQLEXPRESS by using Windows Authentication
sqlcmd -S .\EXPRESS –E -Q "EXEC sp_BackupDatabases @backupLocation='D:\SQLBackups\', @backupType='F'"

*Differential backups of all databases in the local named instance of SQLEXPRESS by using a SQLLogin and its password
sqlcmd -U SQLLogin -P password -S .\SQLEXPRESS -Q "EXEC sp_BackupDatabases  @backupLocation ='D:\SQLBackups', @BackupType=’D’"
And schedule it with windows Task Scheduler.
Reference:
How to schedule and automate backups of SQL Server databases in SQL Server Express

A: I agree with @Farid Cher's answer that ideally you should look to accomplish this through a SQL based backup, rather than an externally scripted backup.  However, if you are determined to backup the data via python, I can think of 2 possibly solutions.  Please note, neither of these are true database backups.  However, they can still externally save the data from your database so, in the event of a loss of the database, you could create a new SDE database and copy the backed-up data into it.
Option 1) Create a one way replica from your SDE database out to a FileGDB that would ideally be on another machine at a different site (replicate either using archiving or traditional versioning based replica).  Then from python you could simply schedule a python script that uses arcpy to synchronize the replica any time you need.  Some of the limitations of this are that it will only back-up one version (whichever version you create the replica off of).  Also, any time you change the schema of your database (adding/changing fields and/or adding/changing feature classes/tables) you will need to either synchronize the schema changes and/or re-create the replica - depending on the type of schema change.  Additionally, all feature classes you want backed-up will need to be either registered as versioned or have archiving enabled, depending on what type of replica you use.
Option 2) You could write a script (or search the forums and help sites and piece together existing code for it), to get a python script that will loop through every feature class, feature dataset, toolbox, table, etc... in the SDE database and copy the dataset to a FileGDB.  Some things to be careful of if using this route: if you have relationship classes, be careful because copying tools in ArcGIS can do some interesting things with related data, so your script will have to make sure all data gets correctly copied over (I have some sample code I can help you with this if you really want to go this route).  The limitations of this are, while you can theoretically do this for multiple versions of data, you will have to do a separate backup FileGDB for each edit version, meaning your backup harddrive space requirements and the time required to run the backup can grow large/long quickly.  Also, this backup method can take considerably longer than is really necessary for a backup.  This also requires re-writing the entire database every time you want to run a backup, so it can be a lot of harddrive disk activity consumption (would need to be scheduled to run at a down time for the server/computer) and would need to definitely not be backed up to a FGDB solid state drive or a flash-drive as this process could relatively quickly max out the write limitations on the disk depending on the frequency and size of the database.  Also, this method may (depending on what copy tools you use) preserve GlobalID field values, but is definitely NOT guaranteed to preserve them, so don't use it if preserved globalids are a requirement for you.
Again, I strongly suggest using a SQL based backup to get a true backup of the database using the scheduled batch file method described in another answer, but, if you absolutely have to do something via Python, hopefully the above gives you a few ideas to work with.


Q: Select 2 ajax search fires when pressing ctrl keys I have the following select 2 field:
$("select#edit-property-id").select2({
  multiple: false,
  width: 150,
  delay: 250,
  placeholder: "Type",
  minimumInputLength: 1,
  ajax: {// instead of writing the function to execute the request we use Select2's
  // convenient helper
    url: "/tell/product_chosen_search",
    dataType: 'json',
    data: function (params) {
      return {
        term: params.term, // search term
      };
    },
    processResults: function (data, page) {
      return {
        results: data
      };
    },
  },
});

The ajax search fires correctly when I enter characters, however it also fires when I press keys such as ctrl, down button etc... How can I prevent that? Is there a setting?

A: This appears to be a defect in the new 4.0 version of Select2, which is still in beta.
jsfiddle
With v3.5.2, the following line in the updateResults function prevents the unnecessary ajax calls:
// prevent duplicate queries against the same term
if (initial !== true && lastTerm && equal(term, lastTerm)) return;

jsfiddle
Here's a somewhat related issue. At least, I think both issues could be fixed at the same time. You may want to add a comment to that issue.


Q: Upload File to Wordpress with AJAX All,
I'm using a HTML5 uploader to upload some images. This is part of the file that sends the data to my PHP processing script:
var ajax    = $.ajax({
    url:        ajaxurl,
    //dataType:     options.ajaxDataType || 'json',
    type:       options.ajaxType || 'POST',
    cache:      false,
    data:       { name: $file.data('filename'), filename: $file.data('file'), file: evt.target.result, data: options.data, action: 'test_upload' },
    headers:    options.ajaxHeaders,

From the uploader they process the file upload with this code:
if (!empty($_POST)) {
    $error                  = false;
    $absolutedir            = dirname(__FILE__);
    $dir                    = '/tmp/';
    $serverdir              = $absolutedir.$dir;
    $tmp                    = explode(',',$_POST['file']);
    $file                   = base64_decode($tmp[1]);
    $extension              = strtolower(end(explode('.',$_POST['filename'])));
    $filename               = $_POST['name'].'.'.$extension;
    //$filename             = $file.'.'.substr(sha1(time()),0,6).'.'.$extension;
    $handle                 = fopen($serverdir.$filename,'w');
    fwrite($handle, $file);
    fclose($handle);
    $response = array(
            "result"        => true,
            "url"           => $dir.$filename.'?'.time(), //added the time to force update when editting multiple times
            "filename"      => $filename
    );
    echo json_encode($response);
    //echo json_encode(array('result'=>true));
}

However, I would like Wordpress to handle my file upload so I'm trying to use the following function to handle my file upload:
function test_upload()
{
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $filename = $_POST['filename'];
    $attachment_id = media_handle_upload( $filename, '1' );
    print_r($attachment_id);

}

I'm trying to pass the filename because the media_handle_upload codex for the first argument (in my example $filename) says this:
Index into the $_FILES array of the upload
How can I successfully use WP to upload this file using AJAX to pass me a POST variable instead of a $_FILES variable?
EDIT: When I currently do it this way I get a WP_ERROR saying the file is empty. I created a pastebin with the JS code to handle the file processing form so you can see where the file names are coming from.
http://pastebin.com/Shc4KqX1
Here is the file input:
<input type="file" name="file" />

A: <input id="uploadBtn" type="file" class="upload" name="pimage">

Function media_handle_upload upload your image in wordpress
Use $filename = $_POST['filename']['temp_name'];  not $filename = $_POST['filename'];
if ( !empty( $_FILES["pimage"]["name"] ) ) {
    $attachment_id = media_handle_upload( 'pimage', 0 );
}


Q: Updating global variable via callback I have the following function
   var urls = '';
    handleFiles(f,function(url){
        urls = urls + url + ',';
        console.log("urls is " + urls);
    });

I get the url after uploading and update my urls. But my Urls never gets updated, it shows the url of the last file uploaded.
UPDATE 1
This is my complete code now.
var urls = '';
document.getElementById('question-file-selector').addEventListener('change',handleFileSelect,false);
    function handleFileSelect(evt){
        var files = evt.target.files; //File list object
            // Loop through file list, render image files as thumbnails
        for (var i = 0,f;f = files[i];i++){

        handleFiles(f,function(url){
                urls = urls + url + ',';
                console.log("urls is " + urls);
                });
        // Only process image files
        if (!f.type.match('image.*')){
            $('#list').append('');
            continue;
        }
        var reader = new FileReader();

        //Closure to capture file information
        reader.onload = (function(theFile){
                return function(e){
                    //Render thumbnail
                    $('#list').append('');
                    };
                    })(f);
        reader.readAsDataURL(f);
    }
    }

console.log("Url is",urls);`

And my ajax function
    //Code for Image upload

// Custom jQuery xhr instance to support our progress bar.

var xhr_with_progress = function() {
     var xhr = new XMLHttpRequest();
     xhr.upload.addEventListener("progress",
         function(evt) {
             if (!evt.lengthComputable) return;
             var percentComplete = evt.loaded / evt.total;
             $("#progress-bar div.progress-bar").css('width', String(100*percentComplete) + "%");
         }, false);
     return xhr;
 };

$.support.cors = true;//For cross origin transfer

//Event listners to avoid default drag and drop reaction of browser
window.addEventListener("dragover",function(e){
  e = e || event;
  e.preventDefault();
},false);
window.addEventListener("drop",function(e){
  e = e || event;
  e.preventDefault();
},false);

function handleFiles(file,callback){

            var filename = file.name;
            $.ajax({
                type:'GET',
                data:{"filename":file.name, "FileType":"question_file"},
                url:'/dashboard/generateuploadurl/',
                contentType:"application/json",
                dataType:"json",
                async:false,
                success: function(data){
                    if(data.UploadUrl){
                      console.log("upload url successfully created for " + file.name + " file");
                        console.log(data.UploadUrl);
                        handleUpload(data.UploadUrl, file, data.Filename,callback);

                    }
                },
                error: function(data){
                    console.log("error occured while creating upload url for " + file.name + ' file');
                    console.log(data);
                },
            });
        }
function handleUpload(UploadUrl, file, Filename,callback){
    $.ajax({
        xhr:xhr_with_progress,
        url:UploadUrl,
        type:'PUT',
        data:file,
        cache:false,
        contentType:false,
        processData:false,
        success: function(data){
            console.log('https://7c.ssl.cf6.rackcdn.com/'+ Filename);
            callback('https://7c.ssl.cf6.rackcdn.com/'+ Filename);
        },
        error: function(data){
            alert("error occured while uploading " + file.name );
            console.log(data);
        },
    });
}

A: Coordinating multiple asynchronous operations is a job best solved with tools like promises.  So, in the long run, I'd suggest you read up about promises and how to use them.
Without promises, here's a brute force way you can tell when all your handleFiles() operations are done by using a counter to know when the last async operation is done and then using the urls variable INSIDE that last callback or calling a function from there and passing the urls variable to that function:
document.getElementById('question-file-selector').addEventListener('change', handleFileSelect, false);

function handleFileSelect(evt) {
    var files = evt.target.files; //File list object
    var urls = "";
    // Loop through file list, render image files as thumbnails
    var doneCnt = 0;
    for (var i = 0, f; f = files[i]; i++) {
        handleFiles(f, function (url) {
            urls = urls + url + ',';
            console.log("urls is " + urls);
            ++doneCnt;
            if (doneCnt === files.length) {
                // The last handleFiles async operation is now done
                // final value is in urls variable here
                // you can use it here and ONLY here

                // Note: this code here will get executed LONG after the
                // handleFileSelect() function has already finished executing
            }
        });
        // Only process image files
        if (!f.type.match('image.*')) {
            $('#list').append('');
            continue;
        }
        var reader = new FileReader();
        //Closure to capture file information
        reader.onload = (function (theFile) {
            return function (e) {
                //Render thumbnail
                $('#list').append('');
            };
        })(f);
        reader.readAsDataURL(f);
    }
}

// You can't use the urls variable here.  It won't be set yet.

Ohhh.  Please remove the async: false from your ajax call.  That's a horrible thing to code with for a variety of reasons.

Here's a version using the promises built into jQuery:
document.getElementById('question-file-selector').addEventListener('change', handleFileSelect, false);

function handleFileSelect(evt) {
    var files = evt.target.files; //File list object
    // Loop through file list, render image files as thumbnails
    var promises = [];
    for (var i = 0, f; f = files[i]; i++) {
        promises.push(handleFiles(f));
        // Only process image files
        if (!f.type.match('image.*')) {
            $('#list').append('');
            continue;
        }
        var reader = new FileReader();
        //Closure to capture file information
        reader.onload = (function (theFile) {
            return function (e) {
                //Render thumbnail
                $('#list').append('');
            };
        })(f);
        reader.readAsDataURL(f);
    }
    $.when.apply($, promises).then(function() {
        var results = Array.prototype.slice.call(arguments);
        // all handleFiles() operations are complete here
        // results array contains list of URLs (some could be empty if there were errors)
    });
}

function handleFiles(file) {
    var filename = file.name;
    return $.ajax({
        type: 'GET',
        data: {
            "filename": file.name,
            "FileType": "question_file"
        },
        url: '/dashboard/generateuploadurl/',
        contentType: "application/json",
        dataType: "json"
    }).then(function(data) {
        if (data.UploadUrl) {
            console.log("upload url successfully created for " + file.name + " file");
            console.log(data.UploadUrl);
            return handleUpload(data.UploadUrl, file, data.Filename);
        }
    }, function(err) {
        console.log("error occured while creating upload url for " + file.name + ' file');
        console.log(err);
        // allow operation to continue upon error
    });
}

function handleUpload(UploadUrl, file, Filename) {
    return $.ajax({
        xhr: xhr_with_progress,
        url: UploadUrl,
        type: 'PUT',
        data: file,
        cache: false,
        contentType: false,
        processData: false
    }).then(function(data) {
        console.log('https://7c.ssl.cf6.rackcdn.com/' + Filename);
        return 'https://7c.ssl.cf6.rackcdn.com/' + Filename;
    }, function(err) {
        console.log("error occured while uploading " + file.name);
        console.log(err);
        // allow operation to continue upon error
    });
}

Since I can't run this code to test it, there could be a mistake or two in here, but you should be able to debug those mistakes or tell us where the errors occur and we can help you debug it.  These are conceptually how you solve these types of problems of coordinating multiple async operations.


Q: how to install android app remotely by sending image? Is it possible to install any android app directly via sending any image or directly on clicking on web link?
when anyone click on link or download image application directly starts downloading and install without manual interaction of user without rooting of android phone.

A: Auto execution/installation of a downloaded file are disabled in every main stream Operating systems, be it windows, android, etc.


Q: LINQ to Entities does not recognize the method NotSupportedException LINQ to EF:
 db.ReadonlyQuery<Transaction>()
     .Select(t => new ACurrentDayInfo
         {
              OrderId = t.TransactionIdentifier,
              OrderTime = t.TransactionTime,
              UserName = JsonConvert.DeserializeObject<UserInfo>(t.UserInfo).RealName ?? ""
         })
     .ToListAsync();

The t.UserInfo is a json string like {"RealName ":"XY"} in each record of in table's field.
How can I translate this to a server query?

A: Extend you ACurrentDayInfo class with a getter like this
class  ACurrentDayInfo
{
    public string UserName
    {
        get
        {
            return JsonConvert.DeserializeObject<UserInfo>(UserInfo).RealName ?? "";
        }
    }
}

and modify your query like this:
db.ReadonlyQuery<Transaction>()
                    .Select(t => new ACurrentDayInfo
                    {
                        OrderId = t.TransactionIdentifier,
                        OrderTime = t.TransactionTime,
                        UserInfo = t.UserInfo
                    }).ToListAsync();

A: In EF Dbcontext don't support cast json in query, You need fix same that:
var listData = db.ReadonlyQuery<Transaction>()
                        .Select(t => new ACurrentDayInfo
                        {
                            OrderId = t.TransactionIdentifier,
                            OrderTime = t.TransactionTime,

                            UserInfo = t.UserInfo
                        }).ToListAsync();

foreach (var item in listData)
{
    item.UserName = JsonConvert.DeserializeObject<UserInfo>(t.UserInfo).RealName ?? ""
}


Q: creating List within a list in recurrsion from string python I am trying to create a list from a string
input string
st = "zzabcxzghfxx"
the list is enclosed in 'z' and 'x'
this is my attempt to create a recursive function
st = "zzabcxzghfxx"

def createlist(strin):
    l1=[]
    for i in st:
        if(i=='x'):
            createlist(strin)
        elif(i=='z'):
            l1.append(i)
    return(l1)

following is the desired output:"[[abc][ghf]]"
string = "zzabcxzghzfxx"=> [[abc][ghzf]]"

A: You could strip the trailing x and z and split on xz:
st.strip('xz').split('xz')
# ['abc', 'ghf']

A: Using regex.
Ex:
import re

st = "zzabcxzghfxx"
print(re.findall(r"z+(.*?)(?=x)", st))
#or print([[i] for i in re.findall(r"z+(.*?)(?=x)", st)])

Output:
['abc', 'ghf']

A: Does it have to be recursive? Here's a solution using itertools.groupby.
from itertools import groupby

string = "zzabcxzghfxx"

def is_good_char(char):
    return char not in "zx"

lists = [["".join(char for char in list(group))] for key, group in groupby(string, key=is_good_char) if key]
print(lists)

Output:
[['abc'], ['ghf']]

EDIT - Just realized that this might not actually produce the desired behavior. You said:

[a] list is enclosed in 'z' and 'x'

Which means a sublist starts with 'z' and must end with 'x', yes? In that case the itertools.groupby solution I posted will not work exactly. The way it's written now it will generate a new sublist that starts and ends with either 'z' or 'x'. Let me know if this really matters or not.

A: st.replace("z", "[").replace("x", "]")


Q: Image Rotates 90 degrees left when resized I have a resize script and it makes every image uploaded 300x300. It works fine when something from computer or mobile is uploaded. The problem is when user decides to take a picture from camera: After the resize script image rotates 90 degrees to the left and it is a problem because it should be displayed correctly without rotating. I don't know the reason here is the script:
    function resize_image($path, $width, $height, $update = false) {
    $size  = getimagesize($path);// [width, height, type index]
    $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
    if ( array_key_exists($size['2'], $types) ) {
       $load        = 'imagecreatefrom' . $types[$size['2']];
       $save        = 'image'           . $types[$size['2']];
       $image       = $load($path);
       $resized     = imagecreatetruecolor($width, $height);
       $transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127);
       imagesavealpha($resized, true);
       imagefill($resized, 0, 0, $transparent);
       imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $size['0'], $size['1']);
       imagedestroy($image);
       return $save($resized, $update ? $path : null);
    }
 }
  if(!resize_image($_FILES["fileToUpload"]["tmp_name"], 300, 300, true))
  {
    exit();
  }


Q: Using capacity and time window constraints with pick up and delivery problem I am new to the OR-Tools libraries. I am trying to solve pick up and delivery problem with capacity and time window constraints. The code is working fine with 5 location nodes (2 pick up and 2 delivery locations and 1 depot location). But, when I change the number of nodes to 17(with 1 depot location), the code does not work and the kernel dies in Spyder editor for Python 3.5 without giving any error. And, if I run it in the terminal it produces following output.
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

System specifications are: OS-Ubuntu 16.04 LTS, Python version - 3.5.2, OR-Tools version - 7.7, RAM - 8GB, Graphics - 2GB AMD Radeon.
I have written the code by combining the relevant parts of the sample codes given on the OR-Tools website.
Following is the code with 16 nodes which is not working:
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['time_matrix'] = [
        [0, 6, 9, 8, 7, 3, 6, 2, 3, 2, 6, 6, 4, 4, 5, 9, 7],
        [6, 0, 8, 3, 2, 6, 8, 4, 8, 8, 13, 7, 5, 8, 12, 10, 14],
        [9, 8, 0, 11, 10, 6, 3, 9, 5, 8, 4, 15, 14, 13, 9, 18, 9],
        [8, 3, 11, 0, 1, 7, 10, 6, 10, 10, 14, 6, 7, 9, 14, 6, 16],
        [7, 2, 10, 1, 0, 6, 9, 4, 8, 9, 13, 4, 6, 8, 12, 8, 14],
        [3, 6, 6, 7, 6, 0, 2, 3, 2, 2, 7, 9, 7, 7, 6, 12, 8],
        [6, 8, 3, 10, 9, 2, 0, 6, 2, 5, 4, 12, 10, 10, 6, 15, 5],
        [2, 4, 9, 6, 4, 3, 6, 0, 4, 4, 8, 5, 4, 3, 7, 8, 10],
        [3, 8, 5, 10, 8, 2, 2, 4, 0, 3, 4, 9, 8, 7, 3, 13, 6],
        [2, 8, 8, 10, 9, 2, 5, 4, 3, 0, 4, 6, 5, 4, 3, 9, 5],
        [6, 13, 4, 14, 13, 7, 4, 8, 4, 4, 0, 10, 9, 8, 4, 13, 4],
        [6, 7, 15, 6, 4, 9, 12, 5, 9, 6, 10, 0, 1, 3, 7, 3, 10],
        [4, 5, 14, 7, 6, 7, 10, 4, 8, 5, 9, 1, 0, 2, 6, 4, 8],
        [4, 8, 13, 9, 8, 7, 10, 3, 7, 4, 8, 3, 2, 0, 4, 5, 6],
        [5, 12, 9, 14, 12, 6, 6, 7, 3, 3, 4, 7, 6, 4, 0, 9, 2],
        [9, 10, 18, 6, 8, 12, 15, 8, 13, 9, 13, 3, 4, 5, 9, 0, 9],
        [7, 14, 9, 16, 14, 8, 5, 10, 6, 5, 4, 10, 8, 6, 2, 9, 0],
    ]
    data['time_windows'] = [
        (0, 1800),  # depot
        (0, 1800),  # 1
        (0, 1800),  # 2
        (0, 1800),  # 3
        (0, 1800),  # 4
        (0, 1800),  # 5
        (0, 1800),  # 6
        (0, 1800),  # 7
        (0, 1800),  # 8
        (0, 1800),  # 9
        (0, 1800),  # 10
        (0, 1800),  # 11
        (0, 1800),  # 12
        (0, 1800),  # 13
        (0, 1800),  # 14
        (0, 1800),  # 15
        (0, 1800),  # 16
    ]
    data['pickups_deliveries'] = [
        [1, 6],     #2
        [2, 10],    #4
        [4, 3],     #1
        [5, 9],     #2
        [7, 8],     #5
        [15, 11],   #3
        [13, 12],   #1
        [16, 14],   #3
        [6, 15],    #5
        [7, 14],    #6
        [12, 9],    #3
    ]
    data['demands'] = [0, 2, 4, -1, 1, 2, 3, 11, -5, -5, -4, -3, 2, 1, -9, -2, 3]
    data['vehicle_capacities'] = [20, 20, 20, 20]
    data['num_vehicles'] = 4
    data['depot'] = 0
    return data

def print_solution(data, manager, routing, solution):
    """Prints solution on console."""
    time_dimension = routing.GetDimensionOrDie('Time')
    total_time = 0
    for vehicle_id in range(data['num_vehicles']):
        index = routing.Start(vehicle_id)
        plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
        while not routing.IsEnd(index):
            time_var = time_dimension.CumulVar(index)
            plan_output += '{0} Time({1},{2}) -> '.format(
                manager.IndexToNode(index), solution.Min(time_var),
                solution.Max(time_var))
            index = solution.Value(routing.NextVar(index))
        time_var = time_dimension.CumulVar(index)
        plan_output += '{0} Time({1},{2})\n'.format(manager.IndexToNode(index),
                                                    solution.Min(time_var),
                                                    solution.Max(time_var))
        plan_output += 'Time of the route: {}min\n'.format(
            solution.Min(time_var))
        print(plan_output)
        total_time += solution.Min(time_var)
    print('Total time of all routes: {}min'.format(total_time))

def main():
    """Solve the VRP with time windows."""
    # Instantiate the data problem.
    data = create_data_model()

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['time_matrix']),
                                           data['num_vehicles'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def time_callback(from_index, to_index):
        """Returns the travel time between the two nodes."""
        # Convert from routing variable Index to time matrix NodeIndex.
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        return data['time_matrix'][from_node][to_node]

    transit_callback_index = routing.RegisterTransitCallback(time_callback)

    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Add Time Windows constraint.
    time = 'Time'
    routing.AddDimension(
        transit_callback_index,
        30000,  # allow waiting time
        3000,  # maximum time per vehicle
        False,  # Don't force start cumul to zero.
        time)
    time_dimension = routing.GetDimensionOrDie(time)
    # Add time window constraints for each location except depot.
    for location_idx, time_window in enumerate(data['time_windows']):
        if location_idx == 0:
            continue
        index = manager.NodeToIndex(location_idx)
        time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])
    # Add time window constraints for each vehicle start node.
    for vehicle_id in range(data['num_vehicles']):
        index = routing.Start(vehicle_id)
        time_dimension.CumulVar(index).SetRange(data['time_windows'][0][0],
                                                data['time_windows'][0][1])

    # Instantiate route start and end times to produce feasible times.
    for i in range(data['num_vehicles']):
        routing.AddVariableMinimizedByFinalizer(
            time_dimension.CumulVar(routing.Start(i)))
        routing.AddVariableMinimizedByFinalizer(
            time_dimension.CumulVar(routing.End(i)))
    # Define Transportation Requests.
    for request in data['pickups_deliveries']:
        pickup_index = manager.NodeToIndex(request[0])
        delivery_index = manager.NodeToIndex(request[1])
        routing.AddPickupAndDelivery(pickup_index, delivery_index)
        routing.solver().Add(
            routing.VehicleVar(pickup_index) == routing.VehicleVar(
                delivery_index))
        routing.solver().Add(
            time_dimension.CumulVar(pickup_index) <=
            time_dimension.CumulVar(delivery_index))

    def demand_callback(from_index):
        """Returns the demand of the node."""
        # Convert from routing variable Index to demands NodeIndex.
        from_node = manager.IndexToNode(from_index)
        return data['demands'][from_node]

    demand_callback_index = routing.RegisterUnaryTransitCallback(
        demand_callback)
    routing.AddDimensionWithVehicleCapacity(
        demand_callback_index,
        0,  # null capacity slack
        data['vehicle_capacities'],  # vehicle maximum capacities
        True,  # start cumul to zero
        'Capacity')

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)

    # Solve the problem.
    solution = routing.SolveWithParameters(search_parameters)

    # Print solution on console.
    if solution:
        print_solution(data, manager, routing, solution)

    print("Status", routing.status())
if __name__ == '__main__':
    main()

And I am replacing the create_data_model() function with following for 5 nodes case which is working:
def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['time_matrix'] = [
        [0, 6, 9, 8, 7],
        [6, 0, 8, 3, 2],
        [9, 8, 0, 11, 10],
        [8, 3, 11, 0, 1],
        [7, 2, 10, 1, 0],
    ]

    data['time_windows'] = [
        (0, 180),  # depot
        (0, 180),  # 1
        (0, 180),  # 2
        (0, 180),  # 3
        (0, 180),  # 4

    ]
    data['pickups_deliveries'] = [
        [1, 3],     #2
        [2, 4],    #4 ripler
            #3
    ]
    data['demands'] = [0, 2, 4, -2, -4]
    data['vehicle_capacities'] = [2, 7]
    data['num_vehicles'] = 2
    data['depot'] = 0
    return data

A: My 2 cents,
If you have 16 nodes, they should be in range [0;15] but in your PickupAndDelivery array we can see a 16...
EDIT: seems you have 17 nodes (with the depot)


Q: Running "pub install" for dart-html5-samples leads to weird errors I encountered some weird errors when running "pub install" for dart-html5-samples. The first one was:
Illegal argument(s): join(): part 0 was null, but part 1 was not.

The second one was:
Running pub install ...
Pub install failed, [1] Resolving dependencies...
Could not find package "unittest 0.0.0-r.13075" at http://pub.dartlang.org.

What's going on, and how do I fix it?

A: The first error is:
Illegal argument(s): join(): part 0 was null, but part 1 was not.

That's because pubspec.yaml contained:
dependencies:
  htmlescape:
    sdk: htmlescape

htmlescape no longer comes with the SDK. Removing the dependency fixed the problem. I simply made a copy of htmlescape.dart in my lib directory. Eventually, I won't need my own copy once the following bug is fixed:
http://code.google.com/p/dart/issues/detail?id=1657
The second error is:
Running pub install ...
Pub install failed, [1] Resolving dependencies...
Could not find package "unittest 0.0.0-r.13075" at http://pub.dartlang.org.

dart-html5-samples depends on vector_math which depends on unittest. I think they must have changed how unittest is loaded by pub. Running pub update fixed the problem.


Q: Yii2 - Unknown error in renderSelectOptions method when using active dropDownList I'm getting an error when the aforementioned method gets called during the use of activeForm's dropDownList. What's weird is that I have already made other dropDownLists in a similar manner and they're working normally.
The error is:
PHP Warning – yii\base\ErrorException
strcmp() expects parameter 2 to be string, object given

The _form code for generating the list is as follows:
$lista_unidades = ArrayHelper::map(Unidad::find()->where('institucion="Carabineros de Chile"')->asArray()->all(), 'id_unidad', 'nombre');

asort($lista_unidades);

$form->field($model, 'id_unidad_que_diligencia')->dropDownList($lista_unidades, ['prompt' => 'Seleccione...']);

Yii2 provides the following information about the error (links to images):
First, Second
Any help will be greatly appreciated.
EDIT:
The Model Class:
<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;

/**
 * This is the model class for table "orden_judicial".
 *
 * @property string $id_orden_judicial
 * @property string $causa_rit
 * @property string $causa_ruc
 * @property string $causa_rol
 * @property string $fecha_emision
 * @property string $tipo
 * @property string $estado
 * @property string $id_unidad_que_direcciona
 * @property string $id_unidad_que_diligencia
 * @property string $id_unidad_que_redirecciona
 *
 * @property AdjuntoOrdenJudicial[] $adjuntoOrdenJudicials
 * @property Aviso[] $avisos
 * @property Persona[] $rutPersonas
 * @property Dilgienciamiento[] $dilgienciamientos
 * @property Unidad $idUnidadQueDirecciona
 * @property Unidad $idUnidadQueDiligencia
 * @property Unidad $idUnidadQueRedirecciona
 */
class OrdenJudicial extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
     public static function tableName()
    {
        return 'orden_judicial';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['fecha_emision', 'tipo', 'estado', 'id_unidad_que_direcciona', 'id_unidad_que_diligencia'], 'required'],
            [['fecha_emision'], 'safe'],
            [['id_unidad_que_direcciona', 'id_unidad_que_diligencia', 'id_unidad_que_redirecciona'], 'integer'],
            [['causa_rit', 'causa_ruc', 'causa_rol', 'tipo', 'estado'], 'string', 'max' => 100]
        ];
    }

    public function behaviors() {
        return [
                [
                    'class' => TimestampBehavior::className(),
                    'createdAtAttribute' => 'fecha_emision',
                    'updatedAtAttribute' => false,
                    'value' => new Expression('NOW()'),
                ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_orden_judicial' => 'Número de orden',
            'causa_rit' => 'Causa RIT',
            'causa_ruc' => 'Causa RUC',
            'causa_rol' => 'Causa ROL',
            'fecha_emision' => 'Fecha de Emisión',
            'tipo' => 'Tipo',
            'estado' => 'Estado',
            'id_unidad_que_direcciona' => 'Tribunal o Fiscalía',
            'id_unidad_que_diligencia' => 'Unidad Policial',
            'id_unidad_que_redirecciona' => 'Unidad que Redirecciona',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAdjuntoOrdenJudicials()
    {
        return $this->hasMany(AdjuntoOrdenJudicial::className(), ['id_orden_judicial' => 'id_orden_judicial']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAvisos()
    {
        return $this->hasMany(Aviso::className(), ['id_orden_judicial' => 'id_orden_judicial']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRutPersonas()
    {
        return $this->hasMany(Persona::className(), ['rut_persona' => 'rut_persona'])->viaTable('aviso', ['id_orden_judicial' => 'id_orden_judicial']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDilgienciamientos()
    {
        return $this->hasMany(Dilgienciamiento::className(), ['id_orden_judicial' => 'id_orden_judicial']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdUnidadQueDirecciona()
    {
        return $this->hasOne(Unidad::className(), ['id_unidad' => 'id_unidad_que_direcciona']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdUnidadQueDiligencia()
    {
        return $this->hasOne(Unidad::className(), ['id_unidad' => 'id_unidad_que_diligencia']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdUnidadQueRedirecciona()
    {
        return $this->hasOne(Unidad::className(), ['id_unidad' => 'id_unidad_que_redirecciona']);
    }
}

And the Controller Class with the relevant action:
<?php

namespace app\controllers;

use Yii;
use app\models\OrdenJudicial;
use app\models\OrdenJudicialSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * OrdenJudicialController implements the CRUD actions for OrdenJudicial model.
 */
class OrdenJudicialController extends Controller
{

    (...)

    public function actionCreate()
    {

        $model = new OrdenJudicial();

        $model->estado = "En Creacion";

        $idUnidadQueDiligencia = Yii::$app->getUser()->identity->getIdUnidad();

        $model->id_unidad_que_diligencia = $idUnidadQueDiligencia;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id_orden_judicial]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    (...)
}

A: Could be your id_unidad_que_diligencia si an object an not a single value.
$idUnidadQueDiligencia = Yii::$app->getUser()->identity->getIdUnidad();

$model->id_unidad_que_diligencia = $idUnidadQueDiligencia;

try chech this situation using
var_dump($model->id_unidad_que_diligencia)

then if is not a flat string value adjust you code for gettin the proper value.


Q: Embedding Instagram post using editor js in react-native I'm trying to embed an instagram post using editor js on react-native. I'm unable to find any approaches similar to,
https://www.npmjs.com/package/editorjs-youtube-embed
Any help would be appreciated.

A: This worked for me
Editor JS Links
Simply add as follows under tools:
embed: {
        class: Embed,
        config: {
          services: {
            instagram: true,
          },
        },
      },


Q: Is it possible to control axis number independently of tickSize? Essentially I want to draw something like this: http://i.stack.imgur.com/JEKOg.png (the gridlines, not the graph).
It seems if tickSize is set to one (below) then there are a bunch of lines drawn with their corresponding axis number below them.
xaxis, yaxis: {
    show: true,
    min: -20,
    max: 20,
    tickSize: 1,
    tickLength: 0
}

If it's not set (below), the graph'll automatically draw one every 5 units along with their numbers
xaxis, yaxis: {
    show: true,
    min: -20,
    max: 20,
    tickLength: 0
}

I want gridlines every 1 unit but numbers every 5 but I don't see a method to do it.

A: You can manually specify the tick labels with an array:
ticks: [[0, "0"], [1, ""], [2, ""], [3, ""], [4, ""], [5, "5"]],

Or, you can specify a function to do it:
ticks: function(axis) {
    var tickArray = [[0,"0"]];
    for(var i=axis.min; i<axis.max+1; i++) {
         var label = i%5?"":i;
         tickArray.push([i, label]);
    }
    return tickArray;
},

Demo: http://jsfiddle.net/jtbowden/gryozh7x/
You can also use a tickFormatter:
tickSize: 1,
tickFormatter: function (val, axis) {
    return val%5?"":val;
}

Demo: http://jsfiddle.net/jtbowden/gryozh7x/1/


Q: How to bind linesements point to xml data in WPF I have some data
<Array>
    <Element Value="30"/>
    <Element Value="50"/>
    <Element Value="10"/>
</Array>

Now I want to create a curve using this data. I think to use the LineSegments. But I can't understand how to bind the LineSegment Points to this data?
I mean, is there any syntax that helps to write instead of
<GeometryDrawing.Geometry>
  <PathGeometry>
    <PathFigure>
      <LineSegment Point="0,30"/>
      <LineSegment Point="20,50"/>
      <LineSegment Point="40,10"/>
    </PathFigure>
  </PathGeometry>
</GeometryDrawing.Geometry>

something like this:
<GeometryDrawing.Geometry>
  <PathGeometry>
    <PathFigure>
      <LineSegment Point={Binding ????}/>
    </PathFigure>
  </PathGeometry>
</GeometryDrawing.Geometry>

The main problem is how to bind the coordinates to point structure of a linesegment using binding.
Thanks in advance!

A: In stead of converting array of points into LineSegment collection, you can simply use PolyLineSegment. If the Binding just need to work intially (turn array of points to PointCollection of the PolyLineSegment intially, after that every changes made on the array of points won't trigger updating to the PolyLineSegment), you can do something like this:
public MainWindow(){
   InitializeComponent();
   //set DataContext
   //Initialize your Points here ...
   //...
   DataContext = this;
}
public Point[] Points {get;private set;}

Here is the converter used to convert the array of points to PointCollection:
public class PointArrayToPointCollection : IValueConverter {
   object IValueConverter.Convert(object value, Type targetType,
                                  object parameter, CultureInfo culture) {
      var points = value as IEnumerable<Point>;
      if(points != null) return new PointCollection(points);
      return Binding.DoNothing;
   }
   object IValueConverter.ConvertBack(object value, Type targetType,
                                      object parameter, CultureInfo culture) {
      throw new NotImplementedException();
   }
}

Then in XAML code:
<Window x:Class="yourNameSpace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:yourNameSpace"/>
  <Window.Resources>
     <local:PointArrayToPointCollection x:Key="pointsToPointCollection"/>
  </Window.Resources>
  <Image>
     <Image.Source>
        <DrawingImage>
           <DrawingImage.Drawing>
             <GeometryDrawing>
               <GeometryDrawing.Pen>
                  <Pen Brush="Red" Thickness="1"></Pen>
               </GeometryDrawing.Pen>
               <GeometryDrawing.Geometry>
                  <PathGeometry>
                    <PathFigure>
                       <PolyLineSegment Points="{Binding Points,
                          Converter={StaticResource pointsToPointCollection}}"/>
                    </PathFigure>
                  </PathGeometry>
               </GeometryDrawing.Geometry>
             </DrawingImage.Drawing>
        </DrawingImage>
     </Image.Source>
  </Image>
</Window>

This answer may not exactly solve your problem but the idea of using PolyLineSegment should point you to the right direction.
Update:
Well I just thought you need some actual code run in real application. If you need just XAML code to test (or play with) right in KXAML editor, there is no reason for you to use XML data here. Because we need exactly a PointCollection for the Points property of a PolyLineSegment, so using any other kind of data will require some conversion (which can be done only via code behind). So we can just need to specify the PointCollection as an instance right in XAML code, it can be like this:
<Page.Resources>
  <PointCollection x:Key="points">
     <Point>0,30</Point>
     <Point>20,50</Point>
     <Point>40,10</Point>
  </PointCollection>
</Page.Resources>
<Grid>
  <Grid.Background>
   <DrawingBrush>
      <DrawingBrush.Drawing>
          <GeometryDrawing>
             <GeometryDrawing.Pen>
                <Pen Brush="Red" Thickness="1"></Pen>
             </GeometryDrawing.Pen>
             <GeometryDrawing.Geometry>
                <PathGeometry>
                   <PathFigure>
                       <PolyLineSegment Points="{StaticResource points}"></PolyLineSegment>
                   </PathFigure>
                </PathGeometry>
             </GeometryDrawing.Geometry>
          </GeometryDrawing>
      </DrawingBrush.Drawing>
    </DrawingBrush>
  </Grid.Background>
</Grid>

I understand that you may have a collection of more continuous points (which can shape a nearly curvy line). If you want some perfect curve, you can try playing with BezierSegment, PolyBezierSegment, QuadraticBezierSegment, PolyQuadraticBezierSegment like this:
<Grid>
 <Grid.Background>
   <DrawingBrush Stretch="None" Viewport="0.2,0.2,0.6,0.6">
      <DrawingBrush.Drawing>
          <GeometryDrawing>
             <GeometryDrawing.Pen>
                <Pen Brush="Red" Thickness="1"></Pen>
             </GeometryDrawing.Pen>
             <GeometryDrawing.Geometry>
                <PathGeometry>
                   <PathFigure>
                       <PolyBezierSegment Points="10,10 200,150 300,30 320,10 330,-100 20,30">
                       </PolyBezierSegment>
                   </PathFigure>
                </PathGeometry>
             </GeometryDrawing.Geometry>
          </GeometryDrawing>
      </DrawingBrush.Drawing>
   </DrawingBrush>
 </Grid.Background>
</Grid>

Or you can even try using the so-called mini Path language to define the PathGeometry like this:
<Grid>
  <Grid.Background>
   <DrawingBrush Stretch="None" Viewport="0.2,0.2,0.6,0.6">
      <DrawingBrush.Drawing>
          <GeometryDrawing Geometry="M0,0 C10,10 200,150 300,30 320,10 330,-100 20,30">
             <GeometryDrawing.Pen>
                <Pen Brush="Red" Thickness="1"></Pen>
             </GeometryDrawing.Pen>
          </GeometryDrawing>
      </DrawingBrush.Drawing>
   </DrawingBrush>
  </Grid.Background>
</Grid>

The mini path language works due to the implicit GeometryConverter. You can use this mini language for PathFigureCollection (converted by PathFigureCollectionConverter) and the Data property of a Path shape.


Q: C# XML serializing with attributes for every element I want to create the following xml:
 <StartLot>
      <fileCreationDate level="7">201301132210</fileCreationDate>
      <fmtVersion level="7">3.0</fmtVersion>
 </StartLot>

Below is the Serialization code:
[Serializable]
class StartLot
{
    public fileCreationDate{get; set;}

    [XmlAttribute("level")]
    public string level = "7";

    public fmtVersion{get; set;}

    [XmlAttribute("level")]
    public string level = "7"; ??
}

Since I already declared attribute level, how do I add the last attribute?

A: You can use a wrapped class to store both values, as in the example below:
public class StackOverflow_15441384
{
    const string XML = @"<StartLot>
                               <fileCreationDate level=""7"">201301132210</fileCreationDate>
                               <fmtVersion level=""7"">3.0</fmtVersion>
                            </StartLot>";
    public class StartLot
    {
        [XmlElement("fileCreationDate")]
        public LevelAndValue FileCreationDate { get; set; }
        [XmlElement("fmtVersion")]
        public LevelAndValue FmtVersion { get; set; }
    }
    public class LevelAndValue
    {
        [XmlAttribute("level")]
        public string Level { get; set; }
        [XmlText]
        public string Value { get; set; }
    }
    public static void Test()
    {
        XmlSerializer xs = new XmlSerializer(typeof(StartLot));
        StartLot sl = (StartLot)xs.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(XML)));
        Console.WriteLine("FCD.L = {0}", sl.FileCreationDate.Level);
        Console.WriteLine("FCD.V = {0}", sl.FileCreationDate.Value);
        Console.WriteLine("FV.L = {0}", sl.FmtVersion.Level);
        Console.WriteLine("FV.V = {0}", sl.FmtVersion.Value);
    }
}

A: I always find Linq To Xml easier to use
var xDoc = XDocument.Parse(xml); /* XDocument.Load(filename); */

var items = xDoc.Root.Descendants()
                .Select(e => new
                {
                    Name = e.Name.LocalName,
                    Level = e.Attribute("level").Value,
                    Value = e.Value
                })
                .ToList();


Q: Swift Firebase persistence I'm trying to enable Firebase Persistence but my code keeps crashing with:

terminating with uncaught exception of type NSException

I have tried the line of code under my viewDidLoad as well as under DataService but I still get the same crash. what do I need to do to resolve this problem I'm facing
import UIKit
import Firebase

class HomeTeamSelectionVC: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var club: Clubs!
    var player = [Players]()
    var playerFirstName = String()
    var playerLastName = String()
    var playerSelected: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        FIRDatabase.database().persistenceEnabled = true //Correct use of????

        CLUB_KEY = ""
        CLUB_KEY = club.clubKey

        tableView.dataSource = self
        tableView.delegate = self

        DataService.ds.REF_PLAYERS.queryOrdered(byChild: "clubKey").queryEqual(toValue: club.clubKey).observe(.value, with: { (snapshot) in

            print("PLAYERS_COUNT: \(snapshot.childrenCount)")
            print("PLAYERS_SNAPSHOT: \(snapshot)")

            self.player = []
            if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {

                for snap in snapshots {
                    if let playerDict = snap.value as? Dictionary<String, AnyObject> {
                        let key = snap.key

                        let players = Players(playerKey: key, dictionary: playerDict)
                        self.player.append(players)

                    }
                }
            }
            //            self.tableView.reloadData()
        }) { (error) in
            print(error.localizedDescription)
            print("CHET: local error")
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return player.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let players = player[indexPath.row]
        if let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTeamPlayersCell") as? HomeTeamPlayersCell {
            cell.configureCell(players)
            return cell
        } else {
            return HomeTeamPlayersCell()
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let players: Players!
        players = player[indexPath.row]

        print (players.playerKey)
        print (players.playerFirstName)
        print (players.playerLastName)

        dismiss(animated: true, completion: nil)
    }
}

A: From Firebase documentation for persistenceEnabled property:

Note that this property must be set before creating your first Database reference and only needs to be called once per application.

As such, the standard practice is to set it once in your AppDelegate class. For instance:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    FIRApp.configure()
    FIRDatabase.database().persistenceEnabled = true
    ...
    return true

}


Q: Given an undirected graph, find the number of ways to remove edges to make all vertices even degree You're given an undirected graph G with E number of edges. You're allowed to remove edges as much as you like to make all the vertices in the graph have an even degree. The task is to find the number of ways we can achieve this. All disconnected graph is also a valid solution. I'm struggling to find an algorithm to find the ways without brute-force. Any direction is appreciated.
Edit:
The order in which edges are selected to be removed doesn't matter. The goal is to find the number of ways to select the set of edges to remove.
Edit:
A graph without all edges is also a valid way and should be counted.

A: Let $G=(V,E)$, where $V$ is the set of vertices and $E$ is the set of edges.
Let $A$ be the $|V|\times|E|$ matrix such that for each $e=\{u,v\}\in E$ we have $A_{u,e}=A_{v,e}=1$, and all the remaining elements of $A$ are zero. Then, if we identify a subgraph (obtained after removing edges) by a map $x : E\to\{0,1\}, e\mapsto x_e$, with $x_e$ indicating the presence of $e$, then the degree of a vertex $v\in V$ in this subgraph is $\sum_{e\in E}A_{v,e}x_e$.
If we consider $A$ as a matrix over the field $\mathbb{F}_2$, and $x$ as a column vector (over $\mathbb{F}_2$), then all the degrees are even if and only if $Ax=0$ (in $\mathbb{F}_2$). So we are facing the problem of computing the kernel of $A$ (the number of solutions $x$ is equal to $2^d$, where $d$ is the dimension of the kernel).
Here, any suitable kernel-finding method will do.


Q: Problemas em fazer acontecer eventos no JS Estou aprendendo sobre events no JavaSCript, e começei a praticar, porém me deparei com uma lógica que não estou conseguindo raciocinar ou associar.
Estou querendo que toda vez que eu clicar no botão, o nome dele seja mudado, no exemplo que está em comentário, esse funciona perfeitamente, claro que lá no primeiro modelo HTML o button não tem o onclick, mas no segundo modelo em que eu coloco o onclick: "myFunction()", e faço a função no .js, dá um Uncaght TypeError. Eu não estou conseguindo entender por o nome do button não muda

Eu acho que tem alguma coisa haver com os parênteses no onclick: "myFunction()", sendo isso ou não, não sei o que está havendo

HTML

Easy Shopping Via Mobile

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lorem justo, sollicitudin vel ultricies
                sed,
                eleifend nec metus. Etiam vitae pellentesque dolor.

            <button onclick="myFunction()">Get Started</button>

JS
const element = document.querySelector("button")

// element.onclick = function () {
//     element.innerHTML = "Hokage"
//  }

const myFunction = (element) => {
    element.innerHTML = "Hokage"
}

A: Ola, seu erro esta no seu evento onclick, a função myFunction recebe um objeto, myFunction(Objeto), porém no seu evento onclick está apenas myFunction(). O correto seria:
<button onclick="myFunction(this)">Get Started</button>


Q: Gmail email contents transfer to google spreadsheet I ask for help. Help me to finish the script. It is necessary to transfer the contents of mail gmail, to Google table. There is a script, but it only transfers the date and subject of the letter, and the message itself does not. Help, that it is possible to correct. Thanks
 function getGmailData() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var threads = GmailApp.search("is:unread in:inbox", 0, 1);
  for (var t=0; t<threads.length; t++) {
    sheet.appendRow([threads[t].getDate(), threads[t].getFirstMessageSubject()])
  }
}

A: How about a following modification?
Modification points :

*

*In order to retrieve messages from threads, getMessages() is used.

*In order to retrieve each message from messages retrieved by getMessages(), it retrieves using one more "for loop".

*For each mail, the Date, From, Subject and Body can be retrieved by getDate(), getFrom(), getSubject() and getPlainBody(), respecrively.

Modified script :
function getGmailData() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var threads = GmailApp.search("is:unread in:inbox", 0, 1);
  var res = [];
  for (var t=0; t<threads.length; t++) {
    var msgs = threads[t].getMessages();
    for (var u=0; u<msgs.length; u++) {
      var m = msgs[u];
      res.push([m.getDate(), m.getFrom(), m.getSubject(), m.getPlainBody()]);
    }
  }
  sheet.getRange(sheet.getLastRow() + 1, 1, res.length, res[0].length).setValues(res);
}

If I misunderstand your question, I'm sorry.
Edit :
When you want to retrieve mails from today, you can use newer_than: and after: operators.
In the case of using newer_than:
var threads = GmailApp.search("newer_than:1d in:inbox", 0, 1);

In the case of using after:
var today = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy/MM/dd');
var threads = GmailApp.search("after:" + today + " in:inbox", 0, 1);


Q: FilteredPaste.js working with textarea I am working with jQuery plugin called FilteredPaste.js that removes all HTML elements when copy and pasted to a input. I want to apply it to textarea element but it does not seems to work. Nothing gets pasted. The example uses contenteditable but I need to use textarea instead. Or any alternative plugin suggestion is welcome.
Here is what I have so far.
  jQuery(document).ready(

    function() {

        $("#content").filteredPaste({
            "filters" : ["default"]
        });

    }
  );

http://jsfiddle.net/9M3vh/


Q: How can I completely disable internal Mic and Webcam I want to disable the internal Microphone on my laptop and the internal Webcam completely that they're no longer selectable, and no longer available?
I will only use my external Webcam, and my external (USB) headset.
The internal audio should still be available for playback.

A: Blacklist the webcam driver and mute the Internal Mic from Alsamixer.
According to the informations you gave here, open a terminal and execute this command
Disable WebCam
echo 'blacklist webcamstudio' | sudo tee -a /etc/modprobe.d/blacklist.conf

Mute the microphone
To mute the internal microphone use the alsamixer.
Open a terminal and give this command
alsamixer

Navigate with arrow keys <--> and find the internal or mic channel and then press the M key on your keyboard to disable - mute [MM] the microphone. Esc to exit

A: Some Notebooks allow to disable their webcam and microphone in the BIOS settings.

A: Blacklist drivers
In both cases kernel drivers may be loaded for both, the internal sound card, and the webcam to be recognized by Ubuntu. We can find out which drivers are loaded by the following command in a terminal:
lsmod

From this list we can see which of these kernel modules may be responsible for our (specific) hardware (e.g. an Intel sound card may need the snd_hda_intel module).
Blacklisting these kernel module will stop this device from being recognized by your system. To do so we edit the file /etc/modprobe.d/blacklist.conf as root to add the following line:
blacklist <name_of_module>

See also: How can I control which sound card Ubuntu uses for playback?
In case we still need the internal audio card for playback audio we can just mute the input microphone source, e.g by running alsamixer in a terminal.

A: Use PulseAudio Volume Control (which has a GUI):

*

*install pavucontrol via terminal (e.g. snap install pavucontrol or sudo apt install pavucontrol)

*launch the tool via terminal or via launcher PulseAudio Volume Control

*Go to the "Configuration" tab (you might need to resize the window to see it)

*Disable the microphone by switching it to Off
This also worked for me after plugging in the webcam again (it's still switched off).


Q: Creating menu for NSSegmentedControl using XIB How do we create menu for a particular segment using xib for NSSegmentedControl ?

A: You just drag an NSMenu from the object library and release it over the segment you want it to be attached to.


Q: While loggin in via fb to website, my function TestApi doesn't collect user data I am trying to create login via facebook on the website. Unfortunately, while user is logged in and the function TestAPI() is triggered, I can't get the data from the user.
 function TestAPI(){
   FB.api('/me?fields=id,name,email', function response (){
     if (response && !response.error){
       console.log(response);
       buildProfile (response);
     }
   })
 }

 function buildProfile(user){
   let profile = `

 $(user.name)

 $(user.id)

 $(user.email)
`;

   document.getElementById('profile').innerHTML = profile;
 }

I've got following communicates in console:
sdk.js:108 Uncaught TypeError: Cannot set property 'innerHTML' of
null
at buildProfile (volunteer_system.html:65)
at response (volunteer_system.html:50)
at a.__wrapper.a.__wrapper (sdk.js:108)
at D (sdk.js:123)
at Object.b.onload (sdk.js:119)
at sdk.js:119
at sdk.js:50
at XMLHttpRequest.c.onreadystatechange (sdk.js:119)

A:
I get the function instead of data

console.log(response);
This prints out the function instead of the response data, because response is the name of your function, not the name of the argument passed to the function. Consider the change below:
function TestAPI() {
    FB.api('/me?fields=id,name,email', function(response) {
        if (response && !response.error) {
            console.log(response);
            buildProfile (response);
        }
   });
}

TypeError: Cannot set property 'innerHTML' of null

This means that document.getElementById('profile') is returning null, it's possible that an element with this id does not exist in your DOM, but this is difficult to confirm without you sharing a code excerpt of the HTML you're trying to modify. You should have an element that looks something like this:


Q: Как сделать у изображения плавный :hover? Есть два изображения для ссылки. Нужно что бы один фон ссылки, в виде изображения переходил плавно во второе.
A: Вот примеры на css:
html:

Label

 Label

css:
switchedBackground {
    width: 300px;
    height: 200px;
    position: relative;
    display: block;
}

.switchedBackground .bg1 ,  .switchedBackground .bg2 {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left:0;
    transition: all 2s;

}
.switchedBackground .bg1 {
   background: url('http://placehold.it/300x200/000/00ee00&text=1');
   opacity:1;
}
.switchedBackground .bg2 {
    background: url('http://placehold.it/300x200/000/00ee00&text=2');
    opacity:0;
}

.switchedBackground .label {
    margin: auto;
    position: absolute;
    top: 0;
}

.switchedBackground:hover .bg2 {
    opacity: 1;
}

/* только в chrome */
.switchedBackground2 {
    width: 300px;
    height: 200px;
    display: block;
    background: url('http://placehold.it/300x200/000/00ee00&text=3');
    transition: all 3s;
}
.switchedBackground2:hover {
    background: url('http://placehold.it/300x200/000/00ee00&text=4');
    transition: all 3s;
}

http://jsfiddle.net/oceog/uyfN8/
A: Посмотреть пример
html

Текст много-много текста

css

.example, .example::after, .example > span {
    display: block;
    height: 50px;
    width: 200px;
}
.example {
    background-image: url(http://placehold.it/200x50/09c/09c.png);
    position: relative;
}
.example::after {
    background-image: url(http://placehold.it/200x50/c90/c90.png);
    content: "";
    opacity: 1;
    -webkit-transition: opacity 0.5s ease-in-out;
    -moz-transition: opacity 0.5s ease-in-out;
    -o-transition: opacity 0.5s ease-in-out;
    transition: opacity 0.5s ease-in-out;
}
.example:hover::after {
    opacity: 0;
    -webkit-transition: opacity 0.5s ease-in-out;
    -moz-transition: opacity 0.5s ease-in-out;
    -o-transition: opacity 0.5s ease-in-out;
    transition: opacity 0.5s ease-in-out;
}
.example::after, .example > span {
    position: absolute;
}
.example > span {
    color: #000;
    line-height: 50px;
    text-align: center;
    z-index: 2;
}
.example:hover > span {
    color: #fff;
}


Q: Ember: How to link to sections and actions (without nesting routes) Let's say that I have a blog where each post can have several sections and comments and I'd like to use a hard-links to navigate and operate on this. There are several samples using some pseudo-code, of course they doesn't work, just demonstring my intends :)
Of course /blog.html#/posts/1 uses PostRoute, PostController etc and uses :post_id for finding object - that's obvoius.

*

*How can I pass (and then access) additional params which doesn't change the controller but I can use them to navigation. ie /blog.html#/posts/1?section=123 should use the same route, controller and view as it was just Post, but I'd like to read the section and just navigate to section with #123

*/blog.html#/posts/1/?comments=456 - actually should behave like section from point 1, but navigates to comment and optionally add some class to the container.

*Other case: I'd like to go to section 123 AND additionally edit it with link like: /blog.html#/posts/1?section=123&action=edit. Now I'm using a button with an action like {{action editSection section}} and {{#if isEdit}} but I'd like to be able to reflect this in URL and also go to this state from URL (de facto my post can have several different modes not only preview/edit, therefore it should be accesible by the link).

I hope that cases makes sense, TBH I have no idea in which direction should I go. Tried with nested routes, but I'd like to avoid changing the controller. Also have no concept how to reflect the action in the URL...
I'm using Ember 1.1.2

A: You can use the model method of the route to handle such parameters, separate them from the model parameter and set the appropriate controller state.
Another approach would be to use nested routes that will render un-nested views(and controllers) - as explained towards the bottom here.


Q: Trying to toggle style CSS link "href" on click Jquery Trying to do a dark-mode toggle on click of element

*

*toggle div class = .dark__mode

*css link class = .css-link

*css link href variable = style__old

I am learning jquery and i think there is a major problem with reasoning and structure of code
The link href changes at first but doesn't change back
Please help and or if using a checkbox option is better
window.onload = function(){

    var  style__old = $(".css-link").attr("href");

    $(".dark__mode").click(function(){

            if (style__old == "css/style.css"){
                var style__new = style__old.replace("style.css","dark-mode.css");
                $(".css-link").attr("href", style__new);
            }
            else
            if (style__old == "css/dark-mode.css"){
                style__old.replace("dark-mode.css","style.css");
                $(".css-link").attr("href", "style__old");
            }
    }

);}

A: The approach you're using of dynamically changing the loaded stylesheet is not very reliable.
A much better approach is to put all the relevant styles in to the page, in separate stylesheets, then toggle() a class on a low level element, such as the body, and hang all your selectors off that.
In practice it would look something like this:

jQuery($ => {
  $('.dark__mode').on('click', (e) => {
    e.preventDefault();
    $('body').toggleClass('dark');
  })
});
/* Normal layout */
div { color: #0C0; }
a { color: #C00; }

/* Dark layout */
body.dark {
  background-color: #333;
  color: #FFF;
}
body.dark div { color: #CCC; }
body.dark a { color: #CC0; }

Toggle

Lorem ipsum dolor sit

  Amet consectetur adipcing elit


Q: How can I determine the window controlled by an instance of NSWindowController ? How can I determine the window controlled by an instance of NSWindowController ? According to Apple's docs, sending the controller the 'window' accessor message returns  "The window owned by the receiver."  But when I use it on an instance loaded from a NIB via initWithWindowNibPath:owner: it always returns 0.
I've searched unsuccessfully through Apple's AppKit docs for another message that might work better. (It's possible that a function that returns the content _view for the window in question would also work, since my ultimate goal is to be able to access the contained Views via their Tag fields.)
Maybe I'm misunderstanding the purpose of this window accessor? If so, is there a method that will allow me to determine the actual window controlled by my NSController instance?
thanks


Q: Show loading image on redirection I have two pages x.php and y.php, I am redirecting the page x.php to y.php. I am redirecting the  page by form post method.
y.php is pulling some more data from mysql database and it is taking 3 to 4 seconds to load that page, I need to show progress bar (loading image) while page loads.
This is what, I am doing,
a html page is submitting to remote server x.PHP page and x.PHP page is pulling data from mysql database and based on the type of data it redirects to y.PHP, this redirection is done by automatic form submit using Javascript.
I need to show loading image on both html to x.php and x.php to y.php.
I tried with echoing image tag on top of x.PHP page, it is working in Mozilla and not an other browsers.
How can I achieve this; can anyone help me?

A: I think that the only way to do this is to use AJAX - either on x.php to load y.php, or on y.php to load data.

A: you need to use jquery.  ı am using this code for that.
when your request start its load a loading image to page. when data return with success function it loading the data to page.
    $('#something').change(function(){ // change, click doesnt matter

    $('#load').html(""); // loading img

    $.post(
            'select.php?do=load', // your y.php
            {s:value},
            function(answer){

            $('#load').html("");
            $('#page').html(answer);

            }
    );

});

A:
Hope it helps


Q: Screen Resolution CentOS 8 - VMware System: CentOS8
I am using VMware ESXi
I can easily change a resolution to 1400x1050, but after reboot/shutdown returns to default resolution (800x600).
I set the .vmx file settings:
svga.vramSize = "67108864"
svga.minWidth="1400"
svga.minHeight="1050"
svga.maxWidth="1400"
svga.maxHeight="1050"
svga.autodetect = "FALSE" -- changing to "TRUE" it doesn't help either

A: Ok... So just for information.
Solution (workaround) is:
When logging in (entering the password), select the cog and change from:
Standard (Wayland display server)
to
Classic (X11 display server)
then the last selected correct resolution will automatically be loaded.
This option will also be remembered after reboot (Classic)


Q: Sample code for unit testing api controllers Is there an sample code that shows unit testing a controller that inherits from the api controller?
I am trying to unit test a POST but it is failing. I believe I need to set up the HttpControllerContext for testing but don't know how
Thanks

A: this code should demonstrate the basics of a post test. Assumes you have a repository injected into the controller. I am using MVC 4 RC not Beta here if you are using Beta the Request.CreateResponse(... is a little different so give me a shout...
Given controller code a little like this:
public class FooController : ApiController
{
    private IRepository<Foo> _fooRepository;

    public FooController(IRepository<Foo> fooRepository)
    {
        _fooRepository = fooRepository;
    }

    public HttpResponseMessage Post(Foo value)
    {
        HttpResponseMessage response;

        Foo returnValue = _fooRepository.Save(value);
        response = Request.CreateResponse<Foo>(HttpStatusCode.Created, returnValue, this.Configuration);
        response.Headers.Location = "http://server.com/foos/1";

        return response;
    }
}

The unit test would look a little like this (NUnit and RhinoMock)
        Foo dto = new Foo() {
            Id = -1,
            Name = "Hiya"
        };

        IRepository<Foo> fooRepository = MockRepository.GenerateMock<IRepository<Foo>>();
        fooRepository.Stub(x => x.Save(dto)).Return(new Foo() { Id = 1, Name = "Hiya" });

        FooController controller = new FooController(fooRepository);

        controller.Request = new HttpRequestMessage(HttpMethod.Post, "http://server.com/foos");
        //The line below was needed in WebApi RC as null config caused an issue after upgrade from Beta
        controller.Configuration = new System.Web.Http.HttpConfiguration(new System.Web.Http.HttpRouteCollection());

        var result = controller.Post(dto);

        Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Expecting a 201 Message");

        var resultFoo = result.Content.ReadAsAsync<Foo>().Result;
        Assert.IsNotNull(resultFoo, "Response was empty!");
        Assert.AreEqual(1, resultFoo.Id, "Foo id should be set");

A: Using AutoFixture, I usually do something like this:
[Theory, AutoCatalogData]
public void PostToCollectionReturnsCorrectResponse(
    CategoriesController sut,
    CategoryRendition categoryRendition)
{
    HttpResponseMessage response = sut.Post(categoryRendition);

    Assert.Equal(HttpStatusCode.Created, response.StatusCode);
}

See this other SO answer for more details about this approach.

A: Sample code for unit testing API controller with async fundtion in C#

*

*Prepare test Models:
        using System;
        namespace TestAPI.Models
        {
            public class TestResult
            {
                public DateTime Date { get; set; }
                public bool Success { get; set; }
                public string Message { get; set; }
            }
        }

*Prepare test controller
        using TestAPI.Models;
        using System;
        using System.Net;
        using System.Threading.Tasks;
        using System.Web.Http;
        using System.Web.Http.Description;

        namespace TestAPI.Controllers
        {
            public class TestController : ApiController
            {
                public TestController()
                {
                }

                [HttpPost]
                [ResponseType(typeof(TestResult))]
                [Route("api/test/start")]
                public async Task<IHttpActionResult> StartTest()
                {
                    DateTime startTime = DateTime.Now;
                    var testProcessor = new TestAsync();
                    await testProcessor.StartTestAsync();

                    HttpStatusCode statusCode = HttpStatusCode.OK;
                    return Content(statusCode, new TestResult
                    {
                        Date = DateTime.Now,
                        Success = true,
                        Message = "test"
                    });
                }

            }
        }

*unit test async controller with result check from response
        using Microsoft.VisualStudio.TestTools.UnitTesting;
        using TestAPI.Controllers;
        using TestAPI.Models;
        using System.Web.Http;
        using System.Threading.Tasks;
        using System.Net;
        using System.Web.Script.Serialization;

        namespace Unit.Tests.Controllers
        {
            /// <summary>
            /// Summary description for ControllerTest
            /// </summary>
            [TestClass]
            public class ControllerTest
            {
                private TestController _testController;
                [TestInitialize]
                public void estAPI_Initializer()
                {
                    _testController = new TestController();
                    var configuration = new HttpConfiguration();
                    System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage();
                    request.Headers.Add("Authorization", "Bearer 1232141241");
                    request.Headers.Add("ContentType", "application/json");
                    _testController.Request = request;
                    _testController.Configuration = configuration;
                }

                [TestCategory("Unit test")]
                [TestMethod]
                public async Task API_Async_Controller_Test()
                {
                    IHttpActionResult asyncResponse = await _testController.StartTest();
                    var cToken = new System.Threading.CancellationToken(true);
                    var rResult = asyncResponse.ExecuteAsync(cToken);
                    Assert.IsNotNull(rResult);
                    Assert.IsNotNull(rResult.Result);
                    Assert.AreEqual(rResult.Result.StatusCode, HttpStatusCode.OK);
                    Assert.IsNotNull(rResult.Result.Content);
                    var rContent = rResult.Result.Content;

                    string data = await rContent.ReadAsStringAsync();
                    Assert.IsNotNull(data);
                    JavaScriptSerializer JSserializer = new JavaScriptSerializer();
                    var finalResult = JSserializer.Deserialize<TestResult>(data);

                    Assert.IsNotNull(finalResult);
                    Assert.IsTrue(finalResult.Success);
                }
            }
        }

A: I've created a general solution for calling some action and getting HttpResponseMessage as Dictionary which is very convenient for usage.
First some extension for the dictionary:
public static class DictionaryExtensions
{
    public static void AddRange<T, S>(this Dictionary<T, S> source,
                                      Dictionary<T, S> collection)
    {
        if (collection == null)
        {
            throw new NullReferenceException("Collection is null");
        }

        foreach (var item in collection)
        {
            source.Add(item.Key, item.Value);
        }
    }
}

Now request creating part:
public class RequestCreator
{
    protected static void FirstPart(ApiController controller,
                                    HttpMethod method,String actionUrl)
    {
        // Creating basic request message with message type and requesting
        // url example : 'http://www.someHostName/UrlPath/'
        controller.Request = new HttpRequestMessage(method, actionUrl);

        // Adding configuration for request
        controller.Request.Properties.
          Add(HttpPropertyKeys.HttpConfigurationKey,new HttpConfiguration());
    }

    protected static Dictionary<String, Object> SecondPart
                                                 (HttpResponseMessage response)
    {
        // Adding basic response content to dictionary
        var resultCollection = new Dictionary<String, Object>
        {
            {"StatusCode",response.StatusCode},
            {"Headers",response.Headers},
            {"Version",response.Version},
            {"RequestMessage",response.RequestMessage},
            {"ReasonPhrase",response.ReasonPhrase},
            {"IsSuccessStatusCode",response.IsSuccessStatusCode}
        };

        var responseContent = response.Content;
        // If response has content then parsing it and
        // getting content properties
        if (null != responseContent)
        {
            var resultMessageString = response.Content.
                                               ReadAsStringAsync().Result;
            resultCollection.AddRange((new JavaScriptSerializer()).
                                       DeserializeObject(resultMessageString)
                                               as Dictionary<String, Object>);
        }

        return resultCollection;
    }
}

And finally response message to dictionary converter class:
public class HttpResponseModelGetter : RequestCreator
{
    public Dictionary<String, Object>
                 GetActionResponse(ApiController controller,HttpMethod method,
                          String actionUrl,Func<HttpResponseMessage> callBack)
    {
        FirstPart(controller, method, actionUrl);
        var response = callBack();
        return SecondPart(response);
    }
}

public class HttpResponseModelGetter<T> : RequestCreator
{
    public Dictionary<String, Object>
             GetActionResponse(ApiController controller,HttpMethod method,
                String actionUrl,Func<T,HttpResponseMessage> callBack,T param)
    {
        FirstPart(controller, method, actionUrl);
        var response = callBack(param);
        return SecondPart(response);
    }
}

public class HttpResponseModelGetter<T1,T2> : RequestCreator
{
    public Dictionary<String, Object>
        GetActionResponse(ApiController controller,HttpMethod method,
             String actionUrl,Func<T1,T2,HttpResponseMessage> callBack,
             T1 param1,T2 param2)

    {
        FirstPart(controller, method, actionUrl);
        var response = callBack(param1,param2);
        return SecondPart(response);
    }
}
//and so on...

and usage :
var responseGetter = new HttpResponseModelGetter();
var result = responseGetter.GetActionResponse(controller,HttpMethod.Get,
                    "http://localhost/Project/api/MyControllerApi/SomeApiMethod",
                                              controller.SomeApiMethod);

Boolean isComplete = Boolean.Parse(result["isComplete"].ToString());


Q: A finite supersolvable group with generators of prescribed order Let $G=\langle a,b\rangle$ be a finite supersolvable group. Is there any special information about the structure of $G$ when $o(a)=2$ and $ o(b)=2^k > 2$?


Q: ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[NavbarComponent -> NavbarComponent I am trying to make a login with google Auth on Firebase and when I login and try to load another component or a page I get the following. I have been trying to fix this bug for a whole day now and am very fed up. If anyone could help it would be appreciated.
My entire project is public at https://github.com/domilx/ProjetBocal-Angular
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[NavbarComponent -> NavbarComponent -> NavbarComponent]:
  NullInjectorError: No provider for NavbarComponent!
get@http://localhost:4200/vendor.js:120414:27

Here is my code
Navbar.component.html:

  <mat-toolbar color="primary">
    <button routerLink="dashboard" mat-button aria-label="Home">
      <mat-icon>home</mat-icon>
      Projet Bocal
    </button>

    <button mat-button aria-label="Classroom">
      <mat-icon>class</mat-icon>
      Classroom
    </button>

    <button mat-button aria-label="Links">
      <mat-icon>links</mat-icon>
      Links
    </button>

    <button mat-button aria-label="Logout" *ngIf="auth.user$ | async as user" (click)="auth.signOut()">
      <mat-icon>exit_to_app</mat-icon>
      Logout, {{ user.displayName }}
    </button>

    <button routerLink="settings" mat-icon-button aria-label="settings" *ngIf="auth.user$ | async as user">
      <mat-icon>settings</mat-icon>
    </button>

  </mat-toolbar>

Auth.service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/compat/firestore';
import { Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from './user.model';
import { AngularFireAuth }  from '@angular/fire/compat/auth';
import { GoogleAuthProvider } from 'firebase/auth';

@Injectable({ providedIn: 'root' })
export class AuthService {
  user$: Observable<User | null | undefined>;
  constructor(
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router,
  ) {
    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          return of(null);
        }
      })
    );
  }

  async googleSignin() {
    const provider = new GoogleAuthProvider();
    const credential = await this.afAuth.signInWithPopup(provider);
    return this.updateUserData(credential.user);
  }

  async signOut() {
    await this.afAuth.signOut();
    return this.router.navigate(['/']);
  }

  private updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL
    };

    return userRef.set(data, { merge: true });

  }
}

Auth.guard.ts
import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router
} from '@angular/router';
import { Observable } from 'rxjs';

import { AuthService } from './auth.service';
import { tap, map, take } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService, private router: Router) {}

  canActivate(next, state): Observable<boolean> {
    return this.auth.user$.pipe(
      take(1),
      map(user => !!user), // <-- map to boolean
      tap(loggedIn => {
        if (!loggedIn) {
          console.log('access denied');
          this.router.navigate(['/']);
        }
      })
    );
  }
}

App.module.ts
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { initializeApp, provideFirebaseApp } from '@angular/fire/app';
import { getAuth, provideAuth } from '@angular/fire/auth';
import { AngularFireModule } from '@angular/fire/compat';
import { AngularFireAuthModule } from '@angular/fire/compat/auth';
import { AngularFireDatabaseModule } from '@angular/fire/compat/database';
import { AngularFirestoreModule } from '@angular/fire/compat/firestore/';
import { getFirestore, provideFirestore } from '@angular/fire/firestore';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
import { environment } from '../environments/environment';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AboutComponent } from './components/pages/about/about.component';
import { ContactComponent } from './components/pages/contact/contact.component';
import { ClassroomComponent } from './components/pages/dashboard/classroom/classroom.component';
import { DashboardComponent } from './components/pages/dashboard/dashboard/dashboard.component';
import { LinksComponent } from './components/pages/dashboard/links/links.component';
import { HomeComponent } from './components/pages/home/home.component';
import { SettingsComponent } from './components/pages/settings/settings.component';
import { FooterComponent } from './components/shared/footer/footer.component';
import { NavbarComponent } from './components/shared/navbar/navbar.component';
import { MaterialModule } from './material.module';
import { AuthService } from './services/auth.service';
import { AuthGuard } from './services/auth.guard';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    FooterComponent,
    AboutComponent,
    SettingsComponent,
    ContactComponent,
    DashboardComponent,
    HomeComponent,
    ClassroomComponent,
    LinksComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    RouterModule,
    MaterialModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    AngularFireAuthModule,
    AngularFirestoreModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule,
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideFirestore(() => getFirestore()),
    provideAuth(() => getAuth()),

  ],
  providers: [
    AngularFirestoreModule,
    AngularFireModule,
    AngularFireAuthModule,
    AngularFireDatabaseModule,
    AuthGuard,
    AuthService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

App-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SettingsComponent } from './components/pages/settings/settings.component';
import { AboutComponent} from './components/pages/about/about.component';
import { ContactComponent} from './components/pages/contact/contact.component';
import { DashboardComponent } from './components/pages/dashboard/dashboard/dashboard.component';
import { HomeComponent } from './components/pages/home/home.component';
import { AuthGuard } from './services/auth.guard';

const routes: Routes = [
  {path:'', component:HomeComponent},
  {path:'settings', component:SettingsComponent,  canActivate: [AuthGuard] },
  {path:'home', redirectTo:'/', pathMatch:'full'},
  {path:'about', component:AboutComponent,  canActivate: [AuthGuard] },
  {path:'contact', component:ContactComponent,  canActivate: [AuthGuard] },
  {path:'dashboard', component:DashboardComponent,  canActivate: [AuthGuard] },
];
  @NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
  })
export class AppRoutingModule { }

navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AuthService } from '../../../services/auth.service';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  constructor(public auth: AuthService) { }
  ngOnInit(): void {
  }

}

A: I found the issue..
In my dashboard.component.ts I had imported the NavBar for test a long while ago and forgot to remove it:
import { NavbarComponent } from './../../../shared/navbar/navbar.component';
import { Component, OnInit,EventEmitter,Output } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AuthService } from '../../../../services/auth.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  @Output() isLogout = new EventEmitter<void>()
  constructor(NavbarComponent : NavbarComponent, public auth: AuthService) { }

  ngOnInit(): void {

  }

}

Just had to remove
NavbarComponent : NavbarComponent


Q: Insert Multiple Array in Array to Store in Cart CodeIgniter I have array from foreach loop like this :
Array (
    [id] => 2
    [qty] => 1
    [price] => 130000
    [name] => 0002/PNBP/411971/1/02/18
)
Array (
    [id] => 3
    [qty] => 1
    [price] => 120000
    [name] => 0003/PNBP/411971/1/02/18
)
Array (
    [id] => 4
    [qty] => 1
    [price] => 150000
    [name] => 0004/PNBP/411971/1/02/18
)

I want insert data array in array like this :
Array(
    Array (
        [id] => 2
        [qty] => 1
        [price] => 130000
        [name] => 0002/PNBP/411971/1/02/18
    ),
    Array (
        [id] => 3
        [qty] => 1
        [price] => 120000
        [name] => 0003/PNBP/411971/1/02/18
    ),
    Array (
        [id] => 4
        [qty] => 1
        [price] => 150000
        [name] => 0004/PNBP/411971/1/02/18
    )
);

I try and code like this :
$data = array();
foreach ($_POST['id_kuitansi'] as $id_kuitansi){
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data = array(
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
    print_r($data);
    //$this->cart->insert($data);
}

A: Try this,
$data = array();
foreach ($_POST['id_kuitansi'] as $id_kuitansi){
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data[] .= array(
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
    print_r($data);
    //$this->cart->insert($data);
}

You were simply reassigned the values to $data each while you need to append the array value to the $data array

A: Problem solved with this code :
foreach ($_POST['id_kuitansi'] as $id_kuitansi)
{
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data[] = array(
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
}
//print_r($data);
$this->cart->insert($data);

Thanks Mohammad...

A: whenever we need to insert multiple data in single query, then we can user batch for inserting data. such as,
$data = $arrInsert = array();
foreach ($_POST['id_kuitansi'] as $id_kuitansi){
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data = array(
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
    //print_r($data);
    $arrInsert[] = $data;
    //$this->cart->insert($data);
}
$this->db->insert_batch('tableName', $arrInsert);

In insert batch you can replace tableName with your table name.