text:
Q: Running the output of script, and checking for consistency Given a file that was output by script, is there a way to run all of those commands in order, and then check to see if the output matches what was in the script file?
I assume that diff can be used for the last part, but I have no idea on how to do the first. Any ideas?
Using a tcsh shell on linux (Debian, but I doubt it matters).

A: Edit: From the manual:

Script places everything in the log file, including linefeeds and backspaces.  This is not what the naive user expects.

This means it might be possible to do in the simplest cases, by looking for occurrences of $PS1 in the output and running the string after it, but it could soon become impossible:

*

*You can't see the difference between a literal character and an escape character like ^C.

*Any background jobs can insert text at any time, messing up the output. while true; do sleep $RANDOM; echo garbage; done &

*If it records standard error, there's the whole asynchronous output issue.

If it's at all an option, I'd rather use /var/log/cmdlog, and see if all of the text produced by the commands recorded there occur anywhere within the script file.

A: Okay, so one of the semantics of diff is that it outputs text if the files differ, and outputs nothing if they are the same.
Given files foo and bar, here's what you can do:
# Run your script
if [ "$(diff foo bar)" = "" ]; then
    echo "They are the same"
else
    echo "They are different"
fi

(You're first part isn't exactly clear - do you have a sample output out.template and script > out.log and want to make sure that out.template and out.log are the same? Or something else?)


text:
Q: bootstrap, button above footer i wanted to put 2 buttons just above the navbar (see the link as below)
http://postimg.org/image/o0dga8wux/
i62.tinypic.com/2r7lc2g.png
this is my code:
<form id="form1"  runat="server">

some content

                    footer

</form>

---------------UPDATE WITH FIDDLE------------------
fiddle: http://www.bootply.com/122652

A: First of all, please reference the official documentation on buttons here.
You could do it like this:
<form id="form1"  runat="server">

some content

        <button type="button" class="btn btn-default">Default</button>
        <button type="button" class="btn btn-primary">Primary</button>

                    footer

</form>

A: Here you go.
.buttons {
   position: relative;
   top: 0px;
   left: 410px;
}

Use this link http://jsfiddle.net/4JAwZ/1/
DEMO

redpajama_set_name: RedPajamaStackExchange


text:
Q: Define Conditional many-to-many in Postgresql I have these three tables,

*

*menu

*item

*category

And the relationship among all these tables are,

*

*A menu can have multiple items and categories. So menu has a one-to-many relationship with item and category.

*Item and category have a many-to-many relationship

*Furthermore, the constraint I am thinking is that item and category can only be connected if they are both under the same menu.

Currently I am thinking to enforce the first two contraint (one-to-many and many-to-many) in the database and handle the 3rd constraint in application side.
Is there a better way in postgres or any other db to define this type of conditional constraint? If yes, is there a industry term for it?

A: Not sure if this makes sense from the point of running a restaurant, but matches constraints as described in the question.
-- Menu MEN exists.
--
menu {MEN}
  PK {MEN}

-- Item ITM is on menu MEN.
--
item {ITM, MEN}
  PK {ITM}
  SK {ITM, MEN}

-- Category CAT is listed on menu MEN.
--
category {CAT, MEN}
      PK {CAT}
      SK {CAT, MEN}

-- Item ITM, from menu MEN, is in category CAT
-- from the same menu.
--
item_category {ITM, CAT, MEN}
           PK {ITM, CAT}

FK1 {ITM, MEN} REFERENCES item {ITM, MEN}
FK2 {CAT, MEN} REFERENCES category {CAT, MEN}

Note:
All attributes (columns) NOT NULL

PK = Primary Key
AK = Alternate Key   (Unique)
SK = Proper Superkey (Unique)
FK = Foreign Key


text:
Q: MS Access - searching for better method to create and edit records I have made a database that I use at work for tracking tags that get signed out. The way I currently have it is I created a table that has 100 records manually entered already. Field Name "TagNumber" 1 to 100. There are several other fields for every record that is currently blank.
A user will have access to a form that they will select a tag number from the "TagNumber" dropdown list. Doing this will allow them to fill in the other fields with the correct info for that tag. When finished they will click a save and exit button that will modify that record they just put the info in for. It will also update a Field named "SignedOut" it is a data type Yes/No field. Once the user has signed out that tag number it will no longer show up on the dropdown list when someone else goes to sign out a tag.
On the same form there is a "SignIn" dropdown list that only shows the tags that are checked yes in the "SignedOut" Field. When a user selects a tag to be signed they enter their name and date and click save and exit. Clicking the save and exit button will run a macro that copies all the data on that single record to another table for tracking purposes. It also sets all the fields back to blank except the "TagNumber" field. This allows another user to sign out that tag again.
examples of my tables:
Nothing signed out yet
Tag 4 signed out
Now my issue I am running into is If I provide this to another section they have different tag numbers and I don't want to have to go to the table and physically change every tag number. Is there a way I can auto populate the list with different tag numbers? or is there a way I should be doing this that is completely different from the way I am doing it?
Thanks for any info you can provide.


text:
Q: Cannot connect to SQL Server using pyodbc from another domain I'm trying to connect to it from another domain with this code below but I'm getting an error like this

