Meteor.js Collection empty on Client

Question: Why is it that myCollection.find().fetch() returns an empty array [] even though the call is made within if(data){...}? Doesn't the if statement ensure that the collection has been retrieved before executing the console.log()?
Template.chart.rendered = function() {

        var data = myCollection.find().fetch();

        if(data) {
            console.log(data);
        }

        $('#chart').render();

}

This returns [] in the browser Javascript console.
Comment: @Jagi `auto-publish` has not been removed, and doing `console.log(myCollection.find().count())` returns a positive number in the browser Javascript console.
Comment: The question was rather, why Meteor is returning empty collection. I suppose you are not publishing it in right way or you don't do it at all. Post the code so, we will be able to help.
Comment: In my case, the tuorial I was following assumed `autopublish` to be installed. But the version I installed didn't have that package.
Answer: You could use count() instead which returns the number of results. data itself would be an empty array, [] which isn't falsey ( [] == true ).
Also don't use fetch() unless you're going to use the raw data for it because its quite taxing. You can loop through it with .forEach if you need to.
var data = myCollection.find();

if(data.count())
  console.log(data);

//If you need it for something/Not sure if this is right but just an example
$('#chart').render(data.fetch())

Comment: Thanks, somehow `data.count()` in the suggested code returns `0`, while doing `data.count()` in the browser Javascript console returns the correct count. So the collection data is stil not fetched. Using something other than `rendered` in `Template.chart.rendered` appeared to hep avoid this problem, why is that?
Comment: Its happening because the code is running too early. When meteor initially loads there's no data in and it comes in a bit later (about a second later). You would have to tie it up to the subscription functions so that it fires after the template is rendered and the data is available
Comment: Or use `Deps.autorun` instead if you know you're on the correct page
Comment: @Akshat could you mention a correct pattern to do the first approach?  My situation is that I need to extend some of the object of the collection (randomly), to tag them as active for a carrousel. Sometimes _.extends receives an empty list as result of find().fetch()
Comment: I got what you meant. Hold On. :) leaving the link for other spaced out alien http://docs.meteor.com/#publishandsubscribe
Answer: The problem is that you have to wait for data from the server. When you just use Template.name.rendered function it is immediately invoked. You have to use Template.name.helpers function to wait for data from the server. Everything is described in the documentation.
Answer: It seems when you "remove autopublish" you have to also subscribe on the client.
  if(Meteor.isClient) {
    Meteor.startup(function() {
      Myvars = new Mongo.Collection("myvars");
      Meteor.subscribe('myvars')
    });
  }

and enable allow and publish on the server
  if(Meteor.isServer) {
    Meteor.startup(function () {
      Myvars = new Mongo.Collection("myvars");
      Myvars.allow({
        insert: function () {
          return true;
        },
        update: function () {
          return true;
        },
        remove: function () {
          return true;
        }
      });
      if (Myvars.find().count() == 0) {
        Myvars.insert({myvalue:'annoyed'});
      }

      Meteor.publish("myvars", function() {
        return Myvars.find();
      });
    });
  }

I'm new to this as well. I was just looking to have a global value that all clients could share. Seems like a useful idea (from a beginner's perspective) and a complete oversight on the Meteor teams behalf, it was nowhere clearly documented in this way. I also still have no idea what allow fetch is, that too is completely unclear in the official documentation.
Comment: you can leave out the `== 0`
Answer: It does, but in javascript you have the following strange behaviour
if ([]){
  console.log('Oops it goes inside the if')
} // and it will output this, nontheless it is counter-intuitive

This happens because JS engine casts Boolean([])  to true. You can how different types are casted to Boolean here.
Check if your array is not empty in the beginning.
a = [];
if (a.length){
  //do your thing
}

Comment: `data` appears to be `[]` when the template helper code is executed, causing the collection data to be missing. However when `console.log(myCollection.find().count()` is executed in the Javascript console, it does show a count of all the documents retrieved for the query.

Meteor.js Collection empty on Client


Change the browse view to show horizontally

Question: On phpmyadmin when I browse a table all the tables are side by side (in a horizontal manner). I want them to be displayed vertically. I changed in my configs $cfg['DefaultDisplay'] = 'vertical'; but that didn't do anything. Am I missing something?
Answer: I fixed the issue. By setting $cfg['DefaultDisplay'] = 'horizontal'; in the config.inc.php the view will change once you restart your apache server, and refresh your cache (best method is to logout and log back in).


array_map not allow to pass object in use()

Question: I am trying this:
array_map(function($data) use ($this->id) {
   //code
}, $arr);

I'm getting an error that I can not pass an object to use().
What am I doing wrong?
Thanks
Comment: how about reasigning as `$id = $this->id`, then using it in `use ($id)`?
Answer: You don't need to pass anything from $this to the closure. $this is available in closures by default. Example:
class A {
    private $id = 500;

    function B() {
        $arr = [1, 2, 3];
        array_map(
            function($data) {
                echo "I'm data $data with id {$this->id}\n";
            },
            $arr
        );
    }
}

$a = new A();
$a->B();

This code will print
I'm data 1 with id 500
I'm data 2 with id 500
I'm data 3 with id 500

Or if you want to pass anything to the use construct instead of using $this directly, just assign your value to a variable and then pass this simple variable to use. You can not list expressions in use.


Why I cannot use the @azure/web-pubsub node package in a react code?

Question: I import the following package in a react/webpack app:
import { WebPubSubServiceClient } from '@azure/web-pubsub'

When I invoke WebPubSubServiceClient as follows:
const connectionString = 'XXXXX'
const hubName = 'YYYY'
let serviceClient = new WebPubSubServiceClient(connectionString, hubName)

I get the following error:
An error occured as follows:  TypeError: url__WEBPACK_IMPORTED_MODULE_1__.URL is not a constructor
    at parseConnectionString (parseConnectionString.js:24)
    at new WebPubSubServiceClient (hubClient.js:31)

By looking at the code in the debugger —which is located in the Microsoft @azure/web-pubsub node package code—, I see the import URL is probably the issue:
import { AzureKeyCredential } from "@azure/core-auth";
import { URL } from "url";
export function parseConnectionString(conn) {
    let parsed = {};
    conn.split(";").forEach((i) => {
        const assignmentPos = i.indexOf("=");
        if (assignmentPos === -1)
            return;
        const key = i.substring(0, assignmentPos).toLowerCase();
        const value = i.substring(assignmentPos + 1);
        parsed[key] = value;
    });
    let endpointPart = parsed["endpoint"];
    if (!endpointPart)
        throw new TypeError("connection string missing endpoint");
    if (!endpointPart.startsWith("http")) {
        endpointPart = `https://${endpointPart}`;
    }
    const key = parsed["accesskey"];
    if (!key)
        throw new TypeError("connection string missing access key");
    const credential = new AzureKeyCredential(key);
    const port = parsed["port"];
  >>  const url = new URL(endpointPart); << the error comes from here
    url.port = port;
    const endpoint = url.toString();
    url.port = "";
    return { credential, endpoint };
}
//# sourceMappingURL=parseConnectionString.js.map

Regarding Webpack I use the following version:
"webpack": "^4.44.2",
"webpack-bundle-analyzer": "^3.9.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0",

I must say that using the same code and module in a pure nodeJS works nice.
So I believe it is related to react?
What should I do?
Comment: are you using this lib as `url` - https://www.npmjs.com/package/url . it hasn't been updated in 6 years, and maybe it doesn't have default export.

Besides, what version of webpack do you use?
Comment: Microsoft @azure/web-pubsub makes use of 'url' package (where the issue is located is the Micorsoft code). and regarding Webpack I use:
    "webpack": "^4.44.2",
    "webpack-bundle-analyzer": "^3.9.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0",
Comment: Regarding the default export: url is imported as non-default import: the code where the issue is located is there: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/web-pubsub/web-pubsub/src/parseConnectionString.ts
Answer: Finally, running on react is hassle-free, provided one choose the right constructor.
So here is how to do it:
// == Azure WebPuSub
import { WebPubSubServiceClient, AzureKeyCredential } from '@azure/web-pubsub'

// == W3C sockets
import { w3cwebsocket as W3CWebSocket } from 'websocket'

// == Create the service client
const hubName = 'telemetry'
const key = <KEY>
const cred = new AzureKeyCredential(key)
const endpoint = "https://XXXXX.webpubsub.azure.com"
const serviceClient = new WebPubSubServiceClient(endpoint, cred, hubName)
console.log('Azure WebPubSub service client is', serviceClient)

/**
 * @summary Connect to the secure socket server thru the WebPubSub service
 */
async function connect ({onError, onOpen, onMessage, onClose}) {
    console.log('About to get auth token…')
    let token = await serviceClient.getAuthenticationToken()
    //console.log('Auth token is', token)

    // == Connect to the secured socket server
    const url = token.url
    let wsClient = new W3CWebSocket(url)

    console.log('Web socket is',wsClient)

    // == Connect the callbacks
    wsClient.onerror = onError
    wsClient.onopen = onOpen
    wsClient.onmessage = onMessage
    wsClient.onclose = onClose
}

// == Now actually connect to the secure web sockets
connect({onError, onOpen, onMessage, onClose})

And voila! Works like charm
Answer: The latest version of @azure/web-pubsub should've removed the "URL" dependency. Fixed with https://github.com/Azure/azure-sdk-for-js/pull/15300


php searching in multidimensional array of unknown depth

Question: I try to select the data of an array that was constructed by json_decode().
In principle it is an multiarray of unknown dimension.
First of all, I want to search recursively for a value in this array. As a next step I want to get some other values of the upper dimension. So here is an example:
I search for: "2345"
....
$json[3][6]['journal']['headline']="news"
$json[3][6]['journal']['article']=2345
....
$json[8]['journal']['headline']="weather"
$json[8]['journal']['article']=2345
....

After that I want to get the value of the element headline (returning "news" and "weather")
It might be that the element 2345 can be found in different dimensions!!!
Answer: just create a function for compile unknown array. try this
$json[1][6]['journal']['headline']="news";
$json[1][6]['journal']['article']=2345;
$json[3][6]['journal']['headline']="HOT";
$json[3][6]['journal']['article']=2345;
$json[8]['journal']['headline']="weather";
$json[8]['journal']['article']=2345;
$json[10]['journal']['headline']="weather";
$json[10]['journal']['article']=2345;

$GLOBALS['list_scan'] = array();
$result = array();

foreach ($json as $key => $value)
{
    if (is_array($value)) {
        _compile_scan($key, $value);
    }
}

echo "
";
print_r($GLOBALS['list_scan']);
echo "
";

$search = "2345";
$keyword = "article";
$keyFinder = "headline";

