text:
Q: How do I recover a dropped stash in Git? I frequently use git stash and git stash pop to save and restore changes in my working tree. Yesterday, I had some changes in my working tree that I had stashed and popped, and then I made more changes to my working tree. I'd like to go back and review yesterday's stashed changes, but git stash pop appears to remove all references to the associated commit.
I know that if I use git stash then .git/refs/stash contains the reference of the commit used to create the stash. And .git/logs/refs/stash contains the whole stash. But those references are gone after git stash pop. I know that the commit is still in my repository somewhere, but I don't know what it was.
Is there an easy way to recover yesterday's stash commit reference?

A: I just constructed a command that helped me find my lost stash commit:
for ref in `find .git/objects | sed -e 's#.git/objects/##' | grep / | tr -d /`; do if [ `git cat-file -t $ref` = "commit" ]; then git show --summary $ref; fi; done | less

This lists all the objects in the .git/objects tree, locates the ones that are of type commit, then shows a summary of each one. From this point it was just a matter of looking through the commits to find an appropriate "WIP on work: 6a9bb2" ("work" is my branch, 619bb2 is a recent commit).
I note that if I use "git stash apply" instead of "git stash pop" I wouldn't have this problem, and if I use "git stash save message" then the commit might have been easier to find.
Update: With Nathan's idea, this becomes shorter:
for ref in `git fsck --unreachable | grep commit | cut -d' ' -f3`; do git show --summary $ref; done | less

A: This worked for me (in 2022) with recovering my accidently deleted stash in git from a windows environment.
These steps outline how to recover any deleted git stashes or branches (assuming it has not been permanently delete by garbage collection).

*

*Navigate to the directory where your project located.

*Enter the command: git fsck --no-reflogs | find  "dangling commit"

*A list of hashes for dangling commits will appear. These will consist of branches and stashes that were deleted. Start with copy and pasting the hashes near the end of the list to find your stash or branch. For example, use the command: git log -1 [hash]

*If the corresponding hash matches what you are trying to recover, use the following command to restore it"
git stash apply [hash]

A: Windows PowerShell equivalent using gitk:
gitk --all $(git fsck --no-reflog | Select-String "(dangling commit )(.*)" | %{ $_.Line.Split(' ')[2] })
There is probably a more efficient way to do this in one pipe, but this does the job.

A: If you didn't close the terminal, just look at the output from git stash pop and you'll have the object ID of the dropped stash. It normally looks like this:
$ git stash pop
[...]
Dropped refs/stash@{0} (2ca03e22256be97f9e40f08e6d6773c7d41dbfd1)

(Note that git stash drop also produces the same line.)
To get that stash back, just run git branch tmp 2cae03e, and you'll get it as a branch. To convert this to a stash, run:
git stash apply tmp
git stash

Having it as a branch also allows you to manipulate it freely; for example, to cherry-pick it or merge it.

A: To see the commits in terminal, only filtering the ones we care about we can use:
git log --oneline --all --grep="^WIP on .*: [a-f0-9]\+" --grep="^On [^ ]*:" --grep="^index on [^ ]*:" $( env LANG=C git fsck --no-reflog | awk '/dangling commit/ {print $3}' )

This is based on Aristotle Pagaltzis answer.

A: git fsck --unreachable | grep commit should show the sha1, although the list it returns might be quite large. git show <sha1> will show if it is the commit you want.
git cherry-pick -m 1 <sha1> will merge the commit onto the current branch.

A: What I came here looking for is how to actually get the stash back, regardless of what I have checked out. In particular, I had stashed something, then checked out an older version, then poped it, but the stash was a no-op at that earlier time point, so the stash disappeared; I couldn't just do git stash to push it back on the stack. This worked for me:
$ git checkout somethingOld
$ git stash pop
...
nothing added to commit but untracked files present (use "git add" to track)
Dropped refs/stash@{0} (27f6bd8ba3c4a34f134e12fe69bf69c192f71179)
$ git checkout 27f6bd8ba3c
$ git reset HEAD^    # Make the working tree differ from the parent.
$ git stash # Put the stash back in the stack.
Saved working directory and index state WIP on (no branch): c2be516 Some message.
HEAD is now at c2be516 Some message.
$ git checkout somethingOld # Now we are back where we were.

In retrospect, I should have been using git stash apply not git stash pop. I was doing a bisect and had a little patch that I wanted to apply at every bisect step. Now I'm doing this:
$ git reset --hard; git bisect good; git stash apply
$ # Run tests
$ git reset --hard; git bisect bad; git stash apply
etc.

A: Recovered it by using following steps:

*

*Identify the deleted stash hash code:
gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )

*Cherry Pick the Stash:
git cherry-pick -m 1 $stash_hash_code

*Resolve Conflicts if any using:
git mergetool
Additionally you might be having issues with commit message if you are using gerrit. Please Stash your changes before following next alternatives:

*

*Use hard reset to previous commit and then recommit this change.

*You may also stash the change, rebase and  recommit.

A: If you want to restash a lost stash, you need to find the hash of your lost stash first.
As Aristotle Pagaltzis suggested a git fsck should help you.
Personally I use my log-all alias which show me every commit (recoverable commits) to have a better view of the situation :
git log --graph --decorate --pretty=oneline --abbrev-commit --all $(git fsck --no-reflogs | grep commit | cut -d' ' -f3)

You can do an even faster search if you're looking only for "WIP on" messages.
Once you know your sha1, you simply change your stash reflog to add the old stash :
git update-ref refs/stash ed6721d

You'll probably prefer to have an associated message so a -m
git update-ref -m "$(git log -1 --pretty=format:'%s' ed6721d)" refs/stash ed6721d

And you'll even want to use this as an alias :
restash = !git update-ref -m $(git log -1 --pretty=format:'%s' $1) refs/stash $1

A: Once you know the hash of the stash commit you dropped, you can apply it as a stash:
git stash apply $stash_hash

Or, you can create a separate branch for it with
git branch recovered $stash_hash

After that, you can do whatever you want with all the normal tools. When you're done, just blow the branch away.
Finding the hash
If you have only just popped it and the terminal is still open, you will still have the hash value printed by git stash pop on screen (thanks, Dolda).
Otherwise, you can find it using this for Linux, Unix or Git Bash for Windows:
git fsck --no-reflog | awk '/dangling commit/ {print $3}'

...or using PowerShell for Windows:
git fsck --no-reflog | select-string 'dangling commit' | foreach { $_.ToString().Split(" ")[2] }

This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you've ever created, will be somewhere in that graph.
The easiest way to find the stash commit you want is probably to pass that list to gitk:
gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )

...or see the answer from emragins if using PowerShell for Windows.
This will launch a repository browser showing you every single commit in the repository ever, regardless of whether it is reachable or not.
You can replace gitk there with something like git log --graph --oneline --decorate if you prefer a nice graph on the console over a separate GUI app.
To spot stash commits, look for commit messages of this form:
        WIP on somebranch: commithash Some old commit message
Note: The commit message will only be in this form (starting with "WIP on") if you did not supply a message when you did git stash.

A: Just wanted to mention this addition to the accepted solution.  It wasn't immediately obvious to me the first time I tried this method (maybe it should have been), but to apply the stash from the hash value, just use "git stash apply ":
$ git stash apply ad38abbf76e26c803b27a6079348192d32f52219

When I was new to git, this wasn't clear to me, and I was trying different combinations of "git show", "git apply", "patch", etc.

A: My favorite is this one-liner:
git log --oneline  $( git fsck --no-reflogs | awk '/dangling commit/ {print $3}' )

This is basically the same idea as this answer but much shorter. Of course, you can still add --graph to get a tree-like display.
When you have found the commit in the list, apply with
git stash apply THE_COMMIT_HASH_FOUND

For me, using --no-reflogs did reveal the lost stash entry, but --unreachable (as found in many other answers) did not.
Run it on git bash when you are under Windows.
Credits: The details of the above commands are taken from https://gist.github.com/joseluisq/7f0f1402f05c45bac10814a9e38f81bf

A: You can list all unreachable commits by writing this command in terminal -
git fsck --unreachable

Check unreachable commit hash -
git show hash

Finally apply if you find the stashed item -
git stash apply hash

A: I liked Aristotle's approach, but didn't like using GITK... as I'm used to using GIT from the command line.
Instead, I took the dangling commits and output the code to a DIFF file for review in my code editor.
git show $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' ) > ~/stash_recovery.diff

Now you can load up the resulting diff/txt file (its in your home folder) into your txt editor and see the actual code and resulting SHA.
Then just use
git stash apply ad38abbf76e26c803b27a6079348192d32f52219

A: To get the list of stashes that are still in your repository, but not reachable any more:
git fsck --unreachable | grep commit | cut -d" " -f3 | xargs git log --merges --no-walk --grep=WIP

If you gave a title to your stash, replace "WIP" in -grep=WIP at the end of the command with a part of your message, e.g. -grep=Tesselation.
The command is grepping for "WIP" because the default commit message for a stash is in the form WIP on mybranch: [previous-commit-hash] Message of the previous commit.
When you have found the commit, apply it with git stash apply <commit_hash>

A: In OSX with git v2.6.4, I just run git stash drop accidentally, then I found it by going trough below steps
If you know name of the stash then use:
$ git fsck --unreachable | grep commit | cut -c 20- | xargs git show | grep -B 6 -A 2 <name of the stash>
otherwise you will find ID from the result by manually with:
$ git fsck --unreachable | grep commit | cut -c 20- | xargs git show
Then when you find the commit-id just hit the git stash apply {commit-id}
Hope this helps someone quickly

A: To see only stash commits, where they attached, and what their contents are
result sample
Checking object directories: 100% (256/256), done.
2022-08-31 10:20:46 +0900 8d02f61 WIP on master: 243b594 add css
A       favicon.ico

command
git fsck --dangling | awk '/dangling commit/ {print $3}' | xargs -L 1 git --no-pager show -s --format="%ct %h" | sort | awk '{print $2}' | { while read hash; do status=$(git stash show $hash --name-status 2>/dev/null); if (( $? == 0 )); then git show $hash -s --format="%C(green)%ci %C(yellow)%h %C(blue)%B"; echo "$status"; fi; done; }

*

*To see full hash, change %h to %H

*To reduce time, tail fsck like git fsck --dangling | tail -100 | awk ...
recover sample

