问:
Alternative to multiple if else statements in JavaScript?
I have an input which contains a dropdown list of 8 items. Depending on the option the user picks, I want to change the value of their input into a a different string value. In order to do this, I am using a ton of if else statements, which make this look very bulky and I would like to condense this if at all possible. I have the following code:

```<code>if (inputFive == "Corporation"){
    inputFive = "534"
} else if (inputFive == "LLC"){
    inputFive = "535"
} else if(inputFive == "LLP"){
    inputFive = "536"
} else if(inputFive == "Partnership"){
    inputFive = "537"
} else if(inputFive == "Sole Proprietorship"){
    inputFive = "538"
} else if(inputFive == "Limited Partnership"){
    inputFive = "539"
} else {
    inputFive = "540"
}
</code>```

As you can see, this looks a little old-school, and I would like to see if there is a better/simpler way to make this happen. Just looking to condense this code if at all possible. I believe that their might be a way to create a dictionary by assigning key/value objects, but I don't know how to do this correctly... All options/hints will be appreciated!

答:
Your intuition is exactly right. You would do it like so:</p>

```<code>var mapping = {
    "Corporation": "534",
    "LLC": "535",
    ...
    "default": "540"
}
inputFive = mapping[inputFive] || mapping["default"]
</code>```

Body:
I have an input which contains a dropdown list of 8 items. Depending on the option the user picks, I want to change the value of their input into a a different string value. In order to do this, I am using a ton of if else statements, which make this look very bulky and I would like to condense this if at all possible. I have the following code:

if (inputFive == "Corporation"){
    inputFive = "534"
} else if (inputFive == "LLC"){
    inputFive = "535"
} else if(inputFive == "LLP"){
    inputFive = "536"
} else if(inputFive == "Partnership"){
    inputFive = "537"
} else if(inputFive == "Sole Proprietorship"){
    inputFive = "538"
} else if(inputFive == "Limited Partnership"){
    inputFive = "539"
} else {
    inputFive = "540"
}

As you can see, this looks a little old-school, and I would like to see if there is a better/simpler way to make this happen. Just looking to condense this code if at all possible. I believe that their might be a way to create a dictionary by assigning key/value objects, but I don't know how to do this correctly... All options/hints will be appreciated!

Body:
Your intuition is exactly right. You would do it like so:

var mapping = {
    "Corporation": "534",
    "LLC": "535",
    ...
    "default": "540"
}
inputFive = mapping[inputFive] || mapping["default"]


来源: stackexchange

问:
How to change Repository RHEL
So, I'm trying to change my Repositorys in RHEL but I allways get the following message and have NO IDEA what it means.</p>

```<code>Loaded plugins: product-id, security, subscription-manager
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
Could not retrieve mirrorlist http://mirrors.elrepo.org/mirrors-elrepo.el6 error was
12: Timeout on http://mirrors.elrepo.org/mirrors-elrepo.el6: (28, 'connect() timed out!')
http://elrepo.org/linux/elrepo/el6/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://elrepo.org/linux/elrepo/el6/x86_64/repodata/repomd.xml: (28, 'connect() timed out!')
Trying other mirror.
http://mirrors.coreix.net/elrepo/elrepo/el6/x86_64/repodata/repomd.xml: [Errno 14] PYCURL ERROR 7 - "Failed to connect to 2a01:c0:2:3d::2: Network is unreachable"

[...]

Trying other mirror.
http://mirror.ventraip.net.au/elrepo/elrepo/el6/x86_64/repodata/repomd.xml: [Errno 14] PYCURL ERROR 7 - "Failed to connect to 2400:b800:1:1::15: Network is unreachable"
Trying other mirror.
Error: Cannot retrieve repository metadata (repomd.xml) for repository: elrepo. Please verify its path and try again
</code>```

答:
You can create your own repository if you have os image.

Mount os image at some folder say /var/rhel-repo using

```<code>mount -o loop /path/to/os_image /var/rhel-repo
</code>```

create repo file in /etc/yum.repos.d/customrepo as

```<code>[customrepo]
name=Custom Repository
baseurl=file:///var/customrepo
enabled=1
gpgcheck=0
</code>```

save file.Then

yum clean all

ContentLicense: CC BY-SA 3.0

Title: How to change Repository RHEL

Body:
So, I'm trying to change my Repositorys in RHEL but I allways get the following message and have NO IDEA what it means.

Loaded plugins: product-id, security, subscription-manager
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
Could not retrieve mirrorlist http://mirrors.elrepo.org/mirrors-elrepo.el6 error was
12: Timeout on http://mirrors.elrepo.org/mirrors-elrepo.el6: (28, 'connect() timed out!')
http://elrepo.org/linux/elrepo/el6/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://elrepo.org/linux/elrepo/el6/x86_64/repodata/repomd.xml: (28, 'connect() timed out!')
Trying other mirror.
http://mirrors.coreix.net/elrepo/elrepo/el6/x86_64/repodata/repomd.xml: [Errno 14] PYCURL ERROR 7 - "Failed to connect to 2a01:c0:2:3d::2: Network is unreachable"

[...]

Trying other mirror.
http://mirror.ventraip.net.au/elrepo/elrepo/el6/x86_64/repodata/repomd.xml: [Errno 14] PYCURL ERROR 7 - "Failed to connect to 2400:b800:1:1::15: Network is unreachable"
Trying other mirror.
Error: Cannot retrieve repository metadata (repomd.xml) for repository: elrepo. Please verify its path and try again

Body:
You can create your own repository if you have os image.

Mount os image at some folder say /var/rhel-repo using

mount -o loop /path/to/os_image /var/rhel-repo

create repo file in /etc/yum.repos.d/customrepo as

[customrepo]
name=Custom Repository
baseurl=file:///var/customrepo
enabled=1
gpgcheck=0

save file.Then

yum clean all


问:
Create Case with Activity through Rest API
I am trying to import cases from our old ticketing system into Acumatica using a C# console application. I have the old tickets loaded, and I am trying to use the REST API to create the cases.

I created a custom web service endpoint to load the cases, but I would also like to create message activities from the posts in our old system. If I use the Cases screen under Organization, I can add a Detail entity for activities.  However, there does not appear to be a way to add the Activity Details field, which is the body of the activity.  Here is a screenshot of the current endpoint setup showing the top-level Case entity I created:

The above image shows the Case entity, which does not appear to have the ActivityDetails field.  However, if I use the Activity screen from the Hidden site map folder, the ActivityDetails is present.  Here is a screenshot of the Activity entity I created, which does have ActivityDetails:

I hope this makes sense, but I would like the ActivityDetails field to be available from the Cases top-level entity so I can insert a complete case including activities and their detail.  Any help would be greatly appreciated.

Thank you.

答:
This is not a behavior that is possible.

The reason for this is that when you go on that screen using the UI, there is no possibility to add new Event, Task or Activity directly from that screen. The action button that are there only serve as to open the other screens a already create a link to the case from where the action was clicked on.

Since the APIs work by dealing with one screen at the time, it is not possible from the Case screen to create an Activity.

So to create an Activity for a Case, you will first have to create the Activity and then link it to the Case.

In order to do so, you must first add some field to both the Case entity and the Activity Entity.
These fields must be added manually as they are not part of the autocompletion.
For the Case entity, you need to add the following field:

```<code>Field Name = "NoteID"
Mapped Object = "Case Summary"
Mapped Field = "NoteID"
Field Value = "GuidValue"
</code>```

enter code here
For the Activity entity please add the following field:enter code here

```<code>Field Name = "RefNoteID"
Mapped Object = "Activities"
Mapped Field = "RefNoteID"
Field Value = "GuidValue"
</code>```

Once these two fields have been added, you can start adding the activity to the case.
In order to do so:

1) Retrieve the Case on which you want to add the activity using A GET call. You will need to use the value from the NoteID field that has just been added.

2) Create the Activity like you normally would, using a PUT call, but instead of trying to add a value in the RelatedEntityDescription field, add the NoteID value you just retrieved from the Case to the RefNoteID field you just added to the Activity entity. In the response you will be able to see that the Activity was linked to the case by checking the RelatedEntityDescription field.

Body:
This is not a behavior that is possible.

The reason for this is that when you go on that screen using the UI, there is no possibility to add new Event, Task or Activity directly from that screen. The action button that are there only serve as to open the other screens a already create a link to the case from where the action was clicked on.

Since the APIs work by dealing with one screen at the time, it is not possible from the Case screen to create an Activity.

So to create an Activity for a Case, you will first have to create the Activity and then link it to the Case.

In order to do so, you must first add some field to both the Case entity and the Activity Entity.
These fields must be added manually as they are not part of the autocompletion.
For the Case entity, you need to add the following field:

Field Name = "NoteID"
Mapped Object = "Case Summary"
Mapped Field = "NoteID"
Field Value = "GuidValue"

enter code here
For the Activity entity please add the following field:enter code here

Field Name = "RefNoteID"
Mapped Object = "Activities"
Mapped Field = "RefNoteID"
Field Value = "GuidValue"

Once these two fields have been added, you can start adding the activity to the case.
In order to do so:

1) Retrieve the Case on which you want to add the activity using A GET call. You will need to use the value from the NoteID field that has just been added.

2) Create the Activity like you normally would, using a PUT call, but instead of trying to add a value in the RelatedEntityDescription field, add the NoteID value you just retrieved from the Case to the RefNoteID field you just added to the Activity entity. In the response you will be able to see that the Activity was linked to the case by checking the RelatedEntityDescription field.


问:
Error while connecting to external SQL Server with an IP using SQL Management Studio 2005
Error while connecting to external SQL Server IP using SQL Management Studio 2005 address

TITLE: Connect to Server

Cannot connect to 1.2.3.4\SQLEXPRESS.

ADDITIONAL INFORMATION:

A network-related or instance-specific error occurred while
  establishing a connection to SQL
  Server. The server was not found or
  was not accessible. Verify that the
  instance name is correct and that SQL
  Server is configured to allow remote
  connections. (provider: SQL Network
  Interfaces, error: 26 - Error Locating
  Server/Instance Specified) (Microsoft
  SQL Server, Error: -1)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=-1&LinkId=20476

答:
Make sure that remote server allows connection to port 1433/tcp, e.g.:

using telnet client (in Windows 7 isn't installed by default, to install use Turn Windows features):

```<code>telnet 1.2.3.4 1433
</code>```

or using nmap (port scanner)

```<code>nmap -sT -r -n -vv -p1433 1.2.3.4
</code>```

If doesn't allow - check inbound firewall rules.

ContentLicense: CC BY-SA 2.5

Body:
Make sure that remote server allows connection to port 1433/tcp, e.g.:

using telnet client (in Windows 7 isn't installed by default, to install use Turn Windows features):

telnet 1.2.3.4 1433

or using nmap (port scanner)

nmap -sT -r -n -vv -p1433 1.2.3.4

If doesn't allow - check inbound firewall rules.


问:
How can I print a set of names in Javascript the first time the script runs followed by a prompt the second time?
This is the exercise:

Create a small program that contains a list of employee
names. Print out the list of names when the program runs
the first time. Prompt for an employee name and remove
that specific name from the list of names. Display the
remaining employees, each on its own line.

Example Output

There are 5 employees:

John Smith

Jackie Jackson

Chris Jones

Amanda Cullen

Jeremy Goodwin

Enter an employee name to remove: Chris Jones

There are 4 employees:

John Smith

Jackie Jackson

Amanda Cullen

Jeremy Goodwin

Constraint

• Use an array or list to store the names.

This is what I've tried so far (although it prompts for the name to be removed as soon as the script loads, rather than after the first 5 names have been printed).

var nameToRemove;
var employee = ["John Smith", "Jackie Jackson", "Chris Jones", "Amanda Cullen", "Jeremy Goodwin"];
var i;

document.write("There are " + employee.length + " employees:

");
for (i = 0; i < employee.length; i++) {
    document.write(employee[i] + "
");
}

nameToRemove = employee.indexOf(prompt("Enter an employee name to remove:"));

if (nameToRemove > -1) {
  employee.splice(nameToRemove, 1);
}

document.write("
There are " + employee.length + " employees:

");
for (i = 0; i < employee.length; i++) {
    document.write(employee[i] + "
");
}```

答:
probably is because javascript is asynchronous, you should use callback function to be sure that the first code is executed before running the rest.quick reference:

https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
https://www.w3schools.com/jquery/jquery_callback.asp

on the other side you can do the prompt inside the loop for the last element:

pseudo code:

```<code>for (i = 0; i < employee.length; i++) {
    document.write(employee[i] + "<br>");
    if (i == employee.length) {
        //do the prompt
    }
}
</code>```

Body:
probably is because javascript is asynchronous, you should use callback function to be sure that the first code is executed before running the rest.quick reference:

https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
https://www.w3schools.com/jquery/jquery_callback.asp

on the other side you can do the prompt inside the loop for the last element:

pseudo code:

for (i = 0; i < employee.length; i++) {
    document.write(employee[i] + "<br>");
    if (i == employee.length) {
        //do the prompt
    }
}


问:
If Loader's sourceComponent Item references its parent, and I set "loader.active = false", I get an error
My code:

```<code>import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Item {
        id: loaderParent
        Loader {
            id: loader
            active: true
            sourceComponent: Item {
                parent: loaderParent
                x: parent.x
            }
        }
    }

    Item {
        focus: true
        Keys.onPressed: {
            loader.active = false;
        }
    }
}
</code>```

When I press any key, I get this error:

qrc:/main.qml:16: TypeError: Cannot read property of null

Thought I suspect this error is harmless, I'd like an explanation or any idea for a fix/workaround?

Reported here.

答:
The Loader appears to set the item parent to null on destruction. QML objects are not deleted immediately, instead they use deleteLater() which leaves the object alive for another event loop cycle.

This leads to a reevaluation of the binding expression, which is no longer possible since the parent is now null. I've had a more severe encounter with this behavior described here.

A simple way to avoid it would be to not use the parent property which you already found, or to use a more complex binding expression such as x: loader.active ? parent.x : someFailsafeValue.

By using onParentChanged: console.log(parent) you can verify that the parent indeed changes to null when the loader is deactivated.

Body:
My code:

import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Item {
        id: loaderParent
        Loader {
            id: loader
            active: true
            sourceComponent: Item {
                parent: loaderParent
                x: parent.x
            }
        }
    }

    Item {
        focus: true
        Keys.onPressed: {
            loader.active = false;
        }
    }
}

When I press any key, I get this error:

qrc:/main.qml:16: TypeError: Cannot read property of null

Thought I suspect this error is harmless, I'd like an explanation or any idea for a fix/workaround?

Reported here.


问:
select query to display result and the parameter that got the result when using OR clause in where (Oracle)
I have a query

```<code>select columnX from tableA
  where (columnY like '%string1%' or columnY like '%string2%');
</code>```

but I also want to know what parameter (string1 or string2) got matched because of which I got my result, so I modify my query to

```<code>  select columnX value,'string1' pattern from tableA
  where columnY like '%string1%'
  union
  select columnX,'string2' from tableA
  where columnY like '%string2%'
</code>```

This gives me my result but makes the query huge (as I have hundreds of patterns to match against so basically I write the entire query for each parameter), I highly doubt this would be the best way to do this, is there some other way to do this where I do not have to write a new query for all the patterns that I want to match ?
Can this be done by simply modifying the query or will I have to use any advanced construct of Oracle SQL to perform what I need ?

答:
```<code>with tableA as(
    select 'asd' columnY  from dual union all
    select 'string2' columnY  from dual union all
    select 'string' columnY  from dual union all
    select 'string1' columnY  from dual union all
    select 'string1 string2' columnY  from dual
)

select * from (
    select tableA.*,
    case when columnY like '%string1%' then 1 else 0 end+
    case when columnY like '%string2%' then 2 else 0 end as res
    from tableA
) t
where res > 0
</code>```

If res column is 1, means that columnY contains only 'string1', if res is 2, this means that contains only 'string2', and if res is 3, then columnY contains both 'string1' and 'string2'

Body:
I have a query

select columnX from tableA
  where (columnY like '%string1%' or columnY like '%string2%');

but I also want to know what parameter (string1 or string2) got matched because of which I got my result, so I modify my query to

  select columnX value,'string1' pattern from tableA
  where columnY like '%string1%'
  union
  select columnX,'string2' from tableA
  where columnY like '%string2%'

This gives me my result but makes the query huge (as I have hundreds of patterns to match against so basically I write the entire query for each parameter), I highly doubt this would be the best way to do this, is there some other way to do this where I do not have to write a new query for all the patterns that I want to match ?
Can this be done by simply modifying the query or will I have to use any advanced construct of Oracle SQL to perform what I need ?

Body:
with tableA as(
    select 'asd' columnY  from dual union all
    select 'string2' columnY  from dual union all
    select 'string' columnY  from dual union all
    select 'string1' columnY  from dual union all
    select 'string1 string2' columnY  from dual
)

select * from (
    select tableA.*,
    case when columnY like '%string1%' then 1 else 0 end+
    case when columnY like '%string2%' then 2 else 0 end as res
    from tableA
) t
where res > 0

If res column is 1, means that columnY contains only 'string1', if res is 2, this means that contains only 'string2', and if res is 3, then columnY contains both 'string1' and 'string2'


答:
Use the switch statement, which is better for times when there is a single variable you want to check against multiple possible values:

switch (inputFive) {
  case "Corporation" :
    inputFive = "534";
    break;
  case "LLC":
    inputFive = "535";
    break;
  case "LLP":
    inputFive = "536";
    break;
  case "Partnership":
    inputFive = "537";
    break;
  case "Sole Proprietorship":
    inputFive = "538";
    break;
  case "Limited Partnership":
    inputFive = "539";
    break;
  default:
    inputFive = "540";
    break;
}```

Title: Alternative to multiple if else statements in JavaScript?


问:
Trying to use Selenium to find a specific entry in a list when what you type highlights that word
DOM:

```<code><span class="item">Does not <span class="highlight">match</span>.</span>
<span class="item">Also not <span class="highlight">match</span>ing.</span>
<span class="item"><span class="highlight">match</span></span>
</code>```

Issue:
I've got a list of items.  When I type into a text box, it eliminates items that do not match, and highlights the ones that do inside a /span.  The issue is that if I type something that matches multiple things, I want to select the EXACT String, and not the ones that partially match (see above DOM example...  the ideal match would be the 3rd one).

So, is my only hope here to go one by one until I find my perfect match, or is there something else that I've been missing?

答:
You are trying to find a span that has no text, with an inner span that has some highlighted text. Here is an XPath selector for that:

```<code>//span[@class='item'][not(text())]/span[@class='highlight'][text()='match']
</code>```

Body:
DOM:

Does not match.
Also not matching.
match

Issue:
I've got a list of items.  When I type into a text box, it eliminates items that do not match, and highlights the ones that do inside a /span.  The issue is that if I type something that matches multiple things, I want to select the EXACT String, and not the ones that partially match (see above DOM example...  the ideal match would be the 3rd one).

So, is my only hope here to go one by one until I find my perfect match, or is there something else that I've been missing?

Body:
You are trying to find a span that has no text, with an inner span that has some highlighted text. Here is an XPath selector for that:

//span[@class='item'][not(text())]/span[@class='highlight'][text()='match']


问:
Adding input query to route value for search function Laravel Scout
Trying to set up basic search functionality for products. I am having trouble sorting the route parameter variable and passing the query string to the search function.

```<code>Route::get('/search/{query?}', 'ProductController@searchable');
</code>```

This works and returns a query when I input the query manually.

Controller

```<code>public function searchable($query)
{
    // search database, with result, list on page, with links to products,
    $products = Product::search($query)->get();

    return view('search.index', compact('products'));
}
</code>```

However, I would like it to come from the URL /search?test.

My form shows:

```<code>{{ Form::open(array('action' => 'ProductController@searchable', 'method' => 'get', 'files' => 'false')) }}
<input type="search" name="search" placeholder="type keyword(s) here" />
<button type="submit" class="btn btn-primary">Search</button>
{{ Form::close() }}`
</code>```

I am new to Laravel and need a little help. I am using Laravel Scout and TNTSearch.

答:
You don't need to user {wildcard} for searching. We have Request for that

```<code>Route::get('search', 'ProductController@searchable');
</code>```

Pass the url instead.

```<code>{{ Form::open(array('url' => 'search', 'method' => 'GET', 'files' => 'false')) }}
    <input type="search" name="search" placeholder="type keyword(s) here" />
    <button type="submit" class="btn btn-primary">Search</button>
{{ Form::close() }}
</code>```

In Controller simple fetch $request->search

```<code>public function searchable(Request $request)
{
    // search database, with result, list on page, with links to products,
    $products = Product::search($request->search)->get();

    return view('search.index', compact('products'));
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Trying to set up basic search functionality for products. I am having trouble sorting the route parameter variable and passing the query string to the search function.

Route::get('/search/{query?}', 'ProductController@searchable');

This works and returns a query when I input the query manually.

Controller

public function searchable($query)
{
    // search database, with result, list on page, with links to products,
    $products = Product::search($query)->get();

    return view('search.index', compact('products'));
}

However, I would like it to come from the URL /search?test.

My form shows:

{{ Form::open(array('action' => 'ProductController@searchable', 'method' => 'get', 'files' => 'false')) }}
<input type="search" name="search" placeholder="type keyword(s) here" />
<button type="submit" class="btn btn-primary">Search</button>
{{ Form::close() }}`

I am new to Laravel and need a little help. I am using Laravel Scout and TNTSearch.

Body:
You don't need to user {wildcard} for searching. We have Request for that

Route::get('search', 'ProductController@searchable');

Pass the url instead.

{{ Form::open(array('url' => 'search', 'method' => 'GET', 'files' => 'false')) }}
    <input type="search" name="search" placeholder="type keyword(s) here" />
    <button type="submit" class="btn btn-primary">Search</button>
{{ Form::close() }}

In Controller simple fetch $request->search

public function searchable(Request $request)
{
    // search database, with result, list on page, with links to products,
    $products = Product::search($request->search)->get();

    return view('search.index', compact('products'));
}


问:
Regular expressions: search (instead of match) with DFA
I have been wondering about theory behind search mode of regex matcher. So, say I have a regex that matches aab, what if instead of match at the beginning of the string I wanna be able to perform this match starting from any position of the string. What I mean - in match mode I can only verify that string aab is consistent with a regex, on the other hand with search this should work with say aaab producing corresponding span result.
So super specifically - is there any way to build DFA searcher, or this is fundamentally impossible since it would require additional memory which you cant have in DFSM. It is obvious though that you can in fact build searcher from matcher by reapplying matcher to input string in a for loop, but complexity of such approach is something like O(len_of_pattern * len_of_input).

答: I think you basically answered your own question. Search, like many other features in modern regex implementations, leverages the wonder of memory to do things unfeasible with a Finite Automata. DFAs traditionally cannot loop over strings or backtrack along input as this would require memory. Search requires the ability to find a match and then understand how that match fits in the string.</p>


问:
How to implement sqlite "like" query in android firebase-database
I am trying to implement sqlite like query in firebase database. For e.g. If there are 10 entries abc1, abc2, abc3, ..... abc10. Query with abc+"%" should display all 10 entries. I tried orderByChild("").equalTo("") as well as startAt(""), but did not get the desired result.

Tried this link, but still stuck. Kindly suggest.

答:
startAt("abc1") with endAt("abc9") will work for the first nine.

However, string sorting wise, abc10 will throw off the sorting abc1, abc10, abc2

So... If you know the cap on how many abc's there are, you can pad with zero's to get the desired output. Here we know we will cap at 999.

```<code>abc_001
abc_002
.
.
.
abc_999
</code>```

Then startAt and endAt will work correctly.

Alternately, you can store the integer values in another child node and order by those numerically.

Body:
startAt("abc1") with endAt("abc9") will work for the first nine.

However, string sorting wise, abc10 will throw off the sorting abc1, abc10, abc2

So... If you know the cap on how many abc's there are, you can pad with zero's to get the desired output. Here we know we will cap at 999.

abc_001
abc_002
.
.
.
abc_999

Then startAt and endAt will work correctly.

Alternately, you can store the integer values in another child node and order by those numerically.


问:
Autohotkey save excel file without seeing overwrite prompt
I have a autohotkey script that saves the file to a backup location in sharepoint. I can save the file there fine but it keeps asking for a okay to overwrite prompt and I am wondering if it is at all possible to get rid of that.

Code is listed below.

```<code>ExcelRefresh(File) { ; Function

sharepointPath := "\\sharepoint\Location\SharepointCompleted.xlsx"
oExcel := ComObjCreate("Excel.Application")
oExcel.Visible := false
oWorkbook := oExcel.Workbooks.Open(File)
oWorkbook.RefreshAll
oWorkbook.Save()
oExcel.ActiveWorkbook.SaveAs(sharepointPath)
oWorkbook.Close(false)
oExcel.Quit()
}
</code>```

答:
What I ended up doing was just a simple check if file exists and from there if it does exist I delete the file before I save it to the backup location in SharePoint. Not the cleaning way but it works.

```<code>IfExist , \\sharepoint\sites\SharepointCompleted.xlsx
;MsgBox, it esxists
FileDelete, \\sharepoint\sites\SharepointCompleted.xlsx

Sleep 15000
</code>```

I added this before I run the function. And so far it has passed my tests.

Body:
I have a autohotkey script that saves the file to a backup location in sharepoint. I can save the file there fine but it keeps asking for a okay to overwrite prompt and I am wondering if it is at all possible to get rid of that.

Code is listed below.

ExcelRefresh(File) { ; Function

sharepointPath := "\\sharepoint\Location\SharepointCompleted.xlsx"
oExcel := ComObjCreate("Excel.Application")
oExcel.Visible := false
oWorkbook := oExcel.Workbooks.Open(File)
oWorkbook.RefreshAll
oWorkbook.Save()
oExcel.ActiveWorkbook.SaveAs(sharepointPath)
oWorkbook.Close(false)
oExcel.Quit()
}

Body:
What I ended up doing was just a simple check if file exists and from there if it does exist I delete the file before I save it to the backup location in SharePoint. Not the cleaning way but it works.

IfExist , \\sharepoint\sites\SharepointCompleted.xlsx
;MsgBox, it esxists
FileDelete, \\sharepoint\sites\SharepointCompleted.xlsx

Sleep 15000

I added this before I run the function. And so far it has passed my tests.


答:
You can use an object as a map:

function getCode(input) {
    var inputMap = {
      "Corporation": "534",
      "LLC": "535",
      "LLP": "536",
      "Partnership": "537",
      "Sole Proprietorship": "538",
      "Limited Partnership": "539"
    };

    var defaultCode = "540";

    return inputMap[input] || defaultCode;
}

console.log(getCode("LLP"));
console.log(getCode("Lorem Ipsum"));```

Body:
I have an input which contains a dropdown list of 8 items. Depending on the option the user picks, I want to change the value of their input into a a different string value. In order to do this, I am using a ton of if else statements, which make this look very bulky and I would like to condense this if at all possible. I have the following code:

if (inputFive == "Corporation"){
    inputFive = "534"
} else if (inputFive == "LLC"){
    inputFive = "535"
} else if(inputFive == "LLP"){
    inputFive = "536"
} else if(inputFive == "Partnership"){
    inputFive = "537"
} else if(inputFive == "Sole Proprietorship"){
    inputFive = "538"
} else if(inputFive == "Limited Partnership"){
    inputFive = "539"
} else {
    inputFive = "540"
}

As you can see, this looks a little old-school, and I would like to see if there is a better/simpler way to make this happen. Just looking to condense this code if at all possible. I believe that their might be a way to create a dictionary by assigning key/value objects, but I don't know how to do this correctly... All options/hints will be appreciated!


答:
You probably want some kind of array.

```<code>businessTypes = [];
businessTypes["Corporation"] = 534;
businessTypes["LLC"] = 535;
businessTypes["LLP"] = 536;
businessTypes["Partnership"] = 537;
businessTypes["Sole Proprietorship"] = 538;
businessTypes["Limited Partnership"] = 539;
</code>```

Then you could reference it with something like:

```<code>businessId = businessTypes[inputFive] ? businessTypes[inputFive] : 540;
console.log(businessId);
</code>```

You could also break it into a function:

function getBusinessId(type) {
  businessTypes = [];
  businessTypes["Corporation"] = 534;
  businessTypes["LLC"] = 535;
  businessTypes["LLP"] = 536;
  businessTypes["Partnership"] = 537;
  businessTypes["Sole Proprietorship"] = 538;
  businessTypes["Limited Partnership"] = 539;
  return businessTypes[type] ? businessTypes[type] : 540;
}

var businessId = getBusinessId("LLC");
console.log(businessId); // 535```

Body:
You probably want some kind of array.

businessTypes = [];
businessTypes["Corporation"] = 534;
businessTypes["LLC"] = 535;
businessTypes["LLP"] = 536;
businessTypes["Partnership"] = 537;
businessTypes["Sole Proprietorship"] = 538;
businessTypes["Limited Partnership"] = 539;

Then you could reference it with something like:

businessId = businessTypes[inputFive] ? businessTypes[inputFive] : 540;
console.log(businessId);

You could also break it into a function:

function getBusinessId(type) {
  businessTypes = [];
  businessTypes["Corporation"] = 534;
  businessTypes["LLC"] = 535;
  businessTypes["LLP"] = 536;
  businessTypes["Partnership"] = 537;
  businessTypes["Sole Proprietorship"] = 538;
  businessTypes["Limited Partnership"] = 539;
  return businessTypes[type] ? businessTypes[type] : 540;
}

var businessId = getBusinessId("LLC");
console.log(businessId); // 535


问:
The length -1 is not valid for function "SUBSTRING". The length parameter cannot be negative in SSIS
I am trying to convert a data from a flat file to a SQL date. I am using variables to separate the Month, Day, and Year and added necessary "0" when needed then concatenate them back together. the job works fine except when I run into a date that is blank and it throws out three errors: "The length -1 is not valid for function "SUBSTRING". The length parameter cannot be negative. Change the length parameter to zero or a positive value.", "Evaluating function "SUBSTRING" failed with error code 0xC004708B.", AND "Evaluating function "LEN" failed with error code 0xC00470C5.". I have a variable for the date 1/2/1995 to find the "/" using Y FINDSTRING( @[User::Scan_Date] , "/", 1 )

and then the example I have for the month is

```<code>@[User::Y] < 1 ?  (DT_STR, 2, 1252) NULL(DT_STR, 2, 1252) :  (LEN( SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 )) < 2 ? "0" + SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 ) : SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 ))
</code>```

As I said, the expression works fine if there is a date, but if it is blank then I receive an error.

答: Wrap your whole expression in an IIF that checks to see if the date is blank.

Body:
I am trying to convert a data from a flat file to a SQL date. I am using variables to separate the Month, Day, and Year and added necessary "0" when needed then concatenate them back together. the job works fine except when I run into a date that is blank and it throws out three errors: "The length -1 is not valid for function "SUBSTRING". The length parameter cannot be negative. Change the length parameter to zero or a positive value.", "Evaluating function "SUBSTRING" failed with error code 0xC004708B.", AND "Evaluating function "LEN" failed with error code 0xC00470C5.". I have a variable for the date 1/2/1995 to find the "/" using Y FINDSTRING( @[User::Scan_Date] , "/", 1 )

and then the example I have for the month is

@[User::Y] < 1 ?  (DT_STR, 2, 1252) NULL(DT_STR, 2, 1252) :  (LEN( SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 )) < 2 ? "0" + SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 ) : SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 ))

As I said, the expression works fine if there is a date, but if it is blank then I receive an error.


问:
Splash screen react-native
Is there any repo or something that can be used to change the splash screen image automatically without doing a release?

For example 1 week I want to display image X and after that I wanna do Y, but Y its also not on the phone so I have to download it from an api and so on.

答:
You can use existing npm packages to make splash screens. like react-native-splash-screen

using setTimeout method

componentDidMount() {
  setTimeout(function(){
    // place your navigator code here
  }, 1000); // update your own time interval value
}```

Hope this will help you :)  Happy coding!

Title: Splash screen react-native

Body:
You can use existing npm packages to make splash screens. like react-native-splash-screen

using setTimeout method

componentDidMount() {
  setTimeout(function(){
    // place your navigator code here
  }, 1000); // update your own time interval value
}

Hope this will help you :)  Happy coding!


问:
How do you reuse the first parameter of a function in its second parameter?
```<code>function generateRandom($s,$len=count($s)){...}
</code>```

How do you set the value of the second param of a function as the length of the first param unless otherwise it's defined?

答:
It only works this way:

```<code>function generateRandom($s, $len=null) {
  if ($len === null) {
    $len = count($s);
  }
}
</code>```

You cannot do any operations as the default value. It needs to be something "simple" like scalars or constants.

Body:
function generateRandom($s,$len=count($s)){...}

How do you set the value of the second param of a function as the length of the first param unless otherwise it's defined?

Body:
It only works this way:

function generateRandom($s, $len=null) {
  if ($len === null) {
    $len = count($s);
  }
}

You cannot do any operations as the default value. It needs to be something "simple" like scalars or constants.


问:
Undoing bitwise operations
I have a Java function written by another programmer, which uses bitwise manipulation.  I need a function that will undo the process (if possible).  Perhaps some of you are more savvy than I with these operators.  Here's what needs to be undone:</p>

```<code>public void someFunc(int[] msg, int[] newMsg) {
    int i = SOME_LENGTH_CONSTANT;
    for (int j = 0; j < newMsg.length; j++) {
        // msg[i] Shift left by 8 bits bitwise or with next msg[i+1]
        // then bitwise not (~) and bitwise and with $FFF
        newMsg[j] = (~(((msg[i] & 0x0f) << 8) | (msg[i + 1]))) & 0xfff;
        i += 2;
    }
}
</code>```

答:
My version, behold:

```<code>public void undoFunc(int[] newMsg, int[] original) {
        int i = SOME_LENGTH_CONSTANT; // starting point
        for (int j = 0; j < newMsg.length; j++) { // Iterate over newMsg

            original[i] = ~((newMsg[j]&0xff00)>>8)&0x000f; // &0x000f to get rid of "mistakes" when NOT-ing
            original[i+1] = (~(newMsg[j]&0x00ff)) & 0xff;
            // i = initial value + 2 * j
            i+=2;
        }
    }
</code>```

What does your code do?

The input is an integer array. Every two values are used to create one value in the 'output' (newMsg) array.

First, it removes the left four bits of the first value in the input.

Then it "scrolls" that value 8 places to the left and puts zeroes in the empty spots.

It places the second value, msg[i+1], in the zeroes in the four rightmost bits.

It negates the value, all ones become zeroes and all zeroes become ones.

When 4) was done, the 4 leftmost bits (cleared in step 1)) become ones, so it undoes this with a &0x0FFF.

Example iteration:

```<code>msg[i] ==   1010'1011
msg[i+1] == 0010'0100

1) 1010'1011           ->           0000'1011
2) 0000'1011           -> 0000'1011'0000'0000
3) 0000'1011'0000'0000 -> 0000'1011'0010'0100
4) 0000'1011'0010'0100 -> 1111'0100'1101'1011
5) 1111'0100'1101'1011 -> 0000'0100'1101'1011