foreach ($GLOBALS['list_scan'] as $key => $value)
{
    if ($value == $search)
    {
        $addr = substr($key, 0, -(strlen($keyword))).$keyFinder;
        if (!empty($GLOBALS['list_scan'][$addr]))
        {
            $result[] = $GLOBALS['list_scan'][$addr];
        }
    }
}
echo "
";
print_r($result);
echo "
";

function _compile_scan($index, $value)
{
    $pointer =& $GLOBALS['list_scan'];

    foreach ($value as $key => $val)
    {
        $temp = '';
        $temp = $index.'|'.$key;
        if (is_array($val))
        {
            // $pointer[$temp] = $val;
            _compile_scan($temp, $val);
        }
        else $pointer[$temp] = $val;
    }
}

output:
Array
(
    [1|6|journal|headline] => news
    [1|6|journal|article] => 2345
    [3|6|journal|headline] => HOT
    [3|6|journal|article] => 2345
    [8|journal|headline] => weather
    [8|journal|article] => 2345
    [9|journal|headline] => Others
    [9|journal|article] => 234521
)
Array
(
    [0] => news
    [1] => HOT
    [2] => weather
)

Answer: Someone could probably do this with a RecursiveIteratorIterator object, but I personally have a hard time with iterator objects, so here is a fairly robust system:
<?php
// This will traverse an array and find the
// value while storing the base key
class RecurseLocator
    {
        public  static  $saved = array();
        public  static  $find;
        public  static  $trigger;
        public  static  function Initialize($find = false)
            {
                self::$find =   $find;
            }

        public  static  function Recursive(array $array)
            {
                foreach($array as $key => $value) {

                        if(!isset(self::$trigger) || (isset(self::$trigger) && empty(self::$trigger))) {
                                if(is_numeric($key))
                                    self::$trigger  =   $key;
                            }

                        if(!is_array($value)) {
                                if($value == self::$find) {
                                        self::$saved[self::$trigger]    =   $value;
                                    }
                            }

                        if(is_array($value)) {

                                $value  =   self::Recursive($value);
                                if(!is_numeric($key))
                                    self::$trigger  =   "";
                            }

                        $return[$key]   =   $value;
                    }

                return $return;
            }
    }

// This class will traverse an array searching
// for a specific key or keys
class   RecurseSearch
    {
        public  $data;
        public  $compare;

        public  function Find($array = '',$find,$recursive = true)
            {
                $find   =   (is_array($find))? implode("|",$find):$find;
                if(is_array($array)) {

                        foreach($array as $key => $value) {

                        if(preg_match("/$find/",$key))
                            $this->compare[$key]    =   $value;

                                if($recursive == true) {
                                        if(!is_array($value)) {
                                                if(preg_match("/$find/",$key)) {
                                                        $this->data[$key][] =   $value;
                                                    }

                                                $array[$key]    =   $value;
                                            }
                                        else {
                                                if(preg_match("/$find/",$key))
                                                    $this->data[$key][] =   $this->Find($value,$find);

                                                $array[$key]    =   $this->Find($value,$find);
                                            }
                                    }
                                else {
                                        if(preg_match("/$find/",$key))
                                            $this->data[$key]   =   $value;
                                    }
                            }

                        $this->data =   (isset($this->data))? $this->data:false;

                        return $this;
                    }
            }
    }

// This function just wraps the RecurseSearch class
function get_key_value($array = array(), $find = array(),$recursive = true)
    {
        $finder =   new RecurseSearch();
        return $finder->Find($array,$find,$recursive);
    }

USAGE:
    $json[3][6]['journal']['headline']  =   "news";
    $json[3][6]['journal']['article']   =   2345;
    $json[8]['journal']['headline']     =   "weather";
    $json[8]['journal']['article']      =   2345;
    $json[4][1]['journal']['headline']  =   "news";
    $json[4][1]['journal']['article']   =   22245;
    $json[5]['journal']['headline']     =   "weather";
    $json[5]['journal']['article']      =   233345;

    // Set the search criteria
    RecurseLocator::Initialize(2345);
    // Traverse the array looking for value
    $arr    =   RecurseLocator::Recursive($json);
    // If found, will be stored here
    $iso    =   RecurseLocator::$saved;

    /* $iso looks like:
    Array
    (
        [3] => 2345
        [8] => 2345
    )
    */

    // Loop through the $iso array
    foreach($iso as $key => $value) {
            // Save to new array your search results
            $new[]  =   get_key_value($json[$key],array("headline","article"),true);
        }

    /* $new looks like:
Array
(
    [0] => RecurseSearch Object
        (
            [data] => Array
                (
                    [headline] => Array
                        (
                            [0] => news
                        )

                    [article] => Array
                        (
                            [0] => 2345
                        )
                )

            [compare] => Array
                (
                    [headline] => news
                    [article] => 2345
                )
        )

    [1] => RecurseSearch Object
        (
            [data] => Array
                (
                    [headline] => Array
                        (
                            [0] => weather
                        )

                    [article] => Array
                        (
                            [0] => 2345
                        )
                )

            [compare] => Array
                (
                    [headline] => weather
                    [article] => 2345
                )
        )
)
    */
?>

Just as a side note, the above class stores multiple found in the [data], and then stores them also in the [compare], however the [compare] will overwrite itself if multiple same-keys are found in one array where as [data] will just keep adding values.


Accessing AppConfig settings via Injection

Question: I have values in my AppConfig like this...
<appSettings>
<add key="id" value="1234" />
</appSettings>

In the IAppConfig class I have...
 public interface IAppConfig
 {
    string id{ get; }
 }

   [ConfigurationProperty("id")]
    public string id
    {
        get
        {
            return (string)this["id"];
        }
        set
        {
            this["id"] = value;
        }
    }

In a startup class I have
using SimpleInjector;

   public static Container Container;

    public static void Start()
    {
        Container = new Container();

         IAppConfig appConfig = (IAppConfig)ConfigurationManager.GetSection("appSettings");
         Container.Register<IAppConfig, AppConfig>(Lifestyle.Singleton);

    }

And I inject it into another class...
       private readonly IAppConfig config;

    public ClassName(IAppConfig config)
    {
        this.config = config;

    }

However the id (and other values) come up as empty strings. This happens in the Getter.   I am calling the Start method before trying to access them.  What am I doing wrong?
Answer: You register type AppConfig as singleton implementation of type IAppConfig, so when you request IAppConfig from container, you'll get an instance created by container, and not 'appConfig' you created in Start.
You need to register instance like:
Container.Instance<IAppConfig>(appConfig);

Comment: Container does not have an Instance property.  Do you mean RegisterInstance?
Comment: Probably, I haven't checked the exact syntax of that container, but most of containers have some method to register instance of object as some interface.
Answer: You have created an appconfig object but have not registered that for injection.
Try the below:
Simplify you AppConfig class
 public class AppConfig
 {
    public string id{ get; set; }
 }

 var appconfig = new AppConfig{ id = ConfigurationManager.AppSettings["id"] };

container.Register<AppConfig>(() => appconfig, Lifestyle.Singleton);

You can keep the Interface pattern as well
Comment: I get this...

System.InvalidCastException: 'Unable to cast object of type 'System.Configuration.KeyValueInternalCollection' to type 'ProjectName.Config.IAppConfig'.'
Comment: There is an issue with this casting
(IAppConfig)ConfigurationManager.GetSection("appSettings");
Comment: Are you asking?  I assume there is an issue.  How would I inject the class?
Comment: I have updated my solution. Can you try? If it still doesn't work i will have to create a fiddlr.
Comment: GetSection is a method which is not valid in the current context.  Also where do you get the key variable?  Is that local?
Comment: It will just be ConfigurationManager.AppSettings["id"]  // "id" is the key in you app.config
Comment: Since I am no longer using the IAppConfig interface, how would I inject that id value into other classes?
Comment: Oh wait it's supposed to be Container.Register
Comment: in constructor inject AppConfig. You can also use IAppConfig if u want, just write some more code. The following code works, here i have registered dependency and then resolving it with type "AppConfig"  ///// container.Register(() => appconfig, Lifestyle.Singleton);
   AppConfig data = container.GetInstance(); //////
Comment: That was some work, I was making a fiddle. Well happy to help. Enjoy Coding


Warning on git bash start "bash: C:/Users/RS3/Anaconda3/etc/profile.d/conda.sh: No such file or directory"

Question: Whenever I open git bash I get the following warning:
bash: C:/Users/RS3/Anaconda3/etc/profile.d/conda.sh: No such file or directory
The problem is that I uninstalled Anaconda, because I installed independent python, which resulted in giving that error.
How to remove this Warning.
Answer: Check the content of ~/.bashrc (which was mentioned here)
Maybe that (or ~/.profile, mentioned here) includes a command for that old uni uninstalled program.
Remove those lines, and try to open again a git bash session.
Comment: Thanks, I removed .profile and .bashrc files. That solved the problem
Answer: To remove that warning, simply erase the file path string in the .bashrc file using nano command. Here's how:
Steps to remove that warning:

Open Git Bash and check .bashrc location by typing ~/.bashrc into git bash.
Navigate to folder where .bashrc file is located.
Type nano .bashrc
Erase the string that says C:/Users/RS3/Anaconda3/etc/profile.d/conda.sh
Press ctrl+O to save .bashrc file and then ctrl+X to exit.

When you reopen git bash nothing should appear because .bashrc doesn't have that path in it anymore. Also, if conda commands were working before it will still continue to work after erasing this.


Não consigo passar os valores de uma página para outra com Laravel

Question: Estou com um problema no Laravel que não consigo resolver, e já tentei muitas coisas: O que quero é pegar os valores que estão em uma página e mandar para outra em um formulário.
O botão editar em uma lista tem o seguinte código:
{{ __('Editar') }}

Essa é a rota:
Route::put('peoples', ['as' => 'peoples.edit', 'uses' => 'PeopleController@edit']);

Esse é o código no controlador
public function edit(People $people)
{
    return view('profilePeople.edit', compact('people'));
}

Esse é o código da classe
<?php namespace App; use Illuminate\Database\Eloquent\Model; class People extends Model { protected $table = 'people'; protected $fillable = ['name', 'email',]; protected $guarded = ['id']; }

Esse é o código onde um input onde deveria recuperar os valores passados.
<input type="text" name="name" id="input-name" class="form-control form-control-alternative{{ $errors->has('name') ? ' is-invalid' : '' }}" placeholder="{{ __('Nome') }}" value="{{ old('name', $people->name) }}" required autofocus>

Não dá nenhum erro porém os valores não são passados.
Não sei se com essas informações alguém pode me ajudar, porém basta me mandar as informações que precisa e eu acrescentarei.
Desde já, obrigado!
Answer: Suas rotas:
// exibe a view com o formulario para editar a pessoa
Route::get('/peoples/{id}/edit', 'PeopleController@edit');
// atualiza a pessoa no banco de dados
Route::put('/peoples/{id}', 'PeopleController@update');