A: Why do people ask this question? Because they don't yet know about or understand the reflog.
Most answers to this question give long commands with options almost nobody will remember. So people come into this question and copy paste whatever they think they need and forget it almost immediately after.
I would advise everyone with this question to just check the reflog (git reflog), not much more than that. Once you see that list of all commits there are a hundred ways to find out what commit you're looking for and  to cherry-pick it or create a branch from it. In the process you'll have learned about the reflog and useful options to various basic git commands.

A: I couldn't get any of the answers to work on Windows in a simple command window (Windows 7 in my case). awk, grep and Select-string weren't recognized as commands. So I tried a different approach:

*

*first run: git fsck --unreachable | findstr "commit"

*copy the output to notepad

*find replace "unreachable commit" with start cmd /k git show
will look something like this:
start cmd /k git show 8506d235f935b92df65d58e7d75e9441220537a4
start cmd /k git show 44078733e1b36962571019126243782421fcd8ae
start cmd /k git show ec09069ec893db4ec1901f94eefc8dc606b1dbf1
start cmd /k git show d00aab9198e8b81d052d90720165e48b287c302e

*

*save as a .bat file and run it

*the script will open a bunch of command windows, showing each commit

*if you found the one you're looking for, run: git stash apply (your hash)
may not be the best solution, but worked for me

A: I want to add to the accepted solution another good way to go through all the changes, when you either don't have gitk available or no X for output.
git fsck --no-reflog | awk '/dangling commit/ {print $3}' > tmp_commits

for h in `cat tmp_commits`; do git show $h | less; done

Then you get all the diffs for those hashes displayed one after another. Press 'q' to get to the next diff.

A: The accepted answer by Aristotle will show all reachable commits, including non-stash-like commits. To filter out the noise:
git fsck --no-reflog | \
awk '/dangling commit/ {print $3}' | \
xargs git log --no-walk --format="%H" \
  --grep="WIP on" --min-parents=3 --max-parents=3

This will only include commits which have exactly 3 parent commits (which a stash will have), and whose message includes "WIP on".
Keep in mind, that if you saved your stash with a message (e.g. git stash save "My newly created stash"), this will override the default "WIP on..." message.
You can display more information about each commit, e.g. display the commit message, or pass it to git stash show:
git fsck --no-reflog | \
awk '/dangling commit/ {print $3}' | \
xargs git log --no-walk --format="%H" \
  --grep="WIP on" --min-parents=3 --max-parents=3 | \
xargs -n1 -I '{}' bash -c "\
  git log -1 --format=medium --color=always '{}'; echo; \
  git stash show --color=always '{}'; echo; echo" | \
less -R

A: Knowing the approximate file name and it's location, and was able to find dropped stash files grepping dangling commits for path
for i in $(git fsck --no-reflogs | awk '/dangling commit/ {print $3}'); do
  if git log -5 --name-only -u $i | grep -q "<path-to-files>/.*<partial-file-name>.*"; then
    echo "found something in commit $i";
  fi;
done

A: You can follow the below process step by step:
1- use below to list all unreachable commits
git fsck --unreachable
2- to show unreachable commit hash by
git show hash
3- copy all log, you can see log like, unreachable blob, commit, tree.
4- apply git stash with log having commit hash
git stash apply [replace hash]

A: Not exactly an answer to get a stash but if the goal is to get uncommited changes that were first stashed and then popped in another branch but meant for both and done in the following way:

*

*Make changes in branch_a

*git stash

*Make branch_b from branch_a

*git stash apply
Then to restore the uncommited changes to branch_a:

*

*git checkout branch_a

*git merge branch_b

*git reset HEAD~1


text:
Q: Mysql date range query only check date without check month and year I want in select records based on date condition of day only without checking month and year.
Table structure
------------------------------------
id | user_id  | amount | created_on
------------------------------------

If I select date 15-April to 25-April, Then I need record between 15-April to 25-April, 15-March to 25-March and so on..
It seems quite easy with fetch day from date and compare it with
Select sum(amount) from sales where DATEFORMAT(created_on, %d) >= 15 and DATEFORMAT(created_on, %d) <=25

But how to find records when i select date 28-March to 5-April, then I need data of 28-February to 5-March, 28-January to 5-February.. and so on

A: If you are using php with it. you can compare minimum and maximum dates and change your query like this:
Attempt #1:
    $min_date = 15;
    $max_date = 25;

Attempt #2:
    $min_date = 28;
    $max_date = 5;

Script:
    if($min_date < $max_date)
    {
        $query = "Select sum(amount) from sales where DATEFORMAT(created_on, %d) >= $min_date and DATEFORMAT(created_on, %d) <=$max_date";
    }
    else
    {
        $query = "Select sum(amount) from sales where DATEFORMAT(created_on, %d) >= $min_date OR DATEFORMAT(created_on, %d) <=$max_date";
    }

A: You can use SQL BETWEEN Operator
Select sum(amount) from sales where created_on BETWEEN '2017/03/28'  and '2017/04/05'

Source SQL Between Operator

A: Can you try this?  (X1 and X2 are your values)
Select sum(amount)
from sales
where
    (1= CASE WHEN X2>=X1 THEN 1 ELSE 0 END AND DATEFORMAT(created_on, %d) >= X1 and DATEFORMAT(created_on, %d) <=x2)
OR (1= CASE WHEN X2<X1 THEN 1 ELSE 0 END AND ( DATEFORMAT(created_on, %d) >=X1 OR DATEFORMAT(created_on, %d) <=X2))

A: use this to extract only date from your timestamp and then compare it with ur requirement.
select SUBSTRING(date(CURRENT_TIMESTAMP), 9, 2) , SUBSTRING(date('2017-04-27' ), 9, 2)
OUTPUT: 27 , 27
Cheers!!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Domain password replication We have an interesting situation.
We have two domains, one, called Smith(not really, but you get the idea) which is our main office based domain against which users are authenticated on login.
Another domain is hosted, and has a couple of servers running a database (SQL Server) server and SharePoint. The problem is that this domain is also called Smith.
How can we synchronise the users passwords between these two domains ?
Can we setup a trust between them (even though they have the same names) and have these users be able to access sharepoint and SQL Server through Windows Authenticated mode ?
If not, do you have any ideas as to how we could achieve this ?
Cheers
Nick

A: Eww! There'll be no trust relationship for you if both the domains have the same name. The domains are essentially "the same" as far as DNS knows, and getting name resolution to work for both domains simultaneously from a single DNS server would have to be a major hack. There would be conflicting records from both domains (the domain's "A" record, for example) that can't "co-exist" in a hacked up amalgamation of both DNS domains, too. What you have there we in "the business" call A Real Mess(tm).
I'm not even sure that Microsoft's Identity Lifecycle Manager could handle synchronizing the passwords because of the name resolution ambiguity between the domains. I don't know enough about the product to say definitively. I can say that it appears to be very expensive. I'd avoid it, and other directory "synchronization" products if at all possible, if only because it's adding a lot of needless complexity.
I'd strongly consider renaming one of the domains. Have a look at the article here: https://web.archive.org/web/1/http://techrepublic%2ecom%2ecom/5208-6230-0.html?forumID=102&threadID=229757&start=0  It's a very straightforward process, and gives you the best possible configuration (unique domain names) moving forward.
I haven't renamed a domain that was as complex as the one in the article, but small domains w/ a couple of DCs and some lab examples that were slightly more complex seemed to go fine.


text:
Q: I am not able to push my docker Image on Elastic container registry I created an ecr
I have authenticated with aws and I am able to do docke login successfully but still getting not authorised while pushing my image
I also tried sudo but I am using windows
I am putting the error image for reference
enter image description here

A: I made a script recently, see if it helps
import os

def build(account_id, image_name, repository_name, docker_file):
    """
    Parameters
    ----------
    account_id: AWS account ID
    image_name: Docker image to be built and assigned a name
    repository_name: AWS ECR repository name
    docker_file: The docker file to use
    """
    print("starting docker build...")
    os.system(
        'docker build --pull --rm -f "'
        + docker_file
        + '" -t '
        + image_name
        + ':latest "."'
    )
    print("done.")

    print("logging in aws ecr...")
    os.system(
        "aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin "
        + account_id
        + ".dkr.ecr.us-east-1.amazonaws.com"
    )
    print("done.")

    print("tagging...")
    os.system(
        "docker tag "
        + image_name
        + ":latest "
        + account_id
        + ".dkr.ecr.us-east-1.amazonaws.com/"
        + repository_name
    )
    print("done.")

    print("pushing to ecr...")
    os.system(
        "docker push "
        + account_id
        + ".dkr.ecr.us-east-1.amazonaws.com/"
        + repository_name
    )
    print("done.")

if __name__ == "__main__":
    docker_file_name = ""
    aws_account_id = ""
    docker_image_name = ""
    ecr_repository_name = ""
    build(aws_account_id, docker_image_name, ecr_repository_name, docker_file_name)


text:
Q: Neo4J Match & Set Multiple Relationships/Nodes in One Query I'm currently running the following query to update the properties on two nodes and relationships.
I'd like to be able to update 1,000 nodes and the corresponding relationships in one query.
MATCH (p1:Person)-[r1:OWNS_CAR]->(c1:Car) WHERE id(r1) = 3018
MATCH (p2:Person)-[r2:OWNS_CAR]->(c2:Car) WHERE id(r2) = 3019
SET c1.serial_number = 'SERIAL027436', c1.signature = 'SIGNATURE728934',
r1.serial_number = 'SERIAL78765', r1.signature = 'SIGNATURE749532',
c2.serial_number = 'SERIAL027436', c2.signature = 'SIGNATURE728934',
r2.serial_number = 'SERIAL78765', r2.signature = 'SIGNATURE749532'

This query has issues when you run it in larger quantities. Is there a better way?
Thank you.

A: You could work with a LOAD CSV. Your input would contain the keys (not the ids, using the ids is not recommended) for Person and Car and whatever properties you need to set. For example
personId, carId, serial_number, signature
00001, 00045, SERIAL78765, SIGNATURE728934
00002, 00046, SERIAL78665, SIGNATURE724934

Your query would then be something like :
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:///input.csv' AS row
MATCH (p:Person {personId: row.PersonId})-[r:OWNS_CAR]->(c:Car {carId: row.carId})
SET r.serial_number = row.serialnumber, c.signature = row.signature

Note that you should have unique constraints on Person and Car to make that work. You can do thousands (even millions) like that very quickly ...
Hope this helps,
Tom


text:
Q: InterruptedException from Thread.sleep() In Java, Thread.sleep() throws InterruptedException.  What is the proper thing to do with this exception?
Should I

*

*propagate the exception up the call chain ?