newMsg[j] == 0000'0100'1101'1011 == 0x04DB (I think, from memory)
</code>```

What my code does:
Getting the value of (what used to be) msg[i+1] is easy, it's the opposite/NOT of the rightmost 8 bits. Because negating it turns all leading zeroes into ones, I'll AND it with 0xff.
Getting the value of (what used to be) msg[i] was more difficult. First scrolled the leftmost 8 bits to the right. Then I negate the value. But the four unused/lost bits are now ones, and I expect that the OP wants these to be zeroes, so I &0x000f it.

NOTE: I used hexes with leading zeroes to make it more clear. These are not necessary.

NOTE: I divided the binary numbers into four bits for readability. So 0000'0100'1101'1011 is actually (0b)0000010011011011.

The values of msg[i+1] are recovered, but the leftmost four bits of msg[i] are lost.

Fwew.

Original Post:

In your code, you use &. What & does, is turn all 'agreeing bits' (when a bit from byte a and the equally significant bit from byte b are both 1) into 1s and the rest into 0s. This means that all bits that don't agree are, as @Mike Harris said, gone and destroyed.

Example & (and operation):

```<code>1010 & 0110 =
    1  &  0 => 0
    0  &  1 => 0
    1  &  1 => 1
    0  &  0 => 0
= 0010
</code>```

As you see, only the second and third most significant bits (or zero-inclusive first and second least significant bit) of byte a are kept (bit #4/#0 is 'luck'), because they are 1s in byte b.

You can reverse all bits that are 1s in byte b in your code (one of which is fff, or 1111 1111 1111 in binary, though remember all bits more significant than the first one are removed, because 1111 1111 1111 == 000000000...00111111111111). But this won't reverse it, and only works depending on what the purpose of reversing it is.

More about the AND Bitwise operation on Wikipedia.

Title: Undoing bitwise operations

Body:
I have a Java function written by another programmer, which uses bitwise manipulation.  I need a function that will undo the process (if possible).  Perhaps some of you are more savvy than I with these operators.  Here's what needs to be undone:

public void someFunc(int[] msg, int[] newMsg) {
    int i = SOME_LENGTH_CONSTANT;
    for (int j = 0; j < newMsg.length; j++) {
        // msg[i] Shift left by 8 bits bitwise or with next msg[i+1]
        // then bitwise not (~) and bitwise and with $FFF
        newMsg[j] = (~(((msg[i] & 0x0f) << 8) | (msg[i + 1]))) & 0xfff;
        i += 2;
    }
}

Body:
My version, behold:

public void undoFunc(int[] newMsg, int[] original) {
        int i = SOME_LENGTH_CONSTANT; // starting point
        for (int j = 0; j < newMsg.length; j++) { // Iterate over newMsg

            original[i] = ~((newMsg[j]&0xff00)>>8)&0x000f; // &0x000f to get rid of "mistakes" when NOT-ing
            original[i+1] = (~(newMsg[j]&0x00ff)) & 0xff;
            // i = initial value + 2 * j
            i+=2;
        }
    }

What does your code do?

The input is an integer array. Every two values are used to create one value in the 'output' (newMsg) array.

First, it removes the left four bits of the first value in the input.

Then it "scrolls" that value 8 places to the left and puts zeroes in the empty spots.

It places the second value, msg[i+1], in the zeroes in the four rightmost bits.

It negates the value, all ones become zeroes and all zeroes become ones.

When 4) was done, the 4 leftmost bits (cleared in step 1)) become ones, so it undoes this with a &0x0FFF.

Example iteration:

msg[i] ==   1010'1011
msg[i+1] == 0010'0100

1) 1010'1011           ->           0000'1011
2) 0000'1011           -> 0000'1011'0000'0000
3) 0000'1011'0000'0000 -> 0000'1011'0010'0100
4) 0000'1011'0010'0100 -> 1111'0100'1101'1011
5) 1111'0100'1101'1011 -> 0000'0100'1101'1011

newMsg[j] == 0000'0100'1101'1011 == 0x04DB (I think, from memory)

What my code does:
Getting the value of (what used to be) msg[i+1] is easy, it's the opposite/NOT of the rightmost 8 bits. Because negating it turns all leading zeroes into ones, I'll AND it with 0xff.
Getting the value of (what used to be) msg[i] was more difficult. First scrolled the leftmost 8 bits to the right. Then I negate the value. But the four unused/lost bits are now ones, and I expect that the OP wants these to be zeroes, so I &0x000f it.

NOTE: I used hexes with leading zeroes to make it more clear. These are not necessary.

NOTE: I divided the binary numbers into four bits for readability. So 0000'0100'1101'1011 is actually (0b)0000010011011011.

The values of msg[i+1] are recovered, but the leftmost four bits of msg[i] are lost.

Fwew.

Original Post:

In your code, you use &. What & does, is turn all 'agreeing bits' (when a bit from byte a and the equally significant bit from byte b are both 1) into 1s and the rest into 0s. This means that all bits that don't agree are, as @Mike Harris said, gone and destroyed.

Example & (and operation):

1010 & 0110 =
    1  &  0 => 0
    0  &  1 => 0
    1  &  1 => 1
    0  &  0 => 0
= 0010

As you see, only the second and third most significant bits (or zero-inclusive first and second least significant bit) of byte a are kept (bit #4/#0 is 'luck'), because they are 1s in byte b.

You can reverse all bits that are 1s in byte b in your code (one of which is fff, or 1111 1111 1111 in binary, though remember all bits more significant than the first one are removed, because 1111 1111 1111 == 000000000...00111111111111). But this won't reverse it, and only works depending on what the purpose of reversing it is.

More about the AND Bitwise operation on Wikipedia.


问:
HQL query for entity with max value
I have a Hibernate entity that looks like this (accessors ommitted for brevity):

```<code>@Entity
@Table(name="FeatureList_Version")
@SecondaryTable(name="FeatureList",
    pkJoinColumns=@PrimaryKeyJoinColumn(name="FeatureList_Key"))