InterfaceError: (pyodbc.InterfaceError) ('28000', '[28000]
[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed.
The login is from an untrusted domain and cannot be used with
Integrated authentication. (18452) (SQLDriverConnect); [28000]
[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed.
The login is from an untrusted domain and cannot be used with
Integrated authentication. (18452)') (Background on this error at:
http://sqlalche.me/e/13/rvf5)

This is my code that I'm using:
import pyodbc
from sqlalchemy import create_engine

server = 'shul'

database = 'db_pre'

uid = 'pre'
pwd = 'pr@20si'

engine = create_engine('mssql+pyodbc://' + server + '/' + database + '/' + uid + '/' + pwd + '?trusted_connection=no&driver=ODBC+Driver+13+for+SQL+Server')

#engine = create_engine('mysql://root:@localhost/daming') # enter your password and database names here

col_names = ["month", "price", "change"]
df = pd.read_csv("kcl.csv",sep=',',quotechar='\'',encoding='utf8', names=col_names,skiprows = 1) # Replace Excel_file_name with your excel sheet name
df.to_sql('kcl',con=engine,index=False,if_exists='replace') # Replace Table_name with your sql table name

In SQL Server Management Studio I used SQL Server authentication instead of Windows Authentication.
Please help me. Thank you in advance.

A: You can study this link :
https://docs.djangoproject.com/en/2.2/ref/settings/#databases
Set similar config :
   DATABASES = {
        "default": {
            "ENGINE": "sql_server.pyodbc",
            "NAME": env("database_name"),
            "USER": env("database_user"),
            "PASSWORD": env("database_password"),
            "HOST": env("database_host"),
            "PORT": env("database_port"),
            "OPTIONS": {
                "driver": "ODBC Driver 17 for SQL Server",
                "unicode_results": True,
            },
        }
    }


text:
Q: How to send ethernet frames from one veth to another? I have two veth pairs (veth1, veth1_0) and (veth2, veth2_0). veth1_0 and veth2_0 are in the default namespace ns0, veth1 is in namespace ns1 and veth2 in namespace ns2. I want to communicate between different namespaces. So I use veth1_0 to send an ethernet frame to veth2_0(use pcap_sendpacket), hoping I can capture the packet at veth2. And in my output, I can capture the packet in namespace 1 at veth1; but fail to do in namespace 2 at veth2. I wonder if it's possible to accomplish the communication in this way; or maybe there are other methods.

A: I am not sure if this solves your problem, but the normal approach is to create a bridge in the main namespace, and just make veth1_0 and veth2_0 members of the bridge.
Then you given veth1 and veth2 proper IP addresses in their respective namespaces, add routing if necessary, let the IP stack do its thing and stop worrying about ethernet packets. In particular, don't use anything like pcap.


text:
Q: Laravel Passport Password Grant - Client authentication failed After hearing a lot about laravel passport, i thought of implementing it into my new project where my requirement is to create an API that'll be used in a mobile app.
So my mobile app is a client, which will further have its users.
I followed the steps mentioned by Taylor and also read about it here. In a nutshell I followed these steps:

*

*Installed laravel/passport.

*Created a website user.

*Generated passport keys php artisan passport:install

*Generated client_id and client_secret using php artisan passport:client

*Added redirection and callback routes in web.php

*Authorized the user and got the final access token.

Then I tried calling api/user( with Header Authorization containing value Bearer eyJ0eXAiOiJKV1...(token)
I received the data. Pretty simple and neat.
But my app users won't have these details. So I thought of configuring Password Grant Tokens which fits perfectly in my requirement.
Now starts the real headache. I've been trying to set this up for the last 3 days and continuously getting
{"error":"invalid_client","message":"Client authentication failed"}

I've tried almost every guide I followed online: Redirection Issues, Add Atleast One Scope Solution, P100Y Issue etc.
But I'm still getting invalid client error. Here's what I'm passing through POSTMAN to oauth/token:
{
    "grant_type": "password,"
    "client_id": "3,"
    "client_secret": "8BUPCSyYEdsgtZFnD6bFG6eg7MKuuKJHLsdW0k6g,"
    "username": "test@gmail.com,"
    "password": "123456,"
    "scope": ""
}

Any help would be appreciated.

A: Have yo try running php artisan config:cache after all the passport commands.

A: use the below code to generate an access token, it has worked for me before:
$request->request->add([
      'client_id' => '2',
      'client_secret' => 'm3KtgNAKxq6Cm1WC6cDAXwR0nj3uPMxoRn3Ifr8L',
      'grant_type' => 'password',
      'username' => 'support@eliteride.co.uk',
      'password' => 'pass22'
    ]);
    $tokenRequest = $request->create('/oauth/token', 'POST', $request->all());

    $token =  \Route::dispatch($tokenRequest);

A: Check your credentials first if they are correct, Secondly check your model table which uses \Laravel\Passport\HasApiTokens trait that whether it contains email column, because by default it is used to identify user when validating credentials. if your table has username column or any other column which is used in validating credentials you must define a function findForPassport in that model. like this,
public function findForPassport($username) {
       return self::where('username', $username)->first(); // change column name whatever you use in credentials
    }

I use username and password column to validate a user,
in {project_directory}\vendor\laravel\passport\src\Bridge\UserRepository.php
this function validates your credentials,
public function getUserEntityByUserCredentials($username, $password, $grantType, ClientEntityInterface $clientEntity)
    {
        if (is_null($model = config('auth.providers.users.model'))) {
            throw new RuntimeException('Unable to determine user model from configuration.');
        }

        if (method_exists($model, 'findForPassport')) { // if you define the method in that model it will grab it from there other wise use email as key
            $user = (new $model)->findForPassport($username);
        } else {
            $user = (new $model)->where('email', $username)->first();
        }

        if (! $user || ! $this->hasher->check($password, $user->password)) {
            return;
        }

        return new User($user->getAuthIdentifier());
    }

notice the second if statement and you will get to know what  is happening there.
hope this help :)

A: {"error":"invalid_client","message":"Client authentication failed"}

means that the client_id and client_secret you're currently sending is one of the following:

*

*client_id and client_secret being sent is not registered in your oauth server

*client_id and client_secret being sent is not of the grant type that you specify in the post body

For me, the password_client column value for that particular client
  was 0. i manually changed it to 1 but it didn't help. – Kanav Oct 4 at
  3:25

As I read your comment to some of the answer makes this one is obvious that you use the wrong type of client_id and client_secret for your password grant flow, so your case was the latter. You can verify that by finding the entry in oauth_clients table for your supplied client_id and client_secret
"grant_type": "password,"
"client_id": "3,"
"client_secret": "8BUPCSyYEdsgtZFnD6bFG6eg7MKuuKJHLsdW0k6g,"

SELECT * FROM oauth_clients WHERE id = 3 AND secret = '8BUPCSyYEdsgtZFnD6bFG6eg7MKuuKJHLsdW0k6g' AND password_client=1;

in your oauth_clients table to check that whether your supplied client_id and client_secret exists for password grant flow in your oauth server. And also you don't manually change the type of client by simply switching the value of that column, you have to create a new client for password grant type.
php artisan migrate

This command will migrate the laravel/passport migration file to generate two default clients for each type that laravel/passport currently supported. You can also create a client for password grant flow with
php artisan passport:client --password

When you have a new client for password grant type, try POSTing again to /oauth/token to generate a token with your new generated client_id and client_secret

A: Make sure you are not trying to obtain a token with a hashed client_secret...
If you are hashing the client secrets with Passport::hashClientSecrets(); within AppServiceProvider, the tokens generated will only be shown in the terminal output once. Loose this token and it is lost forever.
I was in a rush when I set my passport up and forgot that I was hashing the generated client secrets...
My request body should have contained a non-encrypted client secret, but instead I copied and pasted an encrypted secret from the database.
To fix this, either save your client secrets right away, or remove Passport::hashClientSecrets(); and create a new client.

A: This might help point you in the right direction because we're implementing the password grant ourselves.
1 - On your step 4 instead of running this:
php artisan passport:install

run the following to create your password grant Client:
php artisan passport:client --password

The above command will give a followup question to set the name of your Password Grant Client. Be sure to get the id and secret of this new record in your database.
2 - Your POSTMAN Post request object should be wrapped inside an object similar to the following:
'form_params' => [
    'grant_type' => 'password',
    'client_id' => 'my_client-id',
    'client_secret' => 'my_client-secret',
    'username' => 'username or email', <-pass through variables or something
    'password' => 'my-user-password', <- pass through variables or something
    'scope' => '',
],

Update 1 10/12/2016:
On further investigation of this issue I ran into the exact same spot you're at and was forced to dive into the rabbit hole of passport.
Currently from what I'm seeing the system has set the client identifier as 'authorization_code' when it needs to be 'password'. I'm researching how to resolve this issue you're having as I've ran into it too. I will post code to help people follow along where I've been and what I've been doing but it's 2:40 am right now so I need some sleep.
Update 2 10/12/2016
Been debugging the issue for 7 hours now. There is a method within passport that validates the client. This method takes the inputs you've added in the object (mentioned above) and attempts to get the Client Entity through a client repository class based on what you've passed in. If a Client is found it will then be checked to see if an instance of the Client Entity truly exists within the Client Entity Interface which LOOKS like it pulls in the Client's credentials from the database. However, there is a block of code which returns NULL From what I'm getting in my testing. ALL fields are being introduced properly so far but there seems to be a mix-up between the repository and the interface. Which is causing the error to be thrown.
In the end I feel I'm getting close to solving this issue. Your patience is greatly appreciated. =)
Update 3 10/12/2016
After a long period of debugging I've found the initial problem. There were fields that weren't matching up. In short, it's a setup issue.
SO
The solution in this case is:
DOUBLE CHECK ALL FIELDS In the database with ALL credentials being passed in. Right down to periods, dashes, spaces passwords, client id, client secret, VALID redirect URIs/URLs, grant_types, and scopes (if you're using them):
Make sure the client in the database has an ENUM of 1 under the "password_client" column, if not you need to create one using the mentioned php artisan command above, which I'll reference here:
php artisan passport:client --password

Make sure the secret you're passing in matches what is listed for that client in your database character for character
Make sure the id you're passing matches and is of an integer data type.
Make sure there is a name of some sort for the client
Do not worry about the user_id column when using password grants
make sure the route is correct
Make sure the email your entering in (username) is an actual user inside of your users table within your database (or whatever table you customized the laravel 5.3 system to accept as your users table, I will add a link on how to customize laravel 5.3 system to accept a different users table as default if any need it).
Make sure the grant_type is spelled correctly
Make sure you're set up to accept the response bearer token (meaning the access_token and refresh_token).
Other than that, the initial steps I've outlined in the above part of this Answer should put you back on the right track. There are others here who did mention some similar steps that are helpful but address the same error that is related to a seperate issue as well (which I'm sure is a result of a setup issue related to their specific system setup).
I hope this helps though.

A: I had the same issue, and got fixed by setting basic.auth headers, with client_id as username and secret as password.
Then it worked fine.

A: Check thoroughly the Grant Type.
{
    "grant_type": "password",
    "client_id": 2,
    "client_secret":
    "username": ,
    "password":
    "scope": ""
}

In the above example, it says password. Now check the table: oauth_clients
and make sure that the value of column password_client = 1
or look for the entry with the password_client = 1

A: Try commenting out this line Passport::hashClientSecrets(); in the AppServiceProvider file. You cant use hashed client secrets.

A: I have managed to get the Laravel Passport - Password_Grant_Token working through RESTED(POSTMAN like service) without any additional controllers or middlewares. Here is how I've managed to do it!
Install the default Auth-Scaffolding in laravel doc's here
Install the passport doc's here
Register a user through auth-scaffolding
Goto RESTED or POSTMAN, or any other like service
Check data in oauth_clients table for your form_params
With RESTED through Request_body_form_data not headers write yours forms_params and send a POST request to */oauth/token (full url required)(required form_params are grant_type, client_id, client_secret, username and password)
You should get in return an object with 4 keys (token_type, expires_in, access_token & refresh_token) and a status of 200 OK.
If all was succesfull so far...
Open another RESTED window:
Send a GET request to /api/user (again full url required)
In headers write 2 name-value pairs (Accept => application/json, Authorization => Bearer ACCESS_TOKEN_GOTTEN_IN_PREVIOUS_REQUEST (to /oauth/token)
And that should be it. You should get an user object as response from /api/user.

A: Try creating a new password client using  php artisan passport:client --password
then most probably an user wont be assigned to that password client. edit the database row and add an exsting user id to it.
{
    "grant_type": "password,"
    "client_id": "" <- edited and added user id
    "client_secret": "8BU......," <- new secret
    "username": "test@gmail.com," <- email of above added user id
    "password": "123456,"<- password
    "scope": ""
}

Hope you will be able to get token now

A: Check the redirect/callback url when the client is set up on the passport server. Check the entry where you get the client ID and secret from that the Redirect URL is correct.
I was getting the same error and found the Redirect URL wasn't correct.
It needs to be pointing to the /callback route (in the examples that Taylor gives)

A: I was also facing the same issue , i got the solution from this link. Please check that.
https://github.com/laravel/passport/issues/71
It says that :
You make a call to /oauth/token just like you always would to get your token. But do so with a grant_type of custom_request. You'll need to add a byPassportCustomRequest($request) method to your User model (or whatever model you have configured to work with Passport). That method will accept a Illuminate\Http\Request and return the user model if you are able to authenticate the user via the request, or it will return null.

A: if you tried everything and still it's not working means try this solution!!
just give  scope  *.
$query = http_build_query([
    'client_id' => 1,
    'redirect_uri' => 'http://localhost:3000/callback',
    'response_type' => 'code',
    'scope' => '*'
]);

in my case this is the solution. I have checked

A: I had the same problem. When you execute php artisan passport:install it issues you with two types of secrets, one for CLIENT grant type, and other for PASSWORD grant type.
I was using the CLIENT secret to issue PASSWORD tokens. Once I changed that up, I was able to generate the access_token and refresh_token normally.

A: In my case, the solution was to wrap it inside Form-data,
don't miss it out if you use normal parameters with the postman, it won't work,
make sure to use a body request set to FORM-DATA.

A: Hopefully this will save someone the hour I spent debugging this problem:
I went down the rabbit hole to find out why authentication wasn't working. Turned out I was hashing my password in my UsersTableSeeder twice by accident, which is why the hash check failed.
Might be worth checking if the other answers listed don't work for you.

A: I fixed it by making sure that in the oauth_clients table my client has column password_client set to 1:
Source: https://github.com/laravel/passport/issues/589#issuecomment-357515110

There may be quite scenarios for the above issue.I will explain it one
by one. You always need to pass application/json header .

*

*Make sure the client id and secret is in the oauth_clients and you
passed those parameter correctly.In order to generate those client id
and secret use php artisan passport:install.

*Make sure to use password
grant client . To identify that goto oauth_clients table and check if
password_client is set to 1 and personal_access_client is set to 0 and
revoked to 0 . I hope this will solve the issue . Thank you

A: In laravel 9.x, the error : Client authentication failed will also be thrown if you have Passport::hashClientSecrets() in your AuthServiceProvider boot method. Am not sure why, but removing it just saved me time.

A: you can define a two variables like
$client_id = '111';
$client_secret = '1212';

and the condition is in your function like this
protected $clientID = '578324956347895';
protected $clinetSecret ='hflieryt478';

public function index(Request $request)
{

    if (!($request->input('clientID') && $request->input('clinetSecret'))) {
        return false;
    }

    $project = User::all();

   return $project
}

A: I was having this same issue, I tried all the above solutions, no success.
So i just reloaded the tables, recreated the user, the passport client and solved. My solution was reset everything:
php artisan migrate:fresh (will clean your database.)
php artisan passport:client --password


text:
Q: Why the preposition OF in Keats's "... as those whose sobbings were heard [of] none beside the mournful robins"? Written by John Keats in February 1817, on the blank space of a leaf at the end of Chaucer's "Tale Of The Flowre And The Lefe".

This pleasant tale is like a little copse:
  The honeyed lines so freshly interlace,
  To keep the reader in so sweet a place,
  So that he here and there full-hearted stops;
  And oftentimes he feels the dewy drops
  Come cool and suddenly against his face,
  And, by the wandering melody, may trace
  Which way the tender-legged linnet hops.
  Oh! what a power has white simplicity!
  What mighty power has this gentle story!
  I, that do ever feel athirst for glory,
  Could at this moment be content to lie
  Meekly upon the grass, as those whose sobbings
  Were heard of none beside the mournful robins.

Shouldn't it be by?

I, that do ever feel athirst for glory,
  Could at this moment be content to lie
  Meekly upon the grass, as those whose sobbings
  Were heard by none beside the mournful robins.

The robins heard the sobbings.
The sobbings were heard by the robins.
Why is there the preposition of then?

A: In Middle English of was the ordinary preposition for indicating the agent of a passive verb or participle. According to OED 1, s.v. Of, V.:

The regular word for this is now By (sense 33), which began to come in c 1400; but of prevailed till c 1600, and is still in literary use, as a biblical, poetic, or stylistic archaism, or by association with other constructions, e.g. 'on the part of'.

Of is still used in this sense with several participial adjectives, such as terrified, frightened, born, forsaken; with adjectives characterizing conduct, such It was kind/stupid/careless/generous of you; in the "subjective genitive" construction, the action of so-and-so; and designating authors and artists of works, the tragedies of Shakespeare.


text:
Q: What SQLite command can replicate empty fields from a prior row? I am importing some data into sqlite, where some columns use an empty value to indicate that the value is the same as the previous row's value.
How can I accomplish this purely in SQLite SQL?  I have a row number that indicates ordering.
For example, after importing and processing with-blank, it should appear to be identical to importing non-blank.
$ cat with-blank.csv
n,x,y
1,aaa,foo
2,,bar
3,,baz
4,bbb,able
5,,baker

cat non-blank.csv
n,x,y
1,aaa,foo
2,aaa,bar
3,aaa,baz
4,bbb,able
5,bbb,baker

sqlite> .mode csv
sqlite> .import with-blank.csv t

Note: Not a duplicate of Fill empty cells in excel sheet (or SQLite) with the value of nearest filled cell above, which includes Excel as a potential solution.
I'm looking for the Pure SQL command which can do this.  I can of course do this as a preprocessing step prior to importing into SQLite, but I would like to learn what commands, if any, can do this in SQLite.

A: After you have imported the table, you can update the empty column values by using a correlated subquery:
UPDATE tablename AS t1
SET x = (
  SELECT t2.x
  FROM tablename t2
  WHERE t2.n < t1.n AND COALESCE(t2.x, '') <> ''
  ORDER BY t2.n DESC LIMIT 1
)
WHERE COALESCE(t1.x, '') = '';

See the demo.


text:
Q: Add on to a nested object via Object.assign Let's say I have an object
   let sampleObject = {
        "child1": [
            {"id": "id1"},
            {"id": "id2"}
        ]
    };

Is there a way to add another nested property after sampleObject has already been declared?
I want sampleObject to look like
    sampleObject = {
        "child1": [
            {"id": "id1"},
            {"id": "id2"}
         ],
        "child2":[
            {"id": "id3"}
         ]
            };

I tried something like
Object.assign(sampleObject, "child2": [ "id" : "id3" ]); of which is giving syntax errors.
I guess my question is if this is possible via Object.assign and if not, how can I do so?
Thank you!

A: So there's multiple ways you can do this.  The most straightforward way is just adding a new property manually.
const sampleObject = {
  child1: [
    {id: 'id1'},
    {id: 'id2'}
  ]
}

sampleObject.child2 = [{id: 'id3'}]

If this doesn't work in your circumstance, you could try Object.defineProperty(). read more about Object.defineProperty
const sampleObject = {
  child1: [
    {id: 'id1'},
    {id: 'id2'}
  ]
}

Object.defineProperty(sampleObject, 'child2', {
  value: [{id: 'id3'}]
})

Finally, if you want to use Object.assign() you can, but this is mostly for merging two or more objects.  This is a good way to provide defaults, and then optionally override them. read more about Object.assign
const sampleObject = {
  child1: [
    {id: 'id1'},
    {id: 'id2'}
  ]
}

const sampleObject2 = {
  child2: [
    {id: 'id3'}
  ]
}

Object.assign(sampleObject, sampleObject2)

Update: as mentioned by @Ryan Nghiem, you can also use the spread operator (...) in a similar way, though I would discourage reassigning the original variable.  This will "spread" out each property from the original object as properties of the new one. read more about the spread operator
const sampleObject = {
  child1: [
    {id: 'id1'},
    {id: 'id2'}
  ]
}

const sampleObject2 = {
  ...sampleObject,
  child2: [
    {id: 'id3'}
  ]
}

A: With ES6, you can use three dots ...
sampleObject = {...sampleObject, {"child2": { "id" : "id3" }}


text:
Q: usar  con imagenes que no estan en el proyecto sino en el disco local Tengo un problema al usar  con imagenes que no estan en el proyecto sino en el disco local, el p:galleria aparece con 4 cuadritos (por las 4 imagenes) pero esta en blanco y me muestra el alt a pesar de que en la carpeta si estan las imagenes
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"
 xmlns:f="http://java.sun.com/jsf/core"
 xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui"
 template="/WEB-INF/templates/layoutnormal.xhtml">

    <h:form id="form">
 <p:galleria id="galeria" value="#{bean.listaImagenes}" var="image" panelWidth="400" panelHeight="313" showCaption="true">
<p:graphicImage name="#{image}" title="#{image}" alt="#{image}" /> </p:galleria>
</h:form>
</ui:composition>

Bean.java
@ManagedBean(name = "bean")
@ViewScoped
public class Bean extends GenericBean implements Serializable {
List<String> listaImagenes = new ArrayList<>();

@PostConstruct
public void init(){
listaImagenes.add("C:/fotos/img/img1.png");
listaImagenes.add("C:/fotos/img/img2.png");
listaImagenes.add("C:/fotos/img/img3.png");
listaImagenes.add("C:/fotos/img/img4.png");
}
}


text:
Q: c# winform to select a web page dropdown option I am building a application to fill out web forms and I can fill out the text fields but have not been able to figure out how to handle selecting from a drop-down list.
I am able to get it to place the Focus on the element but not able to get set the drop down option.  This is what I have been trying to do to select the drop-down.
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    webBrowser1.Document.GetElementById("BirthMonth").Focus();
    webBrowser1.Document.GetElementById("BirthMonth").InvokeMember("click");
}

private void button1_Click(object sender, EventArgs e)
{
    webBrowser1.Navigate("https://accounts.google.com/SignUp");
}

A: You have to set the "SelectedIndex" property to the integer index of the entry you want.

A: If you're building an aspx web page, you can use the SelectedValue attribute. For eg, DropDownlist.SelectedValue.toString(). That should give you the selected value from the web page.


text:
Q: org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: java.lang.ClassNotFoundException: com.isomorphic.base.InitListener Some background first: Our main objective is to have a reduced development environment in SmartGWT integrated with Maven, to be able to test some of the components and validate if we can use them in our software.
I set the environment, and update the Maven dependencies, but when I deploy the aplication into the Glassfish server, an exception is thrown.
TL;DR: In order to deploy the application, I ran this goal clean compile gwt:compile war:war, after that, I tried to deploy the project in Glassfish (using "Add/Remove") but it failed and threw the exception below
[2021-03-16T17:07:59.614-0500] [glassfish 4.1] [SEVERE] [AS-WEB-CORE-00108] [javax.enterprise.web.core] [tid: _ThreadID=221 _ThreadName=admin-listener(6)] [timeMillis: 1615932479614] [levelValue: 1000] [[
    ContainerBase.addChild: start:
    org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: java.lang.ClassNotFoundException: com.isomorphic.base.InitListener
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5898)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:691)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1041)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:1024)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:747)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2286)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1932)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:139)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:291)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:352)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:500)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:748)
    Caused by: java.lang.IllegalArgumentException: java.lang.ClassNotFoundException: com.isomorphic.base.InitListener
    at org.apache.catalina.core.StandardContext.addListener(StandardContext.java:3302)
    at org.apache.catalina.core.StandardContext.addApplicationListener(StandardContext.java:2508)
    at com.sun.enterprise.web.TomcatDeploymentConfig.configureApplicationListener(TomcatDeploymentConfig.java:251)
    at com.sun.enterprise.web.TomcatDeploymentConfig.configureWebModule(TomcatDeploymentConfig.java:110)
    at com.sun.enterprise.web.WebModuleContextConfig.start(WebModuleContextConfig.java:264)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:486)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:163)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5895)
    ... 49 more