*swallow the exception?

*be doing something else (please suggest)?

A: You should rethrow the exception.
This is an abstract from Brian Goetz, the author of the excellent book "Java Concurrency in Practice":

Dealing with InterruptedException:
If throwing InterruptedException means
  that a method is a blocking method,
  then calling a blocking method means
  that your method is a blocking method
  too, and you should have a strategy
  for dealing with InterruptedException.
  Often the easiest strategy is to throw
  InterruptedException yourself, as
  shown in the putTask() and getTask()
  methods in Listing 1. Doing so makes
  your method responsive to interruption
  as well and often requires nothing
  more than adding InterruptedException
  to your throws clause.

See : Dealing with InterruptedException

A: If all you're trying to do is burn SOME time, I would suggest just catching and ignoring the exception.
If, on the other hand, you need the proper amount of waiting time and any preemptive interruption is REALLY BAD for your program, then you should definitely rethrow the exception.
It just depends on why the exception occurred and what your use case is for Thread.sleep() in the first place.


text:
Q: Passing html form data to a Netsuite form I currently am working on a site for a private school. They have a few netsuite forms that are implemented throughout the site to gather information from prospective students and parents.
Unfortunately we are having a bit of a difficult time coming up with a mobile solution of the netsuite forms. One solution my boss has suggested is constructing an HTML form and passing the data from that form over to Netsuite, where it would be parsed etc.
So I've constructed the html form, but have hit a bit of a wall.
Am I able to pass data over to netsuite? If so is it as simple as adding an action to the form with a specific netsuite form url?
From what I gather netsuite uses specific input fields such as  etc. so how can this be done in html but passing the data back to netsuite? ajax (probably not due to same origin policy)? Form Action?
If none of these are at all plausible, what is a reasonable solution to get a mobile iteration of the netsuite forms?
<form name="consultation-form" id="ConsultationForm" method="post" action="http://www.netsuiteformaddress.com/maybe?">

A: You'll need to make the post to a php redirect file to avoid cross-origin problems:
Use this, and obviously replace the xxx with your account infromation.
<?php
session_start();
$url = 'https://forms.netsuite.com/app/site/crm/externalleadpage.nl?compid=xxxxxx&formid=xxx&h=xxxxxxxxxxxxxxxxxxxx';
$fields_string = '';
foreach($_POST as $key=>$value) {
    $fields_string .= $key.'='.$value.'&';
}
$fields_string = rtrim($fields_string,'&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($_POST));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
$result = curl_exec($ch);
curl_close($ch);
exit();
?>

Only issue is that it takes some time for the repost to be made. NetSuite is pretty slow to answer, so you might be looking at 4-8 sec response time.
The other solution would be a RESTlet, this is just simpler.

A: I suppose that you have designed these HTML forms in a Netsuite Suitlet. Now you can receive the form data in the suitlet using following method
request.getParameter('field_name');

A: Look at implementing RESTlets in NetSuite to capture the form data. Take the form data, put it into JSON or XML, then call the RESTlet (a custom REST interface you create in NetSuite) with the JSON or XML in the payload.
The RESTLet can then parse the JSON and update any standard or custom table you create to store the data.
If you are familiar with NetSuite SuiteScript (JavaScript with NetSuite-specific libraries), you can have this working in no time.

A: Have a look at this article, I believe it covers exactly what you are trying to do:
http://www.fmtconsultants.com/2014/05/the-best-way-to-integrate-external-web-forms-with-netsuite/
The basic idea is as you thought - to use a form post action to the external url of the form, and to name all the fields using their 'internalid'.


text:
Q: Why CSS-Modules is affecting globally when working with html elements? I have a file mycomponent.module.css
button {
    width: 10vw;
    min-width: 150px;
}

Unfortunately this css is affecting globally instead of the specific component where I am importing it. Does CSS modules not work on element names and only works on class-names? So .button instead of button?

A: If you want to style a current button, you should give a className or Id to your button. In this case it was global, for all butons.

A: Write like this.
Make a Class or ID and call them where is needed.

.bu{
    width: 10vw;
    min-width: 150px;
    background-color:red;
}
<button class="bu">button1 </button>

<button>button2 ! </button>


text:
Q: Python script for get data from merriam-webster How can I get specific word's definition from merriam-webster using python's script?
I have window with text box and button, and I want to print word's definition on the screen.
thanks

A: # Import libraries/ modules

import logging
logging.basicConfig(level = logging.INFO)
import json
import requests

# write custom definition

def connect_mw_dictionary(api_key, word):
  logging.info("Connecting...")
  URL = "https://www.dictionaryapi.com/api/v3/references/sd2/json/"+word+"?
  key="+api_key
  PARAMS = {'word': word,'key': api_key}
  r = requests.get(url = URL, params = PARAMS)
  r.encoding = 'utf-8'
  if r.status_code == 200:
    logging.info("Connection successful.")
    return True, r.json()
  logging.info("Connection failed.")
  return False

def fetch_dictionary_result(res, lang, loc, audio_format, word):
  dict_txt = str(res[0]['def'][0]['sseq'][0][0][1]['dt'][0][1]).replace("
{bc}","")
  return dict_txt

api_key = "xxxxxxxxxxxx" # replace with you api key
word = "keyword" # replace with word to lookup
lang = "en"
loc = "us"
audio_format = "mp3"
status, result = connect_mw_dictionary(api_key, word)
if status == True:
  status, dictionary_result = fetch_dictionary_result(result, lang, loc,
audio_format, word)

dictionary_result

A: I am assuming merriam-webster is a website. Check if they an API. If so you can use it to achieve your task. If they do not have an API, I don't see how you can achieve your task without some highly advanced hacking, crawling algorithm. My suggestion is, as it appears you are trying to develop a dictionary type app, research dictionary websites that have open APIs.


text:
Q: Foundation: How to responsively switch between Basic Menu and Dropdown Menu? Using Foundation, I'm trying to make a responsive menu that switches from basic view to dropdown view, and vice versa, depending on media size (mobile or desktop). Is it supported in Foundation or should I implement it by myself?
Mobile view: https://imgur.com/a/biMWB4b
Desktop view: https://imgur.com/a/ZIHWqHL
I have written a Jquery code that moves the menu content from one place to another, depending on media size.
HTML code:

        Drop

One

Two

Three

Four

JS code:
$(document).foundation();

function moveFromBasicToDropdown() {
    $('#mobile-place').append($('.content'));
}
function moveFromDropdownToBasic() {
    $('#desktop-place').append($('.content'));
}

$(window).on('changed.zf.mediaquery', function(event, newSize, oldSize) {
    if (newSize === 'small') {
        moveFromBasicToDropdown();
    }
    else {
        moveFromDropdownToBasic();
    }
});

if (Foundation.MediaQuery.is('small only')) {
    moveFromBasicToDropdown();
}
else {
    moveFromDropdownToBasic();
}

The code works as expected. However, I am not sure if this feature is already supported in Foundation; if not, then I'm wondering if this is the right way to implement it?


text:
Q: count the number of rows with a particular column value I have a table called votes.
ID              int(11) pk ai
candidate_id    int(11)
region          varchar(75)

Can I get an result with an sql statement with something like
West 46
East 75
North 28
etc...

West, East being regions...
Thanks

A: SELECT region, COUNT(region)
FROM votes
GROUP BY region ORDER BY 2 DESC

Hmm, elaborating on your request for totals of votes per candidate, will depend on how your data is laid out. Do you simply have one row per vote for a candidate, if so, then I'd try (although I haven't tested);
SELECT region, COUNT(region), candidate_id, COUNT(candidate_id)
FROM votes
GROUP BY region, candidate_id ORDER BY 2 DESC, 4 DESC

A: Assuming you want one string, containing both fields, you can use MySQL's CONCAT function to concatenate.
Example:
SELECT DISTINCT region, SUM(*) as votes_count, CONCAT(region, " ", votes_count) FROM votes

More info on CONCAT()

A: SELECT DISTINCT Region
, SUM(Candidate_ID) -- Assumes that the SUM of this equals total votes
FROM Votes
GROUP BY Region


text:
Q: Why Java ReplaceAll with Regex boundaries doesn't work when I add a sharp signal? When I try this code below, it works fine using the regex boundaries:
"word john word".replaceAll("\\bjohn\\b","fill")

Result: "word fill word"

But if I need to search for a word that contains "#" it doesn't work:
"word john# word".replaceAll("\\john#\\b","fill")

Result: "word john# word"

How can I solve it?

A: She # symbol is not counted as a word character ([A-Za-z0-9_]), so your word boundary (\b) no longer matches.
You could use a positive lookahead and base yourself on the whitespace instead:
"word john# word".replaceAll("\\bjohn#(?=\\s+)","fill") // word fill word

Or use a non-word boundary (\B):
"word john# word".replaceAll("\\bjohn#\\B","fill") // word fill word

Or nothing at all:
"word john# word".replaceAll("\\bjohn#","fill") // word fill word


text:
Q: Is it possible to perform shell injection through a read and/or to break out of quotes? Consider this example of (attempted) shell injection:
test1.sh:
#!/bin/sh
read FOO
echo ${FOO}

z.dat:
foo && sleep 1 && echo 'exploited'

Then run:
cat z.dat | ./test.sh

On my machine (Ubuntu w/bash) the payload is always (correctly) treated as a single string and never executes the malicious sleep and echo commands.
Question 1: Is it possible to modify z.dat so that test.sh is vulnerable to injection?  In particular are there specific shells that might be vulnerable?
Question 2: If so, is changing the test script to quote the variable (shown below) an absolute defense?
test2.sh:
#!/bin/sh
read FOO
echo "${FOO}"

Thanks!

A: Not according to: https://developer.apple.com/library/mac/documentation/OpenSource/Conceptual/ShellScripting/ShellScriptSecurity/ShellScriptSecurity.html
Search for 'Backwards Compatibility Example'


text:
Q: Why bash alias doesn't work in scripts? I'm using a Mac and I have this alias defined in .bashrc:
$cat .bashrc | grep la
alias la='ls -la'

then I try to use it in a script:
$cat ./mytest.sh
#!/bin/bash
la

It runs and says it cannot find la:
./mytest.sh: line 2: la: command not found

Why is this? I tried on both Mac and Linux, same error!

A: Your .bashrc is only used by interactive shells. https://www.gnu.org/software/bash/manual/bashref.html#Bash-Startup-Files says:

Invoked non-interactively
When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed:
if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi

but the value of the PATH variable is not used to search for the filename.
As noted above, if a non-interactive shell is invoked with the --login option, Bash attempts to read and execute commands from the login shell startup files.

As you can see, there's nothing about .bashrc there. Your alias simply doesn't exist in the script.

But even if .bashrc were read, there's another problem:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt.

So if you wanted aliases to work in a script, you'd have to do shopt -s expand_aliases first. Or just use a shell function instead of an alias:
la() {
    ls -la
}

A: The simplest answer is to fix this issue is to do the 2 important things in your script -or it wont' work, if you just do one thing.
#!/bin/bash -i

# Expand aliases defined in the shell ~/.bashrc
shopt -s expand_aliases

After this, your aliases that you have defined in ~/.bashrc they will be available in your shell script (giga.sh or any.sh) and to any function or child shell within such script.
If you don't do that, you'll get an error:
your_cool_alias: command not found

A: At the beginning of the ~/.bashrc file usually can be found two lines as:
# If not running interactively, don't do anything
[ -z "$PS1" ] && return

This line aborts the inclusion for scripts which is not recommended anyway. For portability issues, you usually write the full command or define the alias in the script itself.


text:
Q: Money Example from Kent Beck's TDD by example So I have worked through the Money example in Kent Beck's book Test Driven Development by Example and have been able to get the code to work up until the last test that he writes:
@Test
public void testPlusSameCurrencyReturnsMoney(){
    Expression sum = Money.dollar(1).plus(Money.dollar(1));
    assertTrue(sum instanceof Money);
}

and here is the function that this calls
public Expression plus(Expression addend) {
    return new Sum(this, addend);
}

When I run this, it gives java.lang.AssertionError, so my question is why is it giving this error and how do I fix it?

A: Lunivore already answered the question with how to solve the problem, but I think you should re-read the paragraph just before and after the block of code (and test), if you want to understand more on what Beck was trying to convey.
The last sentence reads "Here is the code we would have to modify to make it work:". That block of code was first entered on page 75 (with test case). Nothing was changed in end effect on page 79. It was just an indication of what we could change, if we wanted to keep this test.
"There is no obvious, clean way to check the currency of the argument if and only if it is Money. The experiment fails, we delete the test, and away we go".
He also stated that this test is ugly and concluded on the following page "Tried a brief experiment, then discarded it when it didn't work out".
I wrote this just in case you were thinking all of the examples just work and should be kept.

A: You're checking that the sum variable is a Money, but returning a Sum in the plus method.
So, unless Sum is a subclass of Money, that assertion will always fail.
To make it pass, you might want to do something like:
public Expression plus(Expression addend) {
    return new Money(...<whatever>...);
}

Of course, Money would then have to be an Expression too.
Or you might want to evaluate the sum to get the money out of it. Or maybe even do sum instanceof Sum instead. It depends on what behavior you're actually trying to achieve.
By the way, beware the instanceof operator.


text:
Q: ADF Java Desktop Application Jar I have made an ADF Java desktop app, and put all the swing classes in the model.
It runs correctly from Jdevloper.
I access the application module using this way:
private static String amDef = "model.AppModule";
private static String config = "AppModuleLocal";
appModule = (AppModuleImpl)Configuration.createRootApplicationModule (amDef,config);

But, when i deploy it as a jar file and run it, it first runs well, but as soon as it accesses the application module it gives the following exception:
oracle.jbo.ConfigException: JBO-33003: Connection name MyConnection is not defined.
    at oracle.jbo.client.Configuration.initializeFromConnectionName(Configuration.java:1199)
    at oracle.jbo.client.Configuration.getConfiguration(Configuration.java:648)
    at oracle.jbo.common.ampool.PoolMgr.loadConfiguration(PoolMgr.java:605)
    at oracle.jbo.common.ampool.PoolMgr.findPool(PoolMgr.java:526)
    at oracle.jbo.client.Configuration.createRootApplicationModule(Configuration.java:1505)
    at oracle.jbo.client.Configuration.createRootApplicationModule(Configuration.java:1482)
    at classes.ImageCaptureAndPrint.actionPerformed(ImageCaptureAndPrint.java:888)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
    at javax.swing.plaf.basic.BasicRootPaneUI$Actions.actionPerformed(BasicRootPaneUI.java:208)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1663)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2882)
    at javax.swing.KeyboardManager.fireBinding(KeyboardManager.java:307)
    at javax.swing.KeyboardManager.fireKeyboardAction(KeyboardManager.java:250)
    at javax.swing.JComponent.processKeyBindingsForAllComponents(JComponent.java:2974)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2966)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2845)
    at java.awt.Component.processEvent(Component.java:6310)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1954)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:806)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1074)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:945)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:771)
    at java.awt.Component.dispatchEventImpl(Component.java:4760)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