public class FeatureList implements Serializable {

    @Id
    @Column(name="FeatureList_Version_Key")
    private String key;

    @Column(name="Name",table="FeatureList")
    private String name;

    @Column(name="VERSION")
    private Integer version;

}
</code>```

I want to craft an HQL query that retrieves the most up to date version of a FeatureList. The following query sort of works:

```<code>Select f.name, max(f.version) from FeatureList f group by f.name
</code>```

The trouble is that won't populate the key field, which I need to contain the key of the record with the highest version number for the given FeatureList. If I add f.key in the select it won't work because it's not in the group by or an aggregate and if I put it in the group by the whole thing stops working and it just gives me every version as a separate entity.

So, can anybody help?

答:
How about this,

```<code>from FeatureList fl where (fl.name, fl.version) in (
               select f.name, max(f.version) from FeatureList f group by f.name)
</code>```

Note: Try with the createNativeQuery(), its a valid Oracle query, not sure about any other database.

One question, is the pair, name and version, unique? If yes, then its fine, otherwise if the pair is not unique, what do you think how a key will be selected? Suppose one of the record from the original query is,

```<code>f.name         max(f.version)
------         --------------
Django         1.2
</code>```

and assume there are 3 keys having the same pair. Now answer, which key should be assigned to this record? I hope you are getting my point.

Title: HQL query for entity with max value

Body:
I have a Hibernate entity that looks like this (accessors ommitted for brevity):

@Entity
@Table(name="FeatureList_Version")
@SecondaryTable(name="FeatureList",
    pkJoinColumns=@PrimaryKeyJoinColumn(name="FeatureList_Key"))
public class FeatureList implements Serializable {

    @Id
    @Column(name="FeatureList_Version_Key")
    private String key;

    @Column(name="Name",table="FeatureList")
    private String name;

    @Column(name="VERSION")
    private Integer version;

}

I want to craft an HQL query that retrieves the most up to date version of a FeatureList. The following query sort of works:

Select f.name, max(f.version) from FeatureList f group by f.name

The trouble is that won't populate the key field, which I need to contain the key of the record with the highest version number for the given FeatureList. If I add f.key in the select it won't work because it's not in the group by or an aggregate and if I put it in the group by the whole thing stops working and it just gives me every version as a separate entity.

So, can anybody help?

Body:
How about this,

from FeatureList fl where (fl.name, fl.version) in (
               select f.name, max(f.version) from FeatureList f group by f.name)

Note: Try with the createNativeQuery(), its a valid Oracle query, not sure about any other database.

One question, is the pair, name and version, unique? If yes, then its fine, otherwise if the pair is not unique, what do you think how a key will be selected? Suppose one of the record from the original query is,

f.name         max(f.version)
------         --------------
Django         1.2

and assume there are 3 keys having the same pair. Now answer, which key should be assigned to this record? I hope you are getting my point.


问:
How to save image
I want to save image with userdefaults and use it in another view with this code but it shows an error .

```<code>UserDefaults.standard.set(img , forKey : "simg")
</code>```

please help me

答:
You can't save a UIImage directly to NSUserDefaults.  You could save it as NSData, but it really is not advisable.  NSUserDefaults is meant to store small bits of information in key value pairs.  If you start throwing images in there, you could overload the space reserved for it. The contents of the NSUserDefaults is written to a plist. I believe any time you access the user defaults, it reads the whole file. If you put large images in there, it will cause a lot of unnecessary I/O.

If you still decide to do it (not recommended), here is a good post on getting an NSData object from the image.

Title: How to save image

Body:
I want to save image with userdefaults and use it in another view with this code but it shows an error .

UserDefaults.standard.set(img , forKey : "simg")

please help me


问:
How to get job execution time from sidekiq?
I'd like to know execution time every time I run my jobs. Seems like there is a gem sidekiq-statistic that does what I want and even has GUI, but unfortunately it doesn't work with sidekiq 5. Can I get such info from inside perform method somehow? I'd prefer to avoid writing benchmarking code manually, wrapping up my method into Benchmark block

答: You can try this Scout, It is a great tool which will offer detailed method metrics. It works with Heroku as well, they have add-on there.</p>


问:
spring boot assign specific DataSource to JpaRepository
I have two datasources that I'm trying to assign a specific datasource to each JpaRepositories. I'm using the spring boot framework. The primary datasource is used about 90% of the time while the secondary datasource is used about 10% so it would be nice to default to the primary and only assign the secondary datasource when required.  I tried using the docs here https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html , but I dont think its exactly what I need.  Any tips would be great!

```<code>spring.datasource.configuration.url=jdbc:postgresql://localhost:5432/mydatabase
spring.datasource.configuration.username=dockerusername
spring.datasource.configuration.password=dockerpassword
spring.datasource.configuration.driver-class-name=org.postgresql.Driver