Caused by: java.lang.ClassNotFoundException: com.isomorphic.base.InitListener
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1783)
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1633)
    at org.apache.catalina.core.StandardContext.loadListener(StandardContext.java:5446)
    at com.sun.enterprise.web.WebModule.loadListener(WebModule.java:1788)
    at org.apache.catalina.core.StandardContext.addListener(StandardContext.java:3300)
    ... 56 more
]]

I have tried some of the solutions related to this exception, but none of them have worked at my end.

*

*I'm working with:

*

*SmartGWT 6.0 Pro (6.0-p20170526)

*Project based on built-in-ds sample (from SGWT)

*JDK 1.8.0_241

*GWT Libraries 2.8.1

*Eclipse 2020-03 (4.15.0) Build id: 20200313-1211

*Glassfish 4.1

*Apache Maven 3.6.3

*Here is the pom.xml configuration I used:
 <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

 <modelVersion>4.0.0</modelVersion>
 <groupId>co.focuss</groupId>
 <artifactId>SamplesSGWT</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>SamplesSGWT</name>

 <properties>

     <!-- Explictly specify a default encoding to avoid relying on the OS locale. -->
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

     <!-- Artifact versions -->
     <gwt.version>2.8.0</gwt.version>
     <smartgwt.version>6.0-p20170526</smartgwt.version>
     <asm.version>5.0.3</asm.version>
     <dbcp.version>1.4</dbcp.version>
     <sqlserver.version>4.2</sqlserver.version>
     <servlet.api.version>3.0.1</servlet.api.version>
     <jstl.version>1.2</jstl.version>
     <junit.version>4.11</junit.version>
     <slf4j-log4j.version>1.7.12</slf4j-log4j.version>

     <!-- Maven GWT compiler version and parameters -->
     <maven.compiler.version>3.3</maven.compiler.version>
     <maven.compiler.source>1.8</maven.compiler.source>
     <maven.compiler.target>1.8</maven.compiler.target>
     <compiler.style>OBF</compiler.style>
     <compiler.log.level>INFO</compiler.log.level>
     <glassfish.port>8188</glassfish.port>

     <!-- Maven War plugin version and parameters -->
     <war.plugin.version>2.6</war.plugin.version>

 </properties>

 <dependencies>

     <!-- Core: GWT -->
     <dependency>
         <groupId>com.google.gwt</groupId>
         <artifactId>gwt-servlet</artifactId>
         <version>${gwt.version}</version>
         <scope>runtime</scope>
     </dependency>

     <dependency>
         <groupId>com.google.gwt</groupId>
         <artifactId>gwt-user</artifactId>
         <version>${gwt.version}</version>
         <scope>provided</scope>
     </dependency>

     <!-- Core: SmartGWT -->
     <dependency>
         <groupId>com.isomorphic.smartgwt.pro</groupId>
         <artifactId>smartgwt-pro</artifactId>
         <version>${smartgwt.version}</version>
     </dependency>

     <!-- Core: SmartGWT Sql Tools -->
     <dependency>
         <groupId>com.isomorphic.smartgwt.pro</groupId>
         <artifactId>isomorphic-sql</artifactId>
         <version>${smartgwt.version}</version>
     </dependency>

     <!-- Additional Dependency: required for proper SmartGWT dev tools compilation -->
     <dependency>
         <groupId>org.ow2.asm</groupId>
         <artifactId>asm</artifactId>
         <version>${asm.version}</version>
         <scope>compile</scope>
     </dependency>

     <!-- Core: SmartGWT Developer Tools -->
     <dependency>
         <groupId>com.isomorphic.smartgwt.pro</groupId>
         <artifactId>isomorphic-tools</artifactId>
         <version>${smartgwt.version}</version>
     </dependency>

     <!-- Additional SmartGWT Dependencies: DBCP2-->
     <dependency>
         <groupId>commons-dbcp</groupId>
         <artifactId>commons-dbcp</artifactId>
         <version>${dbcp.version}</version>
     </dependency>

     <!-- SQL Server JDBC Driver -->
     <dependency>
         <groupId>com.microsoft.sqlserver</groupId>
         <artifactId>sqljdbc</artifactId>
         <version>${sqlserver.version}</version>
     </dependency>

     <!-- Servlets -->
     <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>javax.servlet-api</artifactId>
         <version>${servlet.api.version}</version>
     </dependency>

     <!-- JSTL for JSP page -->
     <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>jstl</artifactId>
         <version>${jstl.version}</version>
     </dependency>

     <!-- Unit Tests: JUnit -->
     <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>${junit.version}</version>
     </dependency>

     <!-- Logging: Slf4j -->
     <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-log4j12</artifactId>
         <version>${slf4j-log4j.version}</version>
     </dependency>

     <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-api</artifactId>
         <version>${slf4j-log4j.version}</version>
     </dependency>

 </dependencies>

 <build>

     <!-- This will produce a war file named SamplesSGWT.war, rather than
         SamplesSGWT-${project.version}.war. -->
     <finalName>SamplesSGWT</finalName>

     <!-- Make sure classes output dir matches hosted webapp WEB-INF/classes
         folder, so GWT Hosted browser can see the classes. -->
     <directory>target</directory>
     <outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>

     <plugins>

         <!-- Plugin to compile Java code to JavaScript -->
         <plugin>
             <groupId>org.codehaus.mojo</groupId>
             <artifactId>gwt-maven-plugin</artifactId>
             <version>${gwt.version}</version>

             <executions>
                     <execution>
                         <goals>
                             <goal>compile</goal>
                             <goal>generateAsync</goal>
                             <goal>test</goal>
                         </goals>
                     </execution>
             </executions>

             <configuration>

                     <!-- Compiler parameters -->
                     <extraJvmArgs>-Xss1024K -Xmx1024M</extraJvmArgs>
                     <draftCompile>true</draftCompile>
                     <debugSuspend>false</debugSuspend>
                     <logLevel>${compiler.log.level}</logLevel>
                     <style>${compiler.style}</style>

                     <!-- Launch parameters with external server -->
                     <!-- Add the app to Glassfish embedded server and set the server to
                          publsh automatically after each compile -->
                     <noServer>true</noServer>
                     <runTarget>http://localhost:${glassfish.port}/${project.build.finalName}/${project.build.finalName}.html</runTarget>

                     <!-- Build parameters -->
                     <buildOutputDirectory>${project.build.outputDirectory}</buildOutputDirectory>
                     <hostedWebapp>${project.build.directory}/${project.build.finalName}</hostedWebapp>
                     <copyWebapp>true</copyWebapp>

             </configuration>

         </plugin>

         <!-- Plugin to compile the project. Included here only to specifically
              define the source and target versions of the project -->
         <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-compiler-plugin</artifactId>
             <version>${maven.compiler.version}</version>
             <configuration>
                     <source>${maven.compiler.source}</source>
                     <target>${maven.compiler.target}</target>
             </configuration>
         </plugin>

         <!-- Plugin to package in war file -->
         <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-war-plugin</artifactId>
             <version>${war.plugin.version}</version>
             <configuration>
                 <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
                 <!-- Exclude what you want from the final artifact here -->
                 <!-- <warSourceExcludes>.gwt-tmp/**</warSourceExcludes> -->
             </configuration>
         </plugin>

     </plugins>
 </build>

Would you please help me with to find out what is causing this error and how could I solve it.
If you need anything else to review this case, just let me know.
I thank you in advance for all the help you can provide!


text:
Q: NSKeyedArchiver for multiple objects, without NSMutableArray I need to save to disk a large amount of custom objects (the amount is the reason why I cant just fill an array and then save it).
My custom object contains info about a person, such as name and age.
I want to save all objects in the same file at Documents directory using NSKeyedArchiver.
Ideally, I want to have no more than 100 objects on memory, so if I have to save 2000 objects to disk, I will save 20 packages of 100 objects.
I also want the key for each object to be object.name.
Any ideas? Thanks!


text:
Q: Where is the source code of CallObjectMethod in jni.h I searched for the method definition of CallObjectMethod method declared in the file jni.h in OpenJDK 8. However, I can't find it.
Where is the source code of the method CallObjectMethod?
I am studying JDK for the aim of researching. I need to know the JDK entirely.

A: It is defined in jni.cpp
by DEFINE_CALLMETHOD macro.


text:
Q: Rails3: How to pass param into custom will_paginate renderer? I've got a custom will_paginate renderer that overrides WillPaginate::ViewHelpers::LinkRenderer's link method like so:
   def link(text, target, attributes = {})
      "#{text}"
   end

...and that works great, except you can see the hard-coded 95 in that link. How would I pass a parameter (e.g. user or user's ID) into the custom renderer via the Rails view?
<%= will_paginate(@user_friends, :remote => true, :renderer => FriendsRenderer) %>

Or is there something I'm missing, some easier way to do it?
BTW: @user_friends isn't available in the custom renderer, and I've already tried just adding params onto the end of that will_paginate call, e.g. :user => user)

A: View:
<%= will_paginate @user_friends, :renderer => 'FriendsRenderer',
                         :remote => true,
                         :link_path => friends_widget_user_path(@user) %>

class FriendsRenderer < WillPaginate::LinkRenderer
  def prepare(collection, options, template)
    @link_path = options.delete(:link_path)
    super
  end

protected
  def link(page, text, attributes = {})
    # Here you can use @link_path
  end
end

Note that this works for the will-paginate version: 2.3.6

A: will_paginate lets you pass in :params for the links:
will_paginate(@user_friends, :params => { :user_id => 95 })


text:
Q: Why do I get error Uncaugt ReferenceError while it works on other website? My goal is to get the tool working on the website: one-stop-office-shop.nl
My tool works on codepen.io (https://codepen.io/teun-van-lith/pen/mdwNYJN)

<form name="rekenen" /><input onclick="tcoberekenen()" id="input" name="aantalzwart" />

x zwart

€
<input id="output" name="zwarttotaal" />
<input onclick="tcoberekenen()" id="input" name="aantalkleur" />

x kleur

€
<input id="output" name="kleurtotaal" />

Totale afdrukkosten:

€
<input id="outputtotaal" name="totaal" />
</form>

`

and in a standard html.
There is even this website where to tool works.
https://training.2thenext.nl/i/Rekentool.html
Link to website where it doesn't work:
https://www.one-stop-office-shop.nl/artikel/225638/laserprinter-brother-hl-l9310cdw.html
Error:
Uncaught ReferenceError: tcoberekenen is not defined
at HTMLInputElement.onclick (laserprinter-brother-hl-l9310cdw.html:1146)
The code is the same. I just don't get it.


text:
Q: Why progress html element not showing on email (gmail or hotmail), is there any way to show it, and why Nunito google font does not work on emails? I tried using  element and using Nunito font with the external link but does not work on emails
<progress value="10" max="100">10%</progress>

A: For Nunito:
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Nunito" />

/* This text is in Nunito */
.class {
  font-family: Nunito;
}