Seu botão:
id . '/edit') }}">
    {{ __('Editar') }}

Seu controller:
public function edit($id)
{
    $people = People::findOrFail($id);

    return view('profilePeople.edit', compact('people'));
}

public function update(Request $request, $id)
{
    $data = $request->all();
    $people = People::findOrFail($id);

    try {
        DB::transaction(function() use ($data) {
            $people->update($data);
        });
    }catch(\Exception $exception){
        abort(500);
    }

    return redirect('/peoples/' . $id);
}

profilePeople > edit.blade.php
<form action="{{ url('/peoples/' . $people->id) }}" method="post">
    @csrf
    @method('put')

</form>

Comment: Deu super certo! Eu quebrei tanto a cabeça e você resolveu isso tão rápido. Muito obrigado!


N queens problem using backtracking in javascript

Question: I was trying to implement N-Queens problem using a backtracking algorithm. The goal was to place n queens on an n x n chessboard in such a way that no two queens attack each other. A queen can attack other queens if they are in the same row, column or diagonal.
I tried solving this way:
   function nQueen(boolArrBoard,row){
       if(row === boolArrBoard.length){
           display(boolArrBoard)
           return 1 *//count*
       }

       let count = 0
       *//placing the queen and checking every row and column*
       for(let col = 0; col < boolArrBoard.length; col++){
           *//place the queen if it is safe *
           if(isSafe(boolArrBoard,row,col)){
               boolArrBoard[row][col] = true
               count += nQueen(boolArrBoard,row+1)
               boolArrBoard[row][col] = false
           }
       }
       return count
   }

   function isSafe(boolArrBoard,row,col){
       *//vertical*
       for(let i = 0; i < row; i++){
          if(boolArrBoard[i][col]){
           return false
          }
       }

       *//left diagonal*
       let maxLeft = Math.min(row,col)
       for(let i = 1; i <= maxLeft; i++){
           if(boolArrBoard[row - i][col - i]){
               return false
              }
       }

       *//right diagonal*
       let maxRight = Math.min(row, boolArrBoard.length - col - 1)
       for(let i = 1; i <= maxRight; i++){
           if(boolArrBoard[row - i][col + i]){
               return false
              }
       }

       return true
   }

   function display(boolArrBoard){
       for( let row in boolArrBoard){
           for(let column in boolArrBoard[row]){
               if(boolArrBoard[row][column]){
                   process.stdout.write('Q')
               }
               else{
                   process.stdout.write('X')
               }
           }
           console.log()
       }
   }

   let n = 4
   let boolArrBoard = Array.from({length: n}, () => {
       new Array(n).fill(false)
   })
   nQueen(boolArrBoard,0)

I have encountered this error:
node /tmp/Owi55b6DWs.js
/tmp/Owi55b6DWs.js:15
            boolArrBoard[row][col] = true
                                   ^

TypeError: Cannot set property '0' of undefined
    at nQueen (/tmp/Owi55b6DWs.js:15:36)

Can anyone explain the problem in my code and what shall I do to resolve it or provide the correctecd code
Comment: It means that `boolArrBoard[row]` returns `undefined`. See [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173)
Answer: The problem is that your board is not well initialised. This you can easily see when you print boolArrBoard. It looks like this:
[undefined, undefined, undefined, undefined]

The causing bug is that you didn't return anything in this callback:
   let boolArrBoard = Array.from({length: n}, () => {
       new Array(n).fill(false)
   })

Just add return or remove the braces in the arrow function.
It would be good if you would inspect your variables while stepping through your code with a debugger.


Paging in LINQ+MVC with a randomly ordered collection

Question: I have a bunch of records that are sorted RANDOMLY, like so:
var entries = DataContext.Entries.OrderBy(e => Random());

The Random function returns a randomly-generated GUID, thereby ordering the records in a random manner. Now my problem is paging. In MVC, I have a List action for the Entry controller that lists the entries:
public class EntryController : Controller
{
     public ActionResult List(int page)
     {
          int pageSize = 10;

          var entries = DataContext.Entries.OrderBy(e => Random()).Skip((page - 1) *      pageSize).Take(pageSize);
          ViewData["entries"] = entries;
          return View();
     }
}

My problem here is that whenever I go from one page to another page, the entries are REARRANGED ANEW. So when I go to page 1 (step 1), then go to page 2 (step 2), then back to page 1 (step 3), the entries that were shown in the step 1 are different from those shown in step 3. I absolutely need to have the records arranged randomly the first time around, but not in the subsequent look ups.
Any ideas on how best to address this problem?
Comment: any particular reason why you are ordering them randomly?
Comment: @JanR i need to show an list of products which shows randomly on the pages.
Comment: so cache a list of products? order them randomly and grab from there? if you reorder every page hit, you will never be able to paginate, you will need to rethink your design.
Comment: @JanR I want to get the result as same as Justdial.com does. what they guys are doing for this?
Answer: Because each time you invoke the action the randomness occurs all over again to the whole records before paging, what you need to do is:

Order the records randomly as you want it.
Cache the result.
Fetch the cache every time the action is invoked while applying paging.
public ActionResult List(int page)
 {
      var dataSource = CacheContext["RandomRecords"];
      if(dataSource == null){
         dataSource = DataContext.Entries.OrderBy(e => Random());
      }

      int pageSize = 10;
      var entries = dataSource.Skip((page - 1) * pageSize).Take(pageSize);

      ViewData["entries"] = entries;
      return View();
 }

Comment: Of course CacheContex["RandomRecords"] is just a place where you cache and only as an example here, you might have your cache any where you want so this is just for clarification purposes only.
Comment: I want to get the result as same as Justdial.com does. what they guys are doing for this?
Answer: Add a column named sortOrder, being an int.
Do not forget to add a non-unique index on it or sorting on it will be suboptimal.
Put a number there, increased from record to record, not in the same order than your id or an order that would sort the records alphabetically.
Then
dataSource = DataContext.Entries.OrderBy(e => e.sortOrder);

Guids will be slower to sort on, but you can alternatively use a guid column for the task. Every now and then (once per night), you can loop through all records to put new values in the sortOrder column so people will not recognize the order.
Answer: You can add following SQL code to get products, you only need to generate some random number and store it into the session or cache and get product again..
DECLARE @NumberOfProductsInDatabase INT
DECLARE @RandomNumber VARCHAR(10)

SET @NumberOfProductsInDatabase = (SELECT COUNT(*) FROM Product)
SET @RandomNumber = '45'
SELECT CAST(100000 *  SQRT(EXP(COS(p.SellerId + @RandomNumber))) AS INT) % @NumberOfProductsInDatabase AS RandomProductNr,
    p.Id,p.Name,pv.Price,pv.SalePrice
FROM Product p,ProductVariant pv
WHERE pv.ProductId = p.Id
ORDER BY RandomProductNr


Onde implementar Facade no MVC?

Question: Estou desenvolvendo um projeto em C# usando MVC, mas o professor quer que todos os projetos dos alunos tenham Facade, a dúvida é a seguinte !
Onde eu implemento a Facade, Model, View ou Controller ?
Answer: O objetivo principal do  Facade  é mediar a interação entre uma view e um model, ou em alguns casos apenas um model. No seu caso você implementa no controller.

Onde implementar Facade no MVC?


Boostrap sobrescrevendo CSS. Como evitar?

Question: Peguei da internet um template pronto em CSS para escolher uma forma de pagamento do meu site. Segue abaixo o link do mesmo.
https://codepen.io/cusx/pen/aNqQdQ
Porém, ao importar o header e o footer, (estou usando PHP para isso) que utilizam Bootstrap, a página de pagamento fica desconfigurada. Ao remover o link do bootstrap a forma de pagamento fica normal, porém como meu header e footer utilizam bootstrap, ficam quebrados.
Tentei criar uma section com um id e colocar antes de todo código css, não obtendo sucesso tentei criar uma div, assim:
Original
...
.price h1 {
font-weight: 300;
color: #18C2C0;
letter-spacing: 2px;
}
...

Com section id = 'pagamento'
...
#pagamento .price h1 {
font-weight: 300;
color: #18C2C0;
letter-spacing: 2px;
}
...

com uma div class = 'pagamento'
...
.pagamento .price h1 {
font-weight: 300;
color: #18C2C0;
letter-spacing: 2px;
}
...

Mas não obtive sucesso.
Também tentei colocar a chamada do meu estilo css antes do link do boostrap, também não funcionou.
Existe alguma maneira de remover o bootstrap em um determinado pedaço do html? Ou de fazer o meu arquivo de estilo sobrescrever? Ou ainda alguma outra forma de poder usar os dois sem que nenhum fique quebrado?
Answer: Duas coisas, a primeira é que as classes que vc quer que sobrescrevam devem vir por último, e não em primeiro, então seria tipo assim:
<link rel="stylesheet" href="bootstrap.min.css" />
<link rel="stylesheet" href="meu-estilo.css" />

Ou assim si for o caso.... O importante é que venha após o CSS do Bootstrap.
<link rel="stylesheet" href="bootstrap.min.css" />

EDIT:
Vc também pode tentar "resetar" todas as classes inseridas pelo Bootstrap usando um "all:unset" e depois reconstruindo o CSS do seu elemento. Vc pode ler mais sobre essa propriedade aqui Propriedade all no CSS. Para que serve e como funciona?
Então por exemplo seu CSS ficaria assim
.price h1 {
  all: unset; /* aqui vc remove os estilos herdados */
  /* agora apenas os CSSs que quer */
  font-weight: 300;
  color: #18C2C0;
  letter-spacing: 2px;
}

.card {
  all: unset; /* aqui vc remove os estilos herdados */
  /* agora apenas os CSSs que quer */
  margin-top: 30px;
  margin-bottom: 30px;
  width: 520px;
  height: 400px;
}

Opção com iframe
Além disso outra solução seria usar um  Coloque o seu cartão em um iframe e chama ele onde vc  quiser. Assim o CSS do Bootstrap não vai sobrescrever o CSS dos elementos que estão dentro do  Aqui vc pode ler mais sobre o assunto: https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/iframe
Ex: Repare que eu tenho uma Navbar do Bootstrap e no mesmo arquivo chamo um iframe como o exemplo do Codepen que por sua vez não sofre influencia do .CSS indexado do Boostrap

<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Page Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" />
  <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Brand

Link (current)

Link

          Dropdown

Action

Another action

Something else here

Separated link

One more separated link

      </ul

Comment: Mesmo colocando o link após, o bootstrap contia sobrescrevendo. Não posso usar iframe, porque eu estou usando o código para modelo do que estou produzindo, e não mara usar o mesmo, então não funciona.
Comment: @RafaelLazzarettiMadalóz cara fiz um **EDIT** e inclui uma solução que pode te atende, acredito que vale a pena vc fazer um teste ai. Leia lá que tem mais detalhes, e no link que citei tb tem mais coisas que podem te interessar.


Unable to use AAC/AptX codec for bluetooth audio on macOS

Question: When accessing the Bluetooth Explorer and setting the "Enable AAC" and "Force use AptX" to true, all the bluetooth audio devices still use the SBC codec.
When pressing "Reset audio defaults" - bluetooth explorer crashes with:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.'

Tried to use these terminal commands, but still no luck.
sudo defaults write bluetoothaudiod "Enable AptX codec" -bool true
sudo defaults write bluetoothaudiod "Enable AAC codec" -bool true

I'm on a MacBook Pro (Retina, 13-inch, Mid 2014), macOS Catalina 10.15.1
I feel like it's the first time I have a problem that I can't find any info on in google.
Please help! :p
Comment: I have exactly same error when trying to open Bluetooth Explorer -> Tools -> Audio Options.
Comment: I don't really know where to go with this :p
Comment: Same here.
Somebody has reinstalled whole OS and it helped, but that's not acceptable for me
https://discussions.apple.com/thread/250945131
Answer: I have same issue with bluetooth exlplore so i tried disabled the aptx and enabled the AAC via terminal and it works. now my active coded is AAC
sudo defaults write bluetoothaudiod "Enable AptX codec" -bool false
sudo defaults write bluetoothaudiod "Enable AAC codec" -bool true


Definition of elliptic pde

Question: http://en.wikipedia.org/wiki/Elliptic_partial_differential_equation
Very confusing. So are there non-linear elliptic pdes? It seems to be the case. And what about
$$A u_{xx} + C u_{yy} + F u = 0$$
That seems to be elliptic, too...
I know there isn't a precise mathematical definition, but can somebody give me some hints to a bit more complete (and more accessible than this one) definition?
Thank you!
Comment: It depends on $A$ and $C$, namely on the sign of $AC$.
Comment: There **is** a very precise mathematical definition of ellipticity: you can find it in pretty much any sensible textbook on the subject!
Comment: @MarianoSuárez-Alvarez It would be more correct to say that there **are** very precise definitions, each of which applies to a  specific type of PDE, and none of which define *ellipticity* for general PDE.
Answer:
are there non-linear elliptic pdes?

Yes. The $p$-Laplace equation $\operatorname{div}(|\nabla u|^{p-2}\nabla u)=0$ is recognized as elliptic (degenerate elliptic at the singular points of $u$). It is nonlinear when $p\ne 2$.
The above is a special case of an Euler-Lagrange equation for a  convex functional, namely $\int |\nabla u|^p$. All such equations are recognized as elliptic.
To give a nonvariational example: the  Monge-Ampère equation $\det D^2u=f$ is considered elliptic when $u$ is being sought in the class of convex functions. The introduction of Caffarelli's ICM 2002 address explains why.

what about $A u_{xx} + C u_{yy} + F u = 0$

Ellipticity  is determined by the  highest-order derivatives the equation contains. So, this PDE qualifies as elliptic if    $A u_{xx} + C u_{yy}=0$ does.
So what is ellipticity anyway?
It's what makes boundary value problems work. If you have a  PDE for which boundary value problems  are sensibly behaved, your PDE is elliptic. Sensible behavior includes: existence and uniqueness of solutions in some function space, and a bit of extra regularity of solutions compared to general elements of that function space.
This isn't helpful!
Probably. But if you are interested in elliptic PDE, your  goal should not be "I must understand what ellipticity is in general". Rather, you should understand how the Laplace equation works, how the Poisson equation works, what methods to use for  divergence-type vs non-divergence type equations, and so on. The often-cited book by Gilbarg and Trudinger is an excellent guide, provided you have firm foundation of real and functional analysis.
On the other hand, if you are just taking an introductory   course in PDE, then elliptic means whatever your professor tells you, and you should memorize his/her definition.

Definition of elliptic pde


Difference in Difference with control - common trend interpretation

Question: I have a question concerning the interpretation of the common trend assumption in a very specific case of diff-in-diff. I am using a panel to find the effect of a treatment (on houesehold level) on the number of years of schooling of individuals.
The regression I use is
$$\text{yrschl}_{it} = \beta_0 + \beta_1 \text{treatment}_h + \beta_2 \text{after}_t + \beta_3 (\text{treatment}_h \cdot \text{after}_t) + \gamma X_{iht} + \epsilon_{iht}$$
and I cluster the standard errors at the household level.
As there has been no randomization across the two groups, I use control variables as $\text{sex}_{it}$, $\text{age}_{it}$, $\text{age}^2_{it}$, $\text{mother's education}_{it}$, $\text{father's education}_{it}$ and $\text{urban/rural area}_{iht}$.
My question now is how to interpret the ceteris paribus condition jointly with the common trend assumption. In particular, my doubt concerns the ceteris paribus condition related to age.
How do I have to formulate the common trend assumption in this case?
Is it that, IN ABSENCE OF THE TREATMENT, the change in the average number of years of schooling of the children who are, e.g. 14 years old in $t=0$ and therefore 20 years old in $t=1$ (I only have data for 6 years later) and belong to the treatment group is the same as the one of those children who were 14 in $t=0$ and 20 in $t=1$ and are untreated?
Or does it rather mean that, IN ABSENCE OF THE TREATMENT, the change in the average years of schooling between treated 14 years old children in $t=0$ and treated 14 years old children in $t=1$ is the same as the one between untreated 14 years old children in $T=0$ and untreated 14 years old children in $t=1$? Does the ceteris paribus condition hold across time periods?
Since I am using a balanced panel, there would be only observations for young individuals in $t=0$ and not in $t=1$ (as they got 6 years older in the meanwhile). This speaks against this second interpretation, isn't it?
Comment: What is the treatment and when does it kick in?
Comment: treatment is 1 if the individual belongs to a household in which there is a migration happening for the first time between t=0 and t=1 while it is 0 if until t=1 in households who never faced a migration. After_t is equal to 1 if t=1 and equal to 0 if t=0. P.s. I have edited my question because I forgot to write "IN ABSENCE OF THE TREATMENT" when interpreting the common trend assumption.
Answer: When your treatment status depends on (fully!) observed covariates the parallel trends assumption does not depend anymore on the unconditional but the conditional pre-treatment trends. If you were to state the identification assumption in a paper, you would write something like:

The identifying assumption is that pre-treatment trends in the outcome
  for treated and untreated households are parallel conditional on
  observables that determine treatment status. This means that treated
  and control households' outcomes with similar characteristics would
  have continued in a parallel way in the post-treatment period in the
  absence of the treatment.

Since you only have one pre-treatment period it is somewhat odd to speak about pre-treatment trends though. There is no way that you can infer those from a single data point but the required condition would be the one cited. For your case you are conditioning on the baseline period ($t=0$) characteristics.
Typically it is very difficult to sell a difference in differences framework if you cannot show these trends but if this is for an assignment or thesis work then it should be sufficient that you demonstrate your awareness of this problem. Even though it is not asked for in the question I still want to hint to one or two more points that you might want to think about:

migration is a decision of the household and I highly doubt that this decision is fully captured by observables; in this case you might want to instrument the treatment status with some policy change (or another valid instrument) that affects the migration decision but not the educational outcomes
depending on the country you are looking at, education is bounded below by minimum school leaving ages. Suppose your treatment would have a negative effect on years of education you may not be able to find this causal effect if observed educational outcomes cannot go any lower in response to treatment because of compulsory schooling laws

As a minor point you also may want to revisit the subscripts for mother's and father's education. Typically those do not change anymore after people have completed their formal education, i.e. they shouldn't have a time subscript.
Comment: Thanks! In fact, I do have another period, which is 8 years before t=0. However, not all individuals were present/ at school in all three periods (Actually, when adopting the strategy described above, I limit the sample to those who were enrolled at school in t=0). So, even if I can test the common trend assumption, I only can do so for a subset of individuals which leads to a very low number of treated individuals. Therefore, even if I get a non-significant interaction coefficient when doing the placebo test (by changing after_t), it is likely to be due to the large standard errors, right?
Comment: Moreover,if the interpretation of the common trend assumption is the above suggested one,then what is the difference between a simple OLS and a DiD?I know that the OLS assumes the same level of years of schooling across groups while the DiD only assumes the same trend,however,in the specific case of years of schooling,what does this difference exactly mean?Why should treated and control have different levels but the same trend?Is it like saying that we weaken the assumption by allowing, e.g. one group to start school later,but then, once started,the schooling behavior is similar?
Comment: For that you might this other answer useful which explains the common trends assumption: http://stats.stackexchange.com/questions/152138/common-trends-with-difference-in-differences
Comment: Thanks for the link.Actually, I know the difference between the DiD and the OLS, but the problem is the specificity of my dependent variable years of schooling. Assuming that there is a common trend in years of schooling means that,even if the average of both groups is different, its development over time is similar.But how do you interpret the development over time of years of schooling?If this must be similar, then it is logic to think that their behavior with respect to education is similar and thus there should be no reason to have different levels of education(if there was no treatment!).
Comment: It's like the issue I raised regarding the compulsory schooling laws. Suppose you follow two kids of equal age in the base period for 3 years where treatment occurs between year 2 and 3. Say from year one to two they increase schooling by 1. In year three the treated kid quits school because of the treated whereas the control kids increases again by 1 year, which would have happened to the treated kid too in the absence of the treatment.
Answer: Another thing:
I belive that put control variables that are invariant in the time (like sex and father/mother education) don´t have any sense. Your especification already considers time invariant factors.


Install Vimba python on Windows

Question: I am not very familiar with programming on Windows yet. With my code I want to control a camera, for this I wanted to use the Vimba Python interface. Thus I downloaded the GitHub repository of AlliedVision.
Now my question: In the folder is an Install.sh - file, which I know otherwise only from Linux/Ubuntu. How can I execute this file or is there another way to install this repository from Vimba on my PC?
Thanks!
Answer: You need to download the whole Vimba SDK and install the exe, Vimba Python is already included. This is also mentioned on the VimbaPython Github page. The documentation will be installed together with the APIs, in the install directory.
https://www.alliedvision.com/en/products/vimba-sdk/
If you are using Alvium cameras, I would recommend the newer VimbaX API and VmbPy wrapper.
https://www.alliedvision.com/en/products/software/vimba-x-sdk/
Vimba Python is just a wrapper for the underlying C API, so it can't be used on its own.

Install Vimba python on Windows


Property 'token' does not exist on type 'Object'. Typescript issue

Question: So I'm getting a compiler error stating that token doesn't exist on type Object. This object is getting returned from the server with two objects. A token and a user object. I'm not sure how to define res in the code example below so that typescript is okay with this.
return this.http.post(api.url, params)
        .map(res => {
          if (res && res.token) {
              localStorage.setItem('token', res.token);
              localStorage.setItem('user', JSON.stringify(res.user));
              return true;
          }

          return false;
        });

Comment: use res['token'] instead of res.token. your problem will be solved
Answer: Typescript is complaining the response does not have a property named token, Change it as,
return this.http.post(api.url, params)
        .map((res:any) => {

Comment: Use of `any` should be minimal, in this case `res` and `res.token` seems to be potentially null/undefined.
It would reduce mistakes to declare it as

`.map((res?: {token?: string, user: object}) => {`
Answer:  return this.http.post(api.url, params)
    .map(res => {
      if (res && res.token) {
          localStorage.setItem('token', res['token']);
          localStorage.setItem('user', JSON.stringify(res['user']));
          return true;
      }

      return false;
    });


O que é Mersenne Twister?

Question: O PHP possui uma função chamada rand. Também existe uma função chamada mt_rand.
Estava estudando sobre essas funções e percebi que, em versões anteriores, era necessário de utilizar um tal de "semeador de números aleatórios".
Um deles é a função chamada mt_srand.
Nesse trecho do Manual do PHP vi que existe uma referência ao nome Mersenne Twister. Percebi então que esse mt_ no início da função tinha algo relacionado.
Cheguei a ver no Wikipédia alguma coisa, mas achei um pouco vago.
Então gostaria de matar essa curiosidade:

O que é Mersenne Twister? Tem alguma coisa haver com esse semeador ou o processo de randomificação?
Comment: Relacionado: [Como é gerada a randomização pelo computador?](http://pt.stackoverflow.com/q/9026/91)
Comment: Relacionada também @rray: [O que é uma semene aleatória?](http://pt.stackoverflow.com/questions/104335/o-que-%C3%A9-uma-semente-aleat%C3%B3ria)
Answer: Traduzo artigo da Wikipédia a respeito:

O Mersenne-Twister é um pseudogerador de números aleatórios (PRNG). É de longe o pseudogerador de uso geral mais usado. Seu nome deriva do fato que seu intervalo é um número Primo de Mersenne.
Foi desenvolvido em 1997 por Makoto Matsumoto (松本 眞?) e Takuji Nishimura (西村 拓士?). Foi desenvolvido especificamente para retificar velhos problemas encontrados pseudogeradores mais antigos. Foi o primeiro pseudogerador a prover geração rápida de números inteiros pseudoaleatórios com qualidade.
A versão mais comum do algoritmo utilizada é baseada no Primo de Marsenne 219937−1. A implementação padrão dele, MT19937, usa uma palavra inteira de 32 bits. Existe uma outra implementação que usa uma palavra de 64 bits, MT19937-64, e que gera uma sequência bem diferente.

O que é Mersenne Twister?


Update elements in torch.zeros with other given tensors

Question: Let's say, there are a PyTorch torch.zeros tensor (x-dim) and two other tensors 1-dim.
test_t = torch.zeros(2, 1, 1, 1)

output:
tensor([[[[0.]]],

        [[[0.]]]])

t1 = torch.tensor(10.)
t2 = torch.tensor(20.)

I want to modify the original tensor in-place and replace zeros with values in given order.
Required result:
test_t

output:
tensor([[[[10.]]],

        [[[20.]]]])

upd: see solution below
Comment: In general, yes!
Answer: I got a hin from the Community - see comments.
answer:
test_t[0, 0, 0, :] = torch.tensor([10.])
test_t[1, 0, 0, :] = torch.tensor([20.])

test_t, test_t.shape

output:
(tensor([[[[10.]]],

         [[[20.]]]]),
 torch.Size([2, 1, 1, 1]))


Distributions of two random variable remain the same after some operations

Question: I guess that the titles don't say much I'll be clearer here:
Say we have two random variables with the same distributions and parameters, and we make the exact same math operation on both of them (multiplication, adding, subtracting etc..) I would've guessed that they both will have identical distributions afterwards, means the distribution itself can be changed but they both will have the same exact one.
Is there any proof for that assumption?
Thanks.
Answer: Here is an unnecessarily intricate answer:

If a random variable $X : \Omega \to \Sigma$ is given on a probability space equipped with the probability measure $\mathbb{P}$, then its distribution is simply the pushforward measure $X_*\mathbb{P}$ defined by
$$ (X_* \mathbb{P})(A) = \mathbb{P}(X^{-1}(A)) = \mathbb{P}(\{\omega : X(\omega) \in A\}). $$
Now if $X$ and $Y$ have the same distribution, meaning that $X_*\mathbb{P} = Y_*\mathbb{P}$, and if $f$ is a transform, then we are interested in whether distributions of $f(X)$ and $f(Y)$ are the same, i.e. whether the equality $(f\circ X)_* \mathbb{P} = (f\circ Y)_* \mathbb{P}$ holds.
Now it is easy to show that pushforward is covariant, meaning that $(f\circ X)_* = f_* \circ X_*$. Thus
$$ (f \circ X)_*\mathbb{P} = f_*(X_* \mathbb{P}) = f_*(Y_* \mathbb{P}) = (f\circ Y)_* \mathbb{P}, $$
and so, $f(X)$ and $f(Y)$ have the same distribution.

In more friendly wording, we want to know whether the following two different paths commute:
$$
\require{AMScd}
\begin{CD}
X
@>\text{induce distribution}>>
X_*\mathbb{P}
\\
@V{\text{transform by } f}VV
@VV{\text{transform by } f_*}V
\\
f(X)
@>>\text{induce distribution}>
(f\circ X)_*\mathbb{P} \stackrel{?}{=} f_*(X_*\mathbb{P})
\end{CD}
$$
Comment: Thanks! very informative.
Answer: You have one distribution and one transformation of the variable. So there's only one transformed distribution. (Note that there is nothing "random" in the analytical process.)
Comment: great thanks I also saw it that way :).
Answer: Here is a proof.
Assume $X_1$ and $X_2$ are two real random variables with the same distribution.
For every (measurable) subset $A\subset\mathbb R$,  $P(X_1\in A) = P(X_2\in A$).
Choose any (measurable) function $f:\mathbb{R}\rightarrow\mathbb{R}$.  Let $$Y_1=f(X_1)\quad\mathrm{ and }\quad Y_2=f(X_2).$$
Let $C_{Y1}$, and $C_{Y2}$ be the CDFs of  $Y_1,$ and $Y_2$ respectively.
Fix any $y\in\mathbb R$.
Let $A=\{x\in\mathbb R | f(x)<y\}.$
Now
$$
\begin{align}
C_{Y1}(y) &= P( Y_1<y) = P( f(X_1)<y) = P(X_1\in A) =  P(X_2\in A)\\
&=P( f(X_2)<y) = P( Y_2<y)= C_{Y2}(y).
\end{align}
$$
This proves that $Y_1$ and $Y_2$ have the same distribution.


jq: convert array to object indexed by filename?

Question: Using jq how can I convert an array into object indexed by filename, or read multiple files into one object indexed by their filename?
e.g.
jq -s 'map(select(.roles[]? | contains ("mysql")))' -C dir/file1.json dir/file2.json

This gives me the data I want, but I need to know which file they came from.
So instead of
[
    { "roles": ["mysql"] },
    { "roles": ["mysql", "php"] }
]

for output, I want:
{
    "file1": { "roles": ["mysql"] },
    "file2": { "roles": ["mysql", "php"] }
}

I do want the ".json" file extension stripped too if possible, and just the basename (dir excluded).

Example

file1.json

{ "roles": ["mysql"] }

file2.json

{ "roles": ["mysql", "php"] }

file3.json

{ }

My real files obviously have other stuff in them too, but that should be enough for this example. file3 is simply to demonstrate "roles" is sometimes missing.
In other words: I'm trying to find files that contain "mysql" in their list of "roles". I need the filename and contents combined into one JSON object.

To simplify the problem further:
jq 'input_filename' f1 f2

Gives me all the filenames like I want, but I don't know how to combine them into one object or array.
Whereas,
jq -s 'map(input_filename)' f1 f2

Gives me the same filename repeated once for each file. e.g. [ "f1", "f1" ] instead of [ "f1", "f2" ]
Comment: post a minimal and testable input json content (from your input files)
Comment: @RomanPerekhrest Added. Has to be in separate files I think, can't read from stdio because this question pertains to filenames.
Comment: I may have found a solution. I can just run JQ twice: `jq 'input_filename' $^ | jq -s`
Answer: If your jq has inputs (as does jq 1.5) then the task can be accomplished with just one invocation of jq.
Also, it might be more efficient to use any than iterating over all the elements of .roles.
The trick is to invoke jq with the -n option, e.g.
jq -n '
  [inputs
   | select(.roles and any(.roles[]; contains("mysql")))
   | {(input_filename | gsub(".*/|\\.json$";"")): .}]
  | add' file*.json

Comment: I only used "contains" because that is what was in the original question, and it gives equivalence thereto.  However, if you require string equality, then of course you would use `==`.
Comment: If I understand this right, `any(.roles[]; contains("mysql"))` actually means "if any role contains *the substring* 'mysql'" no? For exact equivalence isn't `any(.roles[]; . == "mysql")` more appropriate?
Comment: Ah...fair enough. My mistake then :-) I thought it was like an "array contains" when I first found it :D
Answer: jq approach:
jq 'if (.roles[] | contains("mysql")) then {(input_filename | gsub(".*/|\\.json$";"")): .}
    else empty end' ./file1.json ./file2.json | jq -s 'add'

The expected output:
{
  "file1": {
    "roles": [
      "mysql"
    ]
  },
  "file2": {
    "roles": [
      "mysql",
      "php"
    ]
  }
}

Comment: Beautiful! Didn't know about `if`. Can also be done with `select`: `jq 'select (.roles[]? | contains("mysql")) | {(input_filename | gsub(".*/|\\.json$$";"")): .}' $^ | jq -s 'add'` (formatted for Make)


How to delete extra parens in Paredit mode?

Question: I'm using Paredit in Emacs to edit Lisp code. How do I delete an extra pair of parens that I accidentally inserted? Paredit does not allow this without extra commands.
((square 5)) into (square 5)
Answer: This is called paredit-splice-sexp, keybinding is M-s.
Take a look at the paredit cheat sheet here.
Answer: Read up on barfage and slurpage.
You can also installed "paredit-menu.el" which provides a menu of actions, with tooltips that show you their effects.
Paredit occasionally gets you into a situation when the easiest thing to do is to turn it off, fix everything and turn it on again. However, it is worth the effort.
Answer: If I realized accidental extra parens right after inserting those extra parens, I would invoke the undo command. If I saw the extra parens much later, then there are paredit commands for fixing it as other answers specified, but if I did not know those commands, then I would have put point somewhere within the inner form, and then typed the following, provided that CUA mode is on.
C-M-u C-M-SPC C-x <timeout> <left> C-M-SPC C-v

Answer: The paredit wont let us deleting parens while there is any elements inside. My trick is to cut the the right code and paste it to other place adjacent. It will leave the extra parens empty, then now I can delete it. Actually the right way is using M-s to reindent it. Conversely we can insert single paren using C-q ( or C-q }.


Pandas, simple add one month to a datetime column in a dataframe

Question: As sort of a follow-up question to being able to count activity between two datetimes, ansered very well here: Create a Pandas dataframe with counts of items spanning a date range
The remaining issue is that the final month, ['END_DATE'] ends up showing zero after the two tables are summed and subtracted, which is mathematically correct since all items have an end date in that current month or earlier, however in this case since they have been active in that month at least for some portion, it would be more correct to add one month to END_DATE so they will show as active in the ending month (H2 is a dataframe)
The code is:
ends = H2['END_DATE'].apply(lambda t: t.to_period(freq='m')).value_counts()

I have tried to use rollforward and DateOffset(month=1) eg. for DateOffset:
ends = (H2['END_DATE'].DateOffset(months=1)).apply(lambda t: t.to_period(freq='m')).value_counts()

which gives me this error:
AttributeError: 'Series' object has no attribute 'DateOffset'

Comment: Are you trying to shift ends by one (month)?
Comment: yes I am, so that the ending month will be one greater than now that way the "last" month will be counted and not end up as zeroed out..
Answer: The easiest way is to add one (month) to the PeriodIndex:
In [21]: ends
Out[21]:
2000-05    1
2000-09    1
2001-06    1
Freq: M, dtype: int64

In [22]: ends.index = ends.index + 1

In [23]: ends
Out[23]:
2000-06    1
2000-10    1
2001-07    1
Freq: M, dtype: int64

My initial suggestion was to do the shift after you've reindexed (since you're about to do that anyway):
In [11]: ends
Out[11]:
2000-05    1
2000-09    1
2001-06    1
Freq: M, dtype: int64

In [12]: p = pd.PeriodIndex(freq='m', start='2000-1', periods=19)  # Note: needs to be one more than before

In [13]: sparse_ends = ends.reindex(p)

In [14]: sparse_ends.shift(1)
Out[14]:
2000-01   NaN
2000-02   NaN
2000-03   NaN
2000-04   NaN
2000-05   NaN
2000-06     1
2000-07   NaN
2000-08   NaN
2000-09   NaN
2000-10     1
2000-11   NaN
2000-12   NaN
2001-01   NaN
2001-02   NaN
2001-03   NaN
2001-04   NaN
2001-05   NaN
2001-06   NaN
2001-07     1
Freq: M, dtype: float64

Comment: Thanks, That will probably work, but is there not a simple way to just add a month to ['END_DATE'] ?
Comment: the shift index looks like a better fix, still would like to know if there is a simple date add function, which is how I'd do it in sql,  that could apply?
Comment: I see that, and I like it.. I'd still like to know if there is a simple DateAdd type function that I could use that might also apply for use elsewhere if needed?
Comment: @dartdog ah, to add to Series which have dates as the values? (I don't think so, is for DatetimeIndex, should add same for series)
Comment: Guess that is why I could not find it (seems like a strange omission, I was thinking it might be in some base (non Pandas) function?), but your solution work great, Thanks again
Comment: @dartdog agreed, I think there is an issue to add these helper functions to DatetimeIndex (atm sometimes converting to DatetimeIndex and applying is the fastest approach which seems silly!). I guess more "usual" to have time-indexed data, but I would like this!
Comment: To clarify myself, the issue is to make the datetime helpers (from DatetimeIndex) available to Series (with datetime values).
Comment: What then is DateOffset good for?? Seems like this situation?


NAT444 on vodafone 3g

Question: I am using Huawei K3765 with vodafone as ISP. When i tested my IP with ipconfig, private IP is assigned to me. I dont think this device act as a router, since its just a 3g donle. This created the question that "am i behind NAT444?".
IP address from ipconfig: 10.135.237.173
IP address from dnsstuff: 126.96.36.199
One more question, From RFC 6598, address space "220.127.116.11/10" is reserved for NAT444. But mine starts with 10.?
Comment: You'll need to ask Vodafone that
Comment: An ISP not following RFCs? Shocking! But seriously, what's your question?
Comment: @faker My question is simple, why my ip is different?
Comment: RFCs are not law, companies can and do violate them on a regular basis. The only thing the RFCs do is provide a standard to ensure interoperability. If Vodafone or any other company does not want to ensure interoperability with the rest of the Internet then they have no reason to follow the RFCs.
Answer: Yes, cellular providers nearly universally uses carrier grade NAT. No, they are not forced to adhere to every RFC, thus using RFC1918 address ranges is perfectly possible.
What is your technical problem? Should it be that external servers see it as 184.108.40.206: This is the whole point of NAT -  multiple systems can share the same external address.
Comment: There is no solution and I am quite certain that Vodafone's TOS prohibit running a server anyway. You can try to talk to them to see if they can/want help you but this is extremely unlikely.
Comment: I need to host a TCP server with this device. If i am behind carrier grade NAT, all inbound connection will be blocked. isn't it? In that case what is the solution?

NAT444 on vodafone 3g


Can random number generators be used in compression?

Question: This is basically a recurring thought I have from time to time and I suspect it is flawed, so my question is basically why can't you do the following:
Basically, I imagine that given a seed and a random number generator, the binary result at a given length might have something in common with some target data that you want to compress.  In the case that it just happened to be the same, you'd get a phenomenal amount of compression.
That said, I suspect this is in the same league as the perpetual motion machine I thought I invented when I was a kid (air lock at the bottom of a tube of water, ball floats to top and falls back down to air lock...)
Comment: The probability of any small seed generating exactly the output you are trying to compress is minuscule. So no, it won't work (except 0.0001% of the time).
Comment: This basically comes down to whether you can find a pattern in your data and use just knowledge elf the pattern + a seed case to describe the data in the hope that takes less space
Comment: I just had this thought..
Comment: The random generator would have to create a mix of distorted vectors (trigo maybe) to fit real life organisation of things obeying to physics laws, maths laws, or other general organisation laws. Since you want to optimize it, that could not be totally random. It makes more sense in lossy compression. And probably we could say existing lossy video codec are kinda already using randomness, depending of our definition of 'random' and 'arbitrary'. In the other, an un-optimal - only random - algorithm would cover case where 'white noise' is compressed.
Answer: "In the case it just happened to be the same" is the key.  It will (almost) never happen.  Say you have million bit strings.  There are $2^{1000000}\approx 10^{301030}$ of them.  If the string happened to be $\pi$, you would have a phenomenal amount of compression.  That happens very rarely.  If your random number generator is good, it will happen just as rarely.  The compression we use reflects the non-randomness in the files we compress.  There are tremendous correlations in text (because it is generated in natural language, not random) or photos (big areas are close in color).  Compression takes advantage of that.
Answer: The randomness isn't essential in your argument; what you're really talking about is the idea of a function with small inputs having large outputs. So one idea is instead of doing random numbers, take a huge library of videos or images or code, etc. and analyze them to find frequently recurring patterns, and then make a list of those patterns. The location in that list is similar to the seed for a random number generator.
This has been done before; I went to a talk recently where they said the most common pictures in photographs were sharp lines, so they encoded ever instance of a line-like object (viewed as a subset of a five by five grid) in a list, and then decomposed photographs using these masks. It was really interesting and fun! I think Morse theory had been used similarly, but I'm not sure.
Answer: Consider this. If one small seed generates one long random sequence then it is impossible to create all possible sequences using a random function because for $n$ digit decimal seeds there can be only $10^n$ distinct possible sequences. If you have to create a sequence that doesn't belong to this set, you will have to use a different function... and in the end you will end up using just the same amount of data as the original sequence.
Comment: Amazing!! Thank you for this! This answers the heart of the question with a limiting principle!
Answer: Yes. I've been fiddling around with python to try and do this. But the compression time is impractical.
Basically, you find an n-bit seed that just so happens to output n+ bits of the message. There is a 50% chance of that happening. Once you run through all possible seeds of length n and fail to find an output that generates n+1 bits of the message, you just increase n by 1, and look again for a longer run. For every n bits you search and then increase by 1, you have a 50% chance of finding an output corresponding to the message of length n+1. And a 25% chance of finding a message 2 bits longer, etc. If you allow for seeds 20 bits long, then the chance of finding a seed length-n that outputs message segment n+1 is 1-.5^20, ~99.99999%. So it's practical to losslessly compress a message by 1 bit.
Where it gets unpractical is that for every message segment that does result in a profitable compression (you don't need to compress every segment, just most of them to net a profitable compression), you need to add in extra bits to delineate the segments and the docompressed lengths. This is still possible. You simply look for outputs that are 4 to 5 bits longer than the seed. But much less likely. It becomes more likely if you increase the seed search, but then the computation time becomes infeasible. To counter this, we need a reversible random function (where we can find the seed necessary for a given output quickly, without bruteforce). But the more reversible a function is, the less "random" it is. I'm planning on looking for such functions in the future.
I'm also exploring long-time decompression options as well. This is where onge you have the compressed message, in order to decompress it, you need to search through many valid outputs. This is possible because almost all whe outputs will be gibberish and can be automatically filtered out by spell-checker checks. But it's not feasible as a product since consumers need fast decompression. This compression method would only be useful for esoteric situations (for ex, to ensure data can eventually be brought back after an apocalyptic scenario where all computer technology has disappeared and needed to be redeveloped again and the compressed data courd be recited from memory). Yes, this method would make possible the memorization of arbitrarily long messages, but it would take arbitrarily long to decompress the memorized message.
I can post some python scripts if you're interested.


Replace substrings with elements of a list of tuples

Question: I have a string as such:
string = """
 foobar_tent\n
 missyamica_ole
 """

this is a list of tuples I have:
 t = [("foo","virtue"), ("ole, "allo")]

I'm trying to replace every instance of the first element of each tuple with the second element of each tuple. So the result would be this:
newstring = """
 virtuebar_tent
 missyamica_allo
 """"

I tried doing it as such, but it doesn't alter anything.
newstring = ""
for a,b in t:
     newstring = string.replace(a,b)

Answer: newstring is overwritten in the loop by replaced original string.
Use newstring.replace instead of string.replace, so that the replaced string is not to be overwritten.
>>> string = """
... foobar_tent
... missyamica_ole
... """
>>> t = [("foo", "virtue"), ("ole", "allo")]
>>>
>>> newstring = string  # <-----
>>> for a,b in t:
...     newstring = newstring.replace(a,b) # <----
...
>>> newstring
'\nvirtuebar_tent\nmissyamica_allo\n'
>>> print(newstring)

virtuebar_tent
missyamica_allo

Answer: You were basically right. Main issue is that you were doing string.replace each time so only the last of your replacements in the list would have worked.
newstring = string
for a,b in t:
    newstring = newstring.replace(a,b)


No Result from taxonomy API function

Question: I want to output all the node IDs which belong to a taxonomy term ID. I use the following code in page--taxonomy.tpl.php.
$a = taxonomy_select_nodes(arg(2), $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'));

When on the parent term page, print_r($a) shows an empty array. Why does this happen?
Under the parent term, there are two child terms which have some articles. How do I get the node ID?
Comment: make sure the variable (in the variables table) taxonomy_maintain_index_table is set to true. if it's false, then that's the problem
Comment: @stackoverflow002 Then that's the problem :)
Comment: i am sorry there is no taxonomy_maintain_index_table in the variables table
Comment: @Clive The default value for that Drupal variable is `TRUE`; at least, that is the default value used from [taxonomy_select_nodes()](http://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy_select_nodes/7).
Comment: @kiamlaluno I really should look into these thing more shouldn't I ;)
Answer: taxonomy_select_nodes() is returning an empty array because there aren't nodes using that taxonomy term, since that function doesn't return the nodes using any children of the taxonomy term passed as argument. This is also what a taxonomy term page does.
It could be the database table used from the function doesn't contain any data, simply for the fact the taxonomy_maintain_index_table persistent variable is not set to TRUE. If that is the case, then variable_get('taxonomy_maintain_index_table') returns FALSE (or an equivalent value). A persistent variable can be overridden from the settings.php file; that is the reason I am not suggesting to check the database.
As side notes:

The page--taxonomy.tpl.php template is used not only for taxonomy/term/<term id>, but for any path under taxonomy, for which there isn't a taxonomy term associated. I would rather use page--taxonomy--term--%.tpl.php that is surely associated with a taxonomy term.
If you are calling a function, and want to use the default value for some of its parameters, just leave them off. Instead of calling taxonomy_select_nodes() as taxonomy_select_nodes(arg(2), $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')), call it as taxonomy_select_nodes(arg(2)). What you are doing is assigning TRUE to the $pager local variable, FALSE to $limit (another local variable), and an array to $order; those values are also passed as arguments to the function. So you are setting local variables to pass arguments to a function, and you are passing the default values for those arguments. Keep in mind that in PHP, a function arguments are only positional, differently from Ruby, for example.

No Result from taxonomy API function


Facebook Oauth and sending messages to facebook users

Question: I have Facebook OAuth and Facebook Connect installed on a site. We need to be able to periodically send a message to one of our member's Facebook inbox who logged in with the Facebook Connect.  I've looked all over, and haven't had much luck.
Can anyone point me in the right direction?
Answer: When a user registers or connects with his/her Facebook account, your web application receives that person's Facebook username which you can then store in a field.
On Facebook, you can receive external messages at firstname.lastname@example.com.
Now all that's left to for you to do is set up Rules module (maybe Facebook Rules module can help) so that if a user has connected his account on your website with his Facebook account an email is sent to firstname.lastname@example.com.
Comment: There is no authentication on their side, i.e., anyone can send an email to a facebook user?
Comment: Yes, that is correct.
Comment: I see.  And the messages in their inbox look like one of their friends messaged them?
Comment: Yes. If you have a Facebook account, you should try it out yourself. Send an email from any email address to your firstname.lastname@example.com
Comment: I gave in and set up an account.  Yeah, it worked as you said.  Thanks for the help!


Want to launch ec2 instance with static public ip using terraform script

Question: I have one staging instance in aws whoose IP is 126.96.36.199. It is an elastic IP. Now I am writing terraform script to automate deployment using packer. Is there any way to assign this same IP while creating instance? As application has been configured in this ip.
Answer: The eip_association module can be utilized for that.
Use it like this:
resource "aws_eip_association" "eip_assoc" {
  instance_id   = "${aws_instance.web.id}"
  allocation_id = "EIP ID"
}

resource "aws_instance" "web" {
  ami               = "ami-21f78e11"
  availability_zone = "us-west-2a"
  instance_type     = "t1.micro"
}

Replace EIP ID with the actual Network interface id from the AWS web console.


Background Image need to give innner div space

Question: I would like to give a space of repeating background.
Tried Code :

#bg_img {
  background-image: url("https://image.freepik.com/free-vector/diagonal-lines-vector-background-design_1017-12303.jpg");
  background-repeat: repeat;
  background-position: left center;
}

          No
          Name
          Unit
          Unit Price

          1.
          Banana 1

            FIRE BARRIER CAULK

          Test
          780.00

          2.
          Banana 2

            INTUMESCENT STRIP

          Test
          73,600.00

          3.
          Banana 3

            STAINLESS STEEL HOOP

          25.00
          Test

          4.
          Banana 4

            COATED FIRESTOP BOARD

          Test
          125.00

          5.
          Banana 5

            MORTAR

          Test
          185.00

Is it possible to display Background Images on specific Area only with using backgroud space, margin or padding?
Actual Result :

Expected Result :
Answer: No need to add extra empty element, you can consider multiple background where you can add white layers above the background to control the space. Simply adjust the background-size of each layer to reduce/increase the space:

#bg_img {
  background:
    linear-gradient(#fff,#fff) left  /2% 100% no-repeat,
    linear-gradient(#fff,#fff) right /2% 100% no-repeat,
    linear-gradient(#fff,#fff) top   /100% 25px no-repeat,
    linear-gradient(#fff,#fff) bottom/100% 10px no-repeat,
    url("https://image.freepik.com/free-vector/diagonal-lines-vector-background-design_1017-12303.jpg");
}

          No
          Name
          Unit
          Unit Price

          1.
          Banana 1

            FIRE BARRIER CAULK

          Test
          780.00

          2.
          Banana 2

            INTUMESCENT STRIP

          Test
          73,600.00

          3.
          Banana 3

            STAINLESS STEEL HOOP

          25.00
          Test

          4.
          Banana 4

            COATED FIRESTOP BOARD

          Test
          125.00

          5.
          Banana 5

            MORTAR

          Test
          185.00

Answer: You have to update your table structure with thead and apply background-image to tbody. You also have blank column to achieve the requirement. Mentioned changes done in the below code snippet. Try this I hope it'll help you out. Thanks

#bg_img tbody {
    background-image: url("https://image.freepik.com/free-vector/diagonal-lines-vector-background-design_1017-12303.jpg");
            background-repeat: repeat;
    background-position: left center;
    }

.blank-row {
  padding: 1%;
}

tbody tr td:first-child,
tbody tr td:last-child{
  background-color: white;
}

              No
              Name
              Unit
              Unit Price

              1.
              Banana 1
FIRE BARRIER CAULK
              Test
              780.00

              2.
              Banana 2
INTUMESCENT STRIP
              Test
              73,600.00

              3.
              Banana 3
STAINLESS STEEL HOOP
              25.00
              Test

              4.
              Banana 4
COATED FIRESTOP BOARD
              Test
              125.00

              5.
              Banana 5
MORTAR
              Test
              185.00

Comment: @GhanshyamNakiya please review the above code snippet. Thanks
Comment: Thank You, little more if possible need space in tbody -> top, bottom, right also, shown in the screenshot.(showing space TD also)


Calculate request frequency and bandwidth usage for specific resources (CDN related)

Question: I am currently looking into the viability of using a CDN on my site (~2mill page views per month).  However, before looking at the myriad packages available it makes sense to find out exactly what I need rather than stabbing in the dark with an 'finger in the air' estimate.
So, does anybody know of any utilities that will be able to extract out the volume of requests etc to specific resources (i.e. *.css, *.js, *.gif etc etc) from my Webserver (Apache) logs (or maybe somewhere else).
With this information I will know how many requests per second the CDN will have to support, and more importantly how much bandwidth I will need - From this I should be able to choose the correct CDN package for my needs.
Thanks in advance
Answer: At the risk of going all UNIX-y,
egrep '\.css|\.gif|\.js' httpd.access | awk '{print $10}'| perl -n -e '$sum += $_ ; print "$sum\n" ;'| tail -1

will add up all the bytes delivered in .css, .gif and .js requests, and print the total.  If this doesn't work for you, try
egrep '\.css|\.gif|\.js' httpd.access | head

to make sure it's printing just the relevant lines, then
egrep '\.css|\.gif|\.js' httpd.access | awk '{print $10}' | head

to make sure it's printing only the bytes counts of the relevant lines (should be the field after the HTTP return code), because like most UNIX text hacks, this one depends quite strongly on the format of the file we're operating on.  One you have the byte count, the bandwidth is the byte count divided by the time between the first and last lines in httpd.access.


Correct syntax for inheritance in javascript

Question: Very trivial question
I'm trying to understand inheritance in javascript
function Animal() {
  this.eats = true;
}
function Rabbit() {
  this.jumps = true;
}
//Rabbit is-a Animal
Rabbit.prototype = Animal;  //I'm assuming this does not inherit

alert(Rabbit.prototype.eats); // returns undefined

What is the right way?
Answer: This is "answered" but allow me to offer an alternative for posterity.
It's not a good idea to invoke the parent's constructor to get the parent's prototype. Doing so may have side effects; setting ids, tracking the number of instances, whatever happens inside the constructor.
You can use Parent.call() inside the Child constructor and Object.create or the polyfill to get its prototype:
function Animal () {
    this.eats = true;
}

function Rabbit (legs) {
    Animal.call(this);
    this.jumps = true;
}
Rabbit.prototype = Object.create(Animal.prototype);

// Or if you're not working with ES5 (this function not optimized for re-use):
Rabbit.prototype = (function () {
                        function F () {};
                        F.prototype = Animal.prototype;
                        return new F();
                    }());

var bugs = new Rabbit();
alert(bugs instanceof Animal); // true
alert(bugs.eats); // true


ERR_CONNECTION_REFUSED on browser when opening dtale with Eclipse Pydev

Question: Opening a dtale sheet using Eclipse Pydev on Windows leads to ERR_CONNECTION_REFUSED on browser. The same code works on spyder and jupyter however. I know dtale uses a flask backend but I am inexperienced in flask. Any advice or workaround is welcome but I specifically want to use pydev because of familiarity. The code and output is attached below.
code:
import pandas as pd
import dtale
import dtale.app as dtale_app

# Class=input("Enter Class: ").upper()
Class="A"
pathname="Data/"+Class+".xlsx"
df=pd.read_excel(pathname,header=None)
d=dtale.show(df)
print(d)
d.open_browser()

output:
2021-07-09 21:13:28,554 - INFO     - NumExpr defaulting to 8 threads.
      0    1    2    3    4    5    6  ...  4089  4090  4091  4092  4093  4094  4095
0    12   22   35   45   69   74   79  ...   -21   -14   -14   -25   -28   -11     8
1   -56  -50  -64  -91 -135 -140 -134  ...  -114  -138  -159  -172  -180  -173  -162
2   -37  -22  -17  -24  -31  -20   -5  ...   -23   -14    -5    -3     7     3     4
3   -31  -43  -39  -39   -9   -5   18  ...   -40   -23    -1    11    12    -6    10
4    14   26   32   25   16    8    8  ...   -29   -35   -51   -55   -58   -32    -6
..  ...  ...  ...  ...  ...  ...  ...  ...   ...   ...   ...   ...   ...   ...   ...
95 -133 -144 -113  -74  -41  -41  -61  ...   -70   -58   -62   -71   -79   -83   -87
96   -3   -3  -12  -24  -34  -42  -41  ...    31    54    61    55    42    30    19
97  -51  -42  -39  -47  -51  -46  -29  ...    -7   -16   -18    -9     2    -2     0
98   56   55   38   -5  -47  -72  -79  ...    36    41    14   -27   -45   -32    -4
99  -36  -71 -120 -150 -160 -133  -96  ...    39    57    44    41    14     3   -13

[100 rows x 4096 columns]

Answer: I would try hitting http://localhost:40000/dtale/main/1 in the browser. If that works then you can update your code to use
d = dtale.show(df, host='localhost')
sometimes the computer name is accessible from the browser. You can also try '0.0.0.0' as the host.
Answer: I think you should add localhost and use subprocess:
d = dtale.show(df, host='localhost', subprocess=False)

Also, check your windows firewall settings: https://github.com/man-group/dtale#issues-with-windows-firewall
Answer: I just figured out that your IDE must also be enabled in the windows firewall for it to work.


java & fullscreen over multiple monitors

Question: A snippet from my Java application:
 JFrame f = new JFrame();
 GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
 GraphicsDevice gd = ge.getDefaultScreenDevice();
 gd.setFullScreenWindow(f);

So what it does is make it self fullscreen. Now the odd thing is that the program is fullscreen but only on one monitor!
E.g. I have a windows vista system with two screens that are combined in one desktop.
What to do automatically let it go fullscreen over all monitors?

Ok I tried that:
import java.awt.image.ColorModel;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;

class grdevs
{
    public static void main(String [] args)
    {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] gs = ge.getScreenDevices();
        for(GraphicsDevice curGs : gs)
        {
            GraphicsConfiguration[] gc = curGs.getConfigurations();
            for(GraphicsConfiguration curGc : gc)
            {
                Rectangle bounds = curGc.getBounds();
                ColorModel cm = curGc.getColorModel();

                System.out.println("" + bounds.getX() + "," + bounds.getY() + " " + bounds.getWidth() + "x" + bounds.getHeight() + " " + cm);
            }
        }
    }
}

but it gives:
0.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
0.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
0.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
0.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
0.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
0.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
1024.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
1024.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
1024.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
1024.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
1024.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0
1024.0,0.0 1024.0x768.0 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0

E.g I would expect a device capable of 2048x768 as they are combined in one (I clicked on "extend desktop").
Answer: A more general solution to Ash's code is to union the bounds of all the graphics configurations
Rectangle2D result = new Rectangle2D.Double();
GraphicsEnvironment localGE = GraphicsEnvironment.getLocalGraphicsEnvironment();
for (GraphicsDevice gd : localGE.getScreenDevices()) {
  for (GraphicsConfiguration graphicsConfiguration : gd.getConfigurations()) {
    result.union(result, graphicsConfiguration.getBounds(), result);
  }
}
f.setSize(result.getWidth(), result.getHeight());

This will work for vertically aligned monitors as well as horizontal.
Answer: You could try:
int width = 0;
int height = 0;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
for (GraphicsDevice curGs : gs)
{
  DisplayMode mode = curGs.getDisplayMode();
  width += mode.getWidth();
  height = mode.getHeight();
}

This should calculate the total width of multiple screens. Obviously it only supports horizontally aligned screens in the form above - you'd have to analyse the bounds of the graphics configurations to handle other monitor alignments (depends how bulletproof you want to make it).
Edit: And then set the size of your frame: f.setSize(width, height);
Comment: I agree. Normal behaviour is maximizing/fullscreen in one monitor. If you have an extended desktop monitor can cover only "partial" rectangles inside the big desktop rectangle. Even they could not cover all the desktop area (two monitors in diagonal by example) so you have to find the big desktop rectangle and set the size manually.
Answer: This is not what "setFullScreenWindow" is for. It's really for applications that want more direct access to the framebuffer (better performance) - like a 3D game does in DirectX, for instance. This kind of implies ONE monitor.
See this other answer I did: JDialog Not Displaying When in Fullscreen Mode
Answer: That is the normal behavior when you maximize a window in Windows when you have two monitors. In order two get the full resolution size, you will need to look at GraphicsConfiguration to check each GraphicsDevice.


How do I add the Genymotion plugin to Android Studio?

Question: I am using latest version of Android Studio, and it does not have the Genymotion plugin in it's repositories. How do I add the Genymotion plugin to Android Studio ?
Comment: https://www.genymotion.com/plugins/
Answer: Follow the steps:

Start Android Studio.
Go to:
Windows and Linux: File/Settings.
Mac OS X: Android Studio/Preferences.
Select Plugins and click Browse repositories.
Right-click (double-click for Mac OS X) on Genymotion.
Click Download and install.
Click Yes.
Click Close.
Click OK.
Restart Android Studio by clicking Restart.

For more info Check here https://www.genymotion.com/#!/developers/user-guide
Answer: Go to Preferences / Plugins and click "Browse Repositories", then search for Genymotion. Right click and choose "Download and Install". Restart Android Studio and you should see a new icon in your IDE. Click the icon and it will bring up Preferences, and choose the path to the Genymotion application.
Answer: open Genymotion app,

go to Settings -> ADB
select 'Use custom Android SDK tools'
select location of your SDK.
Restart Android Studio
Try to Run your App again, even if you can get the Icon on the menu, after installing the plugin, your Genymotion device will be listed as one of the target to deploy your app, usually the first device on the list before you have Android available virtual devices if you have any


Start MonoTouch / MonoDevelop debugger when launch app on device?

Question: In MonoTouch, is there a way to automatically connect to debugger when I launch my app on device via device touch (vs. have debugger launch it for me)? I want to debug launch from push notification alert touch with app completely quit.
Answer: Currently this is not possible, and it is not planned for the future either.
Feel free to file an enhancement request if you wish though, explaining your use case: http://bugzilla.xamarin.com, we might decide otherwise one day.


Crontab não executa função PHP do arquivo no diretório

Question: Estou executando o seguinte código no Servidor Linux via Putty da Digital Ocean
Dentro do Crontab-e
Esta assim
01 00 * * * /var/www/html/atualizador/atualizador-global.php

* * * * * /usr/bin/php7.3 http://www.sistemasjca.com.br/atualizador/cronteste.php

mailto="firstname.lastname@example.com"

Entretando o código PHP não executa dentro deste arquivo cronteste.php estou executando um código para inserir uma linha no banco de dados, porém nao tenho retorno de nada, quando olho no banco de dados não foi inserido e também nao recebo email sobre a execução.
Também tentei executar assim
* * * * * /usr/local/bin/php /var/www/html/atualizador/atualizador-global.php

O código de teste que estou tentando executar é o seguinte.
require_once("conexao-com-banco-users.php");
testaCron($conecta_login);

function testaCron($conecta){
    $query_bancos = "INSERT INTO banco_usuarios.tbl_usuarios(funcionario, usuario, email, senha, imagem) VALUES('CronjobUser','CronjobUser','CronjobUser','CronjobUser', '8D')";
    $resultado = mysqli_query($conecta, $query_bancos);

    if($resultado)
        echo 'usuario inserido com sucesso';
}

?>

Este é o log que fui puxado via  "grep CRON /var/log/syslog"
Comment: Quer que o PHP acesse uma pagina remota?
Comment: não quero rodar um código php pelo lado servidor sem envolver o front end esse código basicamente insere um dado no banco de dados
Comment: Mas a execução do teu comando esta assim, por isso perguntei. Não tem haver com front-end, na verdade comando de linha nem interage com o navegador, a não ser que vc queira, mas ai é "outros 500", se quer que a pagina processe é WGET, se o script esta no mesmo servidor e falhou é pq tem alguma coisa errada no script, provavelmente.
Answer: |PROBLEMA RESOLVIDO|Entrando como usuário Root no putty via SSH
No terminal botei
sudo apt-get install php7-cli

Após isso entrei com
sudo crontab -e

Dentro do crontab chamei meu arquivo php desta forma.
* * * * * php /var/www/html/Atualizador/cronteste.php

Após estes passos registrou os dados corretamente no banco via Script no crontab.
Answer: Até aonde sei o comando de linha php não acessa páginas remotas, ou se acessa precisa provavelmente liberar no php.ini o allow_url_fopen, ainda sim não necessáriamente executaria, aliás executaria no servidor, porque é uma requisição HTTP e depois teria pegar a "resposta do HTTP" e executar na sua máquina, o que seria uma bela chance de atacar a maquina com códigos maliciosos.
Resumindo, nada disso ai faz sentido, se é para acessar uma URL esterna o correto é usar wget e configurar assim no crontab:
* * * * * wget 'http://www.sistemasjca.com.br/atualizador/cronteste.php'

Agora se isto não esta funcionando:
 * * * * * /usr/local/bin/php /var/www/html/atualizador/atualizador-global.php

É porque pode ser algum erro no script, talvez seja isto o que espera:
 * * * * * /usr/local/bin/php /var/www/html/atualizador/cronteste.php

Comment: * * * * * /usr/local/bin/php /var/www/html/Atualizador/cronteste.php

Eu coloco assim , mas não executa pode ser o PHP que esta numa pasta diferente como posso saber

o script roda localmente
Comment: @AndrewsGomes Mas o log do PHP emite algo? Sabe configurar o log do PHP no php.ini? Pois como eu disse, pode ser erro no seu script PHP.
Comment: No PHP ele da sucesso na operação ele inclui o registro no banco corretamente quando eu chamo o arquivo diretamente do php coloco localhost/atualizador/cronteste.php e ele me retorna um echo dizendo que foi inserido com sucesso.

eu vi na internet essa possibilidade tambem * * * * * /usr/bin/php /var/www/sistemasjca.com.br/atualizador/cronteste.php > /dev/null 2>&1

mas nao sei se estou fazendo errado
Comment: @AndrewsGomes bem ... não tem como ficarmos especulando, use as ferramentas que tem a seu favor, os LOGs, vá no php.ini, configure os logs para um arquivo ou email e execute o CRON novamente, depois vá no log e veja o que ele coletou.