spring.datasource.cached.url=jdbc:hsqldb:mem:main
spring.datasource.cached.driver-class-name=org.hsqldb.jdbc.JDBCDriver

spring.datasource.initialize=false
spring.jpa.database=default
spring.jpa.hibernate.ddl-auto=update
</code>```

config file

```<code>@Configuration
@ComponentScan({"com.praeses.gov"})
public class Config {
@Bean
@ConfigurationProperties("spring.datasource.configuration")
public DataSourceProperties configDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@ConfigurationProperties("spring.datasource.configuration")
public DataSource configDataSource() {
    return configDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@Primary
@ConfigurationProperties("spring.datasource.cached")
public DataSourceProperties cachedDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("spring.datasource.cached")
public DataSource cachedDataSource() {
return cachedDataSourceProperties().initializeDataSourceBuilder().build();
    }
</code>```

repository that uses the primary datasource

```<code>@Qualifier("spring.datasource.cached")
@Repository("spring.datasource.cached")
public interface GeoitemRepository extends JpaRepository<Geoitem, String> {
}
</code>```

repository that uses the secondary datasource

```<code>@Qualifier("spring.datasource.configuration")
@Repository("spring.datasource.configuration")
public interface GeoitemhistoryRepository extends JpaRepository<Geoitemhistory, String> {
}
</code>```

答:
You can do something on similar lines as below link. Just create two config files instead of one(one each for each datasource) and add both of them to your main application.

Also, in the properties file, give as below:

```<code>datasource.local.url=
datasource.local.driver-class-name=
datasource.local.username=
datasource.local.password=

datasource.primary.url=
datasource.primary.driver-class-name=
datasource.primary.username=
datasource.primary.password=
</code>```

Also, give @Primary annotation to the LocalContainerEntityManagerFactoryBean and platformTransactionManager in the config file for primary datasource.

See this answer for more details:
https://stackoverflow.com/a/44971911/6775742

Body:
I have two datasources that I'm trying to assign a specific datasource to each JpaRepositories. I'm using the spring boot framework. The primary datasource is used about 90% of the time while the secondary datasource is used about 10% so it would be nice to default to the primary and only assign the secondary datasource when required.  I tried using the docs here https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html , but I dont think its exactly what I need.  Any tips would be great!

spring.datasource.configuration.url=jdbc:postgresql://localhost:5432/mydatabase
spring.datasource.configuration.username=dockerusername
spring.datasource.configuration.password=dockerpassword
spring.datasource.configuration.driver-class-name=org.postgresql.Driver

spring.datasource.cached.url=jdbc:hsqldb:mem:main
spring.datasource.cached.driver-class-name=org.hsqldb.jdbc.JDBCDriver

spring.datasource.initialize=false
spring.jpa.database=default
spring.jpa.hibernate.ddl-auto=update

config file

@Configuration
@ComponentScan({"com.praeses.gov"})
public class Config {
@Bean
@ConfigurationProperties("spring.datasource.configuration")
public DataSourceProperties configDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@ConfigurationProperties("spring.datasource.configuration")
public DataSource configDataSource() {
    return configDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@Primary
@ConfigurationProperties("spring.datasource.cached")
public DataSourceProperties cachedDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("spring.datasource.cached")
public DataSource cachedDataSource() {
return cachedDataSourceProperties().initializeDataSourceBuilder().build();
    }

repository that uses the primary datasource

@Qualifier("spring.datasource.cached")
@Repository("spring.datasource.cached")
public interface GeoitemRepository extends JpaRepository<Geoitem, String> {
}

repository that uses the secondary datasource

@Qualifier("spring.datasource.configuration")
@Repository("spring.datasource.configuration")
public interface GeoitemhistoryRepository extends JpaRepository<Geoitemhistory, String> {
}

Body:
You can do something on similar lines as below link. Just create two config files instead of one(one each for each datasource) and add both of them to your main application.

Also, in the properties file, give as below:

datasource.local.url=
datasource.local.driver-class-name=
datasource.local.username=
datasource.local.password=

datasource.primary.url=
datasource.primary.driver-class-name=
datasource.primary.username=
datasource.primary.password=

Also, give @Primary annotation to the LocalContainerEntityManagerFactoryBean and platformTransactionManager in the config file for primary datasource.

See this answer for more details:
https://stackoverflow.com/a/44971911/6775742


问:
Open source C# projects with both unit tests and mocks (not MVC projects)
I would like to know of any prominent projects in Codeplex, GitHub etc which are C# with ASP.NET or even just C# APIs with both functioning tests (NUnit) and mocks (RhinoMocks, NMock etc).

The emphasis is on both tests and mocks.

答:
look at AutoMapper project

This is not ASP.NET but good for investigate Unit tests


问:
Perl remote write file connection error message Net::SFTP::Foreign
When I manually run this Perl script, it can establish a connection. But when I implement into the system, it shows this: authenticity of the target host can't be established, the remote host public key is probably not present on the '~/.ssh/known_hosts' file.

I need help and advice on this.

```<code>my $host = "xxxs.com";
my $sftp = Net::SFTP::Foreign->new($host,user => 'xxx', password => 'xxx',
                                   more => '-v',stderr_fh => $ssherr);
</code>```

答:
Solution for me was:

```<code>my $ftp = Net::SFTP::Foreign->new( $HOST,
                                    user => $USERNAME,
                                    password => $PASSWORD,
                                    more => [-o => 'StrictHostKeyChecking no'] );
</code>```

Where StrictHostKeyChecking did the trick.

ref: https://www.freebsd.org/cgi/man.cgi?query=Net::SFTP::Foreign

Body:
When I manually run this Perl script, it can establish a connection. But when I implement into the system, it shows this: authenticity of the target host can't be established, the remote host public key is probably not present on the '~/.ssh/known_hosts' file.

I need help and advice on this.

my $host = "xxxs.com";
my $sftp = Net::SFTP::Foreign->new($host,user => 'xxx', password => 'xxx',
                                   more => '-v',stderr_fh => $ssherr);

Body:
Solution for me was:

my $ftp = Net::SFTP::Foreign->new( $HOST,
                                    user => $USERNAME,
                                    password => $PASSWORD,
                                    more => [-o => 'StrictHostKeyChecking no'] );

Where StrictHostKeyChecking did the trick.

ref: https://www.freebsd.org/cgi/man.cgi?query=Net::SFTP::Foreign


问:
spring boot configuration properties not working
This is driving me up the wall trying to get spring boot @configurationproperties annotation working. So hoping someone can shed some light on this for me as to what I am doing wrong.
I have a spring boot application and it contains a application.properties on the classpath. It has a value in there of

```<code>server.contextPath=/test/v1
server.port=8080

spring.profiles.active=dev
vendors=me
</code>```

I have a application.class which has the spring boot annotation and sits at the top of my package hierarchy

```<code>package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableConfigurationProperties
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

I am trying to map the property vendors into a configurationproperties bean as below

```<code>package com.test.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:application.properties")
@ConfigurationProperties
public class GlobalProperties {

    private String vendors;

    public String getVendors() {
        return vendors;
    }

    public void setVendors(String vendors) {
        this.vendors = vendors;
    }
}
</code>```

and then call this bean from my rest controller. I know it resolves the property as when i rename it the server fails to start. In the code below the props bean is not getting autowired and is null. //code ommitted for brevity

```<code>package com.test.controller;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.test.config.GlobalProperties;

@RestController
@Component
public class MController {

    //TODO should be wired in from properties file
    @Autowired
    GlobalProperties props;

    private boolean vendorUnknown(String vendor) {
        if(props.getAllowedVendor().equalsIgnoreCase(vendor)) {
            return true;
        }
        return false;
    }

    @RequestMapping(value = "/test/{id}", method = RequestMethod.GET, produces = { "application/json" })
    public ResponseEntity<?> getStatus(
            @PathVariable String id) {
        //@RequestBody Bookmark input
        if(vendorUnknown("me")) {
        System.out.println("found");
    };
        return ResponseEntity.noContent().build();
    }

}
</code>```

Anybody point me to what i have done wrong please?

UPDATE:

changed the code above to be a more simplistic version with a test class to recreate the issue. See below for my pom.xml and test class

Pom.xml

```<code><?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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.me.test</groupId>
    <artifactId>test-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- tag::actuator[] -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- end::actuator[] -->
        <!-- tag::tests[] -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- end::tests[] -->
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Test class:

```<code>package com.test.controller;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @InjectMocks
    MController testController;

    @Before
    public void setup() {

        // this must be called for the @Mock annotations above to be processed
        // and for the mock service to be injected into the controller under
        // test.
        MockitoAnnotations.initMocks(this);

        this.mockMvc = MockMvcBuilders.standaloneSetup(testController).build();
    }

    @Test
    public void testPropertiesMsg() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/test/1").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk());
    }
}
</code>```

答:
Remove @PropertySource. You can keep @Component, or if you don't, specify @EnableConfigurationProperties(GlobalProperties.class).

Don't need @Component on testController. But I think your issue is where you're calling vendorUnknown method from. It's not shown in your code. If calling from the constructor, then the bean initialization has not completed yet, and GlobalProperties props is indeed null.

Edit:

Based on OP's edit, here's a fully working solution.

DemoApplication.java:

```<code>@SpringBootApplication
@EnableConfigurationProperties
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
</code>```

DemoController.java:

```<code>@RestController
public class DemoController {
    @Autowired
    private DemoProperties props;