A: i found the solution
it was to create an ADF Library Jar File in the deployment in the model, it had the database connection by default.


text:
Q: How to find out do I have MLC or SLC SSD? (model: TOSHIBA THNSFC128GBSJ) Please help to find out is TOSHIBA THNSFC128GBSJ SSD
MLC or SLC SSD?

A: According to Toshiba that drive is a member of their HG3 family ("HG Series Solid State Drives")
See: http://www.toshiba-components.com/ssd/lineup/hg.html
Although they don't seem to specify SLC vs. MLC there, additional reference to the HG3 SSDs can be found here at ssd.toshiba.com, which states:

Toshiba's new HG3 MLC SSD drives provide a high level of performance with a maximum sequential read speed of 220MB per second (MBps) and maximum sequential write speed of 180MBps.

So short of a call to Toshiba to confirm, I'd have to go with it being an MLC.


text:
Q: How to log in to Windows when the L key isn't working? I just rebooted my Windows 10 PC and can't log in. I am trying to type in my password but it contains the letter L and when I press the L key nothing appears.
My keyboard was working fine but I thought it might have spontaneously broken so I plugged in another keyboard and it had exactly the same problem!
I have tried checking if the keyboard layout has changed but it hasn't and I can't find any way to bring up an on-screen keyboard.
How do I log in?

A: I tried a bunch more things without any luck. My issue seemed to be similar to this question that was never resolved.
In the end, after a lot of frustration, I realised that some laptops have num pads on their right side. This is a PC and both the keyboards I tried using are PC keyboards without such a feature. However, on a whim, I tried tapping the num lock key once to turn num lock on. Lo and behold my L
key was suddenly working again!
I have no idea how this made became enabled but that was the solution I found. There some more explanation about how you're supposed to enable this mode here. It doesn't make much sense as both keyboards have full dedicated number pads.


text:
Q: Resetting jQuery timer I need to reset my timer back to 5 seconds. But it doesn't work. Can you help:

  <script type="text/javascript">
      "use strict";
      $(document).ready(function() {
          $('span.countdown').countdown({seconds: 5, callback: 'alert("Test");', onExpiry: restart});
      });

      function restart() {
          $('span.countdown').countdown('change', {seconds: 5});
      }
  </script>

A: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
you use setTimeout() for a single countdown
setInterval() to do something every X number of seconds
and clearTimeout() to reset the counter
Bojan is right in saying that this is not normal JQuery syntax, is it a plugin or something? Whatever it is it's probably little less than syntactic sugar.
and yeah the syntax is setTimeout(function(), 5000);


text:
Q: Git HTTP error installing Compass on Rails 3.1 project I am following the guidance provided in this Q&A to install Compass on Rails 3.1 project:
How to use compass with rails 3.1
When I run the bundle update, however, I get the following error:
Fetching https://github.com/chriseppstein/compass.git
error: The requested URL returned error: 403 while accessing https://github.com/chriseppstein/compass.git/info/refs

fatal: HTTP request failed
Git error: command `git clone 'https://github.com/chriseppstein/compass.git' "/Users/csc/.rvm/gems/ruby-1.9.2-p290/cache/bundler/git/compass-71785749c1e54e7e5936dbddfb919ddd014100e8" --bare --no-hardlinks` in directory /Users/csc/source/wtt has failed.

Any guidance would be appreciated.

A: Since you're getting an HTTP error code, can you try using the git protocol?
git clone git://github.com/chriseppstein/compass.git


text:
Q: Install 20.04 for wsl2 if Microsoft Store is dysfunctional? Is there any way to install 20.04 for use with wsl2 that doesn't depend upon Microsoft Store (or Add-AppxPackage) working?
Why: Microsoft Store and Add-AppxPackage are broken on my computer, attempts to fix them were unsuccessful, and Microsoft's only solution is "reinstall Windows" because there's no way to just regenerate it, or to uninstall and reinstall Store by itself. Others have already discovered that Add-AppxPackage isn't a loophole to getting around a broken Microsoft Store.

Incidentally, I already tried to download it by running:
Invoke-WebRequest -Uri https://aka.ms/wslubuntu2004 -OutFile Ubuntu.appx -UseBasicParsing
Add-AppxPackage .\Ubuntu.appx

Unfortunately, here's the error message I got:
Add-AppxPackage : Deployment failed with HRESULT: 0x80073CF3, Package failed updates, dependency or conflict
validation.
Deployment Add operation with target volume C: on Package
CanonicalGroupLimited.Ubuntu20.04onWindows_2004.2020.424.0_x64__79rhkp1fndgsc from:  (Ubuntu.appx)  failed with error
0x80073CF3. See http://go.microsoft.com/fwlink/?LinkId=235160 for help diagnosing app deployment issues.
NOTE: For additional information, look for [ActivityId] 014ee586-6a11-0004-ce43-5001116ad701 in the Event Log or use
the command line Get-AppPackageLog -ActivityID 014ee586-6a11-0004-ce43-5001116ad701
At line:1 char:1
+ Add-AppxPackage .\Ubuntu.appx
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\Downloads\Ubuntu.appx:String) [Add-AppxPackage], IOException
    + FullyQualifiedErrorId : DeploymentError,Microsoft.Windows.Appx.PackageManager.Commands.AddAppxPackageCommand

