text:
Q: Migration error on timestamp change field In laravel 5.7/mysql 5 app I want to set default value to timestamp field(it was not set on creation):
   $table->timestamp('created_at')->useCurrent()->change();

But I got error :
 Unknown column type "timestamp" requested. Any Doctrine type that you use has to be registered with \Doctrine\DBAL\Types\Type::addType(). You can get a list of all the known types with \Doctrine\DBAL\Types\Type::getTypesMap(). If this error occurs during database introspection then you might have forgotten to register all database types for a Doctrine Type. Use AbstractPlatform#registerDoctrineTypeMapping() or have your custom types implement Type#getMappedDatabaseTypes(). If the type name is empty you might have a problem with the cache or forgot some mapping information.

  at /mnt/_work_sdb8/wwwroot/lar/BoxBooking2/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:267
    263|      * @return \Doctrine\DBAL\DBALException
    264|      */
    265|     public static function unknownColumnType($name)
    266|     {
  > 267|         return new self('Unknown column type "' . $name . '" requested. Any Doctrine type that you use has ' .
    268|             'to be registered with \Doctrine\DBAL\Types\Type::addType(). You can get a list of all the ' .
    269|             'known types with \Doctrine\DBAL\Types\Type::getTypesMap(). If this error occurs during database ' .
    270|             'introspection then you might have forgotten to register all database types for a Doctrine Type. Use ' .
    271|             'AbstractPlatform#registerDoctrineTypeMapping() or have your custom types implement ' .

Usually I do not  any problem with timestamp fields and I suppose that method ->change  raised this problem.
How to fix it ?
MODIFIED BLOCK # 1 :
I have it istalled
my  composer.json :
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "doctrine/dbal": "^2.9",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.7.*",
        "laravel/tinker": "^1.0",
        "marktopper/doctrine-dbal-timestamp-type": "^1.0",
        "mews/purifier": "^2.1",
        "proengsoft/laravel-jsvalidation": ">2.2.0",
        "yajra/laravel-datatables-oracle": "~8.0"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.0"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

Googling I found that I need also to install marktopper/doctrine-dbal-timestamp-type
https://github.com/art-institute-of-chicago/data-aggregator/commit/581f4f318468681c71c62103280daedc67bbe118
I installed it and I do not have error running migration, but created_at default timestamp is NOT defined, so added new row has null in created_at.
$ php artisan --version
Laravel Framework 5.7.21
$ node -v
v10.15.0
$ npm -v
6.5.0

Thanks!

A: The documentation states that you can't change / modify the timestamp column types.

Only the following column types can be "changed": bigInteger, binary, boolean, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger and unsignedSmallInteger.

You best bet is to use a raw sql query to update the column with something like:
DB::statement('ALTER TABLE `table_name` CHANGE `column_name` `column_name` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP;');


text:
Q: LinQ query question var icerikler1 = (from x in data.Tbl_Iceriklers
                  where x.ust_kategori_id == 96
                  select x).OrderByDescending(a => a.ID).Take(4);

I have pulled content of the last 4 ,then connect to repeater.I have no problem here.But,I want to be
ust_kategori_id == 96 of the first two records.
Finally,I want to be  ust_kategori_id == 95 of the another two records.
How can I do that?

A: Do you mean a UNION?
var icerikler1 = (from icerik in data.Tbl_Iceriklers
              where icerik.ust_kategori_id == 96
              select icerik).OrderByDescending(a => a.ID).Take(2).Union((from icerik in data.Tbl_Iceriklers
              where icerik.ust_kategori_id == 95
              select icerik).OrderByDescending(a => a.ID).Take(2));

A: You can group by ust_kategori_id, filter out any group besides those with key 95 and 96 and then take 2 of each group with the order you specified:
var icerikler1 = data.Tbl_Iceriklers
                     .GroupBy( x=> x.ust_kategori_id)
                     .Where( g=> g.Key == 95 || g.Key == 96)
                     .SelectMany( g=> g.OrderByDescending(a => a.ID).Take(2));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with Indefinite Integral $\int\frac {\cos^4x}{\sin^3x} dx$ I'm stuck with this integral
$\int\frac {\cos^4x}{\sin^3x} dx$
which I rewrote as
$\int \csc^3x \cos^4xdx$
then after using the half angle formula twice for $\cos^4x$ I got this
$\frac 14\int \csc^3x (1+\cos(2x))(1+\cos(2x))dx$
then after solving those products I got these integrals
$\frac 14 \{\int \csc^3xdx+2\int \csc^3x \cos(2x)dx + \int \csc^3x \cos^2(2x)dx\}$
I do know how to solve the $\int \csc^3xdx$ one but I'm totally lost on the other ones, any tips/help/advice would be highly appreciated! thanks in advance guys!

A: Let $t=\cos x$, then
$$\int \frac{\cos^4 x}{\sin^3 x}dx=-\int \frac{t^4}{(1-t^2)^2}dt.$$
Can you proceed?

A: Integrate by parts instead
\begin{align}
\int\frac {\cos^4x}{\sin^3x} dx
=&-\frac12\int \cos^3x\ d\bigg(\frac1{\sin^2x}\bigg)\\
\overset{ibp}= &-\frac{\cos^3x}{2\sin^2x}+\frac32\int \left(\sin x-\frac{1}{\sin x}\right)dx\\
 = &-\frac{\cos^3x}{2\sin^2x}-\frac32\cos x+\frac32\tanh^{-1}(\cos x)
\end{align}

A: Write $\cos^4x=(1-\sin^2x)(1-\sin^2x)$ and expand. Then split the fraction. You'll then need to integrate $\csc^3x$ , $\csc x$ and $\sin x$ all of which is standard


text:
Q: Python Dictionary of datatypes to dataframe I am trying to convert datatypes in a dataframe in python from a dictionary, so far I cannot see references online. I can only see change columns in a dataframe from a dictionary. https://kanoki.org/2019/04/06/pandas-map-dictionary-values-with-dataframe-columns/
This is the dictionary that contains the datatype. On the left is the current datatype while on the right is the datatype to convert to.
type_conversion = {
    "bigint": "int64",
    "boolean": "bool",
    "character varying": "str",
    "double precision": "float64",
    "integer": "int32",
    "numeric": "float64",
    "timestamp without time zone": "datetime64"
}

Any way on how to achieve this?

A: I think you are looking for this:
df.dtypes.to_dict()

example:
df = pd.DataFrame({'par1': np.array([1]).astype('i'), "par2": np.array([2]).astype('f')})
df.types

output:

df.dtypes.to_dict()

output:


text:
Q: error: not found: value Auctioneer (LiftActor) Greetings
I have the following class
package org.developerworks.comet

import net.liftweb.http._
import net.liftweb.common.Full
import net.liftweb.http.S._
import net.liftweb.http.SHtml._
import net.liftweb.http.js.JsCmd
import net.liftweb.http.js.JsCmds._
import net.liftweb.http.js.JE._
import net.liftweb.util.Helpers._
import net.liftweb.util._
import scala.xml.NodeSeq
import org.developerworks.model._
import org.developerworks.actor._
import java.lang.Long

class AuctionActor extends CometActor {

  var highBid : TheCurrentHighBid = null

  override def defaultPrefix = Full("auction")

  val itemId = S.param("itemId").map(Long.parseLong(_)).openOr(0L)

  def render = {

    def itemView: NodeSeq = {

      val item = if (itemId > 0)
        ItemMetaData.findByKey(itemId).openOr(ItemMetaData.create)
      else ItemMetaData.create
      val currBid = item.highBid
      val bidAmt = if (currBid.user.isEmpty) 0L else currBid.amount.is
      highBid = TheCurrentHighBid(bidAmt, currBid.user.obj.openOr(User.currentUser.open_!))
      val minNewBid = highBid.amount + 1L
      val button = <button type="button">{S.?("Bid Now!")}</button> %
      ("onclick" -> ajaxCall(JsRaw("$('#newBid').attr('value')"), bid _))
      (

          {item.name}

            Current Bid: ${highBid.amount} by {highBid.user.niceName}

            New Bid (min: ${minNewBid}) :
            <input type="text" id="newBid"/>
            {button}

          {item.description}

)
    }

    bind("foo" ->
{itemView}
)

  }

  def bid(s:String): JsCmd = {

    val user = User.currentUser.open_!
    Auctioneer ! BidOnItem(itemId, Long.parseLong(s), user)

  }

  override def localSetup {

    Auctioneer !? AddListener(this, this.itemId) match {

      case Success(true) => println("Listener added")
      case _ => println("Other ls")

    }

  }

  override def localShutdown {

    Auctioneer ! RemoveListener(this, this.itemId)

  }

  override def lowPriority : PartialFunction[Any, Unit] = {

    case TheCurrentHighBid(a,u) => {
        highBid = TheCurrentHighBid(a,u)
        reRender(false)
      }
    case _ => println("Other lp")

  }

}

When compiling with maven sent me the following error:
[ERROR] AuctionActor.scala:64: error: not found: value Auctioneer
[INFO]     Auctioneer ! BidOnItem(itemId, Long.parseLong(s), user)
[INFO]     ^
[ERROR] AuctionActor.scala:71: error: not found: value Auctioneer
[INFO]     Auctioneer !? AddListener(this, this.itemId) match {
[INFO]     ^
[ERROR] AuctionActor.scala:83: error: not found: value Auctioneer
[INFO]     Auctioneer ! RemoveListener(this, this.itemId)
Auctioneer class (LiftActor), call with the line:
import org.developerworks.actor._
anyone know what I'm doing wrong
please help

A: Is Auctioneer defined as a class rather than an object?  In this case, you'll need to instantiate the actor before you can use it.


text:
Q: Not getting result from Google Place Autocomplete Address I am implementing Google Autocomplete Address script with my current project and I am trying to find places with my keywords from Google search but I am not getting that result. I have no restriction for any country.
I am not good with Google codes so don't understand so I am hoping that you will help me.
My search keywords is (Which is not showing Google result):

*

*Technodream Training, Ahmedabad, Gujarat, India

*Zydus Cadila Healthcare Ltd., Changodar, Gujarat, India

*Crop Production Services Inc

My Autocomplete Address Script Code:
HTML:

    <input id="autocomplete" placeholder="Enter your address" type="text"></input>

        Street address

            <input class="field" id="street_number"></input>

            <input class="field" id="route"></input>

        City

            <input class="field" id="locality"></input>

        State

            <input class="field" id="administrative_area_level_1"></input>

        Zip code

            <input class="field" id="postal_code"></input>

        Country

            <input class="field" id="country"></input>

        Lat

            <input type="text" class="field" id="latitude"></input>

        Long

            <input type="text" class="field" id="longitude"></input>

Script Code:
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

$("#autocomplete").on('focus', function () {
    geolocate();
});

var placeSearch, autocomplete;
var componentForm = {
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'short_name',
    country: 'long_name',
    postal_code: 'short_name'
};

function initialize() {
    // Create the autocomplete object, restricting the search
    // to geographical location types.
    autocomplete = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */ (document.getElementById('autocomplete')), {
        types: ['geocode']
    });
    // When the user selects an address from the dropdown,
    // populate the address fields in the form.
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        fillInAddress();
    });
}