You could try out this one for your progress bar:


text:
Q: Spark split a column value into multiple rows My problem is I have a table like this:
------------------------
A  B    C
------------------------
a1 b2   c1|c2|c3|c4

c1|c2|c3|c4 is one value separated by |.
My final result should look like this:
---------
A  B   C
---------
a1 b1  c1
a1 b1  c2
a1 b1  c3
a1 b1  c4

How do I do this?
Thanks

A: This is what you could do, split the string with pipe and explode the data using spark function
import org.apache.spark.sql.functions._
import spark.implicits._

val df = Seq(("a1", "b1", "c1|c2|c3|c4")).toDF("A", "B", "C")

df.withColumn("C", explode(split($"C", "\\|"))).show

Output:
+---+---+---+
|  A|  B|  C|
+---+---+---+
| a1| b1| c1|
| a1| b1| c2|
| a1| b1| c3|
| a1| b1| c4|
+---+---+---+

Hope this helps!


text:
Q: Why does converting a blank string to a date in SQL Server result in 1900-01-01? Running a simple T-SQL query of SELECT CONVERT(date, '') will render a result of 1900-01-01. It seems to me that it would be more consistent to convert a blank string to either 1753-01-01 (the minimum allowable date value) or NULL. 1900 just seems so arbitrary, but I assume this was a deliberate design choice made by the MS SQL programmers. What is the purpose of this functionality?

A: It is due to implicit conversion. The 0 date in sql server is 1/1/1900. Any dates earlier than that are a negative number.

A: SQL Server datetime calendar start point is start of day of 01 January 1900.
https://stackoverflow.com/a/17071583/7974050


text:
Q: How to update my UseEffect component to render new UI after a successful user login I have a login component that after the user have login, I went ahead to get the data to my local storage and if the login is successeful, which means the data is true, I want to update my component by redirecting the user another components and update my component with the user information. Right now the login went successfully and data been passed to the local storage, but, I don't get redirected, because in the next componet, the update is not happening. and in my console logs waning error that said "Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."
here is my login component
const user = JSON.parse(localStorage.getItem("user"));