    @GetMapping(value = "/", produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getVendor() {
        return ResponseEntity.ok(props.getVendors());
    }
}
</code>```

DemoProperties.java:

```<code>@ConfigurationProperties
@Component
public class DemoProperties {
    private String vendors;

    public String getVendors() {
        return vendors;
    }

    public void setVendors(String vendors) {
        this.vendors = vendors;
    }
}
</code>```

application.properties:

```<code>vendors=me
</code>```

DemoControllerTest.java:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoControllerTest {
    @Autowired
    TestRestTemplate restTemplate;

    @Test
    public void testGenVendor() throws Exception {
        String vendor = restTemplate.getForObject("/", String.class);

        assertThat(vendor).isEqualTo("me");
    }
}
</code>```

Problems with OP's code:

MockMvc doesn't use the main class, so EnableConfigurationPropertiesis not processed. MockMvc or WebMvcTest is designed to test the web layer (duh!), not the whole app. Using either of those. the properties bean should be set by the test.

InjectMocks fails silently. See Why You Should Not Use InjectMocks Annotation to Autowire Fields.

Body:
This is driving me up the wall trying to get spring boot @configurationproperties annotation working. So hoping someone can shed some light on this for me as to what I am doing wrong.
I have a spring boot application and it contains a application.properties on the classpath. It has a value in there of

server.contextPath=/test/v1
server.port=8080

spring.profiles.active=dev
vendors=me

I have a application.class which has the spring boot annotation and sits at the top of my package hierarchy

package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableConfigurationProperties
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

I am trying to map the property vendors into a configurationproperties bean as below

package com.test.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:application.properties")
@ConfigurationProperties
public class GlobalProperties {

    private String vendors;

    public String getVendors() {
        return vendors;
    }

    public void setVendors(String vendors) {
        this.vendors = vendors;
    }
}

and then call this bean from my rest controller. I know it resolves the property as when i rename it the server fails to start. In the code below the props bean is not getting autowired and is null. //code ommitted for brevity

package com.test.controller;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.test.config.GlobalProperties;

@RestController
@Component
public class MController {

    //TODO should be wired in from properties file
    @Autowired
    GlobalProperties props;

    private boolean vendorUnknown(String vendor) {
        if(props.getAllowedVendor().equalsIgnoreCase(vendor)) {
            return true;
        }
        return false;
    }

    @RequestMapping(value = "/test/{id}", method = RequestMethod.GET, produces = { "application/json" })
    public ResponseEntity<?> getStatus(
            @PathVariable String id) {
        //@RequestBody Bookmark input
        if(vendorUnknown("me")) {
        System.out.println("found");
    };
        return ResponseEntity.noContent().build();
    }

}

Anybody point me to what i have done wrong please?

UPDATE:

changed the code above to be a more simplistic version with a test class to recreate the issue. See below for my pom.xml and test class

Pom.xml

<?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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.me.test</groupId>
    <artifactId>test-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Test class:

package com.test.controller;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @InjectMocks
    MController testController;

    @Before
    public void setup() {

        // this must be called for the @Mock annotations above to be processed
        // and for the mock service to be injected into the controller under
        // test.
        MockitoAnnotations.initMocks(this);

        this.mockMvc = MockMvcBuilders.standaloneSetup(testController).build();
    }