// [START region_fillform]
function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

    document.getElementById("latitude").value = place.geometry.location.lat();
    document.getElementById("longitude").value = place.geometry.location.lng();

    for (var component in componentForm) {
        document.getElementById(component).value = '';
        document.getElementById(component).disabled = false;
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType).value = val;
        }
    }
}
// [END region_fillform]

// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var geolocation = new google.maps.LatLng(
            position.coords.latitude, position.coords.longitude);

            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            document.getElementById("latitude").value = latitude;
            document.getElementById("longitude").value = longitude;

            autocomplete.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
        });
    }

}

initialize();
// [END region_geolocation]

I am getting all search result in Google script: https://www.google.com/maps/place/ and here is my JSFiddle work: http://jsfiddle.net/upsidown/q8XS6/
Thanks.

A: Your JSFiddle work is actually my JSFiddle work, but let's not care about that! ;-)
You are requesting types: ['geocode'] which, according to the documentation returns addresses.
For businesses, you should use types: ['establishment'] or you can simply remove that line and you will get all types of results.
Hope this helps.


text:
Q: VSCode add parentheses when autocompleting functions Is is possible to tweak VSCode so that when function gets autocompleted, it is written with () instead of just plain function name?
For example when I type str and autocomplete to strlen I would like to get strlen(), it saves quite some time.

A: Some language extensions allow using ( as a so-called "commit character" to trigger the insertion of a completion item. This works in at least TypeScript, JavaScript and Haxe.
If "editor.autoClosingBrackets" has not been disabled, this will also auto-insert the closing ).

If it doesn't work for a particular language extension, perhaps consider opening a feature request on the repository in question.

A: It can be solved by ticking javascript.suggest.completeFunctionCalls property up.

A: Just like @snr's solution in JavaScript.
For TypeScript, you can try this:
"typescript.suggest.completeFunctionCalls": true

A: For Python, when using Pylance, add in settings.json:
"[python]": {
    "python.analysis.completeFunctionParens": true,
},

A: in settings.json file
Set "python.autoComplete.addBrackets": true.

A: You can go-to File->Preferences->Settings
Input python
And click on Edit in settings.json
After that write down "python.analysis.completeFunctionParens": true, and reload VS Code

A: For Python when using the Python extension the relevant setting is:
python.autocomplete.addBrackets
As per the comment bellow, if you use Pylance the setting is:
python.analysis.completeFunctionParens

A: For C and C++, use this setting:
"C_Cpp.autocompleteAddParentheses": true

A: It's possible. You can create your own snippets, and it will be shown in the intellisense:
User Defined snippets. You can also use snippet-creator extension for comfort.

A: In the latest release of vs code open setting > search "parenthesis" > scroll for
python>analysis: Complete Function Parens
mark tick
Then you are ready to go.

A: If you are working in flutter, try resetting all settings of VS Code because it do add parentheses by default.


text:
Q: How to read both double and int from a file in Java So I have this input file that I am trying to read with scanner.The file looks like this.
20 0.4
3  5.6

As you see it has an int and then a double and this goes on until the end of the file.I tried reading both of them as doubles:
while(scanner.hasNextDouble()){
    x = (int) scanner.nextDouble();
    y = scanner.nextDouble();
}

And I also tried this:
while(scanner.hasNext()){
    x = scanner.nextInt();
    y = scanner.nextDouble();
}

But none of them seems to work.What may be a solution to this?

A: Your second loop works fine.
PROOF
String input = "20 0.4\n" +
               "3 5.6\n";
Scanner scanner = new Scanner(input);
while (scanner.hasNext()) {
    int x = scanner.nextInt();
    double y = scanner.nextDouble();
    System.out.printf("x=%d, y=%f%n", x, y);
}

OUTPUT
x=20, y=0.400000
x=3, y=5.600000

This is what is called a Minimal, Complete, and Verifiable example (MCVE).


text:
Q: How to initialize a char array as null within a default constructor? I am trying to set a char array equal to null ('\0') within a default constructor. I am attempting to set the value of an already-initialized char pointer (protected member of the class) to null when there are no arguments passed. The program works perfectly if there are the correct arguments passed, but when I am setting them in the default constructor, I get a segmentation fault: 11 error.
This is the header file:
#ifndef _DVD_H_
#define _DVD_H_

class DVD {
protected:
    unsigned int id;
    char* title;
    char* director;
    char* makecopy(const char*);
public:
    DVD(unsigned int i, const char* t, const char* dir);
    void display();
    DVD ()
    {
        const char temp[] = {'\0'};
        id = 0;
        title = makecopy(temp);
        director = makecopy(temp);

    }
};

#endif /* _DVD_H_ */

and this is the .cpp file:
#include <iostream>
#include "DVD.h"
using namespace std;

DVD::DVD (unsigned int i, const char* t, const char* dir)
{
    //Constructing id
    id = i;
    //Constructing title
    title = makecopy(t);
    //Constructing director
    director = makecopy(dir);
}

void DVD::display()
{
    //Creating variables to track the length of the title/director and the location of the space.
    int len_t,len_dir,space_dir;
    for (len_t = 0; title[len_t] != '\0'; len_t++)
        ;
    for (len_dir = 0; director[len_dir] != '\0'; len_dir++)
        ;
    for (space_dir = 0; director[space_dir] != ' '; space_dir++)
        ;
    //Display the information in the desired format.
    cout << '[' << id << ". " << title << '/';
    for (int p = 0; p < space_dir; p++)
     cout << director[p];
    for (int j = space_dir; j < len_dir; j++)
        cout << director[j];
    cout << ']' << endl;
}

char* DVD::makecopy(const char* str)
{
    int len;
    char* copy;
    for (len = 0; str[len] != '\0'; len++)
        ;
    copy = new char[len+1];
    for (int i = 0; i < len+1; i++)
        copy[i] = str[i];
    return copy;
}

and this is the other .cpp file
#include<iostream>
using namespace std;
#include"DVD.h"

int main()
{
    char str[] = "Gandhi";
    DVD d1(4, str, "Richard Attenborough");
    DVD d2;
    cout << "First step: " << endl;

    cout << "After constructors:" << endl;
    d1.display(); cout << endl; // [4.  Gandhi/Richard Attenborough]
    d2.display(); cout << endl; // [0.  /]

     cout << "Test for dynamically allocated copies" << endl;
     d1.display(); cout << endl; // [4.  Gandhi/Richard Attenborough]
     d2.display(); cout << endl; // [0.  /]
}

A: You are not implementing the Rule of Three, and your makecopy() is suspicious.
Try something more like this instead:
#ifndef _DVD_H_
#define _DVD_H_

class DVD
{
protected:
    unsigned int id;
    char* title;
    char* director;

    static char* makecopy(const char* str);

public:
    DVD();
    DVD(unsigned int i, const char* t, const char* dir);
    DVD(const DVD &src);
    ~DVD();

    DVD& operator=(const DVD &rhs);

    void display() const;
};

#include "DVD.h"
#include <iostream>

DVD::DVD()
    : id(0), title(NULL), director(NULL)
{
}

DVD::DVD(unsigned int i, const char* t, const char* dir)
    id(i), title(makecopy(t)), director(makecopy(dir))
{
}

DVD::DVD(const DVD& src)
    id(src.id), title(makecopy(src.title)), director(makecopy(src.director))
{
}

DVD::~DVD()
{
    delete[] title;
    delete[] director;
}

DVD& DVD::operator=(const DVD& rhs)
{
    if (this != &rhs)
    {
        DVD copy(rhs);

        id = copy.id;

        char *c_temp = copy.title;
        copy.title = title;
        title = c_temp;

        c_temp = copy.director;
        copy.director = director;
        director = c_temp;
    }

    return *this;
}

void DVD::display() const
{
    //Display the information in the desired format.
    std::cout << '[' << id << ". " << title << '/' << director << ']' << std::endl;
}

char* DVD::makecopy(const char* str)
{
    int len = 0;
    if (str)
    {
        while (str[len] != '\0')
            ++len;
    }

    char* copy = new char[len+1];
    for (int i = 0; i < len; ++i)
        copy[i] = str[i];
    copy[len] = '\0';

    return copy;
}

That being said, I strongly advise you to use std::string instead.  Let it, and the compiler, handle all of the memory management for you:
#ifndef _DVD_H_
#define _DVD_H_

#include <string>

class DVD
{
protected:
    unsigned int id;
    std::string title;
    std::string director;

public:
    DVD();
    DVD(unsigned int i, const std::string& t, const std::string& dir);

    void display() const;
};

#endif /* _DVD_H_ */

#include "DVD.h"
#include <iostream>

DVD::DVD()
    : id(0)
{
}

DVD::DVD(unsigned int i, const std::string& t, const std::string& dir)
    : id(i), title(t), director(dir)
{
}

void DVD::display() const
{
    //Display the information in the desired format.
    std::cout << '[' << id << ". " << title << '/' << director << ']' << std::endl;
}


text:
Q: getting data from Web Services c# I have an issue loading data in the correct format from web services.
Web Service code:
   [WebMethod]
    public string LoadLearrner(string id)
    {
        MyFunctions func = new MyFunctions();
        DataSet ds;

        DataSet dtsta = SQLServer.GetDsBySP("Load_Learner_ForCRM","learnerId", id.ToString());

        string[] cntName = new string[dtsta.Tables[0].Rows.Count];
        List<string> list = new List<string>();

        int i = 0;

        foreach (DataRow rdr in dtsta.Tables[0].Rows)
        {
            list.Add(rdr[0].ToString());
            list.Add(rdr[1].ToString());
            list.Add(rdr[2].ToString());
            list.Add(rdr[3].ToString());
            list.Add(rdr[5].ToString());
            i++;
        }

        String[] str = list.ToArray();
        string JSONString=string.Empty;
        JSONString = JsonConvert.SerializeObject(str);
        return JSONString;
    }

Code that's used to call the above web service method is:
WebRequest request = (HttpWebRequest)WebRequest.Create("http://abc/Company/CrmLearner.asmx/LoadLearrner?id=" + item.learner_id);
                    request.Method = "GET";
                    request.ContentType = "application/text";

                    using (Stream dataStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(dataStream);
                        responseFromServer = reader.ReadToEnd();
                        Console.WriteLine(responseFromServer);
                    }

Result is:

I don't want the result like that. I want to load proper XML or JSON and store it in an object.


text:
Q: unable to communicate with payment gateway I used magento v1.9.0.1,i set up my paypal(for testing) setting well, sandbox is off, SSl is off. But still im getting this error: Unable to communicate with the PayPal gateway any help plz?

A: You are running into the POODLE issue.  See the details here:  https://www.angelleye.com/paypal-ssl-error-poodle-vulnerability/
Specifically...