const applicationForm = {
  firstname: "",
  lastname: "",
  middlename: "",
  gender: "",
  dob: "",
  phone: "",
  email: "",
  country: "",
  crr_state: "",
  institution: "",
  fac_dept: "",
  year_entry: "",
  matric_number: "",
  student_status: "",
  edu_level: "",
  applying_as: "",
  team_members: "",
  idea_grant: "",
  category: "",
  current_status: "",
  area_of_interest: "",
  formStatus: "Save and Continur later",
  id: user ? user._id : "",
  idea_summary: "",
  video_url: "",
  textChange: "Sumbit",
};

const NUICAppForm = () => {
  const [formData, setFormData] = useState(applicationForm);
  const [states, setStates] = useState(null);

  const categoryList = [
    "Renewable Energy Technologies",
    "Satellite Communication Technologies",
    "Drone Technologies",
    "E-commerce Development",
    "Smart AgricTech",
    "Mobile Computing and 5G Networks",
  ];

  const {
    firstname,
    lastname,
    middlename,
    gender,
    dob,
    phone,
    email,
    country,
    crr_state,
    institution,
    fac_dept,
    year_entry,
    matric_number,
    student_status,
    edu_level,
    current_status,
    applying_as,
    team_members: {
      memberFullname1,
      memberEmail1,
      memberPhone1,
      memberFullname2,
      memberEmail2,
      memberPhone2,
      memberFullname3,
      memberEmail3,
      memberPhone3,
      memberFullname4,
      memberEmail4,
      memberPhone4,
      memberFullname5,
      memberEmail5,
      memberPhone5,
    },
    idea_grant,
    category,
    area_of_interest,
    idea_summary,
    video_url,
    formStatus,
    id,
    textChange,
  } = formData;

  const clear = () => {
    window.localStorage.clear();
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    setFormData({ ...formData, textChange: "Submitting" });
    axios
      .post("https://i-next-backend.herokuapp.com/nuic/form/register", {
        firstname,
        lastname,
        middlename,
        gender,
        dob,
        phone,
        email,
        country,
        crr_state,
        institution,
        fac_dept,
        current_status,
        year_entry,
        matric_number,
        student_status,
        edu_level,
        applying_as,
        team_members: {
          memberFullname1,
          memberEmail1,
          memberPhone1,
          memberFullname2,
          memberEmail2,
          memberPhone2,
          memberFullname3,
          memberEmail3,
          memberPhone3,
          memberFullname4,
          memberEmail4,
          memberPhone4,
          memberFullname5,
          memberEmail5,
          memberPhone5,
        },
        idea_grant,
        category,
        area_of_interest,
        idea_summary,
        formStatus,
        video_url,
        id: user._id,
      })
      .then((res) => {
        setFormData({
          ...formData,
          firstname: "",
          lastname: "",
          middlename: "",
          gender: "",
          dob: "",
          phone: "",
          email: "",
          country: "",
          crr_state: "",
          current_status: "",
          institution: "",
          fac_dept: "",
          year_entry: "",
          matric_number: "",
          student_status: "",
          edu_level: "",
          applying_as: "",
          team_members: {
            memberFullname1: "",
            memberEmail1: "",
            memberPhone1: "",
            memberFullname2: "",
            memberEmail2: "",
            memberPhone2: "",
            memberFullname3: "",
            memberEmail3: "",
            memberPhone3: "",
            memberFullname4: "",
            memberEmail4: "",
            memberPhone4: "",
            memberFullname5: "",
            memberEmail5: "",
            memberPhone5: "",
          },
          idea_grant: "",
          category: "",
          area_of_interest: "",
          idea_summary: "",
          video_url: "",
          id,
          textChange: "Application submitted for review ",
          formStatus: "Pending application",
        });
        setFormData({
          ...formData,
          textChange: "Application Submitted",
          formStatus: "Application Pendig",
        });
      })
      .catch((err) => {
        setFormData({
          ...formData,
          firstname: "",
          lastname: "",
          middlename: "",
          gender: "",
          dob: "",
          phone: "",
          email: "",
          country: "",
          crr_state: "",
          current_status: "",
          institution: "",
          fac_dept: "",
          year_entry: "",
          matric_number: "",
          student_status: "",
          edu_level: "",
          applyisng_as: "",
          team_members: {
            memberFullname1: "",
            memberEmail1: "",
            memberPhone1: "",
            memberFullname2: "",
            memberEmail2: "",
            memberPhone2: "",
            memberFullname3: "",
            memberEmail3: "",
            memberPhone3: "",
            memberFullname4: "",
            memberEmail4: "",
            memberPhone4: "",
            memberFullname5: "",
            memberEmail5: "",
            memberPhone5: "",
          },
          idea_grant: "",
          category: "",
          area_of_interest: "",
          idea_summary: "",
          video_url: "",
          formStatus: "",
          id,
        });
        setFormData({ ...formData, textChange: err.response.data.message });
      });
  };

  useEffect(() => {
    const fetchStates = async () => {
      const result = await axios(
        "https://nigerian-states-info.herokuapp.com/api/v1/states"
      );
      setStates(result.data.data);
    };
    fetchStates();
  }, [user]);

As you can see above in the useEffect, first I defined a function that check if the user exist outside the ueEffect which the chechking is true but can update when a user login, the I thought of using useState to passed that value but still, it did not works. Please any suggestion on how to update my component when the signin went through ?
Please help.....

A: Your useEffect only runs once and that is right after the component has been loaded. Right now its not aware of any other changes since you have given empty dependency array to it.
To suggest a solution in your case, why don't you just call
history.push("/application")

after you set the data to localStoare? That is after the line
localStorage.setItem("user", JSON.stringify(res.data));

and remove the useEffect

A: You can have a Force Update by React hooks.
Declare const [render, setRerender] = useState(false);
then call the following when you want to update the UI, setRerender(!rerender);


text:
Q: AGSLocalTiledLayer is not loading the map by using .tpk file I'm working on building a simple ios app by using arcgis ios map sdk. According to the guide if we want to load the map by using .tpk file we have to use AGSLocalTiledLayer class by specifying the name of the tpk file as below
import UIKit
import ArcGIS

class ViewController: UIViewController, AGSMapViewLayerDelegate {

    @IBOutlet weak var mapView: AGSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let tiledLayer = AGSLocalTiledLayer(name: "Layers")
        self.mapView.addMapLayer(tiledLayer, withName: "BaseMap")
        self.mapView.layerDelegate = self
    }

    func mapViewDidLoad(mapView: AGSMapView!) {
        print("Loaded")
    }
}

But its not loading the map even though I have that Layers.tpk in the project. Can anyone notify me where I am doing the mistake.

A: Most of the times while we are using files in the project bundle need to take care such that the added file is selected for the project structure in the attribute inspector and while replacing such file when debugging care should be taken.


text:
Q: Convert array in string format from cell in pd.DataFrame to ndarray in python I got an dataframe where one column is image pixels as arrays in string format and I want to convert them to actual arrays.
Here an example where I printed one cell.
X[0] = `
[[[164 164 164]
  [164 164 164]
  [162 162 162]
  ...
  [ 54  54  54]
  [ 54  54  54]
  [ 54  54  54]]

 [[164 164 164]
  [164 164 164]
  [162 162 162]
  ...
  [ 54  54  54]
  [ 54  54  54]
  [ 54  54  54]]

 [[164 164 164]
  [164 164 164]
  [162 162 162]
  ...
  [ 54  54  54]
  [ 54  54  54]
  [ 54  54  54]]

 ...

 [[ 84  84  84]
  [ 84  84  84]
  [ 84  84  84]
  ...
  [ 50  50  50]
  [ 51  51  51]
  [ 51  51  51]]

 [[ 84  84  84]
  [ 84  84  84]
  [ 83  83  83]
  ...
  [ 51  51  51]
  [ 51  51  51]
  [ 51  51  51]]

 [[ 84  84  84]
  [ 84  84  84]
  [ 84  84  84]
  ...
  [ 51  51  51]
  [ 51  51  51]
  [ 51  51  51]]]

I tried doing it in a preprocessing step but that doesn't work
def preprocess(image):
  """
  Takes an image array, turns it into tensor and normalizes the values
  """

  image = tf.cast(np.ndarry(image), tf.float32)
  # turn arrays of data into tensors
  image = tf.convert_to_tensor(image, tf.float32)

  # normalize image
  image = image/255.0

  return image

preprocess(X[0])

EDIT (format the dataset to be a dataframe structure with arrays and labels):
def create_data(datadir):
  """
  Creates a list of images and their labels from a given directory (datadir)
  """
  for category in Classes:
    path = os.path.join(datadir, category)
    label = Classes.index(category)
    for image in os.listdir(path):
      try:
        image_array = cv2.imread(os.path.join(path,image))
        image = cv2.resize(image_array, (IMG_SIZE, IMG_SIZE))
        data.append([image, label])
      except Exception as e:
        pass
```
any alternative suggestions?

Thank you in advance


text:
Q: difference of proxy function and call backs No offense, but I may be asking a strange question. I am a beginner, learning advanced OOP, and confused about a few concepts. Coming to the point. It may be ridiculous. But can someone tell me exactly and correctly what does callback literary mean? And how it differs from a proxy class in C++ which we use for information hiding. Apologies in advance, if I missused the terminology.

A: From Wikipedia:

A callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code.

As for proxy classes, see this question.
It's two different things. An instance of a proxy class can be used as callback, but that's about the only relation I can see between them.

A: The idea of a call back is to start some action then do something else until the action completes.
An example from the real world is to telephone the plumber for a repair.  The plumber says they are currently at a work site and unable to see their schedule for the next day right now.  However the plumber says that they will be in the office later and will be able to check their schedule.  The plumber then promises to give you a call back once they are in the office and able to check the schedule.  You could then either sit down next to the telephone and wait for the return telephone call (blocking call back) or read a book or paint the house until the plumber calls back (deferred call back).
In C, a callback function is a function body that is specified as a callback.  The address of the function, a function pointer, is provided to the function being called to perform some kind of action.  When the action is completed the callback function is invoked to do something, usually some form of cleanup and/or notification.
Normally a callback is used when a function is called to start some action and then returns immediately to the caller before the action completes and its result is known.  The callback is used as a way to notify the result of the action when the started action is completed.
Another form of callback is to register a function for an event so that when the event happens, the function will be called to do something.  So you might specify a callback for when a mouse click event is received.
A proxy class is a class that acts as an interface for a class.  You could think of a proxy class as being similar to a stunt double who does the dangerous things for an actor.  Or a proxy for a share holder's meeting is a person or organization who stands in for the actual share holder to perform specific duties for the share holder.
A callback is not a proxy though a callback may be used by a proxy as part of the functionality required to do its proxy duties.


text:
Q: Universal Link open only base URL is it possible to set a path in the "paths" array inside the apple-app-site-association file that will open only the original domain in the application?
for example,
if my domain is
https://www.example.com
i want the app to be opened if a user clicks a link to
https://www.example.com
but not to
https://www.example.com/a

A: I didn't test solutions below, so I can't guarantee that they will work. At the same time they all are based on documentation, so they should. I currently don't want to invest time into setting up test environment for this, so that would be nice if you share your test results.
My first suggestion would be just this:
{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "%YOUR.APP.ID%",
        "paths": [
             "/"
        ]
      }
    ]
  }
}

If this didn't help, here's another go:
{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "%YOUR.APP.ID%",
        "paths": [
             "NOT /?*",
             "/*"
        ]
      }
    ]
  }
}

Here ? matches any single character, and * matches any substring, including empty. The idea in the second case is that the system might use the rules from top to bottom.

Because the system evaluates each path in the paths array in the order it is specified—and stops evaluating when a positive or negative match is found—you should specify high priority paths before low priority paths.
  https://developer.apple.com/library/archive/documentation/General/Conceptual/AppSearch/UniversalLinks.html?utm_source=revxblog

The third idea would be to at first exclude all the top level components you know then adding allow all. That might be really overwhelming, especially if you don't control paths or they change.


text:
Q: Index Match with Indirect and partial match? I have a Ztable that I want to use as a lookup in a formula based on whatever Zscore I get. I have a Z score of 0.84, and the way the table works is that the first column you look at 0.8 then go to column 0.04 as that is the second decimal of 0.84 (so they combine) and you get your lookup value.
I am trying to achieve this with an Index Match formula, though for some reason it refuses to work, even though all of the parts of the formula works fine separately:
Example in Excel Online: https://1drv.ms/x/s!ArOlf1rKamjocy6zekCl8cG3lAc?e=6ZzuTc
Whole formula:
=1-
INDEX(
INDIRECT("Table1[0.0"&RIGHT(E2,1)&"]"),
MATCH(
LEFT(E2,(FIND(".",E2,1)+1)),
Table1[Z],0))

0.84 is placed in E2
Separately I get 0.8 from this formula:
=LEFT(E2,(FIND(".",E2,1)+1))

..and I get a reference to column 0.04 with this formula:
=INDIRECT("Table1[0.0"&RIGHT(E2,1)&"]")

So why is the Index match formula failing? If I write the formula cleanly, I get 0.7995:
=INDEX(Table1[0.04],MATCH(0.8,Table1[Z],0))

A: You do not need INDIRECT. Try this formula:
=INDEX(Table1[[0]:[0.09]],MATCH(ROUNDDOWN(E2,1),Table1[Z],0),MATCH(TEXT((E2-ROUNDDOWN(E2,1)),"0.00"),Table1[[#Headers],[0]:[0.09]],0))

Change second column header from 0 to 0.00, otherwise the value with one decimal place will not be found.

A: The short answer is that the values in the 'Z' column are numeric, so you need to convert the string LEFT(E2,(FIND(".",E2,1)+1)) to a number before doing the lookup:
=1-INDEX(INDIRECT("Table1[0.0"&RIGHT(E2,1)&"]"),MATCH(--LEFT(E2,(FIND(".",E2,1)+1)),Table1[Z],0))

but @basic is right, there may be a better way of doing this without using Indirect.


text:
Q: Opencv 4 Android: Error in Mat() inizialization inside onCreate i wrote a code starting from the camera view tutorial. In the function "onCameraFrame()" I extract ORB features and draw them on the shownFrame. To this end I first declare and initialize both the detector, descriptor as well as the required arrays to handle the keypoints and the descriptors inside this function and all works well.
 public Mat onCameraFrame(CvCameraViewFrame inputFrame) {

    Mat shownFrame = inputFrame.rgba();

    Mat camDescriptors = new Mat();
    MatOfKeyPoint camKeypoints = new MatOfKeyPoint();

    DescriptorExtractor descriptor;

    //Feature detection
    FeatureDetector detector =  FeatureDetector.create(FeatureDetector.ORB);
    detector.detect(shownFrame, camKeypoints);

    //Feature description
    descriptor = DescriptorExtractor.create(DescriptorExtractor.ORB);
    descriptor.compute(shownFrame, camKeypoints,camDescriptors);

    //Drawing
    Imgproc.cvtColor(shownFrame, shownFrame, Imgproc.COLOR_RGBA2RGB);
    Features2d.drawKeypoints(shownFrame, camKeypoints, shownFrame, new Scalar(255,0,0,0),Features2d.DRAW_RICH_KEYPOINTS);

    Imgproc.cvtColor(shownFrame, shownFrame, Imgproc.COLOR_RGB2RGBA);

    return shownFrame;

but of course it should be better initialize the required objects before this process to save memory and computation. So i declared the detector, descriptor and so on as private variables of the Activity class. Then i've initializated them in the method OnCreate leaving just their use for matching in the onCameraFrame method. But what happens is that an error occur in the first row of onCreate method when i do "camDescriptors = new Mat()", the error is that the method Mat() is not found, and of course the application crashes.
the error message is something like this:
"no implementation found for native Lorg opencv Mat n_Mat: ()"


text:
Q: How to start intermediate ca using docker-compose? The steps which I have followed:
1) started the fabric with 1-ca(which is root ca), 1-orderer, 1-peer and 1-couchdb
2) I attached the shell to ca which is root and fire the 2 commands to
    register the intermediate ca.
  fabric-ca-client enroll -u http://admin:adminpw@localhost:7054
  fabric-ca-client register --id.name ica --id.attrs '"hf.Registrar.Roles=user,peer",hf.Revoker=true,hf.IntermediateCA=true' --id.secret icapw

3) I started the ca1 container as follows:
services:
  ca1.example.com:
    image: hyperledger/fabric-ca:x86_64-1.1.0
    environment:
      - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
      - FABRIC_CA_SERVER_PORT=8054
      - FABRIC_CA_SERVER_CA_NAME=ca1.example.com
    ports:
      - "8054:8054"
    command: sh -c 'fabric-ca-server start -b admin:adminpw -u http://ica:icapw@ca.example.com:7054'
    container_name: ca1.example.com
    networks:
      - basic

But it always creates default certificates so I removed all from container and then fire start command again and when I try to enroll admin using that intermediate ca it gives me following error:
signed certificate with serial number 619423114660023963149266564884451731119475746692
ca1.example.com    | 2018/09/20 06:38:53 [INFO] 127.0.0.1:47144 POST /enroll 500 0 "Certificate signing failure: Failed to insert record intodatabase: attempt to write a readonly database"

I am unsure about the process I followed. So suggest me the exact steps to follow and if the steps are correct then the cause of this error.
I have followed the documentation : https://hyperledger-fabric-ca.readthedocs.io/en/latest/users-guide.htm

A: Lets say you have a Root Fabric-CA ( lets call it RCA) server up and running.
As per my understanding, you are trying to start an Intermediate Fabric-CA server which would be attached to the RCA above.
What I tried is the following.
version: '2'
networks:  fabric-ca:

services:

ica:
container_name: ica
image: hyperledger/fabric-ca
command: /bin/bash -c '/scripts/start-intermediate-ca.sh 2>&1 | tee /data/logs/ica.log'
environment:
  - FABRIC_CA_SERVER_HOME=/etc/hyperledger/fabric-ca
  - FABRIC_CA_SERVER_CA_NAME=ica
  - FABRIC_CA_SERVER_INTERMEDIATE_TLS_CERTFILES=/data/rca-ca-cert.pem
  - FABRIC_CA_SERVER_CSR_HOSTS=ica
  - FABRIC_CA_SERVER_TLS_ENABLED=true
  - FABRIC_CA_SERVER_DEBUG=true
  - BOOTSTRAP_USER_PASS=ica-admin:ica-adminpw
  - PARENT_URL=https://rca-admin:rca-adminpw@rca:7054
  - TARGET_CHAINFILE=/data/ica-ca-chain.pem
volumes:
  - ./data:/data
  - ./scripts:/scripts
  - ./data/fabric_ca_test/ica:/etc/hyperledger/fabric-ca
networks:
  - fabric-ca
ports:
  - 10.10.10.101:7055:7054

Note the use of the script start-intermediate-ca.sh
#!/bin/bash
#
set -e

# Initialize the intermediate CA
fabric-ca-server init -b $BOOTSTRAP_USER_PASS -u $PARENT_URL

# Copy the intermediate CA's certificate chain to the data directory to be used by others
cp $FABRIC_CA_SERVER_HOME/ca-chain.pem $TARGET_CHAINFILE

# Start the intermediate CA
fabric-ca-server start --config $FABRIC_CA_SERVER_HOME/fabric-ca-server-config.yaml

This is also available in an example which is present in the Hyperledger Fabric Examples.
Fabric CA Samples in fabric-samples github Repository
Go through it. Its a comprehensive example.
You should be able to tweak it a bit to handle your scenario.

A: Well first of all, if you are having that kind of troubles I highly recommend to stop and clean all of the containers, running the following docker commands:
docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)

I will be base my explanation on the basic-network example.
After that you must start your containers calling you start.sh ir startFabric.sh that script usually has the docker-compose up who is responsable of starting your docker containers.
I'm not sure that you mean with default certificates, but if you have problem with those you can regenerate them. You probably have an generate.sh script that one generate the new crypto-config and the genesis.block and config, this one is based in two files configtx.yaml and crypto-config.yaml.
Be sure that your version of your crytogen tool is the same as the version that you are using, is very common to be pointing to an older version of the cryptogen tool this generates corruped certificates that won't work.
Well, if any of these solutions doesn't work, maybe you should start over, I wrote a guide based in that example (basic-network) of how to setup an Hyperledger Fabric in multiple physical hosts, maybe you can check it.
Setup Hyperledger Fabric in multiple physical machines


text:
Q: Does $(x_n)$ Cauchy in $\ell^1$ implies $(\|x_n\|_1)$ is Cauchy in $\mathbb F$ Define $\ell^1=\{x\colon\mathbb N\to\mathbb F: \|x\|_1~\mbox{is finite}\}$ where $\mathbb F$ is either $\mathbb R$ or $\mathbb C$. If $(x_n)$ is a Cauchy sequence in $\ell^1$, does that mean that $(\|x_n\|)$ is Cauchy in $\mathbb F?$

A: We have by triangular inequality,$$\lVert x_n\rVert\leq \lVert x_n-x_m\rVert+\lVert x_m\rVert$$
and switching $m$ and $n$ we get
$$|\lVert x_n\rVert-\lVert x_m\rVert|\leq \lVert x_n-x_m\rVert.$$
Now, we can deduce that $\{\lVert x_n\rVert\}$ is Cauchy: for a fixed $\varepsilon>0$, let $N$ such that $\lVert x_n-x_m\rVert\leq \varepsilon$ whenever $m,n\geq N$. Then $|\lVert x_n\rVert-\lVert x_m\rVert|\leq \varepsilon$ whenever $m,n\geq N$.
Note that it's true in any normed space, not only in $\ell^1$.

A: Hints:

*

*Let $u:E\to F$ be Lipschitz between two metric spaces $E$ and $F$. Then, if the sequence $(x_n)_{n\in\mathbb N}$ is Cauchy in $E$, the sequence $(u(x_n))_{n\in\mathbb N}$ is Cauchy in $F$.

*For any norm $\|\ \|$ on any vector space $E$, the map $u:E\to\mathbb R$, $x\mapsto\|x\|$, is $1$-Lipschitz.

*Conclude that the answer to your question is yes.


text:
Q: Node.js check if name matches mask I have a file mask in format like:
'/some/dir/*'

I want to match it with names:
'/some/dir/file1.txt'
'/some/dir/nested/file2.txt'

Is there a standard (common) solution in node.js to check whether name matches such mask?
I could convert mask to regExp, but I wonder if there more standard way of doing this?

A: The wildcard module can help you:
var wildcard = require('wildcard');
var pattern  = '/some/dir/*';
var files    = [
  '/some/dir/file1.txt',
  '/some/dir/nested/file2.txt',
  '/another/dir/file3.txt',
];

files.forEach(function(file) {
  console.log(file, 'match?', wildcard(pattern, file));
});


text:
Q: Undefined Reference to imp using mingw The problem I have is the "undefined reference to '_imp__...' " error that comes up when I build my project. I am using Windows 7, MinGW, Eclipse and .lib and .dll file that I did not make, but I took directly from the company that sold me their product.
I link with the -l command the HRDL.lib file and i have the PicoHRDL.dll at the same directory. The lib file is found (I'm sure about this), but the error comes up. I have included the complete path with the -L command. I have included the header file with the declarations of the functions, I get the undefined reference to, but the error is still there.
I have contacted both Eclipse support and Picotech support (the said company) but they weren't able to locate the problem till now.
These are the commands:
 gcc -O0 -g -Wall -c -fmessage-length=0 -o ACD_SOURCE.o "..\\ACD_SOURCE.c"
 gcc "-LC:\\Users\\Falamana\\Desktop\\Eclipse\\ADC_project1\\Libraries" -shared -o libADC_24_DataLogger_App.exe ACD_SOURCE.o -lHRDL

These are the errors:

ACD_SOURCE.o: In function `main':
C:\Users\Falamana\Desktop\Eclipse\ADC_project1\Debug/../ACD_SOURCE.c:70:
  undefined reference to `_imp__HRDLGetUnitInfo@16'
C:\Users\Falamana\Desktop\Eclipse\ADC_project1\Debug/../ACD_SOURCE.c:99:
  undefined reference to `_imp__HRDLCloseUnit@4'
ACD_SOURCE.o: In function `SelectUnit':
C:\Users\Falamana\Desktop\Eclipse\ADC_project1\Debug/../ACD_SOURCE.c:115:
  undefined reference to `_imp__HRDLGetUnitInfo@16'
C:\Users\Falamana\Desktop\Eclipse\ADC_project1\Debug/../ACD_SOURCE.c:167:
  undefined reference to `_imp__HRDLGetUnitInfo@16'

A: In my case it helpt to add -mwindows flag to linker options.

A: Note that in your compiling information, the -L option symbol should be out of the quote. That's to say, the
gcc "-LC:\Users\Falamana\Desktop\Eclipse\ADC_project1\Libraries" -shared -o libADC_24_DataLogger_App.exe ACD_SOURCE.o -lHRDL

should be
gcc -L"C:\Users\Falamana\Desktop\Eclipse\ADC_project1\Libraries" -shared -o libADC_24_DataLogger_App.exe ACD_SOURCE.o -lHRDL

So please check your configuration of the lib directory in whatever IDE you are using, util the gcc line of compiling information looks normal( util -L stands right ahead of the quote character).


text:
Q: Assign different values to each zone, ArcGIS 10 Is it possible to assign different values to each zone. The value would be decimal.
100==> 4.97
200==> 5.90
300==> 6.01
..ect...
1000==> 9.64
or somehow change value with cost raster.
I have DEM raster, buffer raster, reclass raster, poligon layer.

A: If you have Spatial Analyst, you can use Reclassify tool to change the old pixel values to new values.
However, The tool may not work with decimals (I did not test it with decimals), but I know it works with integer values. You can try with decimals, if it did not work, then multiply the new values with 100 to make it integer.
For example, use 100 -> 497 (integer) instead of 100 -> 4.97 (decimal). Then using raster calculator divide the output by 100 to get the values in decimals.


text:
Q: Getting error when installing Bugsnag 'Error: spawn npm ENOENT' this is the first time I post here so apologies if I don't follow some rules or incorrect formatting.
I'm making an app using React Native and Expo and when I try to install bugsnag I get this error.
$ npx bugsnag-expo-cli init
√ @bugsnag/expo does not appear to be installed, do you want to install it? ... yes
√ If you want the latest version of @bugsnag/expo hit enter, otherwise type the version you want ... latest
√ Using yarn or npm? » npm
> Installing @bugsnag/expo with npm. This could take a while!

  Error: spawn npm ENOENT
      at Process.ChildProcess._handle.onexit (internal/child_process.js:269:19)
      at onErrorNT (internal/child_process.js:465:16)
      at processTicksAndRejections (internal/process/task_queues.js:80:21)

A: Are you attempting to run the bugsnag-expo-cli on Windows? The Expo CLI currently only supports MacOS and Linux:
https://docs.bugsnag.com/platforms/react-native/expo/#installation-and-configuration
As an alternative to the CLI, you can follow the manual integration guide:
https://docs.bugsnag.com/platforms/react-native/expo/manual-setup/


text:
Q: Python3 pika channel.basic_consume() causing MySQL too many connections I had using pika to make a connection to RabbitMQ and consume message, once I start the script on ubuntu prod environment it is working as expected but is opening mysql connection and never closes them and ends up in Too many connection on mysql server.
Will appreciate any recommendation on the code below, as well can not understand what is going wrong. Thanking you in advance.
The flow is the following

*

*Starting pika on Python3

*Subscribe to a channel and waiting for messages

*In callback i do various validation and save or update data inside MySql

*The result that is showing the problem is the at the end of question a screenshot from ubuntu htop, that is showing new connection on MySql and keep adding them on the top

Pika Verion = 0.13.0
For MySql I use pymysql.
Pika Script
def main():
    credentials = pika.PlainCredentials(tunnel['queue']['name'], tunnel['queue']['password'])

    while True:
        try:
            cp = pika.ConnectionParameters(
                host=tunnel['queue']['host'],
                port=tunnel['queue']['port'],
                credentials=credentials,
                ssl=tunnel['queue']['ssl'],
                heartbeat=600,
                blocked_connection_timeout=300
            )

            connection = pika.BlockingConnection(cp)
            channel = connection.channel()

            def callback(ch, method, properties, body):
                if 'messageType' in properties.headers:
                    message_type = properties.headers['messageType']

                    if events.get(message_type):
                        result = Descriptors._reflection.ParseMessage(events[message_type]['decode'], body)
                        if result:
                            result = protobuf_to_dict(result)
                            model.write_response(external_response=result, message_type=message_type)
                    else:
                        app_log.warning('Message type not in allowed list = ' + str(message_type))
                        app_log.warning('continue listening...')

            channel.basic_consume(callback, queue=tunnel['queue']['name'], no_ack=True)
            try:
                channel.start_consuming()
            except KeyboardInterrupt:
                channel.stop_consuming()
                connection.close()
                break
        except pika.connection.exceptions.ConnectionClosed as e:
            app_log.error('ConnectionClosed :: %s' % str(e))
            continue
        except pika.connection.exceptions.AMQPChannelError as e:
            app_log.error('AMQPChannelError :: %s' % str(e))
            continue
        except Exception as e:
            app_log.error('Connection was closed, retrying... %s' % str(e))
            continue

if __name__ == '__main__':
    main()

Inside the script i have a model that doing inserts or updated in the database, code below
def write_response(self, external_response, message_type):
    table_name = events[message_type]['table_name']
    original_response = external_response[events[message_type]['response']]
    if isinstance(original_response, list):
        external_response = []
        for o in original_response:
            record = self.map_keys(o, message_type, events[message_type].get('values_fix', {}))
            external_response.append(self.validate_fields(record))
    else:
        external_response = self.map_keys(original_response, message_type, events[message_type].get('values_fix', {}))
        external_response = self.validate_fields(external_response)

    if not self.mysql.open:
        self.mysql.ping(reconnect=True)

    with self.mysql.cursor() as cursor:
        if isinstance(original_response, list):
            for e in external_response:
                id_name = events[message_type]['id_name']
                filters = {id_name: e[id_name]}
                self.event(
                    cursor=cursor,
                    table_name=table_name,
                    filters=filters,
                    external_response=e,
                    message_type=message_type,
                    event_id=e[id_name],
                    original_response=e  # not required here
                )
        else:
            id_name = events[message_type]['id_name']
            filters = {id_name: external_response[id_name]}
            self.event(
                cursor=cursor,
                table_name=table_name,
                filters=filters,
                external_response=external_response,
                message_type=message_type,
                event_id=external_response[id_name],
                original_response=original_response
            )
    cursor.close()
    self.mysql.close()

    return

On ubuntu i use systemd to run the script and restart in case something goes wrong, below is systemd file
[Unit]
Description=Pika Script
Requires=stunnel4.service
Requires=mysql.service
Requires=mongod.service

[Service]
User=user
Group=group
WorkingDirectory=/home/pika_script
ExecStart=/home/user/venv/bin/python pika_script.py
Restart=always

[Install]
WantedBy=multi-user.target

Image from ubuntu htop, how the MySql keeps adding in the list and never close it

Error
tornado_mysql.err.OperationalError: (1040, 'Too many connections')

A: i have found the issue, posting if will help somebody else.
the problem was that mysqld went into infinite loop trying to create indexing to a specific database, after found to which database was trying to create the indexes and never succeed and was trying again and again.
solution was to remove the database and recreate it, and the mysqld process went back to normal. and the infinite loop to create indexes dissapeared as well.

A: I would say increasing connection may solve your problem temperately.
1st find out why the application is not closing the connection after completion of task.
2nd Any slow queries/calls on the DB and fix them if any.
3rd considering no slow queries/calls on DB and also application is closing the connection/thread after immediately completing the task, then consider playing with "wait_timeout" on mysql side.

A: According to this answer, if you have MySQL 5.7 and 5.8 :

It is worth knowing that if you run out of usable disc space on your
server partition or drive, that this will also cause MySQL to return
this error. If you're sure it's not the actual number of users
connected then the next step is to check that you have free space on
your MySQL server drive/partition.

From the same thread. You can inspect and increase number of MySQL connections.


text:
Q: How do I get a random value from enums in Javascript? I am tinkering with Phaser game engine. I have figured out how to color the sprite, so the next step is giving it a random color. How would I do that using an enum?
var colors = {
    RED: 0xff0000,
    GREEN: 0x00ff00,
    BLUE: 0x0000ff
}

logo.tint = colors[Math.floor(Math.random() * colors.length)];

A: Here is a method I wrote in typescript that I used, remove types if you want to use with javascript.
function getRandomEnumValue<T>(anEnum: T): T[keyof T] {
  //save enums inside array
  const enumValues = Object.keys(anEnum) as Array<keyof T>;

  //Generate a random index (max is array length)
  const randomIndex = Math.floor(Math.random() * enumValues.length);
  // get the random enum value

  const randomEnumKey = enumValues[randomIndex];
  return anEnum[randomEnumKey];
 // if you want to have the key than return randomEnumKey
}

A: I just came to this problem today and able to get a random value by this:
var rand = Math.floor(Math.random() * Object.keys(colors).length);
var randColorValue = colors[Object.keys(colors)[rand]];

A: You should first instance your object as a Array
var colors =[
    {RED: 0xff0000},
    {GREEN: 0x00ff00},
    {BLUE: 0x0000ff}
];

Then, get a random position of the array.
colors[Math.floor(Math.random() * colors.length)];


text:
Q: Accessibility not working properly on UICollectionView inside UITableViewCell in my app i have a UICollectionView and UIPageControl inside UITableViewCell. UICollectionView has three different kind of cells and each cell covers the full width of iPhone. With accessibility on we are facing a problem when the focus is on UIPageControl and we try to adjust its value by swiping up and down and then traverse back to the cell it loses its focus and takes us to some different cell instead of taking control to the cell which we have changed using UIPageControl.
We are changing the cell on value change event of UIPageControl.


text:
Q: How to change keyboard language dynamic in React Native Here is my question:
First Screen would choose Language Option like English/Hindi/Punjabi/Spanish
2nd screen would have 3 text inputs and when user starts typing then a keyboard based on the selected language from screen 1 should appear.
Is is possible to achieve this?


text:
Q: What is the Euclidean inner product intuition? The Euclidean inner product $<x,y>$ of the vectors $x , y \in \mathbb{R}^n$ is defined by:
$\langle x,y\rangle = x_1y_1 + x_2y_2 + x_3y_3 + ... + x_ny_n$
I am unable to find the intuition behind this? Why do we need this inner product? What happens to the vectors under equation and what does the scalar answer tell us?
P.S. I have already seareched it, most the articles take it into geometric terms and introduce $\cos\theta$. Can anybody help me visualize thing without angular stuff?
Edit: Question addressed here uses the angle to explain geometric dot product. I am wondering if there exist some explanation for dot product in Vector Space.

A: You are probably familiar with the following formula involving
a vector $x = (x_1, \ldots, x_n) \in \mathbb R^n$
and $n$ constants $a_1, \ldots, a_n$ that are not all zero:
$$
a_1 x_1 + a_2 x_2 + \cdots + a_n x_n = 0.
$$
This formula describes an $(n-1)$-dimensional hyperplane in $\mathbb R^n.$
Let's call that hyperplane $A.$ That is, any vector $x$ that satisfies the formula lies in the hyperplane $A.$
If we define a vector $a = (a_1, \ldots, a_n),$
then another way to write the formula is
$$  \langle x, a\rangle = 0. $$
Now if we choose an arbitrary vector $x \in \mathbb R^n,$
it may happen that $\langle x, a\rangle \neq 0.$
If we have two such vectors, let's say $x'$ and $x'',$
such that $\langle x', a\rangle > 0$ and $\langle x'', a\rangle > 0,$
then $x'$ and $x''$ will be on the same side of the hyperplane $A.$
But if $\langle x', a\rangle < 0 < \langle x'', a\rangle$ then the vectors are on opposite sides.
For a given vector $x,$ suppose you find a vector $y$ such that
$x - \langle x, a\rangle y$ is in the hyperplane $A.$
Then $x' - \langle x', a\rangle y$ also is in the hyperplane $A$
for any other vector $x'.$
That is, $\langle x, a\rangle$ tells you how many times the length of $y$
you have to travel in the direction of $y$ to get from $x$ to the hyperplane,
or in other words, $\langle x', a\rangle$ is a kind of measurement of the distance of $x$ from the hyperplane (measured in some particular units in some particular direction).
All of this works without any "angles" (unless you consider "parallel" to be a "zero angle").
You don't even need
$(x_1, \ldots, x_n)$ to be coordinates over an orthonormal basis,
although if the basis is orthonormal then other nice results follow.
For example,
$$\sqrt{\langle x, x\rangle} = \sqrt{x_1^2 + x_2^2 + \cdots + x_n^2},$$
which is the length of $x$ (according to the Pythagorean Theorem)
if the basis of $(x_1, \ldots, x_n)$ is orthonormal.
Admittedly, to speak of "normals" one must have a concept of things being perpendicular, which starts to sound like we're dealing with angles again.
But they're right angles, which are especially simple to work with.

A: $<x,y>$ is positive if and only if the angle between $x$ and $y$ is less than 90 degrees. $<x,y>$ is sort of like a measure of how pointed in the same direction $x$ and $y$ are.
The geometry of least squares problems and separating hyperplanes is useful for gaining intuition about inner products.

A: The intuition is gathered from the following, given by the Law of Cosines
$$\| a -b\|^{2} = \| a\|^{2} + \| b\|^{2} - 2\| a\|^{2} \| b\|^{2}\cos(\theta) $$
$$ \| a-b\|^{2}  = (a-b)^{2}\cdot(a-b)^{2} $$
$$ \| a-b\|^{2}  =  a\cdot a - a\cdot b - b\cdot a + b \cdot b $$
useful to note that $a \cdot a = \| a\| $
$$ \| a-b\|^{2}  =  \|a \| - a\cdot b - b\cdot a + \| b\|$$
further more we have $ a \cdot b = b\cdot a $
$$ \| a-b\|^{2}  =  \|a \| - 2 a\cdot b + \| b\|$$
so we have
$$\| a -b\|^{2} = \| a\|^{2} + \| b\|^{2} - 2\| a\|^{2} \| b\|^{2}\cos(\theta) $$
$$ \| a\|^{2} - 2 a \cdot b + \| b\|^{2} = \|a\|^{2} + \|b\|^{2} - 2\|a\| \|b\| \cos(\theta) - 2 a \cdot b = -2 \|a \| \|b\| \cos(\theta) $$
yielding finally
$$a \cdot b  = \| a \| \| b\| \cos(\theta) $$
Now suppose that
$$ \|a\| = \|b\| =1 $$
$$ a \cdot b = 1 \cdot 1 \cos(\theta)  = \cos(\theta)$$
ok when is this negative. We have a unit circle here for vectors
$$ a \cdot b = \cos( \theta) < 0 \implies \frac{n\pi}{2} < \theta < \frac{3n\pi}{2} $$
that is we are in one part of the circle. However, it goes on forever.
Note from lamar


text:
Q: How to change alignment of code segment in ELF In ELF binary, how to change the alignment of loadable segments?
In the below example (See right corner), I want to reduce the 0x200000 to 0x40960.
  LOAD  0x000000 0x000000400000 0x0000000000400000 0x000704 0x000704 R E **0x200000**
  LOAD  0x000e10 0x000000600e10 0x0000000000600e10 0x000230 0x000238 RW  **0x200000**

Can any compiler expert (GCC or clang), provide me a solution for this?

A: I don't know if you really want to do that but you can change the max page size with ld -z  max-page-size=4096:
$ gcc foo.c && readelf -Wl ./a.out | grep LOAD
LOAD 0x000000 0x0000000000400000 0x0000000000400000 0x0008c4 0x0008c4 R E 0x200000
LOAD 0x0008c8 0x00000000006008c8 0x00000000006008c8 0x000250 0x000260 RW  0x200000
$ gcc foo.c -Wl,-z,max-page-size=4096 && readelf -Wl ./a.out | grep LOAD
LOAD 0x000000 0x0000000000400000 0x0000000000400000 0x0008c4 0x0008c4 R E 0x1000
LOAD 0x0008c8 0x00000000004018c8 0x00000000004018c8 0x000250 0x000260 RW  0x1000

Apparently, the reason is that the linker tries to align the segments to the maximum page size available on you architecture (on you CPU?). The standard default page size is 4KiB on x86 but greater pages exist (such as 2MiB pages).


text:
Q: error in ngRoute when my link is not in the index page I refer to this project and its working fine but my problem is that, my links is not in the index page.
https://github.com/facultymatt/angular-unsavedChanges
I have two links for the index page: Setting & Account
here's my index.html:

        Setting

        Account

my script inside index page:
var settingTab = angular.module('settingTab', ['ngRoute']);
             // configure our routes
            settingTab.config(function($routeProvider) {
                $routeProvider
                    // route for the account page
                    .when('/account', {
                        templateUrl : 'setting/angularjs/views/account.html',
                        controller: 'settingNavCtrl'
                    })
                // route for the setting page
                    .when('/', {
                        templateUrl : 'setting/angularjs/views/setting.html',
                        controller: 'settingNavCtrl'
                    })
});

my Controller:
    //for active nav
        settingTab.controller('settingNavCtrl', function($scope) {});
        settingTab.controller('navCtrl', function($scope, $location) {
            $scope.isActive = function(route) {
                return route === $location.path();
            }
        });

It is working fine, but I need to use ngRoute again in my link under Account, so I have 2 links in my Account, the admin & the user.
And when I put the same way like href="#/user" inside user.html & add the .when('/user',{.... inside the index page script, I got error. Why its not working outside the index page? please help me.
here's my account.html

User
Settings

Administrator
Settings

I adder User and admin into my script:
.when('/user', {
        templateUrl : 'setting/angularjs/views/account_sub/userSetting.html',
        controller: 'acctCtrl'
        });
.when('/admin', {
        templateUrl : 'setting/angularjs/views/account_sub/adminSetting.html',
        controller: 'acctCtrl'
        });

And now my Tabs in index page is not working.

A: Instead of specifying "href='#/users'", create a function that uses $location to set it to "/users" and call ng-click="redirect('/users'). It will handle the routes and will prevent the whole page from reloading, just the ng-view. Let me know if this doesn't solve your problem.

A: Thank you guys but I've already fix the problem, I just deleted my controller in my $routeProvider. thank you anyway :)