    @Test
    public void testPropertiesMsg() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/test/1").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk());
    }
}

Body:
Remove @PropertySource. You can keep @Component, or if you don't, specify @EnableConfigurationProperties(GlobalProperties.class).

Don't need @Component on testController. But I think your issue is where you're calling vendorUnknown method from. It's not shown in your code. If calling from the constructor, then the bean initialization has not completed yet, and GlobalProperties props is indeed null.

Edit:

Based on OP's edit, here's a fully working solution.

DemoApplication.java:

@SpringBootApplication
@EnableConfigurationProperties
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

DemoController.java:

@RestController
public class DemoController {
    @Autowired
    private DemoProperties props;

    @GetMapping(value = "/", produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getVendor() {
        return ResponseEntity.ok(props.getVendors());
    }
}

DemoProperties.java:

@ConfigurationProperties
@Component
public class DemoProperties {
    private String vendors;

    public String getVendors() {
        return vendors;
    }

    public void setVendors(String vendors) {
        this.vendors = vendors;
    }
}

application.properties:

vendors=me

DemoControllerTest.java:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoControllerTest {
    @Autowired
    TestRestTemplate restTemplate;

    @Test
    public void testGenVendor() throws Exception {
        String vendor = restTemplate.getForObject("/", String.class);

        assertThat(vendor).isEqualTo("me");
    }
}

Problems with OP's code:

MockMvc doesn't use the main class, so EnableConfigurationPropertiesis not processed. MockMvc or WebMvcTest is designed to test the web layer (duh!), not the whole app. Using either of those. the properties bean should be set by the test.

InjectMocks fails silently. See Why You Should Not Use InjectMocks Annotation to Autowire Fields.


问:
Adding an icon left of primaryText in Material UI's <ListItem>
I have a <ListItem> from React Material UI that currently has a checkbox to the left. I want to add an image/icon in between the checkbox and the title (or rather, to the left of the title) and after looking at the docs, I'm unsure if this can be achieved.

I want to do something like:

This is easily achievable in
 with multiple row columns - is there something similar in ListItems? I see leftIcon on the docs but it isn't working.

```<code>import Checkbox from 'material-ui/Checkbox'

render() {
    <ListItem
        primaryText="autoblog.com"
        leftCheckbox={<Checkbox />
        rightToggle={<div style={{display: 'none'}} />}
    />
}
</code>```

答:
Try this, put the image inside leftCheckbox:

```<code>leftCheckbox={  <div>
                    <Checkbox />
                    <img src='https://www.w3schools.com/css/img_fjords.jpg'/>
                </div>
}
</code>```

Apply css to position the image correctly.

Check this fiddle.

Body:
I have a <ListItem> from React Material UI that currently has a checkbox to the left. I want to add an image/icon in between the checkbox and the title (or rather, to the left of the title) and after looking at the docs, I'm unsure if this can be achieved.

I want to do something like:

This is easily achievable in
 with multiple row columns - is there something similar in ListItems? I see leftIcon on the docs but it isn't working.

import Checkbox from 'material-ui/Checkbox'

render() {
    <ListItem
        primaryText="autoblog.com"
        leftCheckbox={<Checkbox />
        rightToggle={
}
    />
}

Body:
Try this, put the image inside leftCheckbox:

leftCheckbox={  <div>
                    <Checkbox />
                    <img src='https://www.w3schools.com/css/img_fjords.jpg'/>
                </div>
}

Apply css to position the image correctly.

Check this fiddle.


问:
Passing a function as an argument
I am teaching myself javascript and one of the exercises I have tried makes no sense to me.

In the code below 'position' is a parameter that must be defined. However, when I pass the function, displayLocation as an argument to navigator.geolocation.getCurrentPosition, the code executes flawlessly, despite no argument being passed. When I try coords.longitude in the console without the position argument, it does not work.

How does the code work without a defined argument?

```<code>function displayLocation(position)
{
  var latitude = latitude.coords.latitude;
  var longitude = position.coords.longitude;
  var div = document.getElementById("location");
  div.innerHTML = latitude + " " + longitude;
}

navigator.geolocation.getCurrentPosition(displayLocation);
</code>```

答:
When I try coords.longitude in the console without the position
argument, it does not work...

How does the code work without a defined argument?

Arguments of function in JavaScript are optional.

If you don't pass it, it has as value : undefined.
So, yes the function accepts an invocation with a missing argument  position but position.coords would not be usable.

Title: Passing a function as an argument

Body:
I am teaching myself javascript and one of the exercises I have tried makes no sense to me.

In the code below 'position' is a parameter that must be defined. However, when I pass the function, displayLocation as an argument to navigator.geolocation.getCurrentPosition, the code executes flawlessly, despite no argument being passed. When I try coords.longitude in the console without the position argument, it does not work.

How does the code work without a defined argument?

function displayLocation(position)
{
  var latitude = latitude.coords.latitude;
  var longitude = position.coords.longitude;
  var div = document.getElementById("location");
  div.innerHTML = latitude + " " + longitude;
}

navigator.geolocation.getCurrentPosition(displayLocation);


问:
How do I know when HTML has fully rendered
case 1:

I load a very large HTML page that includes a lot of complex layout and fonts.
The page will take some unknown time to render.

case 2:

I use jquery .html() function to make significant changes to my DOM.
The modified DOM will take some unknown time to render.

In both cases, I want to be able to cover the whole screen with a spinner until the page has completely finished rendering.

In searching for answers to this question, I have found similar questions asked but the answers are not relevant. To be clear:

I don't want to know when the DOM is ready.

I don't want to know when the HTTP data has been fetched.

I want to know when everything in the DOM has been completely drawn to the screen.

Setting some worst-case timeout is not an acceptable solution.

I need a solution for WebKit based browsers.

答:
Something like this should hopefully work:</p>

```<code>...
<head>
  ...
  <style type="text/css">
    #overlay {
      background:url(../images/loading.gif) no-repeat 50% 50%;
      display:none;
    }
    .loading #overlay {
      display:block;
      left:0;
      height:100%;
      position:absolute;
      top:0;
      width:100%;
    }
    .loading > #overlay {
      position:fixed;
    }
  </style>
  <script>
    if (document.documentElement) {
      document.documentElement.className = 'loading';
    }
  </script>
</head>
<body>
  ..
  <div id="overlay">
    ..
  </div>
  <script>
    $(document).ready(function() {
      $('.loading #overlay').fadeOut(500,
        function() {
          $(document.documentElement).removeClass('loading');
          $('#overlay').remove();
        });
    });
</body>
</html>
</code>```

Body:
Something like this should hopefully work:

...
<head>
  ...
  <style type="text/css">
    #overlay {
      background:url(../images/loading.gif) no-repeat 50% 50%;
      display:none;
    }
    .loading #overlay {
      display:block;
      left:0;
      height:100%;
      position:absolute;
      top:0;
      width:100%;
    }
    .loading > #overlay {
      position:fixed;
    }
  </style>
  <script>
    if (document.documentElement) {
      document.documentElement.className = 'loading';
    }
  </script>
</head>
<body>
  ..
  <div id="overlay">
    ..
  </div>
  <script>
    $(document).ready(function() {
      $('.loading #overlay').fadeOut(500,
        function() {
          $(document.documentElement).removeClass('loading');
          $('#overlay').remove();
        });
    });
</body>
</html>


问:
Selecting/Inner Joining multiple values from one table into a single row
I've been searching google all afternoon I'm not even sure how I would word the question I have so that google or bing might understand it. So I have 2 tables(the tables and the database setup were not my doing) one is the details of a product

```<code>name, value, weight, weight unit of measure id, length, width, height, dimensions unit of measure id, description
</code>```

Then another table with the units of measure and their ID values

eg.

```<code>id, unit name
1,     cm
2,   inches
3,     lbs
4,     kg
5,    feet
</code>```

I need to select from the products table, but replace the unit of measure ID's with the actual unit of measure text from the other table.

the data looks like

```<code>sm widgets, $10, 20, 3, 10, 10, 10, 1, small widgets
</code>```

I want the results to come out like

```<code>sm widget, $10, 20, lbs, 10, 10, 10, cm, small widgets
lg widget, $15, 50, kg, 10, 10, 10, inches, large widgets
</code>```

thanks for any insight you guys can give me

答:
I think you just need to join the tables and return the description:</p>

```<code>select
    p.name,
    p.value,
    p.weight,
    c.[unitname],
    p.length,
    p.width,
    p.height,
    c2.[unitname] as DimensionUnitName,
    p.[description]
from products p
inner join unitcodetable c
    on c.id = p.[weight unit of measure id]
inner join unitcodetable c2
    on c2.id = p.[dimensions unit of measure id]
</code>```

Body:
I've been searching google all afternoon I'm not even sure how I would word the question I have so that google or bing might understand it. So I have 2 tables(the tables and the database setup were not my doing) one is the details of a product

name, value, weight, weight unit of measure id, length, width, height, dimensions unit of measure id, description

Then another table with the units of measure and their ID values

eg.

id, unit name
1,     cm
2,   inches
3,     lbs
4,     kg
5,    feet

I need to select from the products table, but replace the unit of measure ID's with the actual unit of measure text from the other table.

the data looks like

sm widgets, $10, 20, 3, 10, 10, 10, 1, small widgets

I want the results to come out like

sm widget, $10, 20, lbs, 10, 10, 10, cm, small widgets
lg widget, $15, 50, kg, 10, 10, 10, inches, large widgets

thanks for any insight you guys can give me

Body:
I think you just need to join the tables and return the description:

select
    p.name,
    p.value,
    p.weight,
    c.[unitname],
    p.length,
    p.width,
    p.height,
    c2.[unitname] as DimensionUnitName,
    p.[description]
from products p
inner join unitcodetable c
    on c.id = p.[weight unit of measure id]
inner join unitcodetable c2
    on c2.id = p.[dimensions unit of measure id]


问:
Excel consolidate yields incorrect list of unique values
I have two columns that look like this:

```<code>Make/Model      Parc
Abarth*500      15
Abarth*500      19
Abarth*500      2
Abarth*500      14
Abarth*500      15
Abarth*500      25
Abarth*500      20
Abarth*500      17
Abarth*500C     12
Abarth*500C     16
Abarth*500C     23
Abarth*500C     18
Abarth*500C     1
Alfa Romeo*145  405
Alfa Romeo*145  431
Alfa Romeo*146  36
Alfa Romeo*146  80
Alfa Romeo*146  121
Alfa Romeo*146  72
Alfa Romeo*146  39
</code>```

etc...

The sum of the values in the "Parc" column is 10,475,387.

I perform a consolidate on this table to remove the repetitions in "Make/Model" and sum the values in the "Parc" column for each "Make/Model."

Once I perform the consolidation, everything looks as expected:

```<code>Make/Model      Parc
Abarth*500      127
Abarth*500C     70
Alfa Romeo*145  836
Alfa Romeo*146  348
Alfa Romeo*147  3848
Alfa Romeo*155  29
Alfa Romeo*156  3148
Alfa Romeo*159  573
Alfa Romeo*164  111
</code>```

etc...

So what's the problem? The new sum of the "Parc" column is 10,554,076! Verification against an alternate method indicates that the column of unique labels is incorrect in seemingly random places. I also do not understand how the total sum could have gone up. I have over 18,000 rows in this dataset so individually checking all of the data would be very time consuming.

You can find the full dataset here:
Excel File

What have I tried?

I have tried removing all formatting. Also, these numbers are all integers and the option to "Automatically insert a decimal point" is not checked. I have also tried creating a new column of =INT() values to ensure they are all integers. My results are exactly the same in all cases.

I posted this question yesterday and it was put on hold because it could not be reproduced without the full dataset: Excel consolidate sum yields different column total

EDIT:
As Mauricio Noris Freire has shown, you can create a unique item column using advanced filter, and then use SUMIF to solve this problem correctly. I still would like to know why the Excel data tool consolidate does not work as expected.

答:
I don't think that value is wrong. Take a look into the file which I have recriate the parc column using a sumif formula
https://drive.google.com/open?id=0B4_RkQvn7-_TeG9kSE5NV0Z6Umc</p>

Body:
I have two columns that look like this:

Make/Model      Parc
Abarth*500      15
Abarth*500      19
Abarth*500      2
Abarth*500      14
Abarth*500      15
Abarth*500      25
Abarth*500      20
Abarth*500      17
Abarth*500C     12
Abarth*500C     16
Abarth*500C     23
Abarth*500C     18
Abarth*500C     1
Alfa Romeo*145  405
Alfa Romeo*145  431
Alfa Romeo*146  36
Alfa Romeo*146  80
Alfa Romeo*146  121
Alfa Romeo*146  72
Alfa Romeo*146  39

etc...

The sum of the values in the "Parc" column is 10,475,387.

I perform a consolidate on this table to remove the repetitions in "Make/Model" and sum the values in the "Parc" column for each "Make/Model."

Once I perform the consolidation, everything looks as expected:

Make/Model      Parc
Abarth*500      127
Abarth*500C     70
Alfa Romeo*145  836
Alfa Romeo*146  348
Alfa Romeo*147  3848
Alfa Romeo*155  29
Alfa Romeo*156  3148
Alfa Romeo*159  573
Alfa Romeo*164  111

etc...

So what's the problem? The new sum of the "Parc" column is 10,554,076! Verification against an alternate method indicates that the column of unique labels is incorrect in seemingly random places. I also do not understand how the total sum could have gone up. I have over 18,000 rows in this dataset so individually checking all of the data would be very time consuming.

You can find the full dataset here:
Excel File

What have I tried?

I have tried removing all formatting. Also, these numbers are all integers and the option to "Automatically insert a decimal point" is not checked. I have also tried creating a new column of =INT() values to ensure they are all integers. My results are exactly the same in all cases.

I posted this question yesterday and it was put on hold because it could not be reproduced without the full dataset: Excel consolidate sum yields different column total

EDIT:
As Mauricio Noris Freire has shown, you can create a unique item column using advanced filter, and then use SUMIF to solve this problem correctly. I still would like to know why the Excel data tool consolidate does not work as expected.


问:
Lodash update element values from another array Chain / Map
How I can update an array element values with another array elements data values, using Lodash

```<code>var Master_Array [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
]

var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
]
</code>```

I think that can be did with:

```<code>_.chain()
.mapValues( ...blá blá... )
.values()
.value();
</code>```

Expected result:

```<code>var Master_Array [
{ Name: "Jon", Region: "NAC" },
{ Name: "Ruan", Region: "APAC" }
]
</code>```

答:
A javascript solution

var Master_Array = [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
];
var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
];

var result = [];
Master_Array.forEach(function(data){
  var temp = Regions_Map.filter(function(map){
    if(map.Region === data.Region){
      return map;
    }
  });
  if(temp){
  result.push({
        Name : data.Name,
        NewRegion: temp[0].NewRegion
      });
  }
});

console.log(result);```

Body:
How I can update an array element values with another array elements data values, using Lodash

var Master_Array [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
]

var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
]

I think that can be did with:

_.chain()
.mapValues( ...blá blá... )
.values()
.value();

Expected result:

var Master_Array [
{ Name: "Jon", Region: "NAC" },
{ Name: "Ruan", Region: "APAC" }
]


答:
navigator.geolocation.getCurrentPosition(displayLocation); calls your function with an instance of Position, as documented here.

Please take into account that displayLocation is not called immediately but delayed. This is why you pass it as a callback function.

Title: Passing a function as an argument


问:
Unregistering e.preventDefault in reactJS method
I'm in situation where I need to fire a google analytic event onClicking a link. I wrote a handler for the purpose:

```<code>handleClick(e){
  e.preventDefault();
  // --------------------------
   GA code ...
  // --------------------------
  // now how can I re-eanble the link
  // e.target.click() and similar methods are not working for me

}
</code>```

But after GA event is fired, I couldn't find a way to unbind the preventDefault from the link (created with React's "link" component).

Any pointers will be helpful.

答:
You can try by updating the state.
The below sample I have tried to  conditionally attach the event handler..
I have removed the handler attached to onClick event of the button after the first call.

I have also tried out conditionally executing e.preventDefault for the link.

https://codesandbox.io/s/MQnoVJKJR

```<code>import React from 'react';

export default class Hello extends React.Component {
  state = {
    btnClicked: false,
    linkClicked: false,
  };
  constructor() {
    super();
  }
  handleClick(e) {
    e.preventDefault();
    alert('button clicked');
    this.setState({
      btnClicked: true,
    });
  }
  handleLinkClick(e) {
    if (!this.state.linkClicked) {
      e.preventDefault();
    }
    this.setState({
      linkClicked: true,
    });
  }
  render() {
    return (
      <div>
        <div>
          <button
            onClick={!this.state.btnClicked && this.handleClick.bind(this)}> // Binding onClick event to state change

            Click Me
          </button>
        </div>
        <a
          href="https://www.google.co.in"
          target="_blank"
          onClick={this.handleLinkClick.bind(this)}
        >
          Go to Google.com
        </a>
      </div>
    );
  }
}
</code>```

Body:
I'm in situation where I need to fire a google analytic event onClicking a link. I wrote a handler for the purpose:

handleClick(e){
  e.preventDefault();
  // --------------------------
   GA code ...
  // --------------------------
  // now how can I re-eanble the link
  // e.target.click() and similar methods are not working for me

}

But after GA event is fired, I couldn't find a way to unbind the preventDefault from the link (created with React's "link" component).

Any pointers will be helpful.

Body:
You can try by updating the state.
The below sample I have tried to  conditionally attach the event handler..
I have removed the handler attached to onClick event of the button after the first call.

I have also tried out conditionally executing e.preventDefault for the link.

https://codesandbox.io/s/MQnoVJKJR

import React from 'react';

export default class Hello extends React.Component {
  state = {
    btnClicked: false,
    linkClicked: false,
  };
  constructor() {
    super();
  }
  handleClick(e) {
    e.preventDefault();
    alert('button clicked');
    this.setState({
      btnClicked: true,
    });
  }
  handleLinkClick(e) {
    if (!this.state.linkClicked) {
      e.preventDefault();
    }
    this.setState({
      linkClicked: true,
    });
  }
  render() {
    return (
      <div>
        <div>
          <button
            onClick={!this.state.btnClicked && this.handleClick.bind(this)}> // Binding onClick event to state change

            Click Me
          </button>
        </div>
        <a
          href="https://www.google.co.in"
          target="_blank"
          onClick={this.handleLinkClick.bind(this)}
        >
          Go to Google.com
        </a>
      </div>
    );
  }
}


问:
MATLAB Figure Title gets cut off
When I use the following code to display an image, it displays fine, but the figure window is cropped close around the figure so that the title is cut off. It's definitely there though because if I manually make the window taller, then the title becomes visible.

I think this is my fault because a while back I was messing around with default settings for how MATLAB fits the window to the axis. Now I just can't remember the settings that changed this. Can anyone help? Thanks.

Code:

```<code>figure();
imshow(my_img);
title('A Sample Image');
</code>```

答: Similar to the solution by Blairg23; adding spaces to the end of the title works.</p>

OwnerDisplayName: SSilk

Title: MATLAB Figure Title gets cut off

Body:
When I use the following code to display an image, it displays fine, but the figure window is cropped close around the figure so that the title is cut off. It's definitely there though because if I manually make the window taller, then the title becomes visible.

I think this is my fault because a while back I was messing around with default settings for how MATLAB fits the window to the axis. Now I just can't remember the settings that changed this. Can anyone help? Thanks.

Code:

figure();
imshow(my_img);
title('A Sample Image');