If you want to use TLS 1.2 you'll need to upgrade to OpenSSL 1.0.1 as a minimum, and then you'll be able to set CURLOPT_SSLVERSION to 6 (TLS 1.2).
If you want TLS 1.2 to be used automatically during SSL requests, you'll also need to upgrade to PHP 5.5.19+ (this is the ideal solution but many projects are still on older PHP versions).


text:
Q: Difference Between int[] and list What is the difference between:
    int[] myIntArray

and
 list<int> myIntArray

?
In web services I read that I should pick one or the other and not mix the two, why?

A: On the wire they will be indistinguishable - i.e. both Customer[] and List<Customer> are going to look (roughly) like:
<Customers>
   <Customer name="Fred" ... />
   <Customer name="Barney" ... />
</Customers>

So there is no point having logic that treats the two differently. Ultimately, int[] is a pain to work with (Add etc), so I would tend to use List<T> - of course, wsdl.exe nicely defaults to arrays, IIRC - but there is a command line switch (or perhaps there is for wse/wcf).

A: Depends on what you will be doing with them.
If your dataset is of a fixed size and you will not need to do any sorting, the array is better suited.
If your data needs to be more dynamic, allow for sorting, and be able to take advantage of LINQ, then use the list
Personally, I prefer the flexibility of list types.

A: They are pretty much the same, except that Lists have a lot of built in functions to ease the life of the programmer. Once you start using lists, you'll love them :D
Also, arrays are fixed. You cannnot (easily) change the size of an array.

A: They are functionally equivalent, so you can use either one. Once you use one version, be consistent. It'll help keep your code readable and easier to maintain.

A: int[] is an array of integers.  List is a generic list that holds objects of type int
Which one you pick depends on your requirements.  If you are dealing with immutable collections of objects, int[] would be more suitable.  However, if you need to modify the contents of the collection, List provides that flexibility.


text:
Q: Express: PayloadTooLargeError trying to read POST body containing large JSON despite limits set I have the following main app.js and a supporting file containing some routing handlers
app.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser')

var indexRouter = require('./routes/index');
var testRouter = require('./routes/test');
var routineRouter = require('./routes/routines');

var app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.json({limit: "50mb", extended: true, parameterLimit:50000}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));

app.use('/', indexRouter);
app.use('/test', testRouter);
app.use('/routine', routineRouter);

module.exports = app;

/routes/routines.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser')
var path = require('path');

router.post('/changeBoundary', function(req, res, next) {
    let id = req.body.precinctId;
    let geo = req.body.polygon;
    res.status = 200;
    res.end();
});

I am trying to pass a fairly large JSON file (probably around 5-10mb?) into that 'changeBoundary' handler but I am getting the 'too large' error. I've set the size limits on the body-parser to be larger than I should be needing and I've made sure everything is in the right order but I'm still getting the error. This is my first time using Node.js at all so I'm still trying to figure out how all the different parts fit together.

A: Switching it from
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.json({limit: "50mb", extended: true, parameterLimit:50000}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));

to
app.use(bodyParser.json({limit: "50mb", extended: true, parameterLimit:50000}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));

app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

solved the issue. I don't really know exactly why other than that the order things are loaded matters.


text:
Q: Working with Trees in Rx.NET / ReactiveUI How to observe property changes on any sublevel of a tree?
Consider for example a class TreeNode with the properties Name and ChildNodes. How to observe Name changes on any sublevel of a TreeNode?
The usage might look something like this:
rootNode.FlattenTreeToObservable(x => x.ChildNodes)
        .WhenAnyValue(x => x.Name)
        .Subscribe(...)

TreeNode example:
// NuGet: Install-Package reactiveui
// In case of Splat version issue: Install-Package Splat -Version 1.6.2
using ReactiveUI;

public class TreeNode: ReactiveObject
{
    public string Name
    {
        get { return this._name; }
        set { this.RaiseAndSetIfChanged(ref this._name, value); }
    }
    private string _name = "";

    public ReactiveList<TreeNode> ChildNodes
    {
        get { return this._childNodes; }
        set { this.RaiseAndSetIfChanged(ref this._childNodes, value); }
    }
    private ReactiveList<TreeNode> _childNodes = new ReactiveList<TreeNode>();
}

A: I couldn't get your code to run - I ended up with a DLL versioning issue so I wrote a basic class that uses the same structure as yours to get this to work:
public class TreeNode
{
    public string Name { get; set; }

    public Subject<TreeNode> ChildNodes { get; }
        = new Subject<TreeNode>();
}

I then added the following method:
    public IObservable<TreeNode> FlattenTreeToObservable()
    {
        return
            this.ChildNodes
                .SelectMany(cn => cn.FlattenTreeToObservable())
                .StartWith(this);
    }

Now when I run this test code:
var root = new TreeNode() { Name = "R" };

root.FlattenTreeToObservable().Subscribe(tn => Console.WriteLine(tn.Name));

var a1 = new TreeNode() { Name = "A1" };
root.ChildNodes.OnNext(a1);

var b11 = new TreeNode() { Name = "B11" };
a1.ChildNodes.OnNext(b11);

var b12 = new TreeNode() { Name = "B12" };
a1.ChildNodes.OnNext(b12);

var a2 = new TreeNode() { Name = "A2" };
root.ChildNodes.OnNext(a2);

var b21 = new TreeNode() { Name = "B21" };
a2.ChildNodes.OnNext(b21);

var b22 = new TreeNode() { Name = "B22" };
a2.ChildNodes.OnNext(b22);

I get this output:

R
A1
B11
B12
A2
B21
B22


text:
Q: css3 need help in understanding box-sizing I have found the following from the site: http://www.htmlgoodies.com/html5/tutorials/learn-css3-from-a-z-getting-started-with-layouts-.html#fbid=Byc3E58e8v-
"The CSS3 code for this is very simple. You just need to add the following property to switch the model for a particular element.
#W3C-model {
box-sizing: content-box;
}

#traditional-model {
box-sizing: border-box;
}

Having understood how box-sizing works, the next question is where can you use it? Well, its very useful when you have two equal columns. If you give them 50% width each and add some padding and maybe a border, the columns won't show up side by side. This is an ideal scenario where you can set box-sizing to border-box and happily set the width to 50% for both boxes."
I am not sure what is meant by the columns won't show up side by side? It sounds like what is expected here is the dividing border between the two columns would vanish or something like that - I am not sure. I have this sample code to experiment with:
http://jsfiddle.net/hE8UZ/
I am not seeing any effect at all. Besides not sure why the span elements didn't occupy 250px as width was mentioned as 50% of body.
Please help.
Thanks

A: If you have any container with 500px width and child with 1px border, 10px padding, 100% width and set box-sizing to border-box then the width will be 500px if you set box-sizing to content box then the width will be 500px + 2x10px + 2x1px = 522px.
.container {
    display: block;
    width: 500px;
}

.one {
    display: block;
    padding: 10px;
    -webkit-box-sizing: border-box;
    width: 50%;
    border: 1px solid;
}

.two {
    display: block;
    padding: 10px;
    -webkit-box-sizing: content-box;
    width: 50%;
    border: 1px solid;
}

http://jsfiddle.net/Vaj5x/
EDIT:
If you wanna have tow columns add them float to left. Like here http://codepen.io/Chovanec/pen/cuBpg


text:
Q: Java instance variables initialization order I am asking somethimng quite common in Java, but unfortunately I could find an answer or a resource presenting a complete structured answer to this issue. I would like to know what is the complete process of the initilaization (of an Object) in Java and what is its order? In paticular I am not sure when the instance variables obtain their default values and their values of the initilization. As far as I know the inititialization order in a typical class i.e. A is:
class B {

}

class A extends B {

    int x = 5;

    public A() {
        ...
    }

}

1) static initialization block (provided that it exists)
2) call super() constructor
3) instance initilization block  (provided that it exists)
4) excecute the rest of the constructor
In which point in the above order does the default initiliazation (x=0) and the actual initialization (x=5) gets in the list?


text:
Q: Send CSRF token to javascript Suppose I maintain a anti CSRF token at server side in a session
How am I supposed to pass the token to client side application if my form generation is going to be dynamic(i.e. form will be created after some action has been performed by javascript)
Is there a way to pass the token to javascript so that I can inject the token in the form.
One working way that I found is send a cookie to the browser containing the token which will be then extracted by javascript.
Any suggestions?

A: I would suggest starting out from a secure token, and then improving it through JavaScript according to dynamic form Creation.
Eg, like:
<input type="hidden" name="csrftoken" value="hgdillksdbgjksdbkvbskb">

Where the "value" parameter is generated on server-side when page loads.
And then you have a script like:
csrftoken = document.mainform.csrftoken.value;
# Do something with the CSRF token, like add dynamic values, like sha256(csrftoken + "dynamicvalue");
document.mainform.csrftoken.value = csrftoken;

The main idea of this, is to prevent, that even if they manage to get a exploit that would allow a adverisary to read the JavaScript code, they still cannot make up a valid CSRF token, since they cannot read the original "csrftoken" value that was inside the form at page load.
This can also be used to "chain" AJAX requests, like that you start out with the token X during page load. Then you transform it to Y using JavaScript, send it in a AJAX request. In the next AJAX request, you can use Y as base in the algoritm, to create Z, and send to the server. A attacker cannot gain access to X, thus they cannot either get access to Y neither Z, even if they would in some way be able to exploit running JavaScript code to reveal itself.
Note that page contents cannot be read by a adversiary due to Same origin policy. But Javascript can contain exploits that would make it possible to read the actual running JavaScript code. Theres no such exploits currently, but better be safe than sorry.

A: Sure.  If you're dynamically generating the form on the client side then you're doing it from some kind of template.  The token should be an argument to that creation function.
Pass the token along to the client at request/render time and then inject it into the form as a hidden element at form generation time.