If you dig through the error messages in EventViewer, they ultimately come down to "an XML file needed by Microsoft Store was somehow deleted, and there's no way to get it back without reinstalling Store by reinstalling Windows" :-(
Anyway, I don't expect anyone here to help with diagnosing Microsoft Store, I'm just hoping that there's some alternate way to install Ubuntu 20.04 for WSL2 that doesn't need Windows Store to work.

A: As long as you already have WSL installed (which doesn't rely on the Store anyway, so that shouldn't be a problem), you can use the wsl --import subcommand to get the Ubuntu distribution "side-loaded".
The package that you already downloaded contains the file you need, but for the sake of streamlining the directions, I'm going to have you download it again.  You can tweak this recipe if you'd like, of course:

*

*First, choose a location for your WSL files.  For example:
cd $env:USERPROFILE
mkdir -p wsl\instances\Ubuntu20_04
mkdir wsl\images
cd wsl

*Download the Appx package manually into that wsl directory, either through the proper direct link found here or, in your case, via:
# Assuming we are still in the `wsl` directory created above
Invoke-WebRequest -Uri https://aka.ms/wslubuntu2004 -OutFile Ubuntu.appx -UseBasicParsing

*The resulting file is actually just a renamed .zip file.  Extract it in PowerShell and move the install.tar.gz to the images directory created above:
# Still in the `wsl` directory
Expand-Archive Ubuntu.appx
mv Ubuntu\install.tar.gz images\
Remove-Item -Recurse Ubuntu

*You'll need to extract the install.tar.gz file to install.tar.  Neither PowerShell nor Windows have a built-in feature to do this, so I'll leave that to your preference.  I'm guessing you already have something like 7-zip installed already.

*Rename the images\install.tar to images\Ubuntu20_04.tar.  This isn't strictly necessary, but I like to keep the "pristine" image around in case you want to install additional instances.  WSL is great for spinning up "throwaway" instances where you can try out something potentially destructive without fear of corrupting your main instance.

*Still from within the wsl directory:
wsl --import Ubuntu20.04 instances\Ubuntu20_04 images\Ubuntu20_04.tar --version 2
wsl --set-default Ubuntu20.04 # Optional, and perhaps unnecessary if this is the first distribution installed
wsl -u root useradd --create-home --user-group --groups  adm,dialout,cdrom,floppy,sudo,audio,dip,video,plugdev,netdev --password "encryptedPassword" username

... Of course, adjust username to be your username.  See here for how to create the encrypted password.
To the best of my knowledge, this will create a user the same way that the default user is created by the Microsoft Store installation of Ubuntu 20.04.

*Start WSL Ubuntu as root:
wsl -u root

*To set the default user that runs when the instance starts, create a /etc/wsl.conf with the following contents:
[user]
default=username

... substituting your username, of course.

*Exit back to PowerShell

*Shutdown the instance to allow it to come back up and read the wsl.conf:
wsl --terminate Ubuntu20.04

That should be it.  Running wsl should start Ubuntu 20.04 running under your user ID.
I haven't had a chance to test every step in here end-to-end, but this is a combination of things I've done in the past and other answers I've provided.  I believe I've got all the pieces put together that you need, but if you run into issues, let me know, and I'll review and tweak it.

A: To solve a problem that seemed to require reinstallation of Windows, I made use of a so called "in-place upgrade" capability of Windows installer that reinstalls keeping all your files and apps! This might help you. See this tutorial for example, for details.
Today I even managed to find this ultimate explanation to your main question, if not been copied-by other guy here, as this one is older post:
https://superuser.com/questions/1271682/is-there-a-way-of-installing-ubuntu-windows-subsystem-for-linux-on-win10-v170
As last one, even MS documents this all:
https://docs.microsoft.com/en-us/windows/wsl/install-manual
Hope my post will decrease in number of downvotes now..


text:
Q: IE8 jQuery place cursor in a textbox possible only at the beginning I'am on my limit.
I have to implement some features for a web application. Problem is, it can only be implemented for IE8 because of company policies...
IE8 does even not load jsFiddle normally. I get any possible and unintelligible errors.
I have a lot of php scripts and as an response (ajax-request) from one of it I get a table with some data.
If I click on this element a editbox appears and I can modify this value.
First problem is, that I can only modify this value if I click on this element at first, but I can not set the cursor anywhere else. It is at the beginning at first. If I click anywhere else in the box, cursor disappers and I can't do anything.
I thought it is a problem in my code. But... I have just copied some relevant code to a new file (I can not post entire code here because of policies and copyrights) and I get some silly errors like "Object expected" although the value is already an object!
Here the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Click
Nothing

Click
Nothing

Please, help me someone... I simply does not understand, why I can not place the cursor normally. and why I'am getting such stupid errors. I looked into the debugger and anything was idetically with the other call (from ajax-php), but here it won't proceed on $(value)....
First problem with the "object expected" solved
src="-->.<--/JavaScript/jquery-1.9.1
Was just a point.
But now you can see my problem with the cursor. How can I get the same as when I just have a normally "textbox" (input type="text" value="blabla".....) and I simply can set my cursor wherever I want
Edit
Got something interesting. As it seems to be I have to work with $('#editbox').focus();

Anyone an idea how to free the cursor?

A: You need to change your script to something like this

When you pass an html element to a function, it doesn't pass a jQuery object, just a DOM object.  Using $("#" + value.id) finds the DOM object and converts it to a jQuery object.


text:
Q: find $f(g(x))$ given $f(x)$ and $g(x)$ let $f:\mathbb R \to \mathbb R$ and $g:\mathbb R \to \mathbb R$ be defined
$$f(x) =
\begin{cases}
-1  & x<\frac 12 \\
-\frac12, & \text{if} -\frac12\leq x<0 \\
0  & \text{x=0}\\
1  & \text{x>0}
\end{cases}$$
and
$$g(x)= 1+x-[x],$$ where $[x]$ denoted largest integer not exceeding $x$. then what is $f(g(x))$?

*

*$ -1$

*$-\frac{1}2$

*$0$

*$1$

my doubt: $g(x)$ can be written as $1-\{x\}$ where $\{x\}$ is fractional part of $x$. Since range of $g(x)$ is $(0,1)$ so $f(g(x))=1$. So I want to confirm my answer i get option 4 is it correct? Thanks.

A: Actually $g(x)$ is $1+\{x\}$, not $1-\{x\}$, but the conclusion is basically the same:  $g(x)\ge1\gt0$ for all $x$, so $f(g(x))=1$.


text:
Q: How to run both sorting and filtering on mongodb server with c# code I've found c# code like this (Collection is of type MongoCollection<T> here):
Collection.AsQueryable()
   .OrderByDescending(i => i.SomeField)
   .Where(i => i.OtherField == "bla-bla")

does not run both sorting (OrderBy) and filtering (Where) on a server as I expected, instead it calls sorting with MongoDb engine and all further filtering is processed on a client side, which takes fair amount of time. That what I've found in Mongodb profiler as a result of the code execution:
"query" : {
    "$query" : { },
    "$orderby" : {
       "SomeField" : -1
    }
 }

Note $query is empty. Well, is there any idea over how to make it work on database (both sorting and filtering)?

A: Well, one of the resolution I've just found might look like this:
Collection.Find(
  Query.And(Query.EQ("OtherField", "bla-bla")).
  SetSortOrder(SortBy.Descending("SomeField").ToList()

It builds exactly what I need:
"query" : {
    "$query" : {
       "OtherField" : "bla-bla"
     },
    "$orderby" : {
       "SomeField" : -1
     }
 }

However I do not quite like this approach as it makes me to hardcode database field names. Presumably new c# driver 1.6 will let you build same queries using delegates like i => i.OtherField == "bla-bla".
Any other approaches?

A: To order the items, all have to be retrieved, so if you specify that as the first operation I'd expect the behaviour you observed. So you'd have to reverse your statement (as you do in the IMongoQuery syntax). This can also be done in LINQ syntax, but since Where returns IEnumerable, you need an extra cast:
Collection.AsQueryable()
   .Where(i => i.OtherField == "bla-bla").AsQueryable()
   .OrderByDescending(i => i.SomeField)


text:
Q: Can't compile material-components with webpack-encore yarn encore dev fail after setting up material-components
I installed material-components using yarn add material-components-web --dev
and then configured app.js like this :
/* --- CSS --- */
import "../css/normalize.scss";
import "material-components-web/material-components-web.scss"
import "../css/layout.scss";
import "../css/style.scss";

/* --- RESOURCES ---*/
import $ from "jquery";
import * as mdc from "material-components-web";

When running yarn encore dev, I get the following error :
ERROR  Failed to compile with 1 errors                                                                                22:30:40

 error  in ./node_modules/material-components-web/material-components-web.scss

Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/lib/loader.js):

@import "@material/elevation/mixins";
^
      File to import not found or unreadable: @material/elevation/mixins.
      in /var/www/vhosts/salon-virtuel/node_modules/@material/button/_mixins.scss (line 23, column 1)
    at runLoaders (/var/www/vhosts/salon-virtuel/node_modules/webpack/lib/NormalModule.js:301:20)
    at /var/www/vhosts/salon-virtuel/node_modules/loader-runner/lib/LoaderRunner.js:367:11
    at /var/www/vhosts/salon-virtuel/node_modules/loader-runner/lib/LoaderRunner.js:233:18
    at context.callback (/var/www/vhosts/salon-virtuel/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
    at Object.render [as callback] (/var/www/vhosts/salon-virtuel/node_modules/sass-loader/lib/loader.js:52:13)
    at Object.done [as callback] (/var/www/vhosts/salon-virtuel/node_modules/neo-async/async.js:8077:18)
    at options.error (/var/www/vhosts/salon-virtuel/node_modules/node-sass/lib/index.js:294:32)

 @ ./assets/js/app.js 7:0-62

Entrypoint app [big] = runtime.js vendors~app.js app.css app.js
error Command failed with exit code 2.

Imports in files :
node_modules/material-components-web/material-components-web.scss
@import "@material/elevation/mdc-elevation";

node_modules/@material/elevation/mdc-elevation.scss
@import "./mixins";
@include mdc-elevation-core-styles;

node_modules/@material/elevation/_mixins.scss
@import "@material/feature-targeting/functions";
@import "@material/feature-targeting/mixins";
@import "@material/theme/variables";
@import "./variables";

Any idea about why it's happening, and how to fix this?

A: I think you are very close. Try to edit your encore config to include node_modules to sass loader like this:
// enables Sass/SCSS support
.enableSassLoader(function(options) {
    // https://github.com/sass/node-sass#options
    options.includePaths = ['./node_modules'];
}, {
    // set optional Encore-specific options
    // resolve_url_loader: true
});

explained here

A: For the case, someone else stumbles over this.
It may would have also solved your issue, if you changed the way how you import the scss/sass files.
@import "~@material/feature-targeting/functions";
@import "~@material/feature-targeting/mixins";
@import "~@material/theme/variables";
@import "./variables";

The ~ references the node_modules as well. That is at least how I do it and it works without any special config for the sass-loader.


text:
Q: SQL Azure read scale out feature : Monitor queries on read-only replica Problem : We are experiencing some performance issues when read only replica is enabled on a premium tier in azure SQL which is very strange and unexplainable.
I can find if a query is being executed on a read only replica by using the following inbuilt function

DATABASEPROPERYEX(DB_NAME(),'Updateability')

However there is no way to monitor read only queries.
As per the following article, Extended events and query store is not supported in preview for read only replica
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-read-scale-out
whereas the following article suggests that read scale out feature is now generally available. Still I cannot monitor queries executed on read only replica in premium SQL database tier
https://azure.microsoft.com/en-in/roadmap/azure-sql-database-announces-preview-of-read-scale-out-support-in-premium-service/
I can see a user voice item
https://feedback.azure.com/forums/217321-sql-database/suggestions/34337935-monitor-queries-on-secondary-database-when-read-sc
Is there any other option to monitor read only workload?

A: As you mentioned, you cannot use Query Store or Extended Events to monitor queries on read-only replicas but still can use sys.dm_exec_query_stats dynamic view, which can give you for example top queries by CPU consumption
SELECT TOP (25) MIN(query_stats.statement_text) AS [Statement Text],
SUM(query_stats.total_worker_time) / SUM(query_stats.execution_count) AS [Avg CPU Time],
query_stats.query_hash AS [Query Hash]
FROM (SELECT QS.*, SUBSTRING(ST.[text], (QS.statement_start_offset/2) + 1,
    ((CASE statement_end_offset
        WHEN -1 THEN DATALENGTH(st.[text])
        ELSE QS.statement_end_offset END
            - QS.statement_start_offset)/2) + 1) AS statement_text
     FROM sys.dm_exec_query_stats AS QS
     CROSS APPLY sys.dm_exec_sql_text(QS.sql_handle) AS ST) AS query_stats
GROUP BY query_stats.query_hash
ORDER BY [Avg CPU Time] DESC;

You can change the ORDER BY clause on below query to monitor other resources:
SELECT TOP 10
    (total_logical_reads/execution_count) AS avg_logical_reads,
    (total_logical_writes/execution_count) AS avg_logical_writes,
    (total_physical_reads/execution_count) AS avg_phys_reads,
    (total_worker_time/execution_count) AS avg_cpu_over_head,
total_logical_reads, total_logical_writes, total_physical_reads,
total_worker_time, execution_count, total_elapsed_time AS Duration,
plan_generation_num AS num_recompiles,
statement_start_offset AS stmt_start_offset,
    (SELECT SUBSTRING(text, statement_start_offset/2 + 1,
        (CASE WHEN statement_end_offset = -1
            THEN LEN(CONVERT(nvarchar(MAX),text)) * 2
                ELSE statement_end_offset
            END - statement_start_offset)/2)
     FROM sys.dm_exec_sql_text(sql_handle)) AS query_text,
      (SELECT query_plan FROM sys.dm_exec_query_plan(plan_handle)) AS query_plan
FROM sys.dm_exec_query_stats a
--JUST CHANGE THE ORDER BY TO GET THE OTHER RESOURCES
ORDER BY (total_logical_reads + total_logical_writes)/execution_count DESC

You may want to store the result of queries like the above for later analysis.


text:
Q: React uncontrolled component - updating the input fields despite presence of defaultValue I have an "uncontrolled" React component with an input field like so:
render: function(){

return (

      <input
        id="pickupField"
        tabIndex="1"
        placeholder=""
        className="order-form-input"
        onFocus={this.disableAddresses}
        onBlur={() => {
            this.enableAddresses();
            this.fieldChange('address');
        }}
        defaultValue={(order.pickup || {}).address || ''}
        ref="pickupAddress"
        hintText={(this.state.hideHintText) ? "" : "Enter the pickup address"}
        floatingLabelFixed={true}
        floatingLabelText="Pickup Address"
      />
   )
}

the problem I am having is that I want to update this component with new data after it's rendered the first time, and using defaultValue instead of value means that the input field text won't update after the first render. E.g., the only way to update the text in the input field is for the user to type into it, I cannot seem to change it programmatically.
I can solve this problem by using value instead of defaultValue. However, the reason I do not want to use use value instead of defaultValue, is because then I have to use an onChange listener which is way overkill for my use case here.
The reason using an onChange listener is overkill is because I sync with the database everytime the component state changes. I would rather sync on onblur instead of syncing on onchange.
I see some solutions to this problem out there, using React fields such as "key", but TMK this solution will force the component to re-mount which sounds bad for performance and keeping the logic simple.
Anyone know how to solve this problem? How to update a React component's input fields programmatically, but avoiding an onchange listener?


text:
Q: Visual Studio 2017 KernelBase.dll Module not found exception I am trying to build a 32-bit application on Windows 10 using Visual Studios 2017. The application builds and runs fine in 64-bit, but it does not run properly from a 32-bit build.
Call Stack:
    KernelBase.dll!741b08b2()   Unknown Non-user code. Cannot find or open the PDB file.
    [Frames below may be incorrect and/or missing, no symbols loaded for KernelBase.dll]        Annotated Frame
    common32.dll!77765569() Unknown No symbols loaded.
    common32.dll!77765424() Unknown No symbols loaded.
    [External Code]     Annotated Frame
>   MobileDOAS.exe!ATL::CSimpleStringT<char,0>::CSimpleStringT<char,0>(ATL::IAtlStringMgr * pStringMgr) Line 208    C++ Symbols loaded.
    common32.dll!7776649b() Unknown No symbols loaded.
    common32.dll!7776625b() Unknown No symbols loaded.
    OmniDriver32.dll!778b044e() Unknown No symbols loaded.
    MobileDOAS.exe!CSpectrometer::CSpectrometer() Line 33   C++ Symbols loaded.
    MobileDOAS.exe!CMeasurement_Traverse::CMeasurement_Traverse() Line 7    C++ Symbols loaded.

Debug output:
'MobileDOAS.exe' (Win32): Loaded 'C:\Users\Diana\git\MobileDOAS\Debug\MobileDOAS.exe'. Symbols loaded.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\user32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\win32u.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\gdi32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Program Files (x86)\Ocean Optics\OmniDriver\OOI_HOME\common32.dll'. Module was built without symbols.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\gdi32full.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Program Files (x86)\Ocean Optics\OmniDriver\OOI_HOME\OmniDriver32.dll'. Module was built without symbols.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp_win.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbase.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\comdlg32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcrt.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\combase.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\rpcrt4.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sspicli.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\advapi32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msimg32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cryptbase.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sechost.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcr100.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\bcryptprimitives.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\SHCore.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\shlwapi.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\shell32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_5.82.16299.192_none_d02ca7595f31d9e4\comctl32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cfgmgr32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\windows.storage.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel.appcore.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\powrprof.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\profapi.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ole32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\oleaut32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winspool.drv'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\uxtheme.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\imm32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\oledlg.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\bcrypt.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\IPHLPAPI.DLL'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\WinSxS\x86_microsoft.windows.gdiplus_6595b64144ccf1df_1.1.16299.192_none_8e60f76b0273650f\GdiPlus.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\oleacc.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winmm.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winmmbase.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winmmbase.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Unloaded 'C:\Windows\SysWOW64\winmmbase.dll'
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msctf.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dwmapi.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.16299.192_none_5d760485a7e0eb41\comctl32.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\TextInputFramework.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\CoreUIComponents.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\CoreMessaging.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\WinTypes.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntmarta.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Loaded 'C:\Windows\SysWOW64\WinTypes.dll'. Cannot find or open the PDB file.
'MobileDOAS.exe' (Win32): Unloaded 'C:\Windows\SysWOW64\WinTypes.dll'
Exception thrown at 0x741B08B2 (KernelBase.dll) in MobileDOAS.exe: 0xC06D007E: Module not found (parameters: 0x00DADF0C).
Unhandled exception at 0x741B08B2 (KernelBase.dll) in MobileDOAS.exe: 0xC06D007E: Module not found (parameters: 0x00DADF0C).

Screenshot:
Screenshot of exception
I've checked the project properties for external dependencies and ensured I am using 32-bit versions for include directories. I had it working at one point but after some changes I can no longer get it to work despite trying to revert any changes.

A: Turns out the 32-bit driver for the spectrometer that the code wanted to access was getting overridden by a 64-bit version automatically. After disabling automatic driver updates, removing any copies of 64-bit driver installer on my PC, and reinstalling 32-bit driver; I finally got it working.


text:
Q: Disable connection pool on Vert.x httpclient or webclient I have issue with using Vert.x httpclient or webclient class to call whatsapp API. If I make two API call back to back to whatsapp using the same httpclient / webclient object then I often encountered connection reset error.
I'm thinking that this issue is caused by whatsapp doesn't want to keep long http connection thus causing http connection in the connection pool becomes stale. I tried to set max pool size of httpclient to be 1 but I still encountered this connection reset issue. I tried to set max pool size of 0, but it turned out that it is not allowed.
How do I then disable connection pool in Vert.x httpclient / webclient class so that each http request using fresh new connection ?


text:
Q: C++ Hex string to byte array First off, I've Googled this question over the past few days but everything I find doesn't work. I don't receive runtime errors but when I type in the same key (in the form of a hex string) that the program generates to encrypt, decryption fails (but using the generated key throughout the program works fine). I'm trying to enter a hex string (format: 00:00:00...) and turn it into a 32-byte byte array. The input comes from getpass(). I've done this before in Java and C# but I'm new to C++ and everything seems much more complicated. Any help would be greatly appreciated :) Also I'm programming this on a linux platform so I'd like to avoid Windows-only functions.
Here is an example of what I've tried:
char *pass = getpass("Key: ");

std::stringstream converter;
std::istringstream ss( pass );
std::vector<byte> bytes;

std::string word;
while( ss >> word )
{
    byte temp;
    converter << std::hex << word;
    converter >> temp;
    bytes.push_back( temp );
}
byte* keyBytes = &bytes[0];

A: If your input has format: AA:BB:CC,
you could write something like this:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdint>

struct hex_to_byte
{
    static uint8_t low(const char& value)
    {
        if(value <= '9' && '0' <= value)
        {
            return static_cast<uint8_t>(value - '0');
        }
        else // ('A' <= value && value <= 'F')
        {
            return static_cast<uint8_t>(10 + (value - 'A'));
        }
    }

    static uint8_t high(const char& value)
    {
        return (low(value) << 4);
    }
};

template <typename InputIterator>
std::string from_hex(InputIterator first, InputIterator last)
{
    std::ostringstream oss;
    while(first != last)
    {
        char highValue = *first++;
        if(highValue == ':')
            continue;

        char lowValue = *first++;

        char ch = (hex_to_byte::high(highValue) | hex_to_byte::low(lowValue));
        oss << ch;
    }

    return oss.str();
}

int main()
{
    std::string pass = "AB:DC:EF";
    std::string bin_str = from_hex(std::begin(pass), std::end(pass));
    std::vector<std::uint8_t> v(std::begin(bin_str), std::end(bin_str)); // bytes: [171, 220, 239]
    return 0;
}

A: How about this?
Read it as a word and operate on it after?
You can do any size checking format checking in convert().
#include <iostream>
#include <string>
#include <vector>

char convert(char c)
{
    using namespace std;
    // do whatever decryption stuff you want here
    return c;
}

void test()
{
    using namespace std;

    string word;
    cin >> word;

    vector<char> password;

    for (int i = 0; i < word.length(); i++)
    {
        password.push_back(convert(word[i]));
    }

    for (int i = 0; i < password.size(); i++)
    {
        cout << password[i];
    }

    cout << "";
}

int main()
{
    using namespace std;
    char wait = ' ';

    test();

    cin >> wait;
}

Are there specific reasons for not using cin here?


text:
Q: Excel if A1 cell value is equal to A2 cell value select M3 cell I want a simple thing. if A1 cell value is equal to A2 cell value then select M3 cell (set active cell M3)
How can I do this?

A: if range("A1").value = range("A2").value then
    range("M3").select
end if


text:
Q: How to parse JSON in background thread after Alamofire request finishes? After getting JSON data from Alamofire request, I want to parse it on background thread, because, parsing process is difficult and has some logic in my case. The first idea to solve was executing a async operation on background thread with synchronous request with Alamofire. But, as I've read, Alamofire works completely asynchronously. The second solution of mine was executing a parsing JSON process in another thread after responseJSON of Alamofire gets called. After it completes, I will update my UI in main thread. Here is how it looks:
.responseJSON { (response) in //callback of Alamofire
    if response.result.isSuccess {
        let json = JSON(response.result.value!)
        DispatchQueue(label: "parsing", qos: .userInitiated).async {
            self.parseJSON(json)
            DispatchQueue.main.async {
                self.updateUI()
            }
        }
    }
}

But is it a good approach to solve this problem? I just don't want to parse a JSON on main thread, because parsing process has a couple of for loops and other operations, and, I think it cause on drawing of UI related stuff.

A: Alamofire's response methods take a queue parameter, so you can control where the closure is run:
responseJSON(queue: myQueue) { (response)
    ...
}

Just make sure you call back to the main queue.
Also, if you want to use JSONDecoder, update to Alamofire 5 (currently in beta) or use responseData and feed that data into JSONDecoder.

A: Yes  this is a good approach , but you need to make
DispatchQueue(label: "parsing", qos: .userInitiated).async {

an instance var as crearing a queue is expensive , so try to make it 1 or use the DispatchQueue.global().async , you can also use URLSession.default that runs in background thread , and consider using JSONDecoder instead of swifty json

A: This is perfect. It's a well respected approach to this type of task.
It show's how flexible and easy to use GCD (grand central dispatch) is.
There is nothing wrong with nested GCD calls to dispatch.


text:
Q: How to convert JSON response to tables in Power BI I am the task of consuming from a webservice some data by means of REST, for the consumption of data from Power BI I have used as a source a blank query where later I have added in the advanced editor the following query:
let
    url = "http://*********",
    headers= [#"Content-Type"="application/json"],
    postData = Text.ToBinary("{""token"":""*************""}"),
    response = Web.Contents(
        url,
        [
            Headers = headers,
            Content = postData
        ]
    ),
    jsonResponse = Json.Document(response)
in
    jsonResponse

As an answer I have clearly obtained a JSON file which is composed as follows:
{'result':'1',
'message':'Successful Operation',
'data':[
{'idActivity':'1001',
'organization':'ABC-001' ,
'date':'6/10/2022 2:34:04 PM',
'lat':'57.3497300',
'lng':'-90.3929000',
'status':'0',
'company':'382',
'tag':'0'},
{'idActivity':'1002',
'organization':'DEF-002',
'date':'6/10/2022 2:21:15 PM',
'lat':'83.6718200',
'lng':'-23.3464000',
'status':'0',
'company':'932',
'tag':'0'}]}

I would like to know if there is a way to convert this JSON file to tables and then be able to represent the information in power bi visuals?

A: Click the parse JSON button. That should parse it automatically. You might need to replace your single quotes with double quotes ("). Your sample JSON worked for me using parse JSON when I did that.


text:
Q: SQL Server on Linux, an issue with filesystem privileges for a backup creation I'm trying to backup SQL Server to a directory that different users should have access to. To do this, I create a user group, and include the mssql user there - but when I try to create a backup, an "access denied" error appears.
Here is what I do:

*

*Create a user group:

sudo groupadd sample_group`

*Add mssql user to the new group:

sudo usermod -a -G sample_group mssql

*The result of cat /etc/group | grep mssql command is:

mssql:x:999:
sample_group:x:1006:mssql

*Create a directory:

sudo mkdir /tmp/backup_dir/

*Add sample_group user group to the directory and provide previligious to this directory:

sudo chgrp sample_group /tmp/backup_dir/
sudo chmod 771 /tmp/backup_dir/

*The result of sudo ls -l /tmp/ | grep sample_group command is:

drwxrwx--x 2 root sample_group 4096 Feb 18 12:11 backup_dir

*Try to backup in this directory:

sqlcmd -U sa -P ********* -Q "backup database AdventureWorks TO disk='/tmp/backup_dir/1.bak'"

->

Msg 3201, Level 16, State 1, Server ubuntuAutoTest, Line 1
Cannot open backup device '/tmp/backup_dir/1.bak'. Operating system error 5(Access is denied.).
Msg 3013, Level 16, State 1, Server ubuntuAutoTest, Line 1

Why is there no access? SQL Server runs as mssql user. mssql user is in sample_group group, which owns /tmp/backup_dir/ directory
Notes:
If I use chmod 777, then the backups are created on behalf of the mssql user, the created file is owned in the mssql user group.
If I specify mssql user group as the owners of the directory, then the backups are created.
If I go to the /tmp/backup_dir/ directory on behalf of the mssql user (sudo su - mssql), then I can create files, without any issues, there are all permissions.
For a PostgreSQL database, following the steps above works without problems. Only the postgres user is used instead of the mssql user.

A: mssql will need to login again before getting the new group.  Easiest would be to restart that server.
Alternate solution:
Add the users that need to read the backup, to the sample_group, then
chown mssql:sample_group /tmp/backup_dir
chmod 2750 /tmp/backup_dir

sqlcmd -U sa -P ********* -Q "backup database AdventureWorks TO disk='/tmp/backup_dir/1.bak'"

Test if the users can read the backup (will depend on mssql's umask), if not:
chmod a+r /tmp/backup_dir/1.bak


text:
Q: Escape quotes from the results of a SQL Server query I have this PHP code that executes a query.
$sql = "SELECT ACCOUNTNUM as AccountNumber, NAME AS CompanyName
FROM VENDORTABLE";

$stmt = sqlsrv_query( $conn, $sql );

if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

And I then use the results from the query to populate a datalist:
<form method="POST">

Number/Name:

<input list="A" name="name">
<datalist id="A">
  <?php
    while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) { ?>
      <option value='<?php echo $row[0].",".$row[1] ?>'><?php
    }
  ?>
</datalist>

<input type="submit" value="Continue"">

</form>

The problem is some of the results have characters that HTML doesn't like (namely ' and ") and those reults get cut off ("Mike's" becomes "Mike", for example) when the loop puts them into the datalist.
How can I make it so that what gets put into the datalist includes the whole result and any quotes that are present in the data?
I've tried doing this:
<?php
    while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) { ?>
      <option value='<?php echo $row[0].",".htmlspecialchars($row[1]) ?>'><?php
    }
  ?>

Also with addslashes() instead of htmlspecialchars(), the former just adds a slash on the first occurrence of a quote but still cuts off everything after that

A: Within HTML attribute values you can use HTML entities, so escape your strings with the htmlentities function:
htmlentities($row[1], ENT_QUOTES)

Also have a look at the options you can pass to this function.

A: Two suggestions:

*

*Change single quotes to double ones around value attribute.

*Add ENT_QUOTES flag to htmlspecialchars method

<option value="<?php echo $row[0].",".htmlspecialchars($row[1],ENT_QUOTES) ?>">


text:
Q: Spring AOP proxy My code:-
<context:annotation-config/>
    <bean id="arthmeticCalculator" class="com.manoj.aop.test.CalculatorImpl" lazy-init="true"/>
    <bean id="stubCalculator" class="com.manoj.aop.test.StubCalculator" lazy-init="true"/>
    <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
      <property name="beanNames">
        <list>
          <value>*Calculator</value>
        </list>
      </property>
      <property name="interceptorNames">
        <list>
          <value>methodNameAdvisor</value>
        </list>
      </property>
    </bean>
    <bean id="methodNameAdvisor"
      class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
     <property name="mappedNames">
      <list>
       <value>add</value>
       <value>sub</value>
      </list>
     </property>
     <property name="advice" ref="loggingAroundAdvice" />
    </bean>
    <bean id="loggingAroundAdvice" class="com.manoj.aop.test.LoggingAroundAdvice">
      <constructor-arg><ref bean="arthmeticCalculator"/></constructor-arg>
      <constructor-arg><ref bean="stubCalculator"/></constructor-arg>
      <constructor-arg><value>false</value></constructor-arg>
    </bean>
    <bean id="testService" class="com.manoj.aop.test.TestService">
    <!--
      <property name="arthmeticCalculator" ref="arthmeticCalculator"/>
     -->
    </bean>

Java Code:
package com.manoj.aop.test;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;

public class LoggingAroundAdvice implements MethodInterceptor{

       Calculator actualCalculator;
       Calculator stubCalculator;
       boolean useStub;

 public LoggingAroundAdvice(Calculator actualCalculator, Calculator stubCalculator, boolean useStub) {
   this.actualCalculator = actualCalculator;
   this.stubCalculator = stubCalculator;
   this.useStub = useStub;
  }

 public Object invoke(MethodInvocation methodInvocation) throws Throwable {
  System.out.println("Around Invoice called");
  Calculator calc = useStub ? stubCalculator: actualCalculator;
  System.out.println(calc.getClass().getName());
  Object result = methodInvocation.getMethod().invoke(calc, methodInvocation.getArguments());
  return result;
 }

}

import org.springframework.beans.factory.annotation.Autowired;

public class TestService {

 @Autowired
     private Calculator  arthmeticCalculator;

     public void test(){
      System.out.println(arthmeticCalculator.getClass().getName());
      System.out.println(arthmeticCalculator.add(5, 10.5));
     }

}

Sorry guys I dont know how to format text in this editor,
My problem is :-
Spring is creating proxy for the class but never execute the Invoke method of the Around advice. Can some body please tell me whats going on and how to make it call the invoke method?
Here is the output of test class:-
$Proxy4
15.5
Thanks ,
Manoj

A: Which version of Spring are you using? The way you are doing proxy is the older way. The better way is to use the annotation or pure POJO+XML way. You can check a short introduction on AOP section here


text:
Q: How to calculate size of svm classifier in sklearn-python? I am using LinearSVC from svm. I want to know how much memory the classifiers take after being trained.
from sklearn.svm import LinearSVC
clf_svm = LinearSVC()
clf_svm.fit(xtrain,ytrain)

I used sys.getsizeof but it always returns 56 as it doesn't take complexity of objects into consideration. Is there a way to calculate exact size the classifier takes in memory?

A: Just pickle the object and check the file size. No easy way otherwise.
Anyways, LinearSVC is a simple model which saves its learnt data into coef_ and intercept_ attributes. So you can check the memory taken by these two. The actual size will depend on the features in the data (X).
Other than that, the actual LinearSVC in scikit will also contain some info about the classes learnt, the parameters used to initialize etc.


text:
Q: Resultset Shows first 12 Rows empty of jTable - Java I have created a Method in a same class, which take SQL Query as a parameter but there is a problem:
First time when I call
ABC(String sqlQuery)//Method Definition

this Method is working fine for me.And when I implement action performed event on a button with the following code. then there is problem.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

jScrollPane1.getViewport().remove(jTable1);
ABC(sqlQuery_f2);// Call Mothod and pass parameter
jTable1=new JTable(data,column);
jScrollPane1.getViewport().add(jTable1);

}

When the first time ABC Method is called , the result shows 12 records in jTable and When I call again with the above code on actionperformed, it start record from 13th row to onward and first 12 Row are empty.
When I second time call the Method by Passing Query as a Parameter, It should be start from the first Row and also no row should be there at start  even empty rows.
Note: I am using NetBeans and the follwing code is in non-Editable area :

jTable1.setModel(new DefaultTableModel(data, column));

And I have also declare two arrays named data and Column

Resolution ?

A: According to your scenerio, I think when you first call this method(), you probably use a counter to fill the table according to the row count. Next time the counter already has value = 12, then it increments starting from 13.
I think you need to set counter = 0 at the end of this method.
The name counter is assumed to be an int variable, but may be you have some other name.


text:
Q: ASP NET MVC 4 collection is null on post I read most of Google :-), but I can't proceed. The collection on my object is and stays null on post, whatever I do.
My Model:
public class ArticleViewModel
{
    public Guid EventId { get; set; }
    public IList<ArticleItemViewModel> ArtikelListe { get; set; }

    public decimal GesamtpreisNetto { get; set; }
    public decimal MwSt { get; set; }
}

and
public class ArticleItemViewModel
{
    public Guid EventId { get; set; }
    public Guid Id { get; set; }

    public string Artikelname { get; set; }
    public string Artikelname_EN { get; set; }

    public string Information { get; set; }
    public string Information_EN { get; set; }

    public decimal Preis { get; set; }

    public bool MitAnzahl { get; set; }
    public bool IstKategorie { get; set; }

    public int Anzahl { get; set; }
    public bool Checkbox { get; set; }

    public int Reihenfolge { get; set; }
}

My View:
@using (Html.BeginForm("Next", "Article", FormMethod.Post))
{
@Html.HiddenFor(x => x.EventId)

<input type="hidden" name="ArtikelListe" />

for (var i = 0; i < Model.ArtikelListe.Count; i++)
//  foreach (EventManager.ViewModels.ArticleItemViewModel artikelItem in Model.ArtikelListe)
{

            @if (Model.ArtikelListe[i].IstKategorie)
            {
                @Html.LabelFor(x => x.ArtikelListe[i].Artikelname)

                @Html.LabelFor(x => x.ArtikelListe[i].Information)
            }
            else
            {
                if (Model.ArtikelListe[i].MitAnzahl)
                {
                    @Html.TextBoxFor(x => x.ArtikelListe[i].Anzahl, new { @class = "field text fn" })
                }
                else
                {
                    @Html.LabelFor(x => x.ArtikelListe[i].Anzahl)
                }

                @Html.LabelFor(x => x.ArtikelListe[i].Artikelname)

                @Html.LabelFor(x => x.ArtikelListe[i].Information)
            }

}

On post, I get my Viewmodel back and it has a Collection of ArtikelListe with 15 items (thats correct), but these are all null!
In my HTTP Header I get the following post data:
EventId:824e7f3c-7190-4ebb-aa60-51b57c977b1e
ArtikelListe:
ArtikelListe[1].Anzahl:0
ArtikelListe[2].Anzahl:1
ArtikelListe[3].Anzahl:0
submitButton:Nächste

I wonder why just partial data is sent withon the http post and why all my list items are null. I tried to render by for and foreach. same result.
Any ideas? I'm helpless.

A: Collection indexers must start at zero and be consecutive (unless you include an Index property).Because of your if statements, you are not necessarily generating a control for the property Anzahl. Looking at your header information, you do not have a value for ArtikelListe[0].Anzahl which means that the first item must have either IstKategorie=true or MitAnzahl=false. You can correct this by adding a hidden input so a value posts back
@if (Model.ArtikelListe[i].IstKategorie)
{
  @Html.LabelFor(x => x.ArtikelListe[i].Artikelname)

  @Html.LabelFor(x => x.ArtikelListe[i].Information)
  @Html.HiddenFor(x => x.ArtikelListe[i].Anzahl) // add this
}
else
{
  if (Model.ArtikelListe[i].MitAnzahl)
  {
    @Html.TextBoxFor(x => x.ArtikelListe[i].Anzahl, new { @class = "field text fn" })
  }
  else
  {
    @Html.LabelFor(x => x.ArtikelListe[i].Anzahl)
    @Html.HiddenFor(x => x.ArtikelListe[i].Anzahl) // add this
  }
  @Html.LabelFor(x => x.ArtikelListe[i].Artikelname)

  @Html.LabelFor(x => x.ArtikelListe[i].Information)
}

Alternatively you can add an Index property which the DefaultModelBinder uses to match up collection items that are non-consecutive
@if (Model.ArtikelListe[i].IstKategorie)
{
  @Html.LabelFor(x => x.ArtikelListe[i].Artikelname)

  @Html.LabelFor(x => x.ArtikelListe[i].Information)
}
else
{
  if (Model.ArtikelListe[i].MitAnzahl)
  {
    @Html.TextBoxFor(x => x.ArtikelListe[i].Anzahl, new { @class = "field text fn" })
    <input type="hidden" name="x.ArtikelListe.Index" value="@i" /> // add this manually
  }
  else
  {
    @Html.LabelFor(x => x.ArtikelListe[i].Anzahl)
  }
  @Html.LabelFor(x => x.ArtikelListe[i].Artikelname)

  @Html.LabelFor(x => x.ArtikelListe[i].Information)
}

With the first option, it will post back all items. In the second case it will post back only items that meet the if conditions.
Note as Sergey noted, you need to also remove <input type="hidden" name="ArtikelListe" />

A: The issue in this line:
<input type="hidden" name="ArtikelListe" />

When POST request is sent back:
ArtikelListe:
ArtikelListe[1].Anzahl:0
ArtikelListe[2].Anzahl:1
ArtikelListe[3].Anzahl:0

Then ArtikelListe overrides value for the list and that's why it's always null.
So you just need to rename your hidden field to some another name to not conflict with existing names.
Here is working example based on your MVC code in DotNetFiddle - https://dotnetfiddle.net/BCXduq
You can click RUN, then enter some values in two input fields in the right bottom box, and click Save button. And then it will display model that server received in POST as JSON text.

A: Thank you guys.
The problem was, that I did the testing with the script from the Fiddle. In this code
Model.ArtikelListe[i].MitAnzahl

was always true.
In case it is not true, the value "Anzahl" was not bound to a control containing a value (but just a label).
@Html.LabelFor(x => x.ArtikelListe[i].Anzahl)

As soon as I inserted a hidden field within that scope and bound the "Anzahl" value to it, the post returned with all the data I expected.
Thanks anyway. I learned a lot!


text:
Q: How to change value on regedit using CMD script? Can someone help me to make a cmd script to change value on 3000 out of 3400 subfolders that the value should be changed to the newest value without impacting the 400 subfolders?
The old dbpassword value is Pass123, the newest value is Pass234.
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Myfolder\Mainfolder\BRN3130\Database
https://i.stack.imgur.com/saCZI.jpg

A: Use reg.exe instead of regedit.
reg add /?
REG ADD KeyName [/v ValueName | /ve] [/t Type] [/s Separator] [/d Data] [/f]
        [/reg:32 | /reg:64]

  KeyName  [\\Machine\]FullKey
           Machine  Name of remote machine - omitting defaults to the
                    current machine. Only HKLM and HKU are available on remote
                    machines.
           FullKey  ROOTKEY\SubKey
           ROOTKEY  [ HKLM | HKCU | HKCR | HKU | HKCC ]
           SubKey   The full name of a registry key under the selected ROOTKEY.

  /v       The value name, under the selected Key, to add.

  /ve      adds an empty value name (Default) for the key.

  /t       RegKey data types
           [ REG_SZ    | REG_MULTI_SZ | REG_EXPAND_SZ |
             REG_DWORD | REG_QWORD    | REG_BINARY    | REG_NONE ]
           If omitted, REG_SZ is assumed.

  /s       Specify one character that you use as the separator in your data
           string for REG_MULTI_SZ. If omitted, use "\0" as the separator.

  /d       The data to assign to the registry ValueName being added.

  /f       Force overwriting the existing registry entry without prompt.

  /reg:32  Specifies the key should be accessed using the 32-bit registry view.

  /reg:64  Specifies the key should be accessed using the 64-bit registry view.

Reg Add with the /f will help you overwrite an existing value.