text:
Q: Is it possible to combine textures in Maya into some sort of atlas? I'm starting to use Maya to do some bone animations of a 2D character, which is composed of several different parts (legs, body, head, weapon, etc.). I have each part in a separate .PNG image file. Right now I have a polygon for each part, with its own material and texture:

I was wondering if there's a way to automatically combine the textures into an atlas, make all the polygons use the same material with the atlas, and correct their UV maps so they still point to the right part of the atlas. Right now, I can do it manually in reverse: I can make the atlas outside Maya with other tools, then use the atlas on a material and manually correct the UV maps of each polygon. But it's a very long process and if I need to change a texture, I have to do it all over again. So I was wondering if there's a way to automate it.
The reason why I'm trying to do this is to save draw calls in Unity. From what I understand, Unity can batch objects as long as they share the same material. So instead of having a draw call for each polygon in the character, I'd like to have a single draw call for the whole character. I'm pretty new to Maya, so any help would be greatly appreciated!

A: If you want to do the atlassing in Maya, you can do it by duplicating your mesh and using the Transfer Maps tool to bake all of the different meshes onto the duplicate as a single model. The steps would be:
1) Duplicate the mesh
2) Use UV layout to make sure that the duplicated mesh has no overlapping UVs (or only has them where appropriate, like mirrored pieces.
3) Use the Transfer Maps... tool to project the original mesh onto the new one, using the "Use topology" option to ensure that the projection is clean.
The end result should be that the new model has the same geometry and appearance as the original, but with all of it's textures combined onto a single sheet attached to a single material.
The limitation of this method is that some kinds of mesh (particularly meshes that self-intersect) may not project properly, leaving you to manually touch up the atlassed texture.   As with any atlassing solution you will probably see some softening in the textures, since the atlas texture is not a pixel for pixel copy but rather a a projection, and thus a resampling.
You may find it more flexible to reprocess the character in Unity with a script or assetPostprocessor.   Unity has a native texture atlassing function, documented here.   Unity comes with a script for combining static meshes, but you'd need to implement your own; theres'a an example on the unity wiki that probably does what you want : http://wiki.unity3d.com/index.php?title=SkinnedMeshCombiner (Caveat: we do something similar to this at work, but I can't share it; I have not used the one in this link).  FWIW Unity's native atlassing works only in rectangles, so it's not as memory efficient as something you could do for yourself.


text:
Q: SQL Server : delete specific data after searching column name in whole database I have a table CenterDetails like this
| uid | CenterID | CenterName | AccessLock |
| ----|----------|------------|------------|
|1    |  1       |  Andheri   |    1       |
|2    |  2       |  Borivali  |    1       |
|1    |  3       |  Dadar     |    1       |

I have 100's of tables in my database.
If I want to delete Dadar center, then first I need to check, to the whole database, where centerID=3 exist or not.
If dadar center's CenterID does not exist in the whole database where column names are CenterID.
How can I find that CenterID=3 is present in the whole database or not?
Thanks in advance!

A: I guess this code will help you:
DECLARE @ColumnName SYSNAME = 'CenterID '
       ,@ColumnValue NVARCHAR(256) = '3'

DECLARE @DynamicSQLStatement NVARCHAR(MAX)

SELECT @DynamicSQLStatement  =STUFF
(
    (
        SELECT ' UNION ALL ' + CHAR(10)  + ' SELECT TOP 1 ''' + t.name + ''' AS T FROM ' + SCHEMA_NAME(t.schema_id) + '.' + t.name + ' WHERE ' +  @ColumnName + ' =  ' + @ColumnValue + CHAR(10)
        FROM sys.tables t

        INNER JOIN sys.columns c
            on t.[object_id] = c.[object_id]
        WHERE c.[name] = @ColumnName
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
   ,1
   ,12
   ,''
);

EXEC sp_executesql @DynamicSQLStatement

It is looking for all tables that have specific column. Then it query all these tables in order to find if the given column has a specific value, if yes, it will return the table name.
What will  be better here is to read about data integrity or more specific the foreign keys.

A:
Hope it helps you
DECLARE @TablesColumns TABLE
    (
    ID INT IDENTITY,
    COLUMN_NAME VARCHAR(50),
    TABLE_NAME VARCHAR(50)
    )
    DECLARE @MinId INT,
            @MaxId INT,
            @Sql NVARCHAR(MAX),
            @TableName VARCHAR(50),
            @ColumnName VARCHAR(50)

    INSERT INTO @TablesColumns(COLUMN_NAME,TABLE_NAME)--Here we get list of table containing 'centerID'
    SELECT COLUMN_NAME,TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME='Credits'

    SELECT @MinId=MIN(Id) FROM @TablesColumns
    SELECT @MaxId=MAX(Id) FROm @TablesColumns

    WHILE (@MinId <=@MaxId)
    BEGIN
    SELECT @TableName=TABLE_NAME FROm @TablesColumns WHERE Id=@MinId
    SELECT @ColumnName=COLUMN_NAME FROm @TablesColumns WHERE Id=@MinId
    SET @Sql='DELETE From ' +@TableName+ ' WHERE '+@ColumnName+'=3'
    --PRINT @Sql
    SET @MinId=@MinId+1
    Exec (@Sql)
    END

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hyperopt spark 3.0 issues I am running runtime 8.1 (includes Apache Spark 3.1.1, Scala 2.12) trying to get hyperopt working as defined by
https://docs.databricks.com/applications/machine-learning/automl-hyperparam-tuning/hyperopt-
spark-mlflow-integration.html
py4j.Py4JException: Method maxNumConcurrentTasks([]) does not exist

when I try to
spark_trials = SparkTrials()

Is there anything special I need to do to get this working?
Here is the cluster I am using
{
    "autoscale": {
        "min_workers": 1,
        "max_workers": 2
    },
    "cluster_name": "mlops_tiny_ml",
    "spark_version": "8.2.x-cpu-ml-scala2.12",
    "spark_conf": {},
    "aws_attributes": {
        "first_on_demand": 1,
        "availability": "SPOT_WITH_FALLBACK",
        "zone_id": "us-west-2b",
        "instance_profile_arn": "arn:aws:iam::112437402463:instance-profile/databricks_instance_role_s3",
        "spot_bid_price_percent": 100,
        "ebs_volume_type": "GENERAL_PURPOSE_SSD",
        "ebs_volume_count": 3,
        "ebs_volume_size": 100
    },
    "node_type_id": "m4.large",
    "driver_node_type_id": "m4.large",
    "ssh_public_keys": [],
    "custom_tags": {},
    "spark_env_vars": {},
    "autotermination_minutes": 120,
    "enable_elastic_disk": false,
    "cluster_source": "UI",
    "init_scripts": [],
    "cluster_id": "0xxxxxt404"
}

this is the code I am using
https://docs.databricks.com/applications/machine-learning/automl-hyperparam-tuning/hyperopt-model-selection.html

A: Hyperopt is only included into the DBR ML runtimes, not into the stock runtimes. You can check it by looking into release notes for each of runtimes: DBR 8.1 vs. DBR 8.1 ML.
And from the docs:

Databricks Runtime for Machine Learning incorporates MLflow and Hyperopt, two open source tools that automate the process of model selection and hyperparameter tuning.


text:
Q: the existence of a function $f$,satisfying $1\le f^{(n)}(x)+f^{(n+1)}(x)+\cdots+f^{(3n)}(x) \le 3$ I have a problem and the problem is:
Determine whether or not there exists an infinitely differentiable function $f(x)$ such that for every real $x$ and for every positive integer $n$
$$1\le f^{(n)}(x)+f^{(n+1)}(x)+\cdots+f^{(3n)}(x) \le 3.$$
where $f^{(n)}(x)$ denotes the $n$-th derivative of $f$.
I want some hints to solve the problem or where this problem comes from.
Thanks!
The following is the pirture my friends sends me.

I have find the problem. This problem comes from First HKUST Undergraduate Math Competition-Junior Level.
I paste the solution:
Lemma 1: If there exixts $M\in \mathbb{R}$ and $\varepsilon>0$ such that $f^{n}(x)>\varepsilon$,the $f$ is unbounded above.
Proof: Let $c_n=f^{n-1}(M)$. Since $f^{(n-1)}(x)>c_{n-1}+\varepsilon x$ for all $x> M$ by the mean value theorem, $f^{(n-1)}(x)$ is unbounded above.Then  there exists $M'\in \mathbb{R}$ such that $f^{(n-1)}(x)>\varepsilon$ for all $x\ge M'$.Repeating this $n-1$ times more , we get $f$ is unbounded above. This proved the lemma.
Now assume the such a function $f$ exists, Consider
$A(x)=f^{(1)}(x)+f^{(2)}(x)+f^{(3)}(x)$, $~~~~~~~~~~~~~~B(x)=f^{(4)}(x)+f^{(5)}(x)+\cdots+f^{(12)}(x)$
$C(x)=f^{(13)}(x)+f^{(14)}(x)+\cdots+f^{(39)}(x)$,$D(x)=f^{(19)}(x)+f^{(20)}(x)+\cdots+f^{(57)}(x)$.
Let $E(x)=A(x)+B(x)+C(x)$.We are given $1\le A(x),B(x),C(x)\le 3$(hence $3\le E(x)\le 9$) and $D(x)\ge 1$ for all real $x$.Now
$$D(x)=A^{(18)}(x)+B^{(18)}(x)+D^{(18)}(x)=E^{(18)}(x).$$
By the lemma, $E$ is unbounded above,a contradiction to $E(x) \le 9$ for all real $x$.
The link is https://www.math.hkust.edu.hk/ug/competition/award.php where you can  find the solutions to other problems.


text:
Q: Why is PERSON not a ref class? I don't understand why compiler thinks PERSON is NOT a ref class:

: error C2811: 'Runner' : cannot
  inherit from 'Person', a ref class can
  only inherit from a ref class or
  interface class

I tried....

*

*adding mscorlib.dll to the header files: #using..etc...<> - didn't work.

*making Person an abstract class - didn't work (Im glad since I imagined that to be a instantiatable?? class)

I list the two header files first. Then their cose is listed later if you need it.
PERSON.H
#pragma once
using namespace System;

ref class Person
{
private:
    void copy_ptr_data(Person%);
    void delete_ptr_data(void);
public:
    property String^ Name;
    property String^ Age;

    Person(String^ name, String^ age);
    Person(Person%);
    Person% operator= (Person%);
    bool operator==(Person%);
    bool operator!=(Person%);
    virtual ~Person(void);
};

RUNNER.H
#pragma once
#include "Person.h"

using namespace System;

ref class Runner : public Person
{
private:
    void copy_ptr_data(Runner%);
    void delete_ptr_data(void);
public:
    property String^ Time;
    property String^ Rank;

    Runner(String^ name, String^ age, String^ time);
    Runner(Runner%);
    Runner% operator= (Runner%);
    bool operator==(Runner%);
    bool operator!=(Runner%);
    ~Runner(void);
};

PERSON.CPP
#include "StdAfx.h"
#include "Person.h"

Person::Person(String^ name, String^ age)
{
    Name = name;
    Age = age;
}

Person::Person(Person% p)
{
    Name = p.Name;
    Age = p.Age;

    copy_ptr_data(p);
}

Person% Person::operator= (Person% p)
{
    // prevent self-assignment
    if (this == %p) {
        return *this;
    }

    // deallocate/reallocate/assign dynamic memory
    delete_ptr_data();
    copy_ptr_data(p);

    // assign non-dynamic memory
    Name    = p.Name;
    Age     = p.Age;
    return *this;
}

bool Person::operator==(Person% p)
{
    if ((Name == p.Name) &&
        (Age == p.Age))
        return 1;

    return 0;
}

bool Person::operator!=(Person% p)
{
return !(Person::operator==(p));
}

Person::~Person(void)
{
    delete_ptr_data();
}

void Person::copy_ptr_data(Person% p)
{
    return;
}

void Person::delete_ptr_data()
{
    return;
}

RUNNER.CPP
#include "StdAfx.h"
#include "Runner.h"

Runner::Runner(String^ name, String^ age, String^ time) : Person(name, age)
{
    Time = time;
    Rank = nullptr;
}

Runner::Runner(Runner% r) : Person(r)
{
    Time = r.Time;
    Time = r.Rank;

    copy_ptr_data(r);
}

Runner% Runner::operator= (Runner% r)
{
    // handle self assignment
    if (this == %r) return *this;

    // handle base class portion
    Person::operator=(r);

    // handle dynamic portion
    delete_ptr_data();
    copy_ptr_data(r);

    // handle non-dynamic portion
    Time    = r.Time;
    Rank    = r.Rank;

    return *this;
}

bool Runner::operator==(Runner% r)
{
    if ((Person::operator==(r)) &&
        (Time == r.Time)        &&
        (Rank == r.Rank))
        return 1;

    return 0;
}

bool Runner::operator!=(Runner% r)
{
return !(Runner::operator==(r));
}

Runner::~Runner(void)
{
}

void Runner::copy_ptr_data(Runner% r)
{
    return;
}

void Runner::delete_ptr_data()
{
    return;
}

A: Shouldn't you be putting:
#using <mscorlib.dll>

at the top of your header files? I'm not sure if that would fix the issue to be honest.
Try making your Person class abstract.


text:
Q: ModelBuilder for listing and exporting GDB contents I currently generate a list of the feature classes in a gdb using a submodel with a feature class iterator and use Collect Values to make a multivalue list of the fc names.
My problem comes with trying to send the list to Conversion Tools-->To Shapefile-->Feature Class To Shapefile (multiple) as it only accepts Feature Layers as input.  I am unable to figure out how to manufacture multiple feature layers from the Collect Values output parameter from the submodel.

A: Not sure on the interactive picking, but you could use a 'Feature Classes' iterator, and then make a list from the 'names' box, and then pass that to your user. How to let people pick, I can't speculate. Once you've got the list they want, use a 'Multivalue' iterator for all those filenames, and export them.


text:
Q: what is the selector for jquery find() to select an element with attribute AND no parent with specific class? Here is what I've tried
 $(".stemValueScope[data-stemValueId*="+stemValueId+"]").find("*:not(.stemValueScope) [required]").each(function() { ...}

but for a reason I do not get, all [required] element are selected when I only want required element that are NOT in an element with stemValueScope class
(the purpose is to identify required element only if they are in the scope of a checked question but you do not really need to understand this just saying because SO says may question has mostly code...)
the question really just is about jquery syntax : can I put :not() in a find() selector or else how to have an each() treatment on all [required] elements that are into the element ".stemValueScope[data-stemValueId*="+stemValueId+"]" but not within another element with    .stemValueScope class
please try it out with the widget ...

$(document).ready(function() { // au chargement de la page affiche / masque stemValueScope si $stemValue cochée / décochée
        $("input.stemValue:checked").each(function() {
            var stemValueId=$(this).attr("id");
            $(".stemValueScope[data-stemValueId="+stemValueId+"]").removeClass("hidden");
            $(".stemValueScope[data-stemValueId="+stemValueId+"]").show();
        });
        $("input.stemValue:not(:checked)").each(function() {
            var stemValueId=$(this).attr("id");
            //console.log(".stemValueScope[data-stemValueId="+stemValueId+"]");
            //console.log($(".stemValueScope[data-stemValueId="+stemValueId+"]").length);
            $(".stemValueScope[data-stemValueId="+stemValueId+"]").hide();
        });
    });

$("input:radio[name], input:checkbox[name]").click(function () { // affiche / masque stemValueScope si $stemValue cochée / décochée
        var name = $(this).attr("name");
            name = name.replace("[","\\[").replace("]","\\]");
        $("input.stemValue[name="+name+"]:not(:checked)").each(function() {
            var stemValueId=$(this).attr("id");
            $(".stemValueScope[data-stemValueId~="+stemValueId+"]").hide();
            $(".stemValueScope[data-stemValueId~="+stemValueId+"]").find("input").prop('checked', false); // vide stemValueScope si stemValue décochée
            $(".stemValueScope[data-stemValueId~="+stemValueId+"]").find("input:not([type=radio], [type=checkbox])").val(""); // vide stemValueScope si stemValue décochée
            $(".stemValueScope[data-stemValueId~="+stemValueId+"]").find("textarea").val(""); // vide stemValueScope si stemValue décochée
        });
        $("input.stemValue[name="+name+"]:checked").each(function() {
            var stemValueId=$(this).attr("id");
            //console.log(".stemValueScope[data-stemValueId*="+stemValueId+"]");
            //console.log($(".stemValueScope[data-stemValueId*="+stemValueId+"]").length);
            $(".stemValueScope[data-stemValueId~="+stemValueId+"]").removeClass("hidden");
            $(".stemValueScope[data-stemValueId~="+stemValueId+"]").show();
        });
    });

     $(".record").click(function() {
     var formId = $(this).closest("form").attr('id');
     var isValid=true;

       $("#" + formId +" input.stemValue:checked").each(function() { // pour toutes les stemValue cochées vérifie que les champs required sont saisis
            var stemValueId=$(this).attr("id");
            // vérifie que dans le stemValueScope tous les inputs avec un attribut required sont bien renseignés
            $(".stemValueScope[data-stemValueId*="+stemValueId+"]").find("*:not(.stemValueScope) [required]").each(function() {
                var name =$(this).attr("name");
                if ($(this).attr('type') == "radio") {
                    var value = $("[name="+name+"]:checked").val();
                } else {
                    var value = $(this).val();
                }
                console.log("required in stemValueScope de "+stemValueId+" : "+name+" = "+value);
                if ( (!$(this).hasClass(".jq-allowZero") && value == "0" ) || value == "" || value === undefined || value == "\\N" ) {
                    isValid = false;
                    console.log(isValid);
                    alert('Merci de renseigner '+name);
                }
            });
     });
     if (isValid)  alert('form ok');
     })

 <form id="test" method="post">

Le dossier concerne une tumeur à enregistrer

                        <input class="stemValue" required="" name="tumeur" id="tumeurOui" value="oui" type="radio">
                        Oui

                        <input class="stemValue" name="tumeur" id="tumeurNon" value="non" type="radio">
                        Non

                                Classification

                                    <input required="" name="classification" value="OMS" type="radio">
                                    OMS

                                    <input name="classification" value="SBR" type="radio">
                                    SBR

                                    <input name="classification" value="Fuhrman" type="radio">
                                    Fuhrman

                                    <input id="classificationAutre" class="stemValue" name="classification" value="autre" type="radio">
                                    autre

                                préciser

                                        <input required="" name="classificationPreciser" value="" type="text">

check

                        when no is clicked

                        </form>

A:
what is the selector for jquery find() to select an element with attribute AND no parent with specific class?

You first need to select every element with an attribute with $('[yourAttribute]').
Then you need to filter out those with a parent with a certain class. You can test that pretty easily by looking if $(this).closest('.parentClass').length returns 0 or not.

var result = $('[data-test]').filter(function(){
  return $(this).closest('.test').length;
});

console.log(result.length);

A: here is what I needed :
`$("#" + formId +" input.stemValue:checked").each(function() {

        var stemValueId=$(this).attr("id");

        $(".stemValueScope[data-stemValueId*="+stemValueId+"]").find("[required]").each(function() {

            if($(this).closest('.stemValueScope').attr("data-stemValueId")==stemValueId) {
                var name =$(this).attr("name");
                //name = name.replace("[","\\[").replace("]","\\]");
                if ($(this).attr('type') == "radio") {
                    var value = $("[name="+name+"]:checked").val();
                } else {
                    var value = $(this).val();
                }
                if (<?= $cfg['debug']."0" ?>) { console.log("required in stemValueScope de "+stemValueId+" : "+name+" = "+value);}
                if ( (!$(this).hasClass(".jq-allowZero") && value == "0" ) || value == "" || value === undefined || value == "\\N" ) {
                    isValid = false;
                    console.log(isValid);
                    $(this).notify('Merci de renseigner', { className: "error",position: "top middle" });
                }
            }
        });

               });

had to add a test to see if the closest() item with stemValueScope is the one for which [required] item are being checked and not a nested required item...
if($(this).closest('.stemValueScope').attr("data-stemValueId")==stemValueId)


text:
Q: Displaying better error than TypeException when doing JSON.dump on Python When Python json.dump fails to serialise value, it does not tell what was the invalid key or where it was located. This makes json.dump useless when trying to locate data errors in large JSON objects.
Is it possible to improve json.dump TypeError error messages?

A: One can pre-validate the data before passing it to json.dump. json.dump encoder itself does not pass data locatin information around, making it hard to use it for the task.
Here is a Python code that

*

*Raises nested custom exceptions to locate any keys with bad values

*Contains some useful checks and patterns for common Python libraries which might be pitfalls on naive use os json.dump()
Call validate_nested_state_dict() before passing the data to json.dump.
import datetime
from decimal import Decimal
from enum import Enum
from types import NoneType
from typing import Any

import pandas as pd
import numpy as np

class BadStateData(Exception):
    """Having something we do not support in the state."""

#: Types we know we can safely pass to JSON serialisation
ALLOWED_VALUE_TYPES = (
    dict,
    list,
    float,
    int,
    str,
    NoneType,
    Enum,  # Supported by dadtaclasses_json
    datetime.datetime,  # Supported by dadtaclasses_json
    Decimal,  # Supported by dadtaclasses_json
)

#: We especially do not want to see these in serialisation.
#: We need to do negative test, because Pandas types to some base class
#: magic.
BAD_VALUE_TYPES = (
    np.float32,
    pd.Timedelta,
    pd.Timestamp,
)

def validate_state_value(name: str | int, val: Any):
    if not isinstance(val, ALLOWED_VALUE_TYPES):
        raise BadStateData(f"Bad value {name}: {val} ({type(val)}")

    if isinstance(val, BAD_VALUE_TYPES):
        raise BadStateData(f"Bad value {name}: {val} ({type(val)}")

def walk(name, val):
    """Raise hierarchical exceptions to locate the bad key-value pair in nested data."""
    try:
        if isinstance(val, dict):
            for k, v in val.items():
                walk(k, v)
        elif isinstance(val, list):
            for idx, val in enumerate(val):
                walk(idx, val)
        else:
            validate_state_value(name, val)
    except BadStateData as e:
        raise BadStateData(f"Key {name} contained bad value") from e

def validate_nested_state_dict(d: dict | list | object):
    walk("state", d)


text:
Q: Weighted search on one field and a normal search on other field I am trying to perform a search by matching the search query to either the tag or the name of the doc, I also have a filter on the top, so I do have to use must.
Here is what I have been trying,
{
  "query": {
    "bool": {
      "filter": {
        "term": {
          "type.primary": "audio"
        }
      },
      "must": [
        {
          "nested": {
            "path": "tags",
            "score_mode": "sum",
            "query": {
              "function_score": {
                "query": {
                  "bool": {
                    "must": [
                      {
                        "match": {
                          "tags.tag": "big"
                        }
                      }
                    ]
                  }
                },
                "field_value_factor": {
                  "field": "tags.weight"
                },
                "boost_mode": "multiply",
                "boost": 10
              }
            }
          }
        },
        {
          "bool": {
            "must": [
              {
                "multi_match": {
                  "query": "big",
                  "fields": [
                    "name"
                  ],
                  "type": "phrase_prefix"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

This just results in empty.
If I use should instead of must the query works fine, but it gives me all results with the filter of type.primary: audio.
I am pretty sure there is some other way to search for the name field. Thanks.

A: You're almost there! In your must, you declare that both tags and name has to hit. Try the following:
GET /_search
{
  "query": {
    "bool": {
      "filter": {
        "term": {
          "type.primary": "audio"
        }
      },
      "must": [
        {
          "bool": {
            "should": [
              {
                "nested": {
                  "path": "tags",
                  "score_mode": "sum",
                  "query": {
                    "function_score": {
                      "query": {
                        "bool": {
                          "must": [
                            {
                              "match": {
                                "tags.tag": "big"
                              }
                            }
                          ]
                        }
                      },
                      "field_value_factor": {
                        "field": "tags.weight"
                      },
                      "boost_mode": "multiply",
                      "boost": 10
                    }
                  }
                }
              },
              {
                "multi_match": {
                  "query": "big",
                  "fields": [
                    "name"
                  ],
                  "type": "phrase_prefix"
                }
              }
            ]
          }
        }
      ]
    }
  }
}


text:
Q: How to 'difference' one vector from another? I'm trying to create a mute music button:

And I'm doing it by drawing 2 vector lines over a music note vector.  I've tried selecting them every which way but whenever I try to take the path → difference nothing happens.  Ideally I'd like to subtract the big like (white in the above image) and add the small line.
How would I do this?

A: Got it.  You have to be in the edit paths mode:

You may also need to convert the object into a path.  Path → Object to Path


text:
Q: Call to a member function query() on a non-object, no clue why

SOLVED<<<

I've been busy with creating my CMS and got stuck at a function which throws me this error:

Fatal error: Call to a member function query() on a non-object in E:\Xampp\htdocs\CMS_PF\includes\functions\functions.php on line 40

and it correspondends with this part of the script:
function isUserAdmin($email){
    global $mysqli;

    $acces_admin = 3;
    $query = "SELECT access FROM user WHERE email='$email'";
    $result = $mysqli->query($query);

    while($row = mysqli_fetch_assoc($result)) {
        $user_access = $row['access'];

        if($user_access == 3){
            return true;
        }
    }
}

Where the error is coming from the $result line.
I got no clue why it is throwing this error and was hoping someone could point it out for me.
Thanks in advance,
Remy.

A: try this
function isUserAdmin($email){
    global $mysqli;

    $acces_admin = 3;
    $query = "SELECT access FROM user WHERE email='$email'";
    $result = mysqli_query($conn,$query);//where $conn is your database connection

    while($row = mysqli_fetch_assoc($result)) {
        $user_access = $row['access'];

        if($user_access == 3){
            return true;
        }
    }
}

mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)

A: Problem got solved, forgot to include my connection on a specific page.. facepalm


text:
Q: How to detect and extract signature from an image with OpenCV? I am importing the attached image. After importing the image, I want to remove horizontal lines, detect the signature and then extract it, create rectangle around signature, crop the rectangle and save it. I am struggling to identify entire region of a signature as one contour or a group of contours.
I have already tried findcontour and then various ways to detect signature region. Please refer the code below.
Python Script:
imagePath

#read image
image = cv2.imread(imagePath,cv2.COLOR_BGR2RGB)

#Convert to greyscale
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale

#Apply threshold
ret,thresh1 = cv2.threshold(gray, 0, 255,cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)

plt.imshow(thresh1,cmap = 'gray')

#preprocessing
rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,15))
dilation = cv2.dilate(thresh1, rect_kernel, iterations = 1)
plt.imshow(dilation,cmap = 'gray')

#Detect contours
contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours[0]

height, width, _ = image.shape
min_x, min_y = width, height
max_x = max_y = 0
for contour, hier in zip(contours, hierarchy):
    (x,y,w,h) = cv2.boundingRect(contour)
    min_x, max_x = min(x, min_x), max(x+w, max_x)
    min_y, max_y = min(y, min_y), max(y+h, max_y)
    if w > 80 and h > 80:
        cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

if max_x - min_x > 0 and max_y - min_y > 0:
    fin=cv2.rectangle(image, (min_x, min_y), (max_x, max_y), (255, 0, 0), 2)

plt.imshow(fin)

final=cv2.drawContours(image, contours,-1,(0,0,255),6)

plt.imshow(final,cmap = 'gray')

Final objective is to create rectangle around entire signature

Trying to generalize on the other image:

A: Instead of removing the horizontal lines, it may be easier to perform HSV color thresholding. The idea is to isolate the signature onto a mask and then extract it. We convert the image to HSV format then use a lower/upper color threshold to generate a mask
lower = np.array([90, 38, 0])
upper = np.array([145, 255, 255])
mask = cv2.inRange(image, lower, upper)

Mask

To detect the signature, we can get the combined bounding box for all of the contours with np.concatenate() then use cv2.boundingRect() to obtain the coordinates

Now that we have the bounding box coordinates, we can use Numpy slicing to crop and extract the ROI

import numpy as np
import cv2

# Load image and HSV color threshold
image = cv2.imread('1.jpg')
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([90, 38, 0])
upper = np.array([145, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
result = cv2.bitwise_and(image, image, mask=mask)
result[mask==0] = (255, 255, 255)

# Find contours on extracted mask, combine boxes, and extract ROI
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = np.concatenate(cnts)
x,y,w,h = cv2.boundingRect(cnts)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
ROI = result[y:y+h, x:x+w]

cv2.imshow('result', result)
cv2.imshow('mask', mask)
cv2.imshow('image', image)
cv2.imshow('ROI', ROI)
cv2.waitKey()

Note: The lower/upper color ranges were obtained from choosing the correct upper and lower HSV boundaries for color detection with cv::inRange (OpenCV)


text:
Q: MONO (ARM) running webserver using OWIN I built mono for armv5 I can run a simple helloworld.exe but when I try to
run webserver which uses owin I am having some problems. I believe I need
the library libmono-system-core4.0-cil but I can't seem to find it anywhere
for arm.
mono-4.2.2.30 was built using

./configure --with-tls=__thread --without-mcs-docs
  CFLAGS=-DARM_FPU_NONE
  --disable-mcs-build --host=arm-v5te-linux-gnueabi

Here is the error output

Unhandled Exception: System.IO.FileNotFoundException: Could not load
  file or assembly 'System.Core, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089' or one of its dependencies.
  IO.FileName_Name   at
  Microsoft.Owin.Hosting.Services.ServiceProvider.Add (System.Type
  serviceType, System.Type implementationType) <0xb6f608e8 + 0x00047> in
  :0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory+<>c__DisplayClass1.b__0
  (System.Type service, System.Type implementation) <0xb6f608a0 +
  0x00033> in :0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory+<>c__DisplayClass4.b__3
  (System.Type service, System.Type implementation) <0xb6f60200 +
  0x0014b> in :0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory.DoCallback
  (System.Action2 callback) <0xb6f5ffd8 + 0x00037> in <filename
  unknown>:0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory.DoCallback
  (IDictionary2 settings, System.Action2 callback) <0xb6f5f930 +
  0x000df> in <filename unknown>:0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory.Create (IDictionary2
  settings, System.Action1 configuration) <0xb6f5cff8 + 0x00103> in
  <filename unknown>:0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory.Create (IDictionary2
  settings) <0xb6f5cfa8 + 0x00023> in :0   at
  Microsoft.Owin.Hosting.WebApp.BuildServices
  (Microsoft.Owin.Hosting.StartOptions options) <0xb6f5ce48 + 0x00037>
  in :0   at Microsoft.Owin.Hosting.WebApp.Start
  (Microsoft.Owin.Hosting.StartOptions options) <0xb6f5cd90 + 0x0001b>
  in :0   at
  Microsoft.Owin.Hosting.WebApp.Start[TStartup]
  (Microsoft.Owin.Hosting.StartOptions options) <0xb6f5c908 + 0x00047>
  in :0   at PLT.Web.Program.main (System.String[]
  argv) <0xb6f580d0 + 0x0010b> in :0 [ERROR] FATAL
  UNHANDLED EXCEPTION: System.IO.FileNotFoundException: Could not load
  file or assembly 'System.Core, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089' or one of its dependencies.
  IO.FileName_Name   at
  Microsoft.Owin.Hosting.Services.ServiceProvider.Add (System.Type
  serviceType, System.Type implementationType) <0xb6f608e8 + 0x00047> in
  :0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory+<>c__DisplayClass1.b__0
  (System.Type service, System.Type implementation) <0xb6f608a0 +
  0x00033> in :0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory+<>c__DisplayClass4.b__3
  (System.Type service, System.Type implementation) <0xb6f60200 +
  0x0014b> in :0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory.DoCallback
  (System.Action2 callback) <0xb6f5ffd8 + 0x00037> in <filename
  unknown>:0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory.DoCallback
  (IDictionary2 settings, System.Action2 callback) <0xb6f5f930 +
  0x000df> in <filename unknown>:0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory.Create (IDictionary2
  settings, System.Action1 configuration) <0xb6f5cff8 + 0x00103> in
  <filename unknown>:0   at
  Microsoft.Owin.Hosting.Services.ServicesFactory.Create (IDictionary2
  settings) <0xb6f5cfa8 + 0x00023> in :0   at
  Microsoft.Owin.Hosting.WebApp.BuildServices
  (Microsoft.Owin.Hosting.StartOptions options) <0xb6f5ce48 + 0x00037>
  in :0   at Microsoft.Owin.Hosting.WebApp.Start
  (Microsoft.Owin.Hosting.StartOptions options) <0xb6f5cd90 + 0x0001b>
  in :0   at
  Microsoft.Owin.Hosting.WebApp.Start[TStartup]
  (Microsoft.Owin.Hosting.StartOptions options) <0xb6f5c908 + 0x00047>
  in :0   at PLT.Web.Program.main (System.String[]
  argv) <0xb6f580d0 + 0x0010b> in :0


text:
Q: How do you subset data from a list in R? I would LIKE TO EXTRACT THE job descriptions, aka the "p" TAG HTML ELEMENTS, from all 16 pages generated from the last line of code.
"ret" IS A LIST of 16 HTML pages generated by the last line of code. I'm not used to working with lists of lists, so I'm confused how to extract the data from these lists.
Normally I would use
res %>%
html_elements("body p")

But I'm getting the error message, "Error in UseMethod("xml_find_all") :
no applicable method for 'xml_find_all' applied to an object of class "list"
library(tidyverse)
library(rvest)
library(xml2)

url<-"https://www.indeed.com/jobs?q=data%20analyst&l=San%20Francisco%2C%20CA&vjk=0c2a6008b4969776"
page<-xml2::read_html(url)#function will read in the code from the webpage and break it down into different elements (<div>, <span>, <p>, etc.

#get job title
title<-page %>%
  html_nodes(".jobTitle") %>%
  html_text()

#get company Location
loc<-page %>%
  html_nodes(".companyLocation") %>%
  html_text()

#job snippet
page %>%
  html_nodes(".job-snippet") %>%
  html_text()

#Get link
desc<- page %>%
  html_nodes("a[data-jk]") %>%
  html_attr("href")

# Create combine link
combined_link <- paste("https://www.indeed.com", desc, sep="")

#Turn combined link into a session follow link

page1 <-  html_session(combined_link[[1]])
page1 %>%
  html_nodes(".iCIMS_JobContent, #jobDescriptionText") %>%
  html_text()

#one<- page %>% html_elements("a[id*='job']")

#create function return a list of page-returns

ret <- lapply(paste0("https://www.indeed.com", desc), read_html)

A: We could either use lapply from base R
out <- lapply(ret, function(x) x %>%
         html_nodes(".iCIMS_JobContent, #jobDescriptionText") %>%
          html_text())

or loop with map from purrr
library(purrr)
out <- map(ret, ~ .x %>%
         html_nodes(".iCIMS_JobContent, #jobDescriptionText") %>%
         html_text())

NOTE: Both are looping over the elements of the list, the .x or x are the individual elements (from anonymous function - i.e. function created on the fly (function(x) or ~ - in tidyverse)


text:
Q: Spring AMQP Converting from a Message According to documentation  when using @RabbitListener annotation to configure listener

the inferred type information is added to the MessageProperties; this allows the converter to convert to the argument type of the target method

so i can use custom pojo to convert in.
My question - is it works in the same way when xml-based strategy used to configure listener: <rabbit:listener-container>
        <rabbit:listener ref=...

A: No; that uses a simpler MessageListenerAdapter.
When using that form, if there is no type information in the message headers, you have to configure the message converter to tell it what type you want the data converted to...
<rabbit:listener-container message-converter="jsonConverter">
    <rabbit:listener ref="listener" method="handleFoo" queue-names="input.foo" />
</rabbit:listener-container>

<bean id="listener" class="com.example.Listener" />

<bean id="jsonConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter">
    <property name="classMapper">
        <bean class="org.springframework.amqp.support.converter.DefaultClassMapper">
            <property name="defaultType" value="com.example.Foo" />
        </bean>
    </property>
</bean>

and
public class Listener {

    public void handleFoo(Foo foo) {
        System.out.println(foo);
    }

}

and
Foo [bar=bar]
Foo [bar=bar]

from
{ "bar" : "bar" }

with
content_type: application/json


text:
Q: How to deal with URISyntaxException: Illegal character in path in Hadoop Map Reduce job? I am learning Map-reduce using Hadoop and I was running this command:
hadoop jar /usr/lib/hadoop/share/hadoop/tools/lib/hadoop-streaming-2.7.2.jar -mapper mapper.py -reducer reducer.py -file mapper.py -file reducer.py -input sales_data -output salesout
I am including the full error output i got:
16/04/15 00:39:26 WARN streaming.StreamJob: -file option is deprecated, please use generic option -files instead.
packageJobJar: [mapper.py, reducer.py] [] /tmp/streamjob4183555536412178637.jar tmpDir=null
16/04/15 00:39:28 INFO Configuration.deprecation: session.id is deprecated. Instead, use dfs.metrics.session-id
16/04/15 00:39:28 INFO jvm.JvmMetrics: Initializing JVM Metrics with processName=JobTracker, sessionId=
16/04/15 00:39:28 INFO jvm.JvmMetrics: Cannot initialize JVM Metrics with processName=JobTracker, sessionId= - already initialized
16/04/15 00:39:28 INFO mapreduce.JobSubmitter: Cleaning up the staging area file:/tmp/hadoop-enlighter/mapred/staging/enlighter1664997312/.staging/job_local1664997312_0001
Exception in thread "main" java.lang.IllegalArgumentException: java.net.URISyntaxException: Illegal character in path at index 112: file:/run/media/enlighter/dd3546e2-4871-4fc6-a57e-7336392cb705/home/enlighter/workspace/dbms-lab/assign_4(Hadoop MapReduce project)/code/tester/mapper.py
    at org.apache.hadoop.mapreduce.JobResourceUploader.uploadFiles(JobResourceUploader.java:109)
    at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:95)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:190)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1290)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1287)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1287)
    at org.apache.hadoop.mapred.JobClient$1.run(JobClient.java:575)
    at org.apache.hadoop.mapred.JobClient$1.run(JobClient.java:570)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
    at org.apache.hadoop.mapred.JobClient.submitJobInternal(JobClient.java:570)
    at org.apache.hadoop.mapred.JobClient.submitJob(JobClient.java:561)
    at org.apache.hadoop.streaming.StreamJob.submitAndMonitorJob(StreamJob.java:1014)
    at org.apache.hadoop.streaming.StreamJob.run(StreamJob.java:135)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
    at org.apache.hadoop.streaming.HadoopStreaming.main(HadoopStreaming.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
Caused by: java.net.URISyntaxException: Illegal character in path at index 112: file:/run/media/enlighter/dd3546e2-4871-4fc6-a57e-7336392cb705/home/enlighter/workspace/dbms-lab/assign_4(Hadoop MapReduce project)/code/tester/mapper.py
    at java.net.URI$Parser.fail(URI.java:2848)
    at java.net.URI$Parser.checkChars(URI.java:3021)
    at java.net.URI$Parser.parseHierarchical(URI.java:3105)
    at java.net.URI$Parser.parse(URI.java:3053)
    at java.net.URI.<init>(URI.java:588)
    at org.apache.hadoop.mapreduce.JobResourceUploader.uploadFiles(JobResourceUploader.java:107)
    ... 26 more

It seems the execution is having a problem with the system path where my mapper and reducer scipts are located. It is not properly able to parse the special characters in the path.
What should I do to successfully run the job?
Will I have to change any folder names? Or is there a better solution?

A: I also faced same exception, I was able to resolve with removing space in foldername where mapper and reducer programs are kept .


text:
Q: Write Hermite equation in specific form. Hence show $u=p^\frac{1}{2}y$ satisfies equation.
Write the Hermite equation

$$\frac{\partial^2 y}{\partial x^2}-2x\frac{\partial y}{\partial x}+2\alpha y=0$$

in the form

$$\frac{\partial (p(x)}{\partial x} \frac{\partial y)}{\partial x}+q(x)y=0$$

Hence show that the function $u=p^\frac{1}{2}y$ satisfies

$$u''+(2\alpha+1-x^2)u=0$$

I have

$$y''+py'+q(x)y=0$$$$ry''+rpy'+rq(x)y=0$$$$ry''+pry'=(ry')'=ry''+r'y'$$$$r'=pr, r=e^{\int p(x)dx}$$

But where to from here?

A: $$\frac{d}{dx}\left(p(x)\frac{dy}{dx} \right)+q(x)y=0$$
$$py''+p'y'+qy=0$$
$$y''+\frac{p'}{p}y'+\frac{q}{p}=0$$
to be compared to $$\quad y''-2xy'+2\alpha y=0 \quad\implies$$
$$\begin{cases}\frac{p'}{p}=-2x \quad\to\quad p(x)= c\: e^{-x^2}\\
 \frac{q}{p}=2\alpha \quad\to\quad q(x)=2\alpha p=2\alpha c\: e^{-x^2}
\end{cases}$$
$$u(x)=p^{1/2}y=c^{1/2} e^{-x^2/2}y$$
$u'=c^{1/2} e^{-x^2/2}\left(y'-xy \right)$
$u''=c^{1/2} e^{-x^2/2}\left(y''-xy'-y-x(y'-xy) \right)=c^{1/2} e^{-x^2/2}\left(y''-2xy'+x^2y \right)$
$$u''+(2\alpha+1-x^2)u=c^{1/2} e^{-x^2/2}\left((y''-2xy'-y+x^2y)+(2\alpha+1-x^2)y \right)$$
After simplification :
$$u''+(2\alpha+1-x^2)u=c^{1/2} e^{-x^2/2}\left(y''-2xy'+2\alpha y \right)$$
Since $\quad y''-2xy'+2\alpha y=0 \quad\implies$
$$u''+(2\alpha+1-x^2)u=0$$


text:
Q: "loading" image hangs when navigating to next page I have a webpage that proceeds (when user clicks 'Next') to a complex server-side operation. Internet Explorer sometimes gives the user the impression that nothing is happening at this stage, so I wanted to display a "loader" gif and the message "Please wait..." However, the loader gif e.g. http://ajaxload.info stops spinning as soon as Internet Explorer changes its href location giving the users (who are "special") the impression that the website has "hung" and they close the page!
I thought an <iframe> element was what I needed to stop the spinning loader image from "hanging" but it isnt - does anyone have a clue what Im talking about and how I can achieve this?
Very confusing, thanks for your understanding :P

A: Check Animated GIF in IE stopping


text:
Q: Why only use babel.config.js can compile node_modules babel.config.js use case
In Babel@next Website, I see if I want to compile node_modules, I should use babel.config.js not .babelrc to config babel.
And I have a try, If I using .babelrc with the latest babel@7.x, I can't compile node_modules to ES5 even I include node_modules in webpack config file, So, I'm confused why so design. The documention have no more explain.

A: Because they changed on babel@next so people can do conditions with processd.env.NODE_ENV. Just because of that. You won't be able to use .babelrc


text:
Q: How can you use Python to fill out HTML forms that also have Javascript? I am making a python program that automatically enters information into a form on a website. I looked at a module called mechanize at first but then I realized that it didn't support javascript. Is there any way to take a piece of information and insert it into a "form" on a website that uses javascript?
The website I am using is www.locationary.com.
If you login and then go to a place/business page like this,
http://www.locationary.com/place/en/US/California/Los_Angeles/Z_Pizza-p1001157911.jsp
then you will see a bunch of spots that need to be filled in. I looked at the page source and this "form" uses javascript. I just need a way to fill in those blanks now. Like I said, I tried mechanize and it didn't work but I also googled it and got nothing.
The "form" uses "onclick"
If you could offer any advice, I would really appreciate it.
Thanks.

A: I think probably the best way to do this is to use a framework that can operate through a browser.  There are several options, but the most pythonic is windmill http://www.getwindmill.com/
I've found it useful on a number of projects.


text:
Q: Return static index.html when static file with path not exists I would like to serve a static web application files with spring:

*

*Static

*

*

*index.html

*

*

*file.js

I have created config for this situation:
public class StaticContextConfig implements WebMvcConfigurer {
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS =
            {
                    "classpath:/static/"
            };

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
    }

It works fine when first page is like "localhost/", but when my web app use "localhost/page1" it returns 404. I tried to config it with controller and checking files if they exists, but without success.
Thanks for your attention and potential help.


text:
Q: Node js express\ react js cors issue I'm dealing with an issue with CORS in express js, so the issue is that when I use the CORS Library I receive cors header normally without a problem in postman as shown in the image below postman response headers
But when I call the same api from my React js I get a cors error and there is no header for cors in the response headers.
Second issue is that when I use cors library in my main app like so :
code of server.js using CORS in App
My whole express server just doesn't return anything for a very long time .
Here is the relevant code in express js :
//server.js

  const express = require("express");
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

mongoose.connect(dbConfig.url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(()=>{
    console.log("Successfully connected to the database");

}).catch(err => {
    console.log('Could not connect to the database. Exiting now ...',err);
    process.exit();

})

app.get('/',(req, res) => {
res.json({"message" : "Welcome to EasyNotes application. Take notes quickly. Organize and keep track of all your notes."});
});

require('./app/routes/note.routes.js')(app);

app.listen(3000,() => {

    console.log("Server is listening on port 3000");

})

This is my routing js file
//routing

const cors = require('cors');
module.exports = (app) => {

    const notes = require('../controllers/note.controller.js');

    app.post('/notes', cors(), notes.create);

    app.get('/notes', cors(), notes.findAll);

    app.get('/notes/:noteId', cors(), notes.findOne);

    app.post('/notes/:noteId', cors(), notes.update);

    app.delete('/notes/:noteId', cors(), notes.delete);

}

What is most weird is that I'm using the same api but a different route and its working fine in the browser, like when I use this route :
 app.get('/notes', cors(), notes.findAll);

it works fine.
please help !!

A: From reading your post, I'm not sure you completely understand what is CORS and why the issue is triggered. I recommend you take a look at the Mozilla explanation.
To explain it a little further, the browser probably does an OPTIONS request to your API to check if Cross origin requests are allowed. To do this, you need to use the cors package just as you show in the second screenshot you attached.
You mention that your app does not work when you do this, and this is probably the bug you should be investigating, maybe in the github issues of the package.
Finally, I never used cors() as you're using it in your routing file, just including the middleware as you do in the screenshot should be enough, Maybe this is the cause of the second issue you mention?
Good luck with it

A: in you server.js file you are using app.use(cors) but it should be app.use(cors()). Here is an example from one of my projects that I'm currently working on

require('./db')

const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')

const mongoose = require('mongoose')

const postRouter = require('./routes/post')

const app = express()

app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

app.use('/api', postRouter)

/*
mongoose.connection.on('connected', () => {

    mongoose.connection.db.listCollections().toArray(function (err, names) {
        console.log(names);
    });
})
*/
app.post('/', function(req, res) {
    res.sendStatus(200)
})

app.listen(5000, () => console.log("Server started on port 5000"));


text:
Q: How to know what glassfish is - full plaform or web profile? I have installed glassfish. I can run
asadmin version

It shows what version it is, but how to know it is "Full Platform" or "Web profile"?

A: You could use the
glassfish4\bin>asadmin list-containers

command. Which lists all known application containers. A full profile server reports this:
jpa
jpa
web
weld
weld
security
grizzly
ear
ejb
osgi
resources_ear
resources
appclient
webservices
connector

A web profile server reports this:
jpa
jpa
web
weld
weld
security
grizzly
ejb
osgi
resources_ear
resources
connector

Not much difference but it should be enough ;)

A: You can look at the license file name to determine if it is Full profile or Web profile
<glassfish install dir>/glassfish/legal/3RD-PARTY-LICENSE.txt
<glassfish install dir>/glassfish/legal/3RD-PARTY-LICENSE-WEB-PROFILE.txt

A: *

*GlassFish Web Profile: It is a lighter version of GlassFish that is designed for web applications and only includes a subset of the Java EE technologies.

*GlassFish Full Platform: It is the complete version of GlassFish that includes all Java EE technologies.
Which one to download depends on the requirements of your project. If you are developing a web application and do not need the full Java EE stack, then the GlassFish Web Profile would be a good choice. If you are developing a more complex application that requires the full Java EE stack, then the GlassFish Full Platform would be a better choice.


text:
Q: Log4j is not logging into file i have the following log4j configuration:
# Root logger option
log4j.rootLogger=file, stdout

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.Threshold=WARN
log4j.appender.file.File=logs/log.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.Append=true
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold=INFO
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Logging into stdout works fine but nothing is logged into my file.
There are definately outputs for the file but nothing happens.
Why isnt he logging into my file?

A: you can change your configuration file like this.
# Root logger option
log4j.rootLogger= ALL,file, stdout

And log4j.appender.stdout.Threshold=INFO change level like ALL its print all level logs TRACE to FATAL

A: One reason could be that the Threshold for the stdout appender(INFO) is lower  than the file appender(WARN). So, if there are only INFO messages being logged, you will only see them in the stdout and not in the file.

A: It depends on how you are running it.  Is this just a normal java program?  For example, if you are trying to run it within a container (such as Karaf) then sometimes they can have special log destinations set.


text:
Q: Big O Notation - O(nlog(n)) vs O(log(n^2)) Is the notation of NLog(N) the same as Log(N^2)? If so, why is it not written like that?
Is NLog(N) the standard notation? I feel like Log(N^2) is less confusing to see.

A: Adding logarithms is the same as multiplying numbers, so log(n*n) becomes log(n) + log(n) = 2 log(n).
n log(n) is close to linear. The first n is the important part, as the rest of it grows rather slowly.
For example merge sort has n log n time complexity, because if you think of the merging as a tree, then the tree is log(n) levels tall, and on each level all n elements are processed.

A: *

*O(log(n^2)) is simply O(2 log(n)) = O(log(n)). It is a logarithmic function. Its value is much smaller than the linear function O(n).

*O(n log(n)) is a larger function. Its values are larger than the linear function O(n)
They are completely different functions (and different big-O complexities). O(n log(n)) is much larger than O(log(n^2))
This plot shows the difference:

A: Nlog(N) = log(N^N) so no and as pointed out by zerkms  above log(N^2) = 2log(N)


text:
Q: Upload files and show them in web page using React I am trying upload txt files using React, and show these files or the names of the files front of the user,
to give him permission to change the file or to delete it.
This is my :
 import React from "react";

class Browse extends React.Component
{

state =  {selectedFile:[] , textFile: []};

//fileChangedHandler  Method
fileChangedHandler =event => {
 for(var i=0;i<event.target.files.length;i++){
       this.state.fileees =event.target.files;
       this.setState({selectedFile: event.target.files[i]})

    this.setState((state) => {
        const textFile=[...state.textFile,state.selectedFile.name];
        return {
          textFile,
        };
    });

  }  //for
  } //fileChangedHandler

 render(){
    return(

                Insert DNA Files:
                <input type="file" onChange={this.fileChangedHandler} id="myfile" name="myfile" multiple/>

                  {this.state.selectedFile.name}

    );
}

} //class

export default Browse;

Its works very good if I upload one file, I can see the file name, but Its not work if I upload multiple files.
I need the help for the problem,
why if I upload more than one file, I can't show them in the web front of the user
Thank you .

A: Hi Please check this example. Here I uploaded multiple files and shown file names in the page.
import React from "react";

export default class FIleUploadExample extends React.Component {

    state = {
        files: []
    };

    fileUpload = (e) => {
        this.setState({files: [...e.target.files]});
    };

    render() {
        return (

                File Upload
                <input type="file" multiple="multiple" id="file" onChange={this.fileUpload}/>

                    {
                        this.state.files.map((file, i) =>
{file.name}
)
                    }

        );
    }
}

A: I need to add two buttons near of the name of the files :
first button name:"Delete" when the user  click it all the row disappear.
second button name: "Change" when the user click it he can upload another file, and the new file name must replace the old .
How can I do that ?
import React from "react";
import '../index.css';
import './dna.css';

export default class Browse extends React.Component {

    state = {
        files: [],
       // changeButtons:[],
    //    deleteButtons:[]
    };

    fileUpload = (e) => {
        this.setState({files: [...e.target.files]});
       // this.setState({changeButtons:[<button>Change</button>]});
       // this.setState({deleteButtons:[<button onClick={(e)=>this.onDelete(id)}>Delete</button>]});
    };

        Change(id){
            console.log("Change Function");
        }

    Delete(id) {
        console.log("ssss")
        this.setState((prevState) => ({
          files: prevState.files.filter(files => files.id !== id),
        }))
        console.log(this.state.files.name);
      }

    render() {
        return (

               Insert DNA Files:
                <input type="file" multiple="multiple" id="file" onChange={this.fileUpload}/>

                    {

                        this.state.files.map((file, i) =>

                                                            {file.name} :
                                                            <button onClick={() => this.Change(i)}>Change</button>
                                                            <button onClick={() => this.Delete(i)}>Delete</button>

)
                    }

        );
    }
}


text:
Q: Could not initialize SpringHibernateFactory from Web Service I have a Dynamic web application that uses Struts 1.3 + Spring 3.1 + Hibernate 4.0 and it all works fine when trying to use it from the web project. When I created a WebLogic Web Service that is added to an EAR and also a Web service client to consume and I try to retrieve java objects from the database I get: Could not initialize class com.multivision.ehrms.crud.impl.SpringHibernateFactory
AxisFault
 faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server
 faultSubcode:
 faultString: Could not initialize class com.multivision.ehrms.crud.impl.SpringHibernateFactory
 faultActor:
 faultNode:
 faultDetail:
    {http://jax-ws.dev.java.net/}exception:<message>Could not initialize class com.multivision.ehrms.crud.impl.SpringHibernateFactory</message><ns2:stackTrace><ns2:frame class="com.multivision.ehrms.service.data.BaseDataService" line="unknown" method="getDataRetriever"/><ns2:frame class="com.multivision.crm.service.data.QueryDataService" line="unknown" method="retrieveAllQueries"/><ns2:frame class="com.multivision.crm.ws.CRMdata" file="CRMdata.java" line="22" method="retrieveAll"/><ns2:frame class="sun.reflect.NativeMethodAccessorImpl" file="NativeMethodAccessorImpl.java" line="native" method="invoke0"/><ns2:frame class="sun.reflect.NativeMethodAccessorImpl" file="NativeMethodAccessorImpl.java" line="39" method="invoke"/><ns2:frame class="sun.reflect.DelegatingMethodAccessorImpl" file="DelegatingMethodAccessorImpl.java" line="25" method="invoke"/><ns2:frame class="java.lang.reflect.Method" file="Method.java" line="597" method="invoke"/><ns2:frame class="weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker" file="WLSInstanceResolver.java" line="92" method="invoke"/><ns2:frame class="weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker" file="WLSInstanceResolver.java" line="74" method="invoke"/><ns2:frame class="com.sun.xml.ws.server.InvokerTube$2" file="InvokerTube.java" line="151" method="invoke"/><ns2:frame class="com.sun.xml.ws.server.sei.EndpointMethodHandlerImpl" file="EndpointMethodHandlerImpl.java" line="268" method="invoke"/><ns2:frame class="com.sun.xml.ws.server.sei.SEIInvokerTube" file="SEIInvokerTube.java" line="100" method="processRequest"/><ns2:frame class="com.sun.xml.ws.api.pipe.Fiber" file="Fiber.java" line="866" method="__doRun"/><ns2:frame class="com.sun.xml.ws.api.pipe.Fiber" file="Fiber.java" line="815" method="_doRun"/><ns2:frame class="com.sun.xml.ws.api.pipe.Fiber" file="Fiber.java" line="778" method="doRun"/><ns2:frame class="com.sun.xml.ws.api.pipe.Fiber" file="Fiber.java" line="680" method="runSync"/><ns2:frame class="com.sun.xml.ws.server.WSEndpointImpl$2" file="WSEndpointImpl.java" line="403" method="process"/><ns2:frame class="com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit" file="HttpAdapter.java" line="532" method="handle"/><ns2:frame class="com.sun.xml.ws.transport.http.HttpAdapter" file="HttpAdapter.java" line="253" method="handle"/><ns2:frame class="com.sun.xml.ws.transport.http.servlet.ServletAdapter" file="ServletAdapter.java" line="140" method="handle"/><ns2:frame class="weblogic.wsee.jaxws.WLSServletAdapter" file="WLSServletAdapter.java" line="171" method="handle"/><ns2:frame class="weblogic.wsee.jaxws.HttpServletAdapter$AuthorizedInvoke" file="HttpServletAdapter.java" line="708" method="run"/><ns2:frame class="weblogic.security.acl.internal.AuthenticatedSubject" file="AuthenticatedSubject.java" line="363" method="doAs"/><ns2:frame class="weblogic.security.service.SecurityManager" file="SecurityManager.java" line="146" method="runAs"/><ns2:frame class="weblogic.wsee.util.ServerSecurityHelper" file="ServerSecurityHelper.java" line="103" method="authenticatedInvoke"/><ns2:frame class="weblogic.wsee.jaxws.HttpServletAdapter$3" file="HttpServletAdapter.java" line="311" method="run"/><ns2:frame class="weblogic.wsee.jaxws.HttpServletAdapter" file="HttpServletAdapter.java" line="336" method="post"/><ns2:frame class="weblogic.wsee.jaxws.JAXWSServlet" file="JAXWSServlet.java" line="95" method="doRequest"/><ns2:frame class="weblogic.servlet.http.AbstractAsyncServlet" file="AbstractAsyncServlet.java" line="99" method="service"/><ns2:frame class="javax.servlet.http.HttpServlet" file="HttpServlet.java" line="820" method="service"/><ns2:frame class="weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction" file="StubSecurityHelper.java" line="227" method="run"/><ns2:frame class="weblogic.servlet.internal.StubSecurityHelper" file="StubSecurityHelper.java" line="125" method="invokeServlet"/><ns2:frame class="weblogic.servlet.internal.ServletStubImpl" file="ServletStubImpl.java" line="300" method="execute"/><ns2:frame class="weblogic.servlet.internal.ServletStubImpl" file="ServletStubImpl.java" line="183" method="execute"/><ns2:frame class="weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction" file="WebAppServletContext.java" line="3717" method="wrapRun"/><ns2:frame class="weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction" file="WebAppServletContext.java" line="3681" method="run"/><ns2:frame class="weblogic.security.acl.internal.AuthenticatedSubject" file="AuthenticatedSubject.java" line="321" method="doAs"/><ns2:frame class="weblogic.security.service.SecurityManager" file="SecurityManager.java" line="120" method="runAs"/><ns2:frame class="weblogic.servlet.internal.WebAppServletContext" file="WebAppServletContext.java" line="2277" method="securedExecute"/><ns2:frame class="weblogic.servlet.internal.WebAppServletContext" file="WebAppServletContext.java" line="2183" method="execute"/><ns2:frame class="weblogic.servlet.internal.ServletRequestImpl" file="ServletRequestImpl.java" line="1454" method="run"/><ns2:frame class="weblogic.work.ExecuteThread" file="ExecuteThread.java" line="209" method="execute"/><ns2:frame class="weblogic.work.ExecuteThread" file="ExecuteThread.java" line="178" method="run"/></ns2:stackTrace>

Could not initialize class com.multivision.ehrms.crud.impl.SpringHibernateFactory
    at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:222)
    at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:129)
    at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:601)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1782)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2938)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at javax.xml.parsers.SAXParser.parse(SAXParser.java:395)
    at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
    at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
    at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
    at org.apache.axis.handlers.soap.MustUnderstandChecker.invoke(MustUnderstandChecker.java:62)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:206)
    at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
    at org.apache.axis.client.Call.invoke(Call.java:2767)
    at org.apache.axis.client.Call.invoke(Call.java:2443)
    at org.apache.axis.client.Call.invoke(Call.java:2366)
    at org.apache.axis.client.Call.invoke(Call.java:1812)
    at com.multivision.crm.ws.CRMdataPortBindingStub.retrieveAll(CRMdataPortBindingStub.java:176)
    at com.multivision.crm.ws.DataConsumer.main(DataConsumer.java:12)

Like I said, the SpringHibernateFactory has no problem initializing when using the web project, but when I expose the project using a web service and client then SpringHibernateFactory cannot initialize. Can anyone understand this problem?

A: Did your spring context start when server startup ? Can you find this kind of output in your console ?
[ContextLoader ]  Root WebApplicationContext: initialization started
[XmlWebApplicationContext ]  Refreshing Root WebApplicationContext: startup date [Tue Mar 05 09:34:47 CET 2013]; root of context hierarchy
[XmlBeanDefinitionReader ]  Loading XML bean definitions from class path resource [applicationContext.xml]

Try to add this in your web.xml otherwise
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

No link with your problem but why to use a java EE server if you're using spring ? Tomcat should be sufficient, and if you really need a Java EE server then use CDI and EJB container instead of spring


text:
Q: What's the best way of sharing object across containers? In one of my project I came across a situation where I want to create in-memory indices of objects. The primary index may use a different key and secondary indices would use some other elements as keys.
If I am using std::map for primary index as
std::map<string, Object>

then which's the best way to store reference/pointer for the secondary index using another container (again std::map for instance considering all the Objects are unique) without making additional copies of the Object?

*

*Using raw pointers or references which pose the risk of dangling pointers or references (I know that ideally when Object gets deleted from primary index, care should also be taken to remove it from secondary index but would the pointers/references in secondary indices invalidate when container for primary index adjust itself internally?)
std::map<string, const Object*>

*Or using combination of shared_ptr's in primary index and weak_ptr's secondary index
std::map<string, std::shared_ptr<Object>> // primary index
std::map<string, std::weak_ptr<Object>> // secondary index
I know there are pros and cons for both the approaches. Especially I don't want to lose the flexibility of directly inserting the objects in the primary container but I also do not want the secondary index to copy the Objects again. The difficulty in using smart pointers just for secondary index is that they would not own the Object.
Thanks in advance for help.

A: Place your objects in some container. Depending on the frequency of additions / deletions of objects you may want to consider using a container that does not invalidate references to its elements, like a std::list or a std::deque.
Then, for your maps, just reference the objects (or any of their members) using references, i.e. using std::reference_wrapper.
Encapsulate the backend storage as well as the indices so that whenever you add or remove objects you remove invalid references from the indices as well as add any new references.
That way you only have to store your objects once and get around using smart pointers. This will obviously only work if you actually own the objects and control their lifetimes, and if you can keep the indices encapsulated (in order to keep them updated).


text:
Q: ValueError: logits and labels must have the same shape ((None, 6, 8, 1) vs (None, 1)) I am trying to get my hands dirty with neural networks in practice, for such task i am trying to classify some images, where i'll have two classes basically. So, i took a CNN as an example using keras and tensorflow from tutorial on youtube.
I tried changing my output layer activation to sigmoid and when did it, i started getting the error:
 ValueError: logits and labels must have the same shape ((None, 6, 8, 1) vs (None, 1))

Given specifically at the following line:
validation_steps = nb_validation_Samples // batch_size)

My neural network code:
Libraries
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import numpy as np
from keras.preprocessing import image

Setup
img_width, img_height = 128, 160

train_data_dir = '/content/drive/My Drive/First-Group/Eyes/'
validation_data_dir = '/content/drive/My Drive/First-Validation-Group/'
nb_train_samples = 1300
nb_validation_Samples = 1300
epochs = 100
batch_size = 16

if K.image_data_format() == 'channels_first':
   input_shape = (3, img_width, img_height)
else:
   input_shape = (img_width, img_height, 3)

train_datagen = ImageDataGenerator(
    zoom_range=0.2,
)

test_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
   train_data_dir,
   target_size=(img_width, img_height),
   batch_size=batch_size,
   class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode="binary")

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Dense(64))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.summary()

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data = validation_generator,
error line -> **validation_steps = nb_validation_Samples // batch_size)**

model.save_weights('weights.npy')

A: the input of your network is 4d (batch_dim, height, width, channel), while your target is 2d (batch_dim, 1). you need something in your network to pass from 4d to 2d like flatten or global pooling. for example, you can add one of them after your last max-pooling layer.
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten()) #<========================
model.add(Dense(64))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

the usage of binary_crossentropy as a loss with sigmoid and class_mode='binary' in generator seems ok if u are dealing with a binary classification problem


text:
Q: How to use equivs-build for creating deb from python app? For my PyGtk application in Ubuntu I plan to use 'equivs-build' for the purpose of creating distribution deb file. The application is based on ./configure, make, make install . Any body suggest the step-by-step process to create the same...
Waiting for fast repsonse
Thanks
Anes

A: *

*Similar to meta packages, follow instruction here: How to create a meta-package that automatically installs other packages? or MySQL 5.6 depends on client 5.5

*You need more info to fill in equivs control file, documented in man equivs-build, example: Files: .


text:
Q: What is bitly='BITLY_PROCESSED' in  tag? While i was inspecting facebook html code through with firebug in Chrome, i found this tag :
<a href="http://www.facebook.com/?ref=logo" title="Home" bitly="BITLY_PROCESSED"/>

What is the bitly attribute? Anyone has an idea?
:)

A: It gets added by the bit.ly plug-in (and perhaps some others) when it examines links (see http://bit.ly/pages/tools form more on that). If you don't have that plug-in yoruself, then it may be that someone somewhere along the line did.

A: bit.ly offers URL redirection service with real-time link tracking, or in other words URL shortener, so I am guessing you have it's plugin installed.


text:
Q: How do I use radio buttons in a ListView Flutter? I have a list of varieties [Chocolate, Strawberry, Vanilla]
This list can change depending on the menu item ordered (i.e. [BBQ, Medium, Peri-Peri, Lemon & Herb])
My current code which display the button correctly but is not functional is:
               ListView.builder(
                        shrinkWrap: true,
                        itemCount: varietyList.length,
                        itemBuilder: ((context, index) {
                          return GFRadioListTile(
                            titleText: varietyList[index],
                            size: 25,
                            activeBorderColor: Colors.black,
                            focusColor: Colors.black,
                            type: GFRadioType.basic,
                            value: 0,
                            groupValue: 1,
                            onChanged: (value) {},
                            inactiveIcon: null,
                          );
                        })),

Where ```int number = 20'''. This variable and amount was based off another post where the code looked as follow:
ListView.builder(
                        shrinkWrap: true,
                        itemCount: varietyList.length,
                        itemBuilder: ((context, index) {
                          return RadioListTile(
                            value: index,
                            groupValue: number,
                            onChanged: (ind) => setState(() => number = ind),
                          );
                        })),

But it says "A value of type 'Object?' can't be assigned to a variable of type 'int'."
How can I get the radio button functional?

A: to fix the "object cant be int" problem I had to add as int for the ind object.
GFRadioListTile(
                            padding: const EdgeInsets.all(13),
                            color: Colors.white,
                            radioColor: Color.fromARGB(255, 138, 5, 5),
                            title: Text(
                              varietyList[index],
                              style: const TextStyle(
                                  fontSize: 25, color: Colors.black),
                            ),
                            size: 28,
                            activeBorderColor: Colors.black,
                            focusColor: Colors.black,
                            type: GFRadioType.basic,
                            value: index,
                            groupValue: number,
                            onChanged: (ind) =>
                                setState(() => number = ind! as int),
                            inactiveIcon: null,
                          );


text:
Q: Как правильно достать данные из LocalStorage У меня есть форма в которой  пишется название количество страниц, потом я отдельно записываю количество страниц в LocalStorage. Потом не должен их получать  и суммировать. Но я получаю из LocalStorage количества страниц через запятую. Как я могу их разделить и суммировать.
Код где я записываю в LocalStorage
    addBook=async(name,count)=>{
        let bookInfo = {};
        bookInfo["name"] = name;
        bookInfo["count"] = count;
        await this.setState({
            booksList: [...this.state.booksList,bookInfo],
            nameValue: "",
            countValue: 0,
            booksPages: [...this.state.booksPages,count]
        })
        localStorage.setItem("booksList",JSON.stringify(this.state.booksList));
        localStorage.setItem("booksPages",(this.state.booksPages));
    }

Код где я беру из LocalStorage
componentDidMount(){
        const booksList = localStorage.getItem('booksList');
        const booksPages = localStorage.getItem('booksPages');
        console.log("booksPages",booksPages)
        if(booksList){
            const savedList = JSON.parse(booksList);
            this.setState({
                booksList : savedList,
                booksPages: booksPages
            })
        }else{
            console.log("No list")
        }
    }

Например я ввожу
Test 100
Test 100
То получаю в booksPages 100,100
Как мне это исправить
Спасибо

A: Точно так же, как Вы это делаете для booksList.
localStorage.setItem("booksPages",JSON.stringify(this.state.booksPages));
...
const booksPages = localStorage.getItem('booksPages')? JSON.parse(localStorage.getItem('booksPages')) : [];
const pageSum = booksPages.reduce((acc, i) => acc + i, 0);


text:
Q: Difference between TLC272CP and TLC272CDR I was using an operational amplifier in my project from Texas Instruments. The series is TLC272. There are many different models. Could someone tell me the significance or the meaning of CP or CDR in different types of TLC272?
Can you please explain which one is better and how does it make a difference? And also what is a reel?

A: They are different packages for the IC. Page 2 of the datasheet shows that CP is a plastic DIP package, and CDR is a small outline package. The R at the end means the ICs come in a reel; if there is no R then they come in tubes.

Performance may depend on the package -- you'll have to check the electrical characteristics in the datasheet to see what the differences are and if they matter to you (the package will be listed at the top of the electrical characteristics table). The package choice is mostly dependent on which you would prefer to use.
Reels are used for large quantities. If you only need a couple hundred (or less) units then you just need tubes. There is no difference in performance between tubes vs. reels -- it's just a difference in how the ICs are shipped.
This is what a reel of ICs looks like:

This is what a tube of ICs looks like:


text:
Q: Kubernetes Container Environment I wrote deployment.yml file in k8s:-
spec:
  containers:
  - name: consul
    image: xyz
    ports:
      - name: http
        containerPort: 8500
      - name: http1
        containerPort: 53
    env:
    - name: SERVICE_8500_IGNORE
      value: "true"
    - name: CONSUL_LOCAL_CONFIG
      value: "{"node_name": "docker","acl_datacenter": "dc1", "acl_default_policy": "deny", "acl_down_policy": "deny", "acl_master_token": "fleeture", "acl_agent_token":"xyz", "enable_script_checks": true}"

After running I am getting errors

Error : Unexpected characters near "node_name": "docker","acl_datacenter": "dc1", "acl_default_policy": "deny", "acl_down_policy": "deny", "acl_master_token": "xyz", "acl_agent_token":"xyz", "enable_script_checks": true}"".
  Line : 14  value: "{"node_name": "docker","acl_datacenter": "dc1", "acl_default_policy": "deny", "acl_down_policy": "deny", "acl_master_token": "fleeture", "acl_agent_token":"xyz", "enable_script_checks": true}"

Any Idea how to write ENV for line 14?

A: You need to use \ to escape the double-quotes within the value for CONSUL_LOCAL_CONFIG so that entry becomes:
- name: CONSUL_LOCAL_CONFIG
  value: "{\"node_name\": \"docker\",\"acl_datacenter\": \"dc1\", \"acl_default_policy\": \"deny\", \"acl_down_policy\": \"deny\", \"acl_master_token\": \"fleeture\", \"acl_agent_token\":\"xyz\", \"enable_script_checks\": true}"

A: @ryan-dawson's answer is valid answer.
Also, you can simply replace first double-quote(") with single-quote(') as
- name: CONSUL_LOCAL_CONFIG
  value: '{"node_name": "docker","acl_datacenter": "dc1", "acl_default_policy": "deny", "acl_down_policy": "deny", "acl_master_token": "fleeture", "acl_agent_token":"xyz", "enable_script_checks": true}'


text:
Q: How do I use Theano to solve an ordinary differential equation? Here is my Python code:
import numpy as np

def spread_points_in_cube(n, dimensions=3, rng=None):
    from scipy.integrate import ode
    if rng is None:
        rng = np.random

    size = n * dimensions
    y0 = np.zeros((2 * size))
    y0[:size] = rng.uniform(0, 0.1, size=size)
    t0 = 0.0

    mean = np.zeros(dimensions)
    variance = np.eye(dimensions) * 0

    def decode(y):
        positions = np.remainder(y[:size].reshape((n, dimensions)), 1)
        velocities = y[size:].reshape((n, dimensions))
        return positions, velocities

    def get_forces(positions, velocities):
        delta_positions = positions[:, np.newaxis, :] - positions[np.newaxis, :, :]
        delta_positions = np.remainder(delta_positions + 0.5, 1) - 0.5  # wrapping
        distances = np.linalg.norm(delta_positions, axis=2, ord=2)
        distances += 1e-5
        pairwise_forces = delta_positions * (distances ** -3)[:, :, np.newaxis]
        magnetic_forces = np.sum(pairwise_forces, axis=1) / (n ** 2)

        velocity_mags = np.linalg.norm(velocities, axis=1, ord=2)
        drag_forces = -velocities * velocity_mags[:, np.newaxis]

        forces = magnetic_forces * 0.01 + drag_forces * 10.0
        return forces

    def f(t, y):
        positions, velocities = decode(y)
        forces = get_forces(positions, velocities)
        retval = np.zeros((2 * size))
        retval[:size] = velocities.reshape(size)
        retval[size:] = forces.reshape(size)
        return retval

    r = ode(f).set_integrator('vode', method='bdf')
    r.set_initial_value(y0, t0)
    t_max = 20
    dt = 1
    while r.successful() and r.t < t_max:
        positions, velocities = decode(r.y)
        forces = get_forces(positions, velocities)
        total_speed = np.sum(np.linalg.norm(velocities, axis=1, ord=2))
        total_force = np.sum(np.linalg.norm(forces, axis=1, ord=2))
        #print("\nt", r.t, "\np", positions, "\nv", velocities,
        #      "\nf", forces
        print(total_speed, total_force)
        if total_force < n * 1e-4:
            print("breaking")
            #break
        r.integrate(r.t + dt)
    print("converged after", r.t, total_speed, total_force)
    return positions
spread_points_in_cube(1000, 3)

Is it possible to use Theano to solve the ODE?

A: Here is a VERY simple ode solver in theano:
import numpy
import theano

# the right-hand side
def f(x, t):
    return x*(1-x)

x = theano.tensor.matrix() # why not a matrix
dt = theano.tensor.scalar()
t = theano.tensor.scalar()

x_next = x + f(x, t)*dt # implement your favourite RK method here!

# matrix of random initial values
# store it on the device
x_shared = theano.shared(numpy.random.rand(10, 10))

step = theano.function([t, dt], [],
        givens=[(x, x_shared)],
        updates=[(x_shared, x_next)],
        on_unused_input='warn')

t = 0.0
dt = 0.01

while t < 10:
    step(t, dt)
    t += dt
    # test halt condition here

print(x_shared.get_value()) # read back the result

I hope it helps.
Basically you have to implement your Runge-Kutta method.
And mind that the strength of theano is in vectorization, so I won't bother implementing the time loop in theano. That's why I used a simple python while loop, although I could use theano scan. Anyway, depending on your goal, the optimization can be tricky. I'm not 100% convinced that theano is a good choice for an ODE solver. Numpy does the vectorizations on your force and position matrices anyway, at least on CPU. With a theano implementation you can utilize GPU, but that's not a guarantee for a speedup.


text:
Q: Sequelize List all unmanaged instances of transactions MySQL I have a doubt that there are one or more areas in my node.js app where I did not commit or rollback the unmanaged transaction. I want to know a way to list down all opened unmanaged instances of Sequelize transactions. I am using Sequelize ver 3 and dialect is mysql.
Thank you


text:
Q: Validation in Stepper form not working on next click, React JS The form validation is not working, I used inputProps in the form but the validation is not working and when next button is clicked it moves ahead. Please help.
const User = (props) => {
  const { activeStep: lastActiveStep, userId} = props;
  const classes = useStyles();
  const [Type, setType] = useState(0);
  const [activeStep, setActiveStep] = useState(lastActiveStep || 0);
  console.log(activeStep + "last step user filled");
  const [RelationOptions, setRelationOptions] = useState(0);

  const [DetailsForm, setDetailsForm] = useReducer(
    (state, newState) => ({ ...state, ...newState }),

    {}
  );

  const [validation, setValidation] = useReducer(
    (state, newState) => ({ ...state, ...newState }),

    {}
  );

 function getSteps(){
  return ['Personal Details',
  'Relation',
  'Other Details'];
 }

    const steps = getSteps();

    const inputProps = {
      pattern: "[a-z]"
    }

  function onTypeChangeChange(event) {
    // setAge(event.target.value);
    setType(event.target.value);
    let _RelationOptions = Options.find(options => options.value === event.target.value);
    setRelationOptions(_RelationOptions.relationships);
  }

  const handleDeatilsInput = evt => {
    const name = evt.target.name;
    const newValue = evt.target.value;
    setDetailsForm({ [name]: newValue });
  };

  const handleDetailsSubmit = evt => {
    evt.preventDefault();
    let data = { DetailsForm };
    props.Details(DetailsForm)
    console.log(data + "new user");
  //  console.log( props.onDetails(DetailsForm) + "gana bajao");
     setDetailsForm();
   setActiveStep((prevActiveStep)=> prevActiveStep + 1);

  }

  function getStepContent(step) {
    switch (step) {
      case 0: if ((!props.user.s_firstName)) {
        return (

        <form id ="form-step0" className={classes.root} onSubmit={handleGuardianDetailsSubmit} Validate autoComplete="off">
         <Grid item xs={12} sm={6} md={6}>
         {/* <AccountCircle sx={{ color: 'action.active', mr: 1, my: 1}} /> */}
          <TextField
            id="outlined-basic"
            name="s_firstName"
            label="First Name"
            variant="outlined"
            inputProps={{pattern: "[a-zA-Z]"}}
            defaultValue={DetailsForm.s_firstName}
            onChange={handleDeatilsInput}
            helperText="Only letters are required"
            required= {true}
            />

            </Grid>
            <Grid item xs={12} sm={6} md={6}>
          <TextField
            id="outlined-basic"
            name="s_lastName"
            label="Last Name"
            variant="outlined"
            defaultValue={DetailsForm.s_lastName}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <AccountCircle />
                </InputAdornment>
              ),
            }}
            onChange={handleDeatilsInput}
            required/></Grid>
             <Grid item xs={12} sm={6} md={6}>
          <TextField
            id="outlined-number"
            label="Age"
            name="s_age"
            defaultValue={DetailsForm.s_age}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <AccountCircle />
                </InputAdornment>
              ),
            }}
            type="number"
            InputLabelProps={{
              shrink: true,
            }}
            onChange={handleDeatilsInput}
            variant="outlined"
            required
          /></Grid>
          <Grid item xs={12} sm={6} md={6}>
          <FormControl variant="outlined" className={classes.formControl}
          sx={{ m: 1, minWidth: 250 }} required>
            <InputLabel id="demo-simple-select-outlined-label">Class</InputLabel>
            <Select
              labelId="demo-simple-select-outlined-label"
              id="demo-simple-select-outlined"
              value={DetailsForm.s_class}
              onChange={handleDeatilsInput}
              label="Class"
              name="s_class"
            >
              {studentClasses.map(c =>
                <MenuItem key={c.value} value={c.value}>{c.name}</MenuItem>
              )}
            </Select>
            {/* <Button variant="contained" type="submit" color="primary" >NEXT</Button> */}

          </FormControl></Grid>
        </form>

 )}
;
      case 1: if (!props.user.g_relationship) {
        return (

        <form id="form-step1" className={classes.root} onSubmit={handleDetailsSubmit} noValidate autoComplete="off">
        <Grid item xs={12} sm={6} md={6}>
          <FormControl variant="outlined" className={classes.formControl}
          sx={{ m: 1, minWidth: 120 }} required>
            <InputLabel id="demo-simple-select-outlined-label">Relationship</InputLabel>
            <Select
              labelId="demo-simple-select-outlined-label"
              id="demo-simple-select-outlined"
              onChange={onTypeChangeChange}
              label="Relationship"
            >
              {Options.map(type =>
                <MenuItem key={type.value} value={type.value}>{type.name}</MenuItem>
              )}
            </Select>
          </FormControl>
</Grid>
<Grid item xs={12} sm={6} md={6}>
          {RelationOptions ?

            <FormControl variant="outlined" className={classes.formControl}
            sx={{ m: 1, minWidth: 120 }} required>
              <InputLabel id="demo-simple-select-outlined-label">Relation</InputLabel>
              <Select
                labelId="demo-simple-select-outlined-label"
                id="demo-simple-select-outlined"
                // value={age}
                name="g_relationship"
                value={DetailsForm.g_relationship}
                onChange={handleDeatilsInput}
                label="Relation"
              >
                {RelationOptions.map(type =>
                  <MenuItem key={type.value} value={type.value}>{type.name}</MenuItem>
                )}
              </Select>
            </FormControl> : null

          }
       </Grid>

        </form>

 )}
;
      case 2:
        return (

        <form id="form-step2" className={classes.root} onSubmit={handleDetailsSubmit} noValidate autoComplete="off">
        <Grid item xs={12} sm={6} md={6}>
          <TextField
            id="outlined-basic"
            name="g_firstName"
            label="First Name"
            variant="outlined"
            defaultValue={DetailsForm.g_firstName}
            onChange={handleDeatilsInput}
            required/></Grid>
             <Grid item xs={12} sm={6} md={6}>
          <TextField
            id="outlined-basic"
            name="g_lastName"
            label="Last Name"
            variant="outlined"
            defaultValue={guardianForm.g_lastName}
            onChange={handleDeatilsInput}
            required/></Grid>
             <Grid item xs={12} sm={6} md={6}>
          <TextField
            id="outlined-number"
            label="Age"
            name="g_age"
            defaultValue={DetailsForm.g_age}
            type="number"
            InputLabelProps={{
              shrink: true,
            }}
            onChange={handleDeatilsInput}
            variant="outlined"
            required
          /></Grid>

        </form>

)
;

      default:
        return 'welcome lets fill the progress.' ;
    }
  }

  return (

<Paper square elevation={0}>

              <Typography>{getStepContent(activeStep)}</Typography>
              </Paper>

              <Box sx={{ width: '100%' }}>
      <Stepper activeStep={activeStep} alternativeLabel>
        {steps.map((label) => (
          <Step key={label}>
            <StepLabel>{label}</StepLabel>
          </Step>
        ))}
      </Stepper>
    </Box>

<Button size="small"  onClick={handleDetailsSubmit} type="submit"
        form={`form-step${activeStep}`}>
        {activeStep === steps.length-1? 'Finish' : 'Next'}
        </Button>

  );
        }

      export default User;

Please help how to validate text field with each step validation. Its not working on next click. if every field is not filled still the form is submitted with empty value.