text:
Q: Apple news publisher failed with Word Press plug-in We recently added "Publish To Apple News" plug-in to our Word Press and getting "Date_Not_Recent" error. After talking to the developers and checking their support pages, it looks like it is a a time zone issue between the WP server (Oregon, US with UTC timezone) and Apple News Publisher (which till this moment Apple can't tell me where it is located, i assume California, but who knows for sure?)
Solution, is to sync those time zones together. My questions:
1- Anyone had any issues rezoning their aws servers?
2- If you had this issue before, what did you do?
I am just trying not fix one thing and break 10 other things in return. just being cautions. We all know that Murphy's law roles in IT.
Thanks in advance

A: We figured it out. it was an NTP issue.
We host on AWS, and the time sync packages (NTP) were a little bit out of sync, so we deleted them and installed chrony instead and that worked.
For anyone who is interested, here are the instructions (under configuring the Amazon time sync services):
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html


text:
Q: How to identify a pure UIView subview out of various Custom View subviews I am parsing through the subviews of a parent view,
It has various subviews, all custom classes, of 10 different UIView subclasses.
There is just one class which is a normal UIView.
Now when I am looping thru, I need to get hold of the UIView subview, isKindOfClass is failing to do so as it returns 1 for all the UIView subclasses as well.
Do I have to write a a big if-else construct to check if its an object of any other custom UIView subclass and then in the last else come to a conclusion that its a normal UIView.
Or is there a method that tells me exact class of the view ?

A: You shoud use :
[currentView isMemberOfClass:[UIView class]];

A: http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isMemberOfClass:


text:
Q: Getting email and phone number from website and saving it to a file using bash script? I have this script to collect information from the website and output them to a text file. It downloads the site then uses grep to extract information. I need to use formatting to output them as I wanted to do.
#!/usr/bin/env bash
echo Enter an url

read url

mkdir site
cd site
wget -r -l1 --follow-tags=a --no-check-certificate $url
grep -r -E -o -H "\b[a-zA-Z0-9.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9.-]+\b" * | sort -u >> ~/email.txt
grep -r -E -o -H "\(?[[:digit:]]{5}\)?[[:space:]]?[[:digit:]]{6}" * | sort -u  >> ~/phone.txt
cd ..
rm -rf site

When I run this I get an output like that :
www.example.com/en/contact:91112223334
...
www.example.com/en/contact:info@example.com

I want to make tabular format.
email.txt

url
email

www.example.com
info@example.com

phone.txt

url
phone

www.example.com
0 111 222 33 34

I need to format the phone numbers as shown in table. I've tried to use awk but I couldn't make it.


text:
Q: Counting barcodes This certain problem is related to different combinations of strips in a barcode.
The question is that how many different codes are possible in a barcode, reading from left to right, according to these rules:

*

*barcode should be composed of alternate strips of black and white

*barcode should always be beginning and ending with a black strip

*each strip (of either colour) has the width 1 or 2

*the total width of the barcode is 12

For example, this barcode is one of the many which conform to the rules.

I approached this problem by representing the four different strips by

*

*b1 (black of width 1)

*b2 (black of width 2)

*w1 (white of width 1)

*w2 (white of width 2)

Then all codes would have this pattern

*

*b1 ...... b1 (width so far: 2)

*b2 ...... b2 (width so far: 4)

*b1 ...... b2 (width so far: 3)

*b2 ...... b1 (width so far: 3)

since they always begin and end with black.
Next step was the 2nd and 2nd last strips of white color.
Again the pattern would be:

*

*w1 ...... w1 (width so far: 4)

*w2 ...... w2 (width so far: 8)

*w1 ...... w2 (width so far: 6)

*w2 ...... w1 (width so far: 6)

with all the four patterns of black mentioned above.
This seemed to get automated but the width was hinderance in deriving a formula. Then the question is that should  all of this be done manually or does MATH offer a solution?

A: You can have anywhere from $4$ to $6$ black strips: With $3$ there would be only $5$ strips in total, so the total width would be less than $12$, and with $7$ there would be $13$ strips in total, so the total width would be greater than $12$.
So you just need to add the numbers for these three cases. With $n$ black strips, there are $n-1$ white strips, for a total of $2n-1$ strips, so $12-(2n-1)=13-2n$ of them are $2$s and the others are $1$s. You can choose the $2$s arbitrarily, so the total number of possibilities is
$$\sum_{n=4}^6\binom{2n-1}{13-2n}=\binom{7}{5}+\binom{9}{3}+\binom{11}{1}=21+84+11=116\;.$$


text:
Q: Display date from array lists I have array contain date lists.
I want to display as
25 june & 2,9 July 2021

Here my code:
$dates = array(
        0 => '2021-06-25',
        1 => '2021-07-02',
        2 => '2021-07-09',
    );

    foreach($dates as $date){
        //$data = DateTime::createFromFormat('F j Y', $date);
        $data = date('j F Y', strtotime($date));
        echo $data . ', ';
    }

my attempt it to create Ym-index but the first array lost his month.
$compare = array();

foreach($dates as $date){
    $data = date('j F', strtotime($date));
    $ym = date('F Y', strtotime($date));
    $date = date('j', strtotime($date));
    //$compare[] = $ym;
    if(!in_array($ym, $compare)){

        echo $date . '
';
        $compare[] = $ym;

    }else{

        echo $data . '
';

    }

}

Output:
25
2
9 July

A: Solution with the help of multidimensional auxiliary arrays grouped by year and month.
Input:
$dates = array(
        0 => '2021-06-25',
        1 => '2021-07-02',
        2 => '2021-07-09',
        3 => '2020-05-19',
);

Sort and Create arrays:
sort($dates);

$groupes = $helper = [];
foreach($dates as $date){
  list($year,$month,$day) = explode('-',$date);
  $groupes[(int)$year][(int)$month][] = (int)$day;
}

foreach($groupes as $year => $arr){
  foreach($arr as $month => $dayArr){
    $monthName = date('F',strtotime('2000-'.$month.'-01'));
    $helper[$year][] = implode(',',$dayArr).' '. $monthName;
  }
}

Make output:
foreach($helper as $year => $dateStrings){
  echo implode(' & ',$dateStrings).' '.$year."
\n";
}

The output for the above data:
19 May 2020
25 June & 2,9 July 2021

A: A first approach. It can be improved. It take into account different year.
$dates = array(
        0 => '2020-06-25',
        1 => '2021-06-25',
        2 => '2021-07-02',
        3 => '2021-07-09'
);

$years = array();

foreach($dates as $date) {
    $day = date('j', strtotime($date));
    $month = date('F', strtotime($date));
    $year = date('Y', strtotime($date));

    if(array_key_exists($year, $years)) {
        if(array_key_exists($month, $years[$year])) {
            $years[$year][$month] .= ',' . $day;
        } else {
            $years[$year][$month] = $day;
        }

    } else {
        $years[$year] = array($month => $day);
    }
}

$showYearSepartor = false;
$showMonthSepartor = false;

foreach($years as $year => $months) {
    if($showYearSepartor) {
        echo ' - ';
    }

    $showYearSepartor = true;

    foreach($months as $month => $day) {
        if($showMonthSepartor) {
            echo ' & ';
        }

        echo $day . ' ' . $month . ' ';

        $showMonthSepartor = true;
    }

    $showMonthSepartor = false;

    echo $year;
}


text:
Q: как отобразить значок svg в nuxt 3 Я использую nuxt 3 и Compositions API.
У меня получается такая вложенность как на скрине ниже, как избавиться от лишнего тега svg?
Я также хотел бы получить атрибуты svg по возможности и изменить, например fill
<template>
  <div>
    <component :is="render"></component>
  </div>
</template>

Sctipt Setup
import { h } from "vue";

const { data, pending, error, refresh } = await useFetch(svgURL);

const getDataVal = data.value
const SvgToRaw = await getDataVal.text();

const render = () => {
  return h("svg", {
    class: "bar",
    innerHTML: SvgToRaw,
  });
};

Я пытался создать виртуальное дерево DOM и получить оттуда элемент HTML, а не текст, но я думаю, что это плохое решение.
import hv from "virtual-dom/h";
import diff from "virtual-dom/diff";
import patch from "virtual-dom/patch";
import createElement from "virtual-dom/create-element";

const betaRender = hv("span", { innerHTML: svgString });
var rootNode = createElement(betaRender);
var patches = diff(rootNode);
return patches[0].vNode.innerHTML

Поддержка SSR важна для меня, поэтому я не могу использовать стандартные инструменты


text:
Q: Why would my Excel 2010 UDF quit working with a #NAME? error? I have Excel 2010. A couple of months ago I wrote some UDF's and got them debugged and working. Today I changed a value in the spreadsheet, and suddenly all the UDF's displayed #NAME?
Ultimately I decided to start from scratch. I created a new workbook with just one UDF. Here it is, in it's entirety:
Function say7() As Integer
    say7 = 7
End Function

I then went to Sheet1 and in box A1 entered "=say7()". I got "#NAME?".
If I type "sa", the dropdown shows "say7". I can press tab or enter and it fills in the function name. And then it says #NAME?.
I understand that Excel 2010 is no longer supported. Did Microsoft do something to break UDFs?
My XLSM was working a few weeks ago. Indeed, the file where I made the change was a copy of the original spreadsheet. I went back to the original, changed a value in one cell that should have forced a recalculation, and it said #NAME?. I didn't change the code, I didn't change any settings, nothing. The only thing I changed was one data value and somehow that makes the function name not be recognized anymore.
Update: Several posters have pointed out that "say7" is not a legal name for a function in Excel and that using this name would produce a #REF? error. True. But my problem was that I was getting a #NAME? error, not a #REF? error. In my attempt to create a simplified scenario -- to make sure that the problem wasn't some error within the function -- I created a new, deliberately very simple function that got the same #NAME? error. Yes, I gave this function an illegal name, which muddles my question. I apologize for the confusion. Explaining why say7 is an invalid name is interesting and useful information, but sadly does not solve my original problem.

A: When you are writing the function then there are conventional rules of naming it. One of them says

You should not use any names that are identical to the functions, statements, and methods in Visual Basic because you may shadow the same keywords in the language.

The name Say7 while it looks innocuous enough, clashes with a column numbered 12895 which is named as SAY. So in principle, below works for me but I do not have Excel 2010 to see and confirm.
Public Function SaySeven() As Integer
    SaySeven = 7
End Function

Edit:
After reading OP's own answer post and other details over, I can think of one more situation where we may encounter #NAME error. This can be reproduced fairly easily.
Step 1: Create a UDF and save the workbook. When you do so, it should not be saved at Excel's trusted locations and the file shall not be identified as trusted. If it is trusted then Excel doesn't prompt for enabling active content. At the point of creation, Excel will produce results without any error. Now close the workbook.
Step 2: Reopen this workbook. You will be prompted with below message.

Ignore this message i.e. do not press "Enable Content" button. OP may have missed this message somewhere.
Step 3: If the UDF was implemented in the previous session and it has returned a valid result then it will not return any error upon recalculation. However, if you enter this UDF in a new cell then Excel will return #NAME error. In below snapshot, both green cell and yellow cell contain exactly the same formula i.e.
=dist3()

But the outcome differs.
So in conclusion: UDF name dist3 is valid and it should work as cited by OP in his later postings. However, in above specific case, one may encounter error of this kind. It will, however, apply to all UDFs and not just dist3.

I have tested this in Excel's Office 365 version but I don't think there will be any major differences in this behavior across versions.

A: I eventually partly figured it out. At least enough to get it working.
Excel normally blocks you from running UDF's unless you explicitly give it permission. When you try to use the first UDF it pops up a question at the top of the window asking for permission, and if you don't give it, then UDFs aren't recognized and you get #NAME? errors for them.
Apparently -- and this is the part I'm not sure about -- the message telling me that support for Excel 2010 had expired was displayed on top of this message so I couldn't see it. Or something like that. I copied the file to another computer that had a newer version of Excel and I got the message. I clicked OK and the UDFs worked. I then saved it and copied it back to the original computer and it worked fine.
As I had previously clicked Ok on this and this answer is apparently saved with the file, I'm not sure why it asked again. Maybe some changes to the file invalidate the previous answer? I'm not sure.
I created a new file and saw the message about "UDFs ok?" on that one. So maybe my theory that the message was covered by the expiration notice is not correct. I guess it's possible that the message was there all along and I was just blind and didn't see it. That seems unlikely as I was searching for some explanation, but, etc.
In my first version of this post I said that the function name "say7" worked. This was incorrect. When I got the spreadsheet to work I had gone back to my original spreadsheet, where the function that was referenced in the spreadsheet was called "dist3", which works. (There were other functions but they wee all called from within dist3.)
In any case, before I created "say7" I was trying to get it to work with a function called "dist3" and that was also failing with the #NAME?. And as I said in the question, it worked a month ago and I didn't change any function names, so I knew that an illegal function name was not the issue. My attempt to create a simple function to test the problem was a wrong turn because I used an illegal function name that created different problems.

A: Seeing the logic of @shrivallbha redij's reply I changed the function's name to SAYG (with the idea that G defines the 7th column) and still got a #NAME error. However this can be avoided by passing an argument in the function call, even if the argument isn't used by the function or if it's blank.
=SAYG -  returns an error
=SAYG(A1)  - returns 7
=SAYG()  - returns 7


text:
Q: tf.keras "history not defined"... but it appears to me to be defined I am building a simple model in TensorFlow for an introductory course that I am taking.  I cannot find the reason for the error "history not defined." I would be extremely grateful for any assistance in identifying the source of this error and fixing it.
Here is the code:
def train_model(model, scaled_train_images, train_labels):
    history = model.fit(scaled_train_images, train_labels, epochs=5, batch_size=256)

# Run function to train the model
train_model(model, scaled_train_images, train_labels)

Output:
Train on 60000 samples

Epoch 1/5
60000/60000 [===] - 56s 936us/sample - loss: 0.0623 - accuracy: 0.9809

Epoch 2/5
60000/60000 [===] - 56s 932us/sample - loss: 0.0538 - accuracy: 0.9838

Epoch 3/5
60000/60000 [===] - 56s 925us/sample - loss: 0.0475 - accuracy: 0.9858

Epoch 4/5
60000/60000 [===] - 55s 923us/sample - loss: 0.0422 - accuracy: 0.9869- los

Epoch 5/5
60000/60000 [===] - 55s 917us/sample - loss: 0.0380 - accuracy: 0.9883

#Load the model history into a pandas DataFrame

frame = pd.DataFrame(history.history)

---------------------------------------------------------------------------
NameError
Traceback (most recent call last)
<ipython-input-22-895ca3f31ddf> in <module>
    1 # Run this cell to load the model history into a pandas DataFrame
    2
----> 3 frame = pd.DataFrame(history.history)

NameError: name 'history' is not defined

A: The history variable is only defined inside the train_model function and therefore is not accessible outside.
To fix this return it:
def train_model(model, scaled_train_images, train_labels):
    return model.fit(scaled_train_images, train_labels, epochs=5, batch_size=256)

history = train_model(model, scaled_train_images, train_labels)

frame = pd.DataFrame(history.history)


text:
Q: Backbone save triggers 'get' request + urlRoot gets ignored I have the strangest issue ever.
I instantiate the most basic model:
define([
  'backbone'
], function(Backbone){

    //Role - permissions model
    var Rp_model = Backbone.Model.extend({
        urlRoot: '/ingeb/api_v1/users/rolespermissions/'
    });

    return Rp_model;

});

And I save the model like this:
Rolespermissions_controller.prototype.save_userpermission = function(resource_id, role_id, verb){
    var rp_model = new Rp_model({'resource_id': 1, 'role_id': 1, 'verb': 'get'});
    console.log(rp_model);
    console.log(rp_model instanceof Backbone.Model);
    console.log(rp_model.urlRoot);
    rp_model.save();
};

The console.logs generate the following output:

It doesn't make any sense to me.
I'm saving the model, and it makes a 'GET' request to the backend.
Also, it's not clear to me why it ignores the URLRoot completely.

A: I had a trailing slash at the end of the urlRoot definition.
It should be:
var Rp_model = Backbone.Model.extend({
    urlRoot: '/ingeb/api_v1/users/rolespermissions',
});


text:
Q: Why do I have to divide the total work in the method of images? I got that potential, field and force don't need division since as long as it satisfies the boundary conditions it is correct as the answer is unique due to the uniqueness theorem.
But what qualities of work make only work different from the others?
I think I'm grasping it but it is still very vague that I can't explain to others satisfactorilly.
For example, there is a charge in the first quadrant. Then I would introduce image charges into the second, third and fourth.
Electric field, force, potential do not change because of the introduction but the work done by the real charge is fourths of the work done by the all charges together. Why is that?

A: The purpose of the image charges is to help you calculate the electric potential and electric field in the region of interest. Introducing an image charge in (say) a region occupied by a conductor doesn't introduce an electric field in that region.
When calculating the potential energy of the original situation, it may be useful to think in terms of energy-density and note that the energy-density in the conducting regions is zero since the field is zero there.
For example, for a charge above a conducting plane, the electric energy density is zero below the plane. So, the potential energy of the point charge above the conducting plane is half of what you get from the potential energy of a point charge above a real-version of the image charge.


text:
Q: React Router v4 - How to get current route? I'd like to display a title in <AppBar /> that is somehow passed in from the current route.
In React Router v4, how would <AppBar /> be able to get the current route passed into it's title prop?
  <Router basename='/app'>

      <Menu active={menu} close={this.closeMenu} />
      <Overlay active={menu} onClick={this.closeMenu} />
      <AppBar handleMenuIcon={this.handleMenuIcon} title='Test' />
      <Route path='/customers' component={Customers} />

  </Router>

Is there a way to pass a custom title from a custom prop on <Route />?

A: If you are using react's templates, where the end of your react file looks like this: export default SomeComponent you  need to use the higher-order component (often referred to as an "HOC"), withRouter.
First, you'll need to import withRouter like so:
import {withRouter} from 'react-router-dom';

Next, you'll want to use withRouter.  You can do this by change your component's export.  It's likely you want to change from export default ComponentName to export default withRouter(ComponentName).
Then you can get the route (and other information) from props.  Specifically, location, match, and history.  The code to spit out the pathname would be:
console.log(this.props.location.pathname);

A good writeup with additional information is available here: https://reacttraining.com/react-router/core/guides/philosophy

A: There's a hook called useLocation in react-router v5, no need for HOC or other stuff, it's very succinctly and convenient.
import { useLocation } from 'react-router-dom';

const ExampleComponent: React.FC = () => {
  const location = useLocation();

  return (
    <Router basename='/app'>

        <AppBar handleMenuIcon={this.handleMenuIcon} title={location.pathname} />

    </Router>
  );
}

A: Add
import {withRouter} from 'react-router-dom';

Then change your component export
export default withRouter(ComponentName)

Then you can access the route directly within the component itself (without touching anything else in your project) using:
window.location.pathname

Tested March 2020 with: "version": "5.1.2"

A: In the 5.1 release of react-router there is a hook called useLocation, which returns the current location object. This might useful any time you need to know the current URL.
import { useLocation } from 'react-router-dom'

function HeaderView() {
  const location = useLocation();
  console.log(location.pathname);
  return Path : {location.pathname}
}

A: Here is a solution using history Read more
import { createBrowserHistory } from "history";

const history = createBrowserHistory()

inside Router
<Router>
   {history.location.pathname}
</Router>

A: Has Con Posidielov said, the current route is present in this.props.location.pathname.
But if you want to match a more specific field like a key (or a name), you may use matchPath to find the original route reference.
import { matchPath } from `react-router`

const routes = [{
  key: 'page1'
  exact: true,
  path: '/page1/:someparam/',
  component: Page1,
},
{
  exact: true,
  key: 'page2',
  path: '/page2',
  component: Page2,
},
]

const currentRoute = routes.find(
  route => matchPath(this.props.location.pathname, route)
)

console.log(`My current route key is : ${currentRoute.key}`)

A: In react router 4 the current route is in -
    this.props.location.pathname.
Just get    this.props and verify.
If you still do not see    location.pathname then you should use the decorator withRouter.
This might look something like this:
import {withRouter} from 'react-router-dom';

const SomeComponent = withRouter(props => <MyComponent {...props}/>);

class MyComponent extends React.Component {
  SomeMethod () {
    const {pathname} = this.props.location;
  }
}

A: I think the author's of React Router (v4) just added that withRouter HOC to appease certain users. However, I believe the better approach is to just use render prop and make a simple PropsRoute component that passes those props. This is easier to test as you it doesn't "connect" the component like withRouter does. Have a bunch of nested components wrapped in withRouter and it's not going to be fun. Another benefit is you can also use this pass through whatever props you want to the Route. Here's the simple example using render prop. (pretty much the exact example from their website https://reacttraining.com/react-router/web/api/Route/render-func)
(src/components/routes/props-route)
import React from 'react';
import { Route } from 'react-router';

export const PropsRoute = ({ component: Component, ...props }) => (
  <Route
    { ...props }
    render={ renderProps => (<Component { ...renderProps } { ...props } />) }
  />
);

export default PropsRoute;

usage: (notice to get the route params (match.params) you can just use this component and those will be passed for you)
import React from 'react';
import PropsRoute from 'src/components/routes/props-route';

export const someComponent = props => (<PropsRoute component={ Profile } />);

also notice that you could pass whatever extra props you want this way too
<PropsRoute isFetching={ isFetchingProfile } title="User Profile" component={ Profile } />


text:
Q: Best approach to maintain a single set of DDLs and DMLs for multiple database type In our application, we support multiple types of databases namely Oracle, IBM DB2 (both UDB and ZOS), postgresql and So on. Currently we are maintaining separate DDLs and DMLs for each of these different databases.
It is difficult to maintain these multiple set of DDLs/DMLs and moreover in future our application might support few more database type.
What will be the best approach if we want to maintain a single set of DDLs/DMLs?

A: The best way to support multiple database types is to optimize the sql statements for each on of them. Otherwise you will one day end up with huge performance problems on one or the other database types.
Additionally to that it's unfair for your customers to tell them "I support Oracle, DB2, MSSQL, etc.) and not optimizing the SQL for each one of them. Why? Because your customer pays a lot for the database and your application does not use the advantages and features the database provides.

A: I'm going to list a different option here, having come from a development background. At one point, we had developed a client/server application, where we wanted the DDL (for the most part) to be the same between the client and the server. The challenge was the client and the server used different database engines.
So what we did was use XML. We defined all our tables (and even upgrades within XML). And then used differing XSL stylesheets to create the specific creation (or upgrade) scripts (with the correct DB engine DDL dialect) to run against the client or the server. So they went from XML to SQL. And we didn't have to maintain differing SQL definitions. Just one XML file.
Now, I know this option might turn a few heads, but it worked. And I am not saying you should pursue this option. Just that it is an option.


text:
Q: Linking to an ajax div Okay guys hopefully I can explain this effectively, so here goes.
I have a unordered list where each list item loads html pages into a div on click via jquery on my "Services" page.
Basically on the front page I have a couple links, when one is clicked, I need it to go to the "Services" and see the appropriate html page in the div.
Here's kinda how the code is:
Services Page:

Interlocking

Pool Backfill

Poured Concrete

Parging

Custom Landscaping

Snow Removal

Excavation

Front Page:

Interlocking

Pool Backfill

Poured Concrete

And here is my jQuery for your reference:

A: ok, suppose we want to show the interlocking page, so your front page should be like this:
1.

Interlocking

2.In your service page, the jquery code should be:


text:
Q: Transform new column with counts of items in a row I have a data frame with items separated with commas. I would like to transform a new column with the counts of each items within a row.
df = pd.DataFrame({'A' : [['one', 'two', 'three' ],
                          ['four', 'five', 'six', 'seven']
                         ]})

for the first row I would like to return 3, and the next 4 and transform a new column. I tried:
df.A[0].count(',') + 1

That would give me a count of the first row, but how do I transform a new column with the counts?

A: What you need to go is essentially create a list of the values that you want, and assign it to this new column.
This could be done using list comprehension like this:
# This will assign the lengths of the lists to a column called 'count'
df['count'] = [len(l) for l in df['A']]

You can also use pandas' own apply method, either directly to the Series:
df['count'] = df['A'].apply(lambda x: len(x))

Or applied across the whole row, which would allow you to access the values from other columns if you desired:
df['count'] = df.apply(lambda x: len(x['A']), axis=1)

As your attempt shows you counting commas, I assume that the values in the columns are strings, rather than lists. I would check that this is the intended behaviour, and if not convert the strings into lists.
If you do just want to do a count of the commas, you could apply your methods like so:
df['count'] = df.apply(lambda x: x.A.count(',') + 1, axis=1)


text:
Q: Riehl Universal Property of Tensor Product / "Tracing around the Commutative Square" $$
\newcommand{\Hom}{\mathrm{Hom}}
\newcommand{\Bilin}{\mathrm{Bilin}}
\newcommand{\Vect}{\mathrm{Vect}}
\newcommand{\Set}{\mathrm{Set}}
\newcommand{\k}{\mathbb{k}}
\newcommand{\fcmp}{\mathtt{;}}
$$

Related: Understanding Universal Property and Universal Element (from Category Theory in Context, Riehl)

Context
I'm self-studying category theory primarily through Riehl, "Category Theory in Context", which gives the following definition:

(Riehl Def. 2.3.3) A universal property of an object $c \in C$ is expressed by a (covariant) representable functor $F$ together with a universal element $x \in Fc$ that defines a natural isomorphism $\Hom_C(c,-) \cong F$ via the Yoneda lemma.

My initial interest in category theory was the result of seeing the phrase "universal property" thrown around in textbooks, without ever being given a precise definition.  So, Riehl's definition appeals to me, since it gives a recipe for actually coming up with new universal properties:  Define a category and a representable functor in that category!  The only trouble is that Riehl's definition looks nothing like the universal properties stated in textbooks!
Riehl gives an example to try to connect the two notions, but I feel like some details are missing.  The linked question also gives helpful clarification, but I'm still having trouble connecting the dots.
Tensor Product Setup
Let's walk through Riehl's  Ex 2.3.7 (changing the notation slightly to avoid the suggestive $\otimes$ symbol).  Below, I will use the notation $(f \fcmp g) := g \circ f$, which you should read "$f$ then $g$".
Fix $\k$-vector spaces $V,W \in \Vect_\k$.  Consider the (covariant) functor which sends every vector space $U$ to the set $\Bilin(V,W;U)$ of bilinear maps $V \times W \rightarrow U$, and which sends each linear transformation to its postcompositor,
$$
\begin{aligned}
\Bilin(V,W;-) : \Vect_\k &\rightarrow \Set \\
U &\mapsto
  \left\{ \substack{\text{bilinear maps}\\{V \times W \rightarrow U}} \right\} \\
(T : U_1 \rightarrow U_2) &\mapsto (-;T)_{V \times W}
\end{aligned}
$$
Assume we know $\Bilin(V,W;-)$ is a represented functor, that is, there is an object $Z \in \Vect_\k$ and a natural isomorphism
$$
\eta : \Vect_\k(Z,-) \Leftrightarrow \Bilin(V,W;-)
$$
whose components $\eta_U$ define bijections between the sets of linear maps $Z \rightarrow U$ and bilinear maps $V \times W \rightarrow U$, subject to the following naturality condition:

Where the subscript on $(-;f)_A$ marks the domain of the input function.  By the natural isomorphism, each bilinear map $g \in \Bilin(V,W;U)$ is associated with a linear map $\hat{g} : Z \rightarrow U$.  Pictured below is the naturality square when $f := \hat{g}$.

By the Yoneda Lemma, the natural isomorphism $\eta$ is determined by some universal element $\varphi \in \Bilin(V,W;Z)$, which is a bilinear map.  The pair $(Z,\varphi)$ has the universal property that it represents the functor $\Bilin(V,W;-)$.
Question
The universal property for tensor products is usually stated as follows:

For every vector space $U \in \Vect_\k$, and for every bilinear map $h : V \times W \rightarrow U$, there is a unique linear map $\overline{h} : Z \rightarrow U$ such that $h = (\varphi \fcmp \overline{h})$.

How can we use the setup above to arrive at this familiar universal property?
Riehl's Answer
According to Riehl, all we need to do is "trace $id_Z$ around the commutative square" shown above, which should reveal that the bilinear map $g$ factors uniquely through $\varphi$ along the linear map $\hat{g}$.  So, let's try it:

I'm not sure how this helps.  We know the equation $(\eta_Z id_Z) \fcmp \hat{g} = \eta_U ( id_Z \fcmp \hat{g})$ should hold, but I'm not sure how we can go from here to the universal property stated above.  For one, we've only used the naturality squares so far, without taking into account the universal element $\varphi$, so I don't know how we can conclude anything about $\varphi$.
I feel like I must be missing something simple, as the book makes this out to be trivial.  I think I've gotten myself too in the weeds that I can't see it.  Any help would be appreciated!
Riehl, Ex 2.3.3
Here is the original example from Riehl, for comparison:

A: The universal element is the image of the identity morphism under the isomorphism that shows the representability of the functor (it is $\eta$ here). This is what you marked as "$???$". So, the commutativity of that square gives us: for any element $g \in \operatorname{Bilin}(V,W;U)$, there exists a (unique as $\eta$ is iso) map $Z \to U$ (it is $\hat{g}$) such that $(-;\hat{g})_{V \times W}$ applied to the universal element gives $g$. In other words, $g$ is expressed as the composition of $\hat{g}$ and the universal map $V \times W \to Z = V \otimes W.$


text:
Q: How to get cypress code coverage for iframe? I'm trying to generate cypress code coverage for iframe which is part of my application.
Cypress creates an object called __coverage__ for the instrumentation that is present in my iframe window(main content). But at the end of each spec, it shows the below message

Without an iframe, it's generating the report.
I followed this link
https://github.com/cypress-io/code-coverage#instrument-your-application

A: I don't think adding an <iframe> can affect the code coverage, since the counters in __coverage__ are counting lines of javascript code and not HTML.
To check it out, I downloaded the latest repo from code-coverage/tree/v3.10.0 and added an <iframe> to one of the simple examples under /test-apps.
The coverage report was still created even though there was now an iframe on the page.

If you can provide more details, preferably a repo I can check further - but as it stands, it seems it's not reproducible.
BTW Cypress v10 is used in the code-coverage repo (not yet visible/released on the Cypress repo).


text:
Q: c++11 emplace_back and push_back syntax with struct I'm using MSVC, Visual Studio 2013.
Suppose I have a struct:
struct my_pair {
    int foo, bar;
};

And I want to add a bunch of these efficiently, without too creating a temporary and then discarding it:
vector<my_pair> v;
v.push_back(41, 42); // does not work              [a]
v.push_back({41,42}); // works                     [b]
v.emplace_back(41,42); // does not work            [c]
v.emplace_back({41,42}); // does not work          [d]
v.emplace_back(my_pair{41,42}); //works            [e]

Now if I add a constructor and copy constructor to my code:
my_pair(int foo_, int bar_) : foo(foo_), bar(bar_)
{
    cout << "in cstor" << endl;
}
my_pair(const my_pair& copy) : foo(copy.foo), bar(copy.bar)
{
    cout << "in copy cstor" << endl;
}

Then the behavior changes:
v.push_back(41, 42); // does not work                              [f]
v.push_back({41,42}); // displays "in cstor" and "in copy cstor"   [g]
v.emplace_back(41,42); // displays "in cstor"                      [h]
v.emplace_back({41,42}); // does not work                          [i]
v.emplace_back(my_pair{41,42}); // "in cstor" and "in copy cstor"  [j]

If I add a move constructor:
my_pair(my_pair&& move_) : foo(move_.foo), bar(move_.bar)
{
    cout << "in move cstor" << endl;
}

Then:
v.emplace_back(my_pair{41,42}); //displays "in cstor", "in move cstor"   [k]
v.emplace_back({41,42}); // still does not work                          [l]
v.push_back({41,42}); // displays "in cstor", "in move cstor"            [m]

Questions:
for [a,b] I understand the reason for working and not working.
for [c], it doesn't work because there is no constructor to forward the arguments to.
for [d], why doesn't this work like in the push case?
for [e], why does it work when the class name is added?
for [h], it seems like this is the most efficient code if there is a constructor that maps the arguments to the members
for [j], it seems like this is as bad as a push_back and with extra typing I'm not sure why anyone should do this over push_back
for [k,m], with the addition of a move constructor it seems like push_back(T&&) is being called which results in the same performance as emplace. But again, with the extra typing I'm not sure why anyone would do this.
I read that MSVC doesn't add a move constructor for you:
Why is copy constructor called in call to std::vector::emplace_back()?
What is the difference between [d,e] and why is emplace picky about it. And why does push_back(T&&) work without addition of the struct's name?
I can only get the full benefits of emplace if I know that there is a constructor that takes each member as argument?
Should I just stick with push_back? Is there any reason to use emplace_back(structname{1,2,3}) instead of push_back({1,2,3}) because it will end up calling push_back(T&&) anyway, and is easier to type?
Third, how does emplace_back(arg1,arg2,etc), do its magic to avoid the copy or move constructor completely?

A: For v.emplace_back({41,42});, see how to use std::vector::emplace_back for vector<vector<int> >?

v.emplace_back(41,42); does not work because of some rules in the standard (some emphasis mine):

Table 101 — Optional sequence container operations
Expression: a.emplace_back(args)
Return type: void
Operational semantics:
Appends an object of type T constructed with std::forward<Args>(args)....
Requires: T shall be EmplaceConstructible into X from args. For vector, T shall also be MoveInsertable into X.

For a type to be EmplaceConstructible,

§ 23.2.1.13
— T is EmplaceConstructible into X from args, for zero or more arguments args, means that the following expression is well-formed:
allocator_traits<A>::construct(m, p, args);

std::allocator_traits::construct() in turn does (if possible) a.construct(p, std::forward<Args>(args)...) (where a is m in the EmplaceConstructible expression).
a.construct() here is std::allocator::construct(), which calls ::new((void *)p) U(std::forward<Args>(args)...). This is what causes the compile error.
U(std::forward<Args>(args)...) (take note of the use of direct initialization) will find a constructor of U which accepts the forwarded arguments. However, in your case, my_pair is an aggregate type, which can only be initialized with braced-initialization syntax (aggregate initialization).

v.emplace_back(my_pair{41,42}); works because it calls either the implicitly generated default copy constructor or move constructor (note that these two may not always be generated). A temporary my_pair is first constructed which goes through the same process as that of v.emplace_back(41,42);, only that the argument is an r-value my_pair.

ADDITIONAL 1:

And why does push_back(T&&) work without addition of the struct's name?

It's because of push_back's signatures. push_back()'s argument isn't deduced, which means by doing push_back({1, 2}), a temporary object with the type of the vector's element type is first created and initialized with {1, 2}. That temporary object will then be the one that is passed to push_back(T&&).

Should I just stick with push_back? Is there any reason to use emplace_back(structname{1,2,3}) instead of push_back({1,2,3}) because it will end up calling push_back(T&&) anyway, and is easier to type?

Basically, emplace* functions is meant to optimize and remove the cost of creating temporaries and copying or move constructing objects when inserting them. However, for the case of aggregate data types where doing something like emplace_back(1, 2, 3) isn't possible, and the only way you could insert them is through creating a temporary then copying or moving, then by all means prefer the leaner syntax, and go for push_back({1,2,3}), where it would basically have the same performance as that of emplace_back(structname{1,2,3}).


text:
Q: Displaying elements other than fullscreen element (HTML5 fullscreen API) When I "fullscreen" an element (let's say a div), I can't get anything other elements to appear (while in fullscreen mode). Why is that happening? How can I accomplish this?
Related: Is there a way to overlay a <canvas> over a fullscreen HTML5 <video>?

A: It seems that browsers (Chrome 28, Firefox 23) set the z-index of fullscreened elements to 2147483647 (the largest 32-bit signed number). According to tests, setting the z-index of other elements to the same z-index will cause them to show, but the z-index of the fullscreened element can not be changed (it can, but the browser just ignores the value — even with !important).
Maybe the only reference I could find to this:
https://github.com/WebKit/webkit/blob/master/LayoutTests/fullscreen/full-screen-zIndex.html
Also, in Chrome dev tools:

So either set elements to the maximum z-index, or, the better solution would be to just create a container element, make it so that all elements you want to display are children of the container element, and fullscreen it.


text:
Q: React Native: The minCompileSdk (31) specified in a dependency's AAR metadata is greater than this module's compileSdkVersion (android-30) I am using React Native:
npx react-native run-android

I have many other solutions. Like force or update the targetsdk version and compile the SDK version, but nothing worked.
I tried changing compileSdkVersion 30 to compileSdkVersion 31 and targetSdkVersion 30 to targetSdkVersion 31.
The issue
The minCompileSdk (31) specified in a dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.appcompat:appcompat:1.4.1.

My buiild.gradle file
// Top-level build file where you can add configuration
// options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
        ndkVersion = "21.4.7075529"
        firebaseMessagingVersion = "21.1.0"
        googlePlayServicesVisionVersion = "19.0.0"
        playServicesVersion = "17.0.0" // or find latest version
        androidMapsUtilsVersion = "2.2.5"
        kotlin_version = "1.5.0"
        androidXCore = "1.5.0"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.2.2")
        classpath('com.google.gms:google-services:4.3.2')

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenLocal()
        mavenCentral()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        maven { url 'https://www.jitpack.io' }
    }
}

configurations.all {
    resolutionStrategy { force 'androidx.core:core-ktx:1.6.0' }
}

A: That is because of an Android build issue since 2022-11-04. I have resolved that by adding a few lines of code based on the report.
You can add this in the allprojects area of your android/build.gradle file.
def REACT_NATIVE_VERSION = new File(['node', '--print',"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim())

allprojects {
    configurations.all {
        resolutionStrategy {
            // Remove this override in 0.65+, as a proper fix is included in react-native itself.
            force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION
        }
    }

In my case, I have added it under repositories. See below.
allprojects {
    repositories {
        google()
        mavenCentral()
    }
    configurations.all {
        resolutionStrategy {
            // Remove this override in 0.65+, as a proper fix is included in react-native itself.
            force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION
        }
    }
}


text:
Q: Can ChaCha20 symmetric encryption be implemented in VB.NET even though it lacks circular bit rotation? After reading up on encryption algorithms and getting some really good advice from Maarten, I see that the ChaCha20 encryption algorithm has the potential to provide strong symmetric encryption AND good performance on older computers that lack specialized AES encryption/decryption instructions.
Is there a good example of VB.NET code that implements the ChaCha20 encryption algorithm in VB.NET?
VB.NET may not be ideal because it lacks a lot of specific instructions, for instance for circular bit rotation on unsigned integers (which are a key part of ChaCha20), so the question is can this algorithm still be implemented well in VB.NET?

A: After trying to write the ChaCha20 encryption algorithm in VB.NET, it seems that it will work quite well. Please see the code below.
There is no circular bit rotation for integers in VB.NET, but in the code you will find a solid workaround for achieving circular bit rotation.
I have added a test subroutine that tests the code against some official ChaCha20 test vectors you can find in the final spec here.
PLEASE TAKE IN TO ACCOUNT THESE GUIDELINES BEFORE USING THIS CODE:

*

*It has not been assessed by encryption experts and may contain security issues, especially on older CPUs that are chock-full of Meltdown and Spectre-type security flaws as well as a whole bunch more security flaws.

*Feedback to improve the code and performance is more than welcome, you can use this code freely and unrestricted.

*Until this code is assessed by experience encryption algorithm developers, use it where you are looking for obfuscation rather than strong encryption. (it is likely to offer this already, but zero guarantees)

*Make sure you protect the key you use, never store it unencrypted.

*Never ever (ever ever ever) use the same Nonce + Counter combination twice. You need these to decrypt the information, no need to protect these from an adversary put all your efforts in to making sure your key is safe.

*The subs for Encrypting and Decrypting are exactly the same, as this is symmetric encryption (that is why the sub names contain EncDec in the name).
Don't forget to check the Remove integer overflow checks-checkbox, see here how to do so.
Enjoy and let me know what needs to be improved!
Sub ValidateChaCha20AlgorithmAgainstStandard()

    'See final spec for ChaCha20 with test vectors here: https://datatracker.ietf.org/doc/rfc7539/

    Dim Key As String
    Dim Nonce As String
    Dim Counter As UInt32
    Dim HowMany As UInt32

    'Final spec for two blocks!
    Key = "03020100-07060504-0b0a0908-0f0e0d0c-13121110-17161514-1b1a1918-1f1e1d1c"
    Nonce = "00000000-4a000000-00000000"
    Counter = 1
    HowMany = 2

    Dim KeyStream() As Byte

    KeyStream = ChaCha20_GenerateEncDecByteStream(Key, Nonce, Counter, HowMany)

    Dim KeyStreamOutputHexString As String

    KeyStreamOutputHexString = ByteArrayToString(KeyStream)

    Dim ValidatedKeyStreamOutput As String

    ValidatedKeyStreamOutput = "224f51f3401bd9e12fde276fb8631ded8c131f823d2c06e27e4fcaec9ef3cf788a3b0aa372600a92b57974cded2b9334794cba40c63e34cdea212c4cf07d41b769a6749f3f630f4122cafe28ec4dc47e26d4346d70b98c73f3e9c53ac40c5945398b6eda1a832c89c167eacd901d7e2bf363740373201aa188fbbce83991c4ed"

    Dim StringCompareThatMustFail As String

    StringCompareThatMustFail = "I will fail for sure!"

    If KeyStreamOutputHexString.Equals(StringCompareThatMustFail) = False Then Debug.Print("String compare works properly")
    If KeyStreamOutputHexString.Equals(StringCompareThatMustFail) = True Then Debug.Print("String compare has FAILED DO NOT TRUST this verification!!!")

    If KeyStreamOutputHexString.Equals(ValidatedKeyStreamOutput) = True Then Debug.Print("ChaCha20 algorithm has passed the validation check, output is 100% correct")
    If KeyStreamOutputHexString.Equals(ValidatedKeyStreamOutput) = False Then Debug.Print("ChaCha20 algorithm has FAILED the validation check do NOT USE the algorithm!!!")

    'Now we test the bytestream encoding!

    Dim PlainText As String
    Dim PlainByteStream As Byte()

    PlainText = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, suncreen would be it."

    PlainByteStream = UTF8StringToBytes(PlainText)

    Dim EncryptedStream As Byte()
    Dim DecryptedStream As Byte()
    Dim DecryptedString As String

    EncryptedStream = ChaCha20_EncDecByteStream(PlainByteStream, KeyStream)
    DecryptedStream = ChaCha20_EncDecByteStream(EncryptedStream, KeyStream)
    DecryptedString = UTF8BytesToString(DecryptedStream)

    If DecryptedString.Equals(PlainText) = True Then Debug.Print("2dn ChaCha20 validation check passed, algorithm has SUCCESFULLY performed a full encryption/decryption round trip yielding exactly the source data!")

End Sub

Function ChaCha20_EncDecByteStream(StreamToEncDec() As Byte, KeyStream() As Byte) As Byte()

    Dim b As Byte
    Dim ProcessedStream As Byte()
    Dim LoopCounter As Integer

    ReDim ProcessedStream(StreamToEncDec.Length - 1)

    For LoopCounter = 0 To (StreamToEncDec.Length - 1)

        ProcessedStream(LoopCounter) = StreamToEncDec(LoopCounter) Xor KeyStream(LoopCounter)

    Next

    Return ProcessedStream

End Function

Function ChaCha20_GenerateEncDecByteStream(Key As String, Nonce As String, CounterStartPosition As UInt32, HowManyBlocks As UInt32) As Byte()

    'This function creates a bytestream with the ChaCha20 encryption algorithm that can be used for further processing
    'The stream is always in units of 64 bytes (512 bits).

    'The key and the nonce are Hexadecimal strings with every 8 Hex characters (32 bits) separated by a - for readability 'coz that is just very convenient to use :)

    Dim KeyStringArray() As String
    Dim NonceStringArray() As String

    KeyStringArray = Split(Key, "-")
    NonceStringArray = Split(Nonce, "-")

    Dim ChaChaStartBlock(15) As UInt32

    'See specified under https://datatracker.ietf.org/doc/html/rfc7539
    ' The first four words (0-3) are constants: 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574.

    'Here we set the constants
    ChaChaStartBlock(0) = &H61707865
    ChaChaStartBlock(1) = &H3320646E
    ChaChaStartBlock(2) = &H79622D32
    ChaChaStartBlock(3) = &H6B206574

    'Here we set the key
    ChaChaStartBlock(4) = CUInt("&H" & KeyStringArray(0))
    ChaChaStartBlock(5) = CUInt("&H" & KeyStringArray(1))
    ChaChaStartBlock(6) = CUInt("&H" & KeyStringArray(2))
    ChaChaStartBlock(7) = CUInt("&H" & KeyStringArray(3))
    ChaChaStartBlock(8) = CUInt("&H" & KeyStringArray(4))
    ChaChaStartBlock(9) = CUInt("&H" & KeyStringArray(5))
    ChaChaStartBlock(10) = CUInt("&H" & KeyStringArray(6))
    ChaChaStartBlock(11) = CUInt("&H" & KeyStringArray(7))

    'Here we set the initial counter position
    ChaChaStartBlock(12) = CounterStartPosition

    'Here we set the Nonce
    ChaChaStartBlock(13) = CUInt("&H" & NonceStringArray(0))
    ChaChaStartBlock(14) = CUInt("&H" & NonceStringArray(1))
    ChaChaStartBlock(15) = CUInt("&H" & NonceStringArray(2))

    Debug.Print("Start block:")
    Debug.Print(Hex(ChaChaStartBlock(0)) & " " & Hex(ChaChaStartBlock(1)) & " " & Hex(ChaChaStartBlock(2)) & " " & Hex(ChaChaStartBlock(3)))
    Debug.Print(Hex(ChaChaStartBlock(4)) & " " & Hex(ChaChaStartBlock(5)) & " " & Hex(ChaChaStartBlock(6)) & " " & Hex(ChaChaStartBlock(7)))
    Debug.Print(Hex(ChaChaStartBlock(8)) & " " & Hex(ChaChaStartBlock(9)) & " " & Hex(ChaChaStartBlock(10)) & " " & Hex(ChaChaStartBlock(11)))
    Debug.Print(Hex(ChaChaStartBlock(12)) & " " & Hex(ChaChaStartBlock(13)) & " " & Hex(ChaChaStartBlock(14)) & " " & Hex(ChaChaStartBlock(15)))

    'Now we create a byte array of the size we will need
    Dim ChaChaByteArray() As Byte

    ReDim ChaChaByteArray(HowManyBlocks * 64 - 1)

    Dim ByteArrayFillLoop As Integer
    Dim ChaChaResultBlock(15) As UInt32
    Dim InnerLoop As Integer
    Dim FourByteArray(3) As Byte
    Dim FourByteArrayReverseOrder(3) As Byte

    For ByteArrayFillLoop = 0 To (HowManyBlocks - 1)

        ChaChaStartBlock(12) = CounterStartPosition + ByteArrayFillLoop

        ChaChaResultBlock = ChaCha20_GenerateEncDecBlock(ChaChaStartBlock)

        Debug.Print("Result block:")
        Debug.Print(Hex(ChaChaResultBlock(0)) & " " & Hex(ChaChaResultBlock(1)) & " " & Hex(ChaChaResultBlock(2)) & " " & Hex(ChaChaResultBlock(3)))
        Debug.Print(Hex(ChaChaResultBlock(4)) & " " & Hex(ChaChaResultBlock(5)) & " " & Hex(ChaChaResultBlock(6)) & " " & Hex(ChaChaResultBlock(7)))
        Debug.Print(Hex(ChaChaResultBlock(8)) & " " & Hex(ChaChaResultBlock(9)) & " " & Hex(ChaChaResultBlock(10)) & " " & Hex(ChaChaResultBlock(11)))
        Debug.Print(Hex(ChaChaResultBlock(12)) & " " & Hex(ChaChaResultBlock(13)) & " " & Hex(ChaChaResultBlock(14)) & " " & Hex(ChaChaResultBlock(15)))

        'Here we copy the block into the byte array
        For InnerLoop = 0 To 15

            FourByteArray = BitConverter.GetBytes(ChaChaResultBlock(InnerLoop))

            If BitConverter.IsLittleEndian = False Then
                FourByteArrayReverseOrder(0) = FourByteArray(3)
                FourByteArrayReverseOrder(1) = FourByteArray(2)
                FourByteArrayReverseOrder(2) = FourByteArray(1)
                FourByteArrayReverseOrder(3) = FourByteArray(0)

                FourByteArray = FourByteArrayReverseOrder
            End If

            Buffer.BlockCopy(FourByteArray, 0, ChaChaByteArray, ByteArrayFillLoop * 64 + InnerLoop * 4, 4)

        Next

    Next

    Return ChaChaByteArray

End Function

Function ChaCha20_GenerateEncDecBlock(CC20M As UInt32()) As UInt32()

    Dim M(15) As UInt32

    Array.Copy(CC20M, M, M.Length)

    Dim R10CTR As Integer

    For R10CTR = 1 To 10

        Call ChaCha20_QR(M(0), M(4), M(8), M(12))
        Call ChaCha20_QR(M(1), M(5), M(9), M(13))
        Call ChaCha20_QR(M(2), M(6), M(10), M(14))
        Call ChaCha20_QR(M(3), M(7), M(11), M(15))

        Call ChaCha20_QR(M(0), M(5), M(10), M(15))
        Call ChaCha20_QR(M(1), M(6), M(11), M(12))
        Call ChaCha20_QR(M(2), M(7), M(8), M(13))
        Call ChaCha20_QR(M(3), M(4), M(9), M(14))

    Next

    Dim CTR As Integer

    For CTR = 0 To 15
        M(CTR) = M(CTR) + CC20M(CTR)
    Next

    Return M

End Function

Sub ChaCha20_QR(ByRef a As UInt32, ByRef b As UInt32, ByRef c As UInt32, ByRef d As UInt32)

    a = a + b
    d = d Xor a
    d = d << 16 Or d >> 16

    c = c + d
    b = b Xor c
    b = b << 12 Or b >> 20

    a = a + b
    d = d Xor a
    d = d << 8 Or d >> 24

    c = c + d
    b = b Xor c
    b = b << 7 Or b >> 25

End Sub

Function ByteArrayToString(ba() As Byte) As String

    Dim hex As New StringBuilder(ba.Length * 2)
    Dim b As Byte

    For Each b In ba
        hex.AppendFormat("{0:x2}", b)
    Next

    Return hex.ToString()

End Function

Private Function UTF8StringToBytes(
ByVal str As String) As Byte()

    Return System.Text.Encoding.UTF8.GetBytes(str)
End Function

Private Function UTF8BytesToString(
ByVal bytes() As Byte) As String

    Return System.Text.Encoding.UTF8.GetString(bytes)
End Function


text:
Q: get correct .mp3 url from soundcloud api for use with soundmanager2 360-player My question is identical to this one here, however as the question was never resolved and I can't message PeeHaa privately to ask the answer I'll ask again here.
I've successfully queried the soundcloud api and gotten my the stream_url for each track and added it to all the hrefs of my 360 player (demo here). My code for the elements looks something like this:

 play "an.mp3"

I have this script to find all the a tags with data-title attributes and give them the correct href based on the stream_url, but when I try to click the soundmanager icon in the browser and play the track, it just gets redirected to the .mp3 url.
SC.initialize({
  client_id: 'MY_CLIENT_ID'
});

SC.get('/playlists/2450655', 'allow_redirects=False', function(playlist) {

  var titles = $('.audio .ui360 a').each(function(index){
    this.index = index;
  });

  for (var i = 0; i < playlist.tracks.length; i++) {
    var id = '?client_id=MY_CLIENT_ID'
    for (var j = 0; j < titles.length; j++) {
      if (playlist.tracks[i].title === $(titles[j]).attr('data-title')) {
        $(titles[j]).attr('href', playlist.tracks[i].stream_url+id)
      }
    }
  }

});

Does anyone know how to get the correct url for playing tracks hosted on soundcloud in this manner?

A: I know this is an old question, but the problem was driving me up the wall and I finally figured it out, so here's my answer for others:
Soundmanager will work if you specify an mp3 mimetype in the link:

    play "an.mp3"

A: Why not just use the SoundCloud JavaScript SDK to stream the tracks? Something like:
SC.get('/playlists/2450655', function(playlist) {
  $(playlist.tracks).each(function(index, track) {
    $('a[href="' + track.stream_url + '"]').click(function(e) {
       e.preventDefault();
       SC.stream('/tracks/' + track.id, function(sound) {
         sound.play();
       });
    });
  });
});

Would that solve your problem, or is there a particular reason you need to resolve the URL?


text:
Q: Reading record at particular index from Linux Message Queue I know that behavior of message queue is sequential but is there any way to read a particular record from Linux message queue ?
Like I want to pass index and msg queue id and I should get data/record present at that index.
For eg. If I have 100 records in a message queue and I want to read 23rd record then I can pass index as 23 and I should get record present at 23rd position by skipping first 22 records.
I tried using message type but it is also sequential.

A: Specify the message index in "msgtyp" while sending the message. And while receiving the message specify the index you want to read in that "msgtyp". That way you will able to read specific index messages in the mesgqueue
struct msgbuf {
    long mtype;       /* use message type as a message index*/
    char mtext[1];    /* message data */
};


text:
Q: Protractor won't run chrome Protractor was running fine but suddenley won't run chrome anymore. This is mye current configuration:
exports.config = {
    baseUrl: 'http://localhost:1384/#/',
    framework: 'jasmine',
    seleniumAddress: 'http://localhost:4444/wd/hub',
    specs: ['./tests/e2e/*.js'],
    multiCapabilities: [{
      //'browserName': 'firefox',
      'browserName': 'chrome',
    },
    ],
    jasmineNodeOpts: {
      showColors: true
    }
  }

I am running latest of all the related dependencies:

*

*protractor : "protractor": "^5.2.0",

*chromedriver:  2.33.506092

*webdriver:  selenium standalone version available: 3.7.1 [last]
when I run webdriver-manager start eveything runs fine, and then running protractor conf.js gives the following output in the window running the selenium server:
Starting ChromeDriver 2.33.506092 Only local connections are allowed.

The terminal windows running the protractor config, gives the following errros:
E/launcher - WebDriverError: unknown error: Chrome failed to start: exited abnormally

I have already tried reinstalling protractor and updating the chromedriver. Running the tests work fine in firefox with the exact same configurations.
I am also running tests with karma, and karma runs fine in a chrome browser window.

A: Add directConnect: true to your config file. It might help you.

A: this would be your conf file
exports.config = {
  directConnect: true,

  // Capabilities to be passed to the webdriver instance.
  capabilities: {
    'browserName': 'chrome',
  },

  // Framework to use. Jasmine is recommended.
  framework: 'jasmine',
  baseUrl: "YOUR URL",

  // Spec patterns are relative to the current working directory when
  // protractor is called.
  specs: ['../Tests/test.js'],

  // Options to be passed to Jasmine.
  jasmineNodeOpts: {
    defaultTimeoutInterval: 30000
  },
    };

you don't need to give below dependencies because chrome get launched from conf file only

*

*chromedriver: 2.33.506092

*webdriver: selenium standalone version available: 3.7.1 [last]

A: Ran into similar issue. Try updating chrome which should fetch the new compatible chrome driver.