Why doesn't "cd" work in a shell script?

Question: I just want to write a script which changes my directory.
I put the below commands in the file /home/alex/pathABC
#!/bin/sh
cd /home/alex/Documents/A/B/C
echo HelloWorld

I did
chmod +x pathABC

In the Terminal, while in /home/alex, I ran ./pathABC, but the output is just HelloWorld and the current directory is not changed.
So what is wrong?
Comment: Look at this [Why doesn't "cd" work in a bash shell script?](https://stackoverflow.com/questions/255414/why-doesnt-cd-work-in-a-bash-shell-script)
Comment: 'cd' works in a shell script. For example, you might have placed any script  onto /home/alex/Documents/A/B/C path and you write shell script like: first it will go to the directory(via cd) then run the script(via ./) then it will. However, after that control will return back to the current path from where you are running ./pathABC script. The same case is happening with your script, it's going to the path and then once execution exits ,it return back to the location from where it's been called.
Answer: As others have explained, the directory is changed in the child process of your script, not in the terminal process from which the script is called. After the child process dies, you are back in the terminal which is left where it was.
Several alternatives:
1. Symbolic link
Put a symlink in your home to the long path you want to easily access
$ ln -s /home/alex/Documents/A/B/C ~/pathABC

then access the directory with:
$ cd ~/pathABC

2. Alias
Put an alias in your ~/.bashrc:
alias pathABC="cd /home/alex/Documents/A/B/C"

(from here)
3. Function
Create a function that changes the directory, the function runs in the process of your terminal and can then change its directory.
(from here)
4. Avoid running as child
Source your script instead of running it. Sourcing (done by . or source) causes the script to be executed in the same shell instead of running in its own subshell.
$ . ./pathABC

(from here and here)
5. cd-able vars
Set the cdable_vars option in your ~/.bashrc and create an environment variable to the directory:
shopt -s cdable_vars
export pathABC="/home/alex/Documents/A/B/C"

Then you can use cd pathABC
(from here)
Comment: Now I understand the usage of `source`! I always wondered why I do `source .bashrc` and not `bash .bashrc`
Comment: > 5. cd-able vars -- isn't it `cd $pathABC` ?
Comment: Option 3 worked great. I just defined a function go_to_wherever() { cd my/directory } at the beginning of my script. Called it before running the operations in that directory.
Comment: 4th solution was more handy and useful at the moment
Comment: @loxaxs no, that's what `cdable_vars` does for you https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html.
Answer: When you run script in a Terminal, a child process runs. In this child program i.e. your script will change to whatever directory specified. But in the parent process, i.e. where you run the script is still in the old path.
OR simply we can say:

The scope of cd command is only for child process not parent.
Comment: Adding to this, @alex to achieve the effect you are looking for, execute the script _within_ the parent process by sourcing it: either `. pathABC` or `source pathABC`.
Answer: You are making a thinking error. While the current shell stays in the same directory, the script has moved to the new directory.
You could see that by creating another script in the new directory, and running it from your script, after it has changed directory:
#!/bin/sh
cd /home/alex/Documents/A/B/C && ./another_script.sh # (if it is executable)

The second script would run from the new directory.
HelloWorld

is just the output of the script.
Comment: HelloWorld is not "returned" to the parent shell, it's output to the standard output
Comment: Might be clearer if you just run `pwd` in the new directory, instead of adding a whole new script to the situation.
Answer: Actually, I just found, after many searches, that if you need to change the directory, and still keep the same shell, so you will get all the answers in your current script, you can use:
(cd your_dir; do_some_command_there)

For example, what I needed to use, was:
(cd your_dir; git remote -v | wc -l)

Works like a charm!
Answer: Use $SHELL at the end

A bash script operates on its current environment or on that of its
children, but never on its parent environment.

However, this question often gets asked because one wants to be left at a command prompt in a certain directory after execution of a script from within another directory.
If this is the case, simply execute a child $SHELL instance at the end of the script:
# !/usr/bin/env bash
cd /home/alex/Documents/A/B/C
echo -e '\nHit [Ctrl]+[D] to exit this child shell.'
$SHELL

To return to the previous, parental shell instance, use Ctrl+D.
Answer: Trying to use cd inside the shell script does not work because the shell script runs in the subshell and once the script is over it returns to the parent shell, which is why the current directory does not change.
To achieve changing of the directory use sourcing.You can either use . scriptname.sh or source scriptname.sh command to use sourcing.
Note : Also when you use sourcing do not use the exit command because it then closes your connection.
Answer: Because hello world is just a trace statement, let's try this:
Create bash script file cd.sh containing:
#!/bin/bash
echo "/home/mike/Documents/A/B/C"

The .sh extension is an older convention of giving bash script filenames an extension. It's purely cosmetic and usually unnecessary. However in this case it's important to differentiate from the core cd command.

Mark the bash script file executable using:
chmod a+x cd.sh

Now run the file:
$ cd $(./cd.sh)
bash: cd: /home/alex/Documents/A/B/C: No such file or directory

cd we all know.
$(...) executes command inside parenthesis and returns output.
If cd.sh was in your path you don't need to specify where it is. We prefix with ./ to specify the command is in the current directory.
The echo output from the cd.sh script is sent back to the parent via the $(...). The parent (our shell prompt) uses this output and passes it to the Linux cd command.

As others have mentioned a child process can't change the parent's directory. This is one way the child can tell the parent where to go after the process ends.
Comment: @wjandrea That's what you get for coding on a phone! Just got home, I'll fix it up. Thanks. Um just checked and it works fine. Maybe it's your `14.04` version I read about an hour ago or so?
Comment: Well, you totally changed the script. Previously it was just one command: `cd /home/mike/Documents/A/B/C`, which didn't produce any output. Now it's `echo "/home/mike/Documents/A/B/C"`, which does produce output.
Comment: @wjandrea True, I also totally changed the way of calling the script too. Instead of a simple `./cd.sh` it's now `cd $(./cd.sh)` but it accomplishes the goal of the child changing the parent's current directory. Yes it's unconventional but it's another way of doing it that I hope people find interesting.
Answer: CDPATH might help in some cases.
# add this to .bashrc .zshrc or whatever
export CDPATH="/home/alex/Documents/A/B:$CDPATH"

# and then you can just do...
cd C

Note u have to add 'A/B' to CDPATH, not 'A/B/C'
You can add multiple paths to CDPATH just like PATH.


Coordinated save in database and disk in java

Question: In my task I need to save file on disk and update info about in database.
Exception can happen when saving file and when updating info in database.
Do exist some ready open source solutions for it or it need write from scratch?
Thanks.
Comment: Are you using any transaction coordinating system already?
Answer: There's XADisk which provides transactional access to file systems. From their web site:

XADisk (pronounced 'x-a-disk') enables transactional access to
  existing file systems by providing APIs to perform file/directory
  operations. With simple steps, it can be deployed over any JVM and can
  then start serving all kinds of Java/JavaEE application running
  anywhere.
Comment: to be more specific, because we have more than one resources (in this case two, file system and database) to be combined into a single transaction, the Java application will need to use: 1) an XA Transaction-Manager (e.g. Atomikos), 2) XA support from the database (which most databases already have), 3) XA support from the file-system (as most file-systems themselves don't support XA, XADisk can be used to add the XA support).
Answer: In Java, enterprise transactions management is ruled by the JTA spec wich is used in Java EE.
JTA allows to create several TransactionManager with differents implementations (one for database, one for file) and make them work together to define a cross-transaction
I think this could be a way for you to do what you want
Outside of a container, there are possibility to integrate JTA. You should have a look at Spring or JBoss implementations
Look at this blog post for more information about Spring and transactions usage
Answer: The file system isn't directly supported by Java EE, but you could implement/ search for a resource adapter for the file system.
http://docs.oracle.com/javaee/6/tutorial/doc/gipgl.html
http://docs.oracle.com/javaee/6/tutorial/doc/giqjk.html
Comment: Why the down-vote? Even the specific solution provided by Nicholas (XADisk) is providing a resource adapter (rar).


Payne gas furnace, model # PY3GNAA36090AATP.

Question: Indoor fan blows continually, with 4 flashes on control board
Comment: Hello, and welcome to Stack Exchange. We'll need some more information about this: how did it start? What else does the furnace do? What do you get when you google "4 flashes on Payne gas furnace control board"?
Answer: It sounds like a choked indoor fan
A four-flash code on the control for your furnace (PY3G--A) means that the high limit is tripping repeatedly and cutting out combustion.  The continuously running blower is a sign that the control board is calling for fan due to the high plenum temperatures that aren't going away, as well.  I would check for a clogged filter or other airflow restriction that's keeping things from working properly. If this is a new install, then you'll have to get the HVAC contractor back out and beat them upside the head with a Manual D until they can install ductwork with low enough static pressure losses to keep the furnace happy.


jQuery broken in IE7 & IE9 only

Question: For some reason, on this really simple page, jQuery will not work on IE7 or IE9, yet it works in IE8 and all other modern browsers. Any ideas why this might be the case?
$(document).ready(function() {

$(".thumb").fancybox();

$("a.group").fancybox({
    'transitionIn'  :   'elastic',
    'transitionOut' :   'elastic',
    'speedIn'       :   600,
    'speedOut'      :   200,
    'overlayShow'   :   false
});

$('.note').live('click', function() {
    $(this).parents('.result').next('.notes').slideToggle();
});

});

Baffling. Any help would be greatly appreciated! BTW, if you'd like to check out the whole deal, you can see it at http://moveout.dancormier.com
Thanks in advance.
Comment: I don't have IE, so can you tell use what's wrong? How's it broken? What errors are you getting?
Comment: I just tried this in IE7 and it seemed to be working? Certainly the toggling of notes was working like a champ and even the fancybox calls worked. What specifically is broken?
Comment: The javascript was broken entirely.
@SteveWellens suggestion fixed it.
Thanks for the help everyone!
Answer: Can you tell us what errors you're encountering when viewed in IE? (The prospect of booting up a Windows VM and IE to look for myself is not exactly appealing)
A guess:
A lot of times IE7/IE8 seems to be very picky about JSON notation. e.g., if you end an object literal with a , it bugs out.
{foo1: 'bar',
 foo2: 'baz',} // <-- This , seems to be ignored by everything but IE

So perhaps you should play around with your object literal there? Maybe don't quote the keys and remove the superfluous spacing between the key, : and value.
General advice:
Try using the DebugBar to debug problems in IE. It's certainly no FireBug but its the best you can get for free for IE debugging.
Comment: IE is fine with quoted object keys
Comment: I've run into the 'trailing comma' issue before. It took me a while to figure out what was wrong.
Answer: Try a newer, or older, version of jQuery.
Comment: Surprisingly, this seems to have been the issue. Somewhere along the line, the IE7 problem went away, but the IE9 issue persisted. When I changed the jquery from 1.5.0 to 1.5.2, the IE9 issue went away.
BTW: To those of you asking, the javascript as a whole was broken. Nothing worked. But this seemed to fix it! Thanks!
Answer: What exactly are the errors that you're getting?
I don't know about jQuery and IE per se, but I did have to tango with fancybox a while back with IE 7. I kept getting UI layout errors related to the IFRAMEs that fancybox were throwing out.
If this sounds like what you're getting, I posted a blog post on a workaround I did at that time if you're interested in looking at it.
Comment: Thanks for the suggestion @richardneililagan. Fancybox wasn't the issue this time. Updating jquery from 1.5.0 to 1.5.2 fixed it.

jQuery broken in IE7 & IE9 only


Require only one codeowner on GitHub to review a PR

Question: We have a GitHub repo with a CODEOWNERS file. For the main branch we also have a protection rule to "Require review from Code Owners". However, some folders of the repo belong to multiple code owners, and if they have changed then GitHub requires ALL code owners to approve the change.
Is there a way to tell GitHub that an approval from one of the code owners is sufficient?
(Note that there is another option in the branch protection rules, which requires approvals for a change, and one can define how many such approvals are necessry. This is not what I am looking for, I am solely talking about the review of code owners.)
Comment: Did you ever find a solution?
Comment: @Gajus Unfortunately not.
Answer: According to the GitHub CODEOWNERS documentation, this is possible with this example syntax:
# In this example, any change inside the `/scripts` directory
# will require approval from @doctocat or @octocat.
/scripts/ @doctocat @octocat

Also, users and teams are treated equally according to the same documentation:
The pattern is followed by one or more GitHub usernames or team names using the standard @username or @org/team-name format.

Are you experiencing a different behaviour? If so maybe post (the relevant portion of) your CODEOWNERS? It may be the case that your CODEOWNERS file is complex - see this thread where it says:

It's hard to say why you're experiencing this behavior without some more information. Is the repository in question public? Can you share a link to a specific PR that is behaving in a way that you believe is not expected?
Assuming that the repository in question is private, I can guess at one reason why more than one reviewer might be required. Let's say you have a CODEOWNERS like the following:

* @foo @bar @baz

In this case, any PR would require one (and only one) of those three people to approve it before it could be merged. But let's say you have a more complex CODEOWNERS file:

*.js @foo @bar`
docs/ @baz`

And you submit a PR that includes both a JavaScript change as well as a change to some associated documentation. That PR would require one of either foo or bar to approve it for the JavaScript change and a separate approval from baz for the documentation.
Maybe you could share just your CODEOWNERS file?


RHC setup fail in OpenShift - UTF8 - SSH

Question: I am using OpenShift for my studies and in my case the RHC setup does not work.
When I try to execute it, it fails while generating an authorization token saying:

Generating an authorization token for this client... Only valid UTF-8 encoded inputs are accepted

and then it stops.
My platform is Windows 7.
Answer: I had exactly the same issue. I fixed it by removing non-ascii characters from my Windows 8 computer name in control panel/system/advanced system settings/computer name/change. Give it a try.


parameter lost when the function is called

Question: I have a weird thing.
When I call a function from my service, the service lost all the parameters.
I don't know when and why.
The debug says that there's is the parameters when they get in the class and then, nothing.
I make a similar function in another service and it works. Its realy weird.
Look (debug print) :
c.f.timesheet.web.rest.AppUserResource Enter: getAllAppUsersByCompany() with argument[s] = [1, AppUserCriteria{}, Page request [number: 0, size 20, sort: undefined: DESC,id: ASC]]
c.f.timesheet.web.rest.AppUserResourceREST request to get AppUsers by company id: 1
c.f.timesheet.service.AppUserService  Enter: findByCompany() with argument[s] = [1, Page request [number: 0, size 20, sort: undefined: DESC,id: ASC]]
c.f.timesheet.service.AppUserService :Request to get all AppUsers by company id !!!!!!!!!!!!!!!!!!!!! The problem the id is missing
Exception in findByCompany() with cause = 'java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: undefined of: com.freemind.timesheet.domain.AppUser [select appUser from com.freemind.timesheet.domain.AppUser appUser where appUser.id=?1 order by appUser.undefined desc, appUser.id asc]'
Here's the code:
AppUserRessource:
@GetMapping("/app-users/company/{id}")//tayo
public ResponseEntity<List<AppUserDTO>> getAllAppUsersByCompany(@PathVariable Long id,Pageable pageable) {
    log.debug("REST request to get AppUsers by company id: {}", id);
    Page<AppUserDTO> page = appUserService.findByCompany(id,pageable);
    return ResponseEntity.ok().body(page.getContent());
}

AppUserService
   public Page<AppUserDTO> findByCompany(Long id,Pageable pageable){//?
        log.debug("Request to get all AppUsers by company id", id);
        return  appUserRepository.findByCompany(id,pageable).map(appUserMapper::toDto);
    }

the query:
   @Query("select appUser from AppUser appUser where appUser.id=?1")
    Page<AppUser> findByCompany( Long id, Pageable pageable);

Do You have any idea?
Thanks you.
Answer: Your debug statement is wrong
log.debug("Request to get all AppUsers by company id", id);

should be
log.debug("Request to get all AppUsers by company id {}", id);

The error message says
order by appUser.undefined desc, appUser.id asc

So the problem is the order by statement, which has undefined in it. It seems like your paging request is not formed correctly on the client side, that is what you should investigate.
Comment: Indeed thank you. So the error in my request is something else.
Comment: Are you using javascript on the client? That's probably where the undefined is coming from, when the paging is being worked out.
Comment: I'm using Angular. I see the issue but don't know how to solve it. I have a sorting function send to the backend => [number: 0, size 20, sort: undefined: DESC,internal_user_id: ASC]]. It knows the id for the asc but it doesn't want for the desc. There's the function  const result = [this.predicate + ',' + (this.ascending ? 'asc' : 'desc')];
    if (this.predicate !== 'internal_user_id') {
      result.push('internal_user_id');
    }
    return result;
Comment: What are you trying to sort by?
Comment: By the id. I saw the error, wasn't the good string as predicate. Now it works. Thank you! : )
Comment: @Girbouille you should accept Vlad's answer


How to test the existence of a Word Custom Document Property (CDP) in a field code?

Question: The following fieldcode in Word displays the contents of the custom document property "myproperty" when it exists; otherwise it does nothing
<code>{IF {DOCPROPERTY "myproperty"} <> "Error! Unknown document property name." {DOCPROPERTY "myproperty"}}
</code>
The test for existence is based upon the error message that Word returns if the property does not exist. Trouble is: this error message can be localized (e.g. in French etc).
Do you know how to test for existence of a custom document property in a locale independent manner? This would be equivalent to something like:
<code>{IF {EXIST-DOCPROPERTY "myproperty"}{DOCPROPERTY "myproperty"}}
</code>
Answer: IMHO you've stumbled over the few issues in Word which are language-content-related and for which no correct solution exists.
Another example is the {STYLEREF} field, which needs a reference to the style you want to refer to. While you have in VAB/VSTO the possibility to refer to the built-in styles through a constant, e.g. wdStyleHeading1, to be language-independent, with the field you must add the style name as "Heading 1" in an English Word. Open the document in a German Word, and you'll get a "style name not defined" error, and vice versa opening a German "STYLEREF "Überschrift 1"} in an English Word.
You haven't said anything about the whole situation in which you want to address your issue. In my document template sets, I'm normally in control of the documents, e.g. there's a global add-in running through which I can control documents. Additionally, templates issued by me do have the custom document properties already defined, so that errors of your kind can not happen. However, even if they're not defined, you may create them while opening a document.


CRLfile: none??? Trying to update R to latest version been googling for days

Question: Ubuntu 14.04
I get an error after
sudo apt-get update
###other stuff###
Err https://cran.mtu.edu trusty/ Packages
server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys E084DAB9
gpg: requesting key E084DAB9 from hkp server keyserver.ubuntu.com
gpg: key E084DAB9: "Michael Rutter <firstname.lastname@example.com>" not changed

gpg: Total number processed: 1
gpg:              unchanged: 1
gpg -a --export E084DAB9 | sudo apt-key add -
OK

sudo apt-get install r-base
Reading package lists... Done
Building dependency tree
Reading state information... Done
r-base is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 152 not upgraded.

But....
~$ R

 R version 3.0.2 (2013-09-25) -- "Frisbee Sailing"
 Copyright (C) 2013 The R Foundation for Statistical Computing
 Platform: x86_64-pc-linux-gnu (64-bit)

These seem to be the instructions on https://cran.r-project.org/bin/linux/ubuntu/README and various blog posts
Answer: The approach I use for up to date R and CRAN packages is adding Michael Rutter's PPAs (also used by CI-Travis):
sudo add-apt-repository ppa:marutter/rrutter
sudo add-apt-repository ppa:marutter/c2d4u
sudo apt-get update
sudo apt-get upgrade

Comment: This is what I got back                                                                                'Fetched 5,132 kB in 7s (720 kB/s)
W: Failed to fetch https://cran.mtu.edu/CRAN/bin/linux/ubuntu/trusty/Packages  server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none'
Comment: This is from the repository you added first, that wasn't correctly identified. After you add the PPAs as I described, you can remove those from the Software Sources program.
Comment: I just entered the code you put down. Was I supposed to do something else? Brand new. Oh I should remove that from the sources.list?
Comment: Yes, it adds two [PPAs](https://en.wikipedia.org/wiki/Personal_Package_Archive), updates the package database, and upgrades installed packages. Since you already have `R` installed, and (presumably) some CRAN pacakges as well, those will all be updated.
Comment: If the answer solved your question then, please accept the answer by clicking on [the upvote arrow and then the tick below it](http://i.imgur.com/YN8AQkd.png?1).


Error. mysql installer when installing mysql onwndows 10 laptop

Question: enter image description here
when installing mysql there is show a error "mysql installer did not find packages in the current bundle suitable for installation windows".
how can I solve this problem ,I am using windows 10, 64bit with 8GB ram laptop.
Answer: I ran into the same problem and deleting C:\ProgramData\MySQL\MySQL and restarting the installer worked for me.
https://www.reddit.com/r/mysql/comments/lw3yy0/issues_installing_mysql_no_packages_found/
Comment: Thanks for your help!


exterior clearcoat for flashings

Question: Manufacturers of certain metal roofing materials which can be used for flashings and valleys advise clearcoating the metal before exposing it to the acids of certain woods.
I am looking for a clear coating that will adhere to copper and terne coated stainless roof flashings for valleys, chimney crickets, and pipe penetrations.
What kind of exterior clearcoat should this be? Are there exterior paints without pigments which have good adhesion to metal?
Answer: I would use a prefinished aluminum (with Kynar finish).  If you can't attain it or already installed the flashing - purchase Parapro - it's a liquid applied membrane that is amazing!
Comment: Thanks for the tip about Papapro, I will keep it in mind, but my question here is really specific.  I need a clear coat.
Comment: You can try this...http://www.elastomericroofcoating.com/

exterior clearcoat for flashings


Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension ubuntu

Question: While running bundle install i am getting the following error in 'pg' gem i changed the gem as sqlite then too am getting same error. This is my error message.
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

        /usr/bin/ruby1.9.1 extconf.rb
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- mkmf (LoadError)
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from extconf.rb:2:in `'

Gem files will remain installed in /var/lib/gems/1.9.1/gems/pg-0.16.0 for inspection.
Results logged to /var/lib/gems/1.9.1/gems/pg-0.16.0/ext/gem_make.out

An error occurred while installing pg (0.16.0), and Bundler cannot continue.
Make sure that `gem install pg -v '0.16.0'` succeeds before bundling.

I tried apt-get install libpg-dev gem install pg -v '0.16.0' nothing helps me
Comment: it should be a dev package missing, see [this question](http://stackoverflow.com/questions/7645918/require-no-such-file-to-load-mkmf-loaderror) or [this one](http://stackoverflow.com/questions/12731904/rails-installation-failed-on-ubuntu-with-cannot-load-such-file-mkmf)
Comment: Possible duplicate of  http://stackoverflow.com/questions/13767725/unable-to-install-gem-failed-to-build-gem-native-extension-cannot-load-such
Comment: possible duplicate of [Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension](http://stackoverflow.com/questions/15816331/geminstallerextensionbuilderror-error-failed-to-build-gem-native-extension)
Answer: You should have postgresql installed before you install pg gem.
sudo add-apt-repository ppa:pitti/postgresql
sudo apt-get update
sudo apt-get install postgresql libpq-dev

If your sqlite is not working, it looks like there are some packages you might have missed.
sudo apt-get install libreadline-dev libssl-dev zlib1g-dev build-essential bison openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev

Comment: For sqlite, did you install the dependencies? I will update the answer with dependencies
Comment: I am not sure about sqlite dependencies but for postgresql i installed everything and its working in command line. But i am unable to locate gem.
Comment: The dependencies I have given is not restricted to sqlite. It also includes packages other than sqlite. Try installing the packages I have given, it should work.
Comment: Its throwing same error. I tried most of the Stackoverflow answers.
Comment: you tried this one `sudo aptitude install ruby1.9.1-dev` and then reinstalling the gems?
Comment: Here are the updated instructions on how to install postgress http://wiki.postgresql.org/wiki/Apt
Comment: Installing those dependencies worked for me!  Thanks!
Answer: On Ubuntu 14.04 (and possibly every other Debian 7 based distro) this problem is caused by the absence of the Ruby development package. Thus the fix is simply to install it:
sudo apt-get install ruby1.9.1-dev

Comment: `sudo yum install ruby-devel` for CentOS (solved my issue)
Answer: I have the same problem i solved it by installing it in ubuntu as normal user not as root user. I hope this may help you.
Answer: I solved it by follwing these steps

Uninstalled ruby completely using sudo apt-get purge ruby*
Then in removed curl sudo apt-get purge curl

Then i followed this link to install Ruby RVM and rails 4.0.0
Install Rails 4.0.0
Answer: Install
http://postgresapp.com/

then
PATH="/Applications/Postgres.app/Contents/MacOS/bin:$PATH"

then
bundle install

Answer: Sometimes you need to update your Ruby library, run this code:
sudo gem update --system

Answer: I had an issue with slightly different Ruby builds. The existing application's Gemfile.lock was created using ruby-1.9.3-p194 and my local ruby was ruby-1.9.3-p484. Switching to the proper ruby allowed for a successful bundle.
Answer: I had the same problem with CentOS 6.5.

Created a new user
Added this users to the sudoers file /etc/sudoers
Install ruby-devel using yum -y install ruby-devel
Answer: On Debian, the pg install was failing to build native extensions because postgres wasn't installed.
I installed the postgres dependencies with:
$ apt-get install postgresql postgresql-client libpq-dev

Then the pg gem built its dependencies just fine:
$ gem install pg -v '0.18.3'
Building native extensions.  This could take a while...
Successfully installed pg-0.18.3
1 gem installed


Why do I get un-queued while levelling?

Question: I am currently in the process of finishing levelling one of each class before the start of the next expansion through a combination of questing and completing battlegrounds.
At the lower levels it is only taking me 10-15 minutes to complete each level and move onto the next one, however, I have noticed that I get removed from the queue for battlegrounds each time I level.
Why would this be?
Comment: I do not have any sources, but it is a known bug. My whole guild complains about it while we are leveling alts (especially when a tank levels and the leader doesn't realize it to back out of the queue for them). I can say from my experience since 5.0.4, it is a bug that I've had to deal with while leveling two accounts.
Comment: I don't think it's a bug because battlegrounds have level tiers i.e. you can enter a battleground with people in levels similar to yours. If you queue to a battleground in level 12 you queue with other player in the tier 10-19 or something and if you level up then you may change tier. So I do not know if the game prevents you from queueing in a different tier on level up and you must requeue manually so the server adjust your queue to the new level you got.
Comment: My comment to pixel was referring to also being in those tiers (i.e. 10 - 19 tier, I level from 12 to 13, then get kicked out of the queue). This also happens during dungeon finder as well.
Comment: In [patch 4.0.3](http://www.wowwiki.com/Patch_4.0.3), the battle ground system was split up into 5 level brackets.
Answer: This is an intended feature to keep higher levels out of lower level brackets.
Comment: Do you have a source for this?
Comment: No, but it's pretty logical from a design perspective. Not many people want level 55's in the 50-54 bracket.

Why do I get un-queued while levelling?


Kate crashes while clicking Open

Question: I am running on Ubuntu 12.04 I recently noticed that Kate 4.8.4 which have been installed in my 64-bit PC is crashing whenever I try to open a file in it. It shows no problem when I open files via terminal.
It displays the following in the terminal while crashing.
trying to create local folder /home/myusername/.kde/tmp-MYPCNAME: Permission denied
trying to create local folder /home/myusername/.kde/socket-MYPCNAME: Permission denied
trying to create local folder /home/myusername/.kde/tmp-MYPCNAME: Permission denied
QFile::remove: Empty or null file name
kdeinit4: Aborting. bind() failed: Permission denied
Could not bind to socket '/home/myusername/.kde/socket-MYPCNAME/kdeinit4__0'
trying to create local folder /home/myusername/.kde/cache-MYPCNAME: Permission denied
trying to create local folder /home/myusername/.kde/share: Permission denied
kate(3237) fileModule: Failed to load configured file module "kfilemodule"
KCrash: Application 'kate' crashing...
KCrash: Attempting to start /usr/lib/kde4/libexec/drkonqi from kdeinit
sock_file=/home/myusername/.kde/socket-MYPCNAME/kdeinit4__0
Warning: connect() failed: : Permission denied
KCrash: Attempting to start /usr/lib/kde4/libexec/drkonqi directly
trying to create local folder /home/myusername/.kde/cache-MYPCNAME: Permission denied
QFile::remove: Empty or null file name
drkonqi(3251)/KSharedDataCache KSharedDataCache::Private::mapSharedMemory: Failed to establish shared memory mapping, will fallback to private memory -- memory usage will increase

From the above I understand that this is a problem of user privileges. I checked running Kate from the terminal as root it works fine.
As I am new to linux can someone point me in a direction that could solve the problem.
Answer: I was experiencing a similar issue when running Kexi on my Linux Mint 17.2 system:
...
kexi(9324) fileModule: Failed to load configured file module "kfilemodule"
KCrash: Application 'kexi' crashing...
...

The solution in my case (found here) was to manually install some KDE-specific packages:
$ sudo apt-get install -y kdelibs-bin kdelibs5-data kdelibs5-plugins

Initially I thought this was a packaging issue specific to Kexi, but since it seems to affect multiple KDE applications, I guess it might be a KDE packaging problem.
Comment: this worked for me for KCachegrind on Mint 17.3
Comment: I appreciate that you were facing this problem years ago, but it seems that people (myself included) are still experiencing this, so I've posted an answer in case it helps others.
Comment: I moved to Arch now. And I mostly use vi and sublime, so I really don't have the means to test your solution...
Answer: Change the ownership of the .kde folder with these console commands:
cd ~
sudo chown -R yourusername .kde

Replace yourusername with your actual user name. You will be prompted for the sudo password.
This error usually happens as a result of running graphical programs (like kate) as root directly with sudo, which can cause root to create its own configuration files in your home directory (or effectively take ownership of the ones that are already there). Instead, a graphical sudo frontend, such as kdesudo (or gksu/gksudo) should always be used when running graphical programs as root.
Comment: That solved the issue. But isn't user the owner of his or her home folder ?
Comment: @mahesmohan I've expanded this answer with an explanation for how `root` can come to own files in users' home folders (and how to avoid this problem in the future).
Comment: Can someone edit this to replace the "yourusername" bit with `$USER`? Then it'll work as-is
Answer: If Kate crashes when you try to open or save a file, try installing kdelibs5-plugins:
sudo apt-get install kdelibs5-plugins

Kate crashes while clicking Open


replumb leaning post

Question: 6 ft tall 4x4 PT post out of plumb by 1-3/8". Excellent condition. Years old. Set in cement. Rock solid in part because tree roots have encased the cement. Tree too valuable to risk damaging roots by removing old post and cement, or placing new post nearby.
I plan to replumb the post by crosscutting about 2/3 the way through the post at 12" above the top of the cement. This will weaken it enough to bend at the kerf. Once replumbed (past plumbed, actually, to balance out forces), scab on 30" length of 2x4 PT, fitted to the bend, on the side with the kerf.
Question is on which side of the post should the kerf be placed? on the "overhanging" side so that the kerf opens when bent plumb? or on the sloped side so that the kerf closes when plumbed?  Aesthetically doesn't matter.
EDIT: or maybe snap a plumb line from top to bottom, then saw off the "overhanging" 6 ft wedge, then scab it on to the sloping side.
Comment: Your second (edited-in) idea is a good one. It leaves the bottom of the post nearly full-thickness. It will be challenging to get clean, straight, well-aligned cuts from both sides, however.
Comment: what is not clear is what the post is for and why it is imperative that it be plumb and its dimentions be 4x4? . can you pretend you are Leonardo Da Vinci and see the straight board inside the 4x4 and remove everything that is not straight and plumb?.
Comment: Unless you need to mount to both sides of the post, use the edit solution, but without cutting anything off.  Just trim a 2x4 into a wedge and attach it to create a vertical surface on the side you need,  If the post is also rotated so that the face isn't parallel with the next post, you can cut a compound angle on the wedge to correct both at once.
Answer: Stronger if the kerf pinches, the reason being ...
Consider a post that is simply crosscut as mentioned (not reinforced with the 2x4 scab).  This weak point will fail much more easily when the post takes a load (bent) in the direction that opens the kerf, as opposed to the opposite direction.  This is because the post, when loaded in that direction, is vulnerable to splitting-out at the kerf.  When loaded in the opposite direction (that closes the kerf), the post is not vulnerable to splitting out, but would break due to tension failure.  Intuitively, it would take much less load to split out than to fracture under tension. If you don't trust my intuition, try this on a 2x4 to see which direction it more easily breaks.
Now consider a post that is crosscut and then reinforced with 2x4 scab as mentioned.  If the kerf was placed so that replumbing opened the kerf, then the post would be under a permanent partial load to split out.  If the kerf was placed so that replumbing closed the kerf, then the the post would be under a permanent partial negative load to split out, and under a permanent partial load for tension failure.  Intuitively, the later makes for a much stronger repair.
The theoretical kerf width required for the closed-kerf scenario is 4 * 1.375 / 60 = 0.092, or about 3/32".
Attach the 2x4 scab with numerous smaller fasteners (not in the same grain line) rather than a couple large fasteners.
As for option two, snapping a plumb line, the easier thing to do is cut a short piece of 2x4 that is 1-3/8" long, then  use it to space off one end of straight 6' 2x4 when screwing (or clamping) the 6 footer temporarily to the the post on the opposite side of the cut, then use an adjustable ripping T-guide (that came with the circular saw) to carry out a uniform width rip.  Make the rip top to bottom on one side, then bottom to top on the other, keeping the wide part of saw shoe on the post.  If the post is too thick for the rips to meet (6x6) complete the rip with a third pass using a sawzall.
In the end, I used the closed kerf method, and attached the trimmed-to-fit 2x4 scab with 12 torx head 3" screws and full caulk.  When hit with a fist, it vibrates just as the intact post did, like a tuning fork, though rigidity and strength are not the same. If I had to do it over again, I'd use the same approach.
Comment: Hi, please come back and click the check-mark next to your self answer. This is a perfectly acceptable thing to do here, and it prevents the system from automatically bumping your question to the top of the pile every now and then (since it doesn't have an accepted answer). Thanks, and congrats for figuring this out on your own!
Answer: You could try a Simpson E-Z Mender for fence posts.
https://www.buildsite.com/pdf/simpsonstrongtie/E-Z-Mender-Product-Data-1461816.pdf

replumb leaning post


Configure registry permission tool

Question: I have to write a key value pair in the registry. This is done using a tool. This fails sometimes.
Is there any windows utility available which can set the permissions of the registry? If the specific user does not have permission to the registry, I should be able to configure the permissions accordingly - from an administrator account.
I have the only option of invoking it during system startup to set the parameters.
Answer: try this
 bool flag1 = false;
            try
            {
                new System.Security.Permissions.RegistryPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
               // Your Work
            }
            catch (Exception obj1) //when (?)
            {
            }
            finally
            {
                System.Security.Permissions.RegistryPermission.RevertAssert();
            }
            return flag1;

Answer: Look at the Regini.exe tool. See here for more details: How to change registry values or permissions from a command line or a script

Configure registry permission tool


Parallel.For/Foreach threads reuse C#

Question: Is there a way to reuse threads used in consecuent calls of Parallel.ForEach loop? I am tring to do because I understand that thread creation can be costly.
Thats what i would like to do:
var collection = CreateMyCollection()
var pool = CreateThreadPool()
for(int i =0 ; i<1000 ; i++)
      Parallel.ForEach(pool, collection, (element) => Calculate(element, i))

Is it possible?
Note: I cannot parallize the external loop instead (hard dependancy between 'i's')
Comment: I want to say that the threads that the `Parallel` methods use just come from the task pool, so using tasks should essentially be reusing those same threads.
Comment: Wow, I will lookup the documentation for that, do you have a link?
Answer: Parallel.ForEach is part of TPL. By default TaskSceduler, responsible for queuing work items onto threads, will use ThreadPool.

An instance of the TaskScheduler class represents a task scheduler. A
  task scheduler ensures that the work of a task is eventually executed.
  The default task scheduler is based on the .NET Framework 4 thread
  pool, which provides work-stealing for load-balancing, thread
  injection/retirement for maximum throughput, and overall good
  performance. It should be sufficient for most scenarios. The
  TaskScheduler class also serves as the extension point for all
  customizable scheduling logic. This includes mechanisms such as how to
  schedule a task for execution, and how scheduled tasks should be
  exposed to debuggers. If you require special functionality, you can
  create a custom scheduler and enable it for specific tasks or queries.
Comment: Thank you very much

Parallel.For/Foreach threads reuse C#


How to edit partitions in my computer

Question:
The above picture,as you might have seen is a lot messed.Now,I would like to express my problem.
Now,what I wanna do is merge all those 3 unallocated spaces into a single drive and then merge it into the Windows drive.How can I do it? Any idea.
Comment: Why do you want these to be added to Windows? Do you want to go through a lot of steps to get just around 6MB? I would say add these unallocated spaces to partitions near them. Saves a lot of work!
Comment: Besides that: You can not. The 1.44 is there to create a boundary between NTFS and ext4. On a disk size like that I would not bother.
Answer: It is fairly normal to have a few megabytes between partitions (some software do this purposefully, and as some have said, are necessary to have). To remove these few megabytes you will need to move the partitions above the unallocated space down. This will group the unallocated space so that you can combine the space left over into another partition.
For a few megabytes, this is simply not worth it. This would take quite a while (many hours), can put quite alot of wear on the disk, and has the potentiality of data loss, or corruption.
Comment: It's worth adding that the GUI representation of that free space is deceptive, since it exaggerates the amount of free space involved. There's a total of 5.4 MiB of unallocated space in the partition table. The Windows partition (`/dev/sda3`) is 39.07 GiB -- note GiB vs. MiB.  In other words, even if you could add all that space to `/dev/sda3`, you'd increase its size by just 0.0135%. Another way of looking at it: An Ubuntu 14.04 Desktop `.iso` file is 964MiB, so you'd need over 178 times as much space as you'd gain to store an Ubuntu `.iso` file.
Answer: Partitions need to be aligned on particular boundaries. Although disk data is referred to in 512 byte sectors, modern drives work on much bigger sectors internally. So having a partition boundary that is not aligned to the disk physical page size can have a very serious performance hit.
This is especially relevant for SSD drives. These have page sizes of 4096 bytes or 8192 bytes.
The gParted software will try and make sure that partitions are aligned so will leave small portions of the disk unused to achieve this.
There is a good discussion of Partition Alignment here.

How to edit partitions in my computer


JsonDeserializer is not working with gson

Question: I have a list(list contains the requiredFields and this list can get the dynamic data from text file) and I have api response jsonData.
Now, I need to extract the data from api(jsonData) response, only the required fields(what list contained fields). All this need to be done using gson serializer
 public class EDSJsonSerializer implements JsonDeserializer {

    final list<String>;  //  list can be populated by reading data from text
 file

  //ex: list<Strin> is : [ab,bc]

     @Override
    public JsonElement deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

        jsonElement => {"ab":"234234","bc":"wrwerewe","ww":"345fsd","456":"dfgdfg"}

        final Map map = new HahMap();

        map should contain only 2 elements {"ab":"234234","bc":"wrwerewe"}
        map can be populated with list above given as keys and values from json passed

    }
}

final String json = "";  // json is the api response string
 final GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Map.class, new EDSJsonSerializer());

        final Gson gson = builder.create();

        final String map =  gson.toJson(json);

    it is not working as expected and not throwing any error/exception.

Please help me on this
Thanks,
Syamala.
Answer: Firstly 456 is not a valid Java class field name. It might be one reason of your problems even you might never use it from Json.
Secondly you migh better use ExclusionStrategy to decide which fields to de- & serialize.
In your case something like:
@RequiredArgsConstructor
public class ExcludeUnlistedFields implements ExclusionStrategy {
    @NonNull
    private Set<String> fieldsToInclude;
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        // if you need to restrict to specific a class/classes
        // add the checks here also
        return ! fieldsToInclude.contains(f.getName());
    }
    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
}

and use it like:
 Set<String> fieldsToInclude = new HashSet<>(Arrays.asList("ab", "bc"));
 ExclusionStrategy es = new ExcludeUnlistedFields(fieldsToInclude);
 Gson gson = new GsonBuilder().setPrettyPrinting()
                              .addDeserializationExclusionStrategy(es).create();


Garage Sensors Work Separately but Not Together?

Question: Genie Intellicode IS Series, it had a previous owner.
Sensors mounted in garage but not electrically connected (door closed by holding down button).
Attached the sensors to the opener. The indication lights were completely off, nothing... so decided to get new sensors and re-do the wiring.
Next, bought new Genie Safe-T-Beam Replacement Kit sensors and did new wiring.
For the wires, I took the same wire position from each sensor and twisted them together at the very end where connected to the openers electrical ports #3 and #4 (Figure 3-5 B in Genie manual link above).
When connected, one sensor will blink red - the other sensor completely off.
According to Lester's Trouble Shooting Guide (fyi word file):
If,

Sensor 1: Red LED light: 2 blinks, pause (repeat)
Sensor 2 Green LED Light: OFF
Wire to sensor missing or bad

However, if I connect only Sensor 2 to the openers ports (and not Sensor 1) the green light will come on.
So this tells me the wiring to that sensor is working.
Why would the sensors not work when connected in pair?
Any help is appreciated.
Answer: The blinking red light on the sender would indicate that they are mis-aligned. The best way to test this is to remove them from the mounting brackets and hold them a couple of inches apart with the sensors aligned. Have somebody hit the door closer, then point them away from each other.  If they work as expected that way, you'll just have to fiddle around with the mounts until you have them correctly aligned.


Hibernate Lazy Loading doesn't work with forEach() in java 11

Question: I don't know where one reports java bugs.  I can honestly say I've never seen one before.  BUT the lazy load of hibernate JPA and Java foreach doesn't work in Java 11.0.2.  I do not see it listed as fixed in 11.0.3 but didn't test.
It does work in Java 8.  So I suppose buyer beware!
Frameworks:
Spring Boot 2.1.1 (Spring 5.1.3)
Hibernate 5.3.7.Final
BEGIN EDIT
Partial Parent Model:
@Entity
@Table(name = "REST_ENDPOINT")
public class RestEndpoint extends AuditModel {
    private String  endpointName;
    private String  httpVerb;
    private String  httpTemplate;
    private String  serviceName;
    ...
    @OneToMany(mappedBy = "restEndpoint", cascade = CascadeType.ALL, orphanRemoval = true)
public List<RestEndpointParam> params = new ArrayList<>();

public void addRestEndpointParam(RestEndpointParam param) {
    params.add(param);
    param.setRestEndpoint(this);
}

public void removeRestEndpointParam(RestEndpointParam param) {
    params.remove(param);
    param.setRestEndpoint(null);
}

public void setParams(List<RestEndpointParam> params) { this.params = params; }

public List<RestEndpointParam> paramsList() {
    return params;
}

END EDIT
The Child table:
@Entity
@Table(name = "REST_ENDPOINT_PARAM")
public class RestEndpointParam {
...
private Long endpointId;
private RestEndpoint restEndpoint;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ENDPOINT_ID", insertable = false, updatable = false)
public RestEndpoint getRestEndpoint() { return restEndpoint; }

Now for the scary part.  With 2 items in the child table, The first foreach does not even print the log statement.
    // First set up the URI replacement variables
    restEndpoint.paramsList().forEach(restEndpointParam -> {
        logger.warn("ENDPOINT 1st forEach access PARAM:{}", restEndpointParam.getType());
        if (restEndpointParam.getType().equals("URI")) {
            uriParams.put(restEndpointParam.getKey(), restEndpointParam.getValue());
    }});

// Now apply the Query parameters
    restEndpoint.paramsList().forEach(restEndpointParam -> {
        logger.warn("ENDPOINT 2nd foreach access PARAM:{}", restEndpointParam.getType());
        if (restEndpointParam.getType().equals("QUERY")) {
            builder.queryParam(restEndpointParam.getKey(), restEndpointParam.getValue());
    }});

The second forEach works as expected.  So it is the first reference that fails.  Also replacing the first access (forEach) with a conventional loop:
for (RestEndpointParam restEndpointParam : restEndpoint.paramsList())

The results are as expected.  So obviously there is an loading problem between hibernate and Java 11.
Comment: If the second `restEndpoint.paramsList().forEach` works but the first one does not, the logical assumption is that the problem lies in the first `forEach`. But it's hard to tell without a stacktrace and explanation of what "doesn't work' means...
Comment: Have you tried to set a break point in the forEach method of Iterable?
Comment: I did set breakpoints.  Actually that is why I added the log statement.  In the first case the lamba is not executed at all.  In IntelliJ I can see parmlist has 2 entries.  But my only explanation is that it evaluates as size()==0 - or more probably null.  Otherwise forEach should execute.
Comment: Please post the code or `paramsList()`. I'm guessing you are accessing `params` in there, which would explain why it is broken, because you are actually side stepping JPAs Lazy Loading.
Comment: @Jens Schauder I added the entire section showing how I map the child table.  I will admit I had some problems with this so it may not be "the right way".  But it does work in Java 8. The down side of "the internet remembers everything" is that stuff that hasn't worked in 7 years are the first 10 pages of google hits.  So  good; working; modern; code is very hard to find for stuff like this.
Answer: I have no idea why this works with Java 8 or why the second foreach works.
But paramsList() is accessing the field params directly. Hibernate attaches lazy loading to getters but since there are no getters this doesn't work.
If your rename paramsList() to getParams() Hibernate should detect it as the getter and perform propper lazy loading.
Comment: TBH I don't see how JPA lazy loading is being side-stepped here. Hibernate initializes lazily-fetched lists with `PersistentList`s and the `PersistentList` itself is responsible for loading the data on first access. You only need to go through the getter for the inverse, optional side of a `@OneToOne`, not for multi-valued associations
Comment: It sounds like the solution I figured out for my other question is what is causing this.  But with my structure I cannot just change parmsList to getParams because then I get the error that Hibernate SessionFactory cannot determine the type for the List.  If you would be so kind as to review my previous issue it will probably be  illuminating (as well as humorous)  https://stackoverflow.com/questions/55048028/spring-jpa-manytoone-doesnt-instantiate-children


How to solve Uncaught SyntaxError: Unexpected token '<' using Vue JS / Laravel

Question: Hi developers i currently have issue this project is old work of developer, this is already perfectly working on our server and there is no error. however after i pull it on our server and run the project on my localhost it gives Uncaught SyntaxError: Unexpected token '<' after i run watch watch. there is no error on my run watch and php artisan serve.
Question: Why does my app.js file has an error of that.?
I currently use Laravel as backend and Vue Js as front end

app.blade.php
<!doctype html>
getLocale() }}">

        <meta charset="utf-8">
        <link rel="icon" type="text/css" href="{{asset('../public/img/tempologo.png')}}">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Mywebsite</title>
        <title>
            @yield('title')
        </title>

        <link rel="stylesheet" type="text/css" href="{{asset('css/app.css')}}">
        <link rel="stylesheet" type="text/css" href="{{asset('css/materialicon.css')}}">
        {{-- <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> --}}

Comment: what do you mean?
Comment: app.js is a unique generated of laravel.
Comment: when i click the app.js error it redirect me on app.blade.php file
Comment: please see the new update question.
Comment: Why your the codes in app.js?
Comment: @xNoJustice can you explain more
Comment: why does you app.js contains html codes in the first place a js file is to write javascript code
Answer: Your html has a script tag pointing to /public/js/app.js. This should probably be /js/app.js.


How to call a filter hook in a PHP external file

Question: I'm trying to call a filter hook in a standalone PHP file in Wordpress.
This is the code of the file: my_external_file.php:
<?php
require( dirname(__FILE__) . '/../../../../../../../wp-load.php');

add_filter('init', 'test_function');

function test_function (){
    global $global_text_to_shown;

    $global_text_to_shown = 'Hello World';

}

global $global_text_to_shown;

$quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,spell,close' );

//This work fine, shown editor good.
wp_editor( $global_text_to_show, 'content', array( 'media_buttons' => false, 'tinymce' => true, 'quicktags' => $quicktags_settings ) );

//Load js and work fine the editor - wp_editor function.
wp_footer();

?>

The issue is that the filter isn't get executed hence the function doesn't get executed.
How can I execute the filter hook on this external PHP file?
Answer: First and main problem $global_text_to_show is not $global_text_to_shown.
The hook init is not a filter, it's an action: add_action('init', 'test_function');. See Actions and Filters are not the same thing.
Loading wp-load.php this way is... crappy code ;) See Wordpress header external php file - change title?.
The second main problem is why and what for do you you need this?
Anyway, init will not work, using the filter the_editor_content will. Although I don't understand the goal:
<?php
define( 'WP_USE_THEMES', false );
require( $_SERVER['DOCUMENT_ROOT'] .'/wp-load.php' );

// Requires PHP 5.3. Create a normal function to use in PHP 5.2.
add_filter( 'the_editor_content', function(){
    return 'Hello World';
});

$quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,spell,close' );

?><!DOCTYPE html>

<?php wp_head(); ?>

<?php
    wp_editor(
        '',
        'content',
        array(
            'media_buttons' => false,
            'tinymce' => true,
            'quicktags' => $quicktags_settings
        )
    );
    wp_footer();
?>


Create a random CLLocationCoordinate in a certain area

Question: I've got an MKMapRect.
How do I create a random CLLocationCoordinate inside there?
I know there is arc4random(), but how can I use it for GPS Coordinates?
Comment: what is that MKMapRect value you are using?
Please tell me i also have the same problem how you solved this
Answer: #define ARC4RANDOM_MAX      0x100000000
...

//val is a double between 0 and 1
double xOffset = ((double)arc4random() / ARC4RANDOM_MAX);
double yOffset = ((double)arc4random() / ARC4RANDOM_MAX);
MKMapPoint randomPoint;

randomPoint.x = maprect.origin.x + xOffset*maprect.size.width;
randomPoint.y = maprect.origin.y + yOffset*maprect.size.height;

CLLocationCoordinate2D randomCoordinate = MKCoordinateForMapPoint(randomPoint);

Comment: As written, this will only generate points along a diagonal line in the map rect, since you're using the same random value for each axis. (i.e. you want to use a different `val` to make randomPoint.y)
Comment: Thanks, this is working nicely. Can you explain what `0x100000000` does?
Comment: This is just the max value arc4random can generate (in hex format). If you divide the result generated by arc4random by this value, you get a floating point number between 0 and 1
Comment: @JesseRusak Thanks for pointing it out. I have corrected the answer.
Answer: From the MapRect, you could got MKMapPoint origin and MKMapSize size, then the random CLLocationCoordinate should be {origin.x + [0 ~ size.width], origin.y + [0 ~ size.height]}
typedef struct {
       MKMapPoint origin;
       MKMapSize size;
    } MKMapRect;

the code like this:
#define ARC4RANDOM_MAX      0x100000000
- (double)createRandomsizeValueFloat:(double)fromFloat toFloat:(double)toFloat
{
    if (toFloat < fromFloat) {
        return toFloat;
    } else if (toFloat == fromFloat) {
        return fromFloat;
    }
    return ((double)arc4random() / ARC4RANDOM_MAX) * (toFloat - fromFloat) + fromFloat;
}

//CLLocationDegrees lat = mapRect.origin.x + [self createRandomsizeValueFloat:0 toFloat:mapRect.size.width];
//CLLocationDegrees lng = mapRect.origin.y + [self createRandomsizeValueFloat:0 toFloat:mapRect.size.height];

Answer: Just set the latitude and longitude properties of your CLLocationCoordinate instance.
Take care about ranges : -90 < latitude < 90, -180 < longitude < 180.
Hope this helps.
Comment: This doesn't really help. He/She is looking to keep that location within a certain area.


How to display R Shiny output in R Markdown?

Question: I'm new to R markdown here and I am trying to create an R Shiny app which I can enter a list of names, and then download the output (like a name list) as HTML file. I am using R markdown to create the HTML file. Here are my sample codes:
R Shiny:
library(shiny)

ui <- list(
  textInput("name", "Type new text input name", value = ""),
  actionButton("btn", "click me to create text input"),
  uiOutput("newInputs"),
  downloadButton("download_report", "Download")
)

server <- function(input, output)
{
  family_member <- reactiveValues(
    add_family_info = list()
  )

  observeEvent(input$btn, {

    newid <- paste(length(family_member$add_family_info))

    family_member$add_family_info <- c(family_member$add_family_info, list(c(newid, input$name)))

    family_member

  })

  output$newInputs <- renderUI({
    lapply(family_member$add_family_info, function(a)
      c(paste(a[2])))

  })

  output$download_report <- downloadHandler(
    filename = "name.html",
    content = function(file) {
      tempReport <- file.path(tempdir(), "name.Rmd")
      file.copy("name.Rmd", tempReport, overwrite = TRUE)

      params <- list(report = uiOutput("newInputs"))

      rmarkdown::render(tempReport, output_file = file,
                        params = params,
                        envir = new.env(parent = globalenv()))
    }
  )

}

runApp(list(ui = ui, server = server))

R Markdown:
---
runtime: shiny
output: html_document
params:
  report: NA

---
\
\

# Member names

`r params$report`

Appreciate any help! Thanks in advance!!!!
Answer: If you are just using a Shiny to render an Rmarkdown document, you don't need the runtime of the document to be Shiny. This is only needed if the document itself will ultimately be a shiny app.
Looking at the download handler
params <- list(report = uiOutput("newInputs"))

The uiOutput function generates the html for the element. It doesn't retrieve the values (you can see this if you run execute it in the console by itself). Additionally newInputs just refers to the container for the text (it's not actually inputs). Instead, you would want to use the reactive value storing the list
params <- list(report = family_member$add_family_info)

However, since this will be printed it can't be an arbitrary R object. It has to be something that cat can handle. In this case family_member$add_family_info is a list of list. Try flattening it with something like
params <- list(report = unlist(family_member$add_family_info))

Comment: Thanks for your reply! However, I am still not able to download the HTML file with the correct output :( Currently it displays the title "Member Names", without the list of name inputs in the Shiny app. Any ideas on how to fix this?
Comment: Edited my answer with some additional thoughts
Comment: I think there is a typo in your code, I assume you were to type params <- list(report=family_member$add_family_info)? The code still doesn't work though :(
Comment: Corrected the typo. What do you mean by not working? Is it generating a blank html document or is there any sort of error message?
Comment: The download button doesn't work, the report cannot be generated. There's a message in the console:
processing file: name.Rmd
  |................................................................................................................................................................................| 100%
   inline R code fragments

Quitting from lines 2-12 (name.Rmd)

Warning: Error in vapply: values must be length 1,
 but FUN(X[[1]]) result is length 2
  [No stack trace available]
Comment: I think, especially given the format of your Rmd, you can only pass in R objects capable of being used by cat. Updated answer.
Comment: It works! Thanks! However with this code, for example if I input 2 names, e.g. John, Mary, the output would be " 0, John, 1, Mary".. I think the "0" and "1", comes from the 'newid' in the observeEvent.. any ways to remove this?
Comment: My bad, i could just remove the "newid" in the list! Thanks a lot for your help!


a compact uniform space which is not metrizable

Question: Let $(X, \mathcal{U})$ be  a compact uniform space which is not metrizable and and $\{U_i\}_{i=0}^{\infty}$ be a countable set of $U_i\in \mathcal{U}$ with $U_{i-1}\subseteq U_i$ and $U_1\subseteq V$ that $V\in \mathcal{U}$ and $V\circ V\circ V\subseteq U$ for $U\in \mathcal U$. In Proof of  Theorem 1 in https://projecteuclid.org/download/pdf_1/euclid.pjm/1103038056, author claimed that since $\{U_i\}_{i=1}^{\infty}$  is not a base for the uniformity $\mathcal{U}$, there is $W\in \mathcal{U}$ with $W\subseteq U$ such that for every $i>0$, $U_i\cap comp W\neq \emptyset$,
Q.   Proof of $U_i\cap comp W\neq \emptyset$ is not clear for me, ( The notation $camp W$ is not define in this paper and it is not clear for me)
can someone help me please
Thanks
Answer: $\operatorname{comp}W$ is just the complement of $W$ in $X$, which I'll denote by $W^c$ instead.
Recall that $\{U_i\}_{i=1}^\infty$ being a base (for entourages inside $U$) means:
$$\forall W \in \mathcal{U}( W \subset U) \implies (\exists i: U_i \subseteq W)\text{.}$$
So not being a base means, applying standard logic:
$$\exists W \in \mathcal{U}: (W \subset U)\land (\forall i: U_i \nsubseteq W)$$
and the last negation of inclusion can be written as $U_i \cap W^c \neq \emptyset$ (not all members of $U_i$ are in $W$, so some of them are in $W^c$...). So indeed:
$$\exists W \in \mathcal{U}: (W \subset U)\land (\forall i: U_i \cap W^c \neq \emptyset)$$
So the negation of being a base inside $U$ gives us the promised $W$.
(If the $(U_i)$ would be a base for entourages inside $U$, then for any $V \in \mathcal{U}$, $V \cap U \in \mathcal{U}$ would contain some $U_i$ so $V$ would contain a $U_i$ as well, and $\mathcal{U}$ would have a countable base and thus be metrisable, which it is not. So the negation holds.)


How to track Java parent thread id using aspectj?

Question: I am trying to track to obtain the parent thread id of each new thread created in a program using AspectJ. Since a new thread starts execution using the start() method, I thought the following technique should work:
aspect getParentThread {
    pointcut threadStarting(): call(public void start());
    Object around(): threadStarting() {
         long parentThread = Thread.currentThread().getId();
         Object ret = proceed();
         long newThread = Thread.currentThread().getId();
         if (parentThread != newThread) {
              /*Store parentThread id in data structure */
         }
         return ret;
     }
}

But this simply does not work. Although the advice executes, even after proceed() completes there is just a single thread id. So what am I getting wrong here?
Answer: Warren Dew is right, but I want to add some sample code in order to show how you can easily do it with AspectJ. You do not even need an around() advice, a simple before() is enough.
Driver application:
package de.scrum_master.app;

public class Application {
    public static void main(String[] args) {
        new Thread(
            new Runnable() {
                @Override
                public void run() {}
            },
            "first thread"
        ).start();
        new Thread(
            new Runnable() {
                @Override
                public void run() {}
            },
            "second thread"
        ).start();
    }
}

Aspect:
package de.scrum_master.aspect;

public aspect ThreadStartInterceptor {
    before(Thread childThread) :
        call(public void Thread+.start()) &&
        target(childThread)
    {
        System.out.printf(
            "%s%n  Parent thread: %3d -> %s%n  Child thread:  %3d -> %s%n",
            thisJoinPoint,
            Thread.currentThread().getId(),
            Thread.currentThread().getName(),
            childThread.getId(),
            childThread.getName()
        );
    }
}

As you can see, I am limiting method interception to Thread+, i.e. to Thread and subclass instances. I am doing this explicitly even though it is not strictly necessary because the next point already does it implicitly:
I am also binding the child thread to a variable which can be used neatly from within the aspect.

Console log:
call(void java.lang.Thread.start())
  Parent thread:   1 -> main
  Child thread:   11 -> first thread
call(void java.lang.Thread.start())
  Parent thread:   1 -> main
  Child thread:   12 -> second thread

Answer: The issue is that all of your code executes in the parent thread, including the code after the child thread starts, because the start() method is called from and executes in the parent thread.
You could try getting the ID of the new thread from the Thread object on which the start() method is called.
Comment: Thanks a lot! You are right -- it is easily possible to get it from the Thread object (instead of using current thread).


Power equipment for removing compacted gravel?

Question: I have a gravel driveway in my front yard that I want to remove to put a garden bed. The gravel is large (1/2" to 1" dia.) and very compacted, so it is nearly impossible to remove by hand.
I want to rent some small power equipment to do the task, but I'm not sure if a skid loader, excavator, or something else is the right tool for the job. Opinions?
Comment: This is exactly what bulldozers have [ripper](https://en.wikipedia.org/wiki/Bulldozer#Ripper)s for. Perhaps there's a small, walk-behind earth mover with such a tool?
Comment: A tractor with a box scraper that has rippers would be the way I would do it. As you rip the box drags the rock to where you want it.
Answer: Nope, you don't want to remove a stitch of it. What you want to do is take advantage of what you've got & capitalize on the perfect setup for a perfect garden. A Raised Bed Garden on top is what this has been patiently waiting for. The gravel is key to keeping pests at bay & to relieve overwatering. This is why garden centers & nurseries have gravel all over & under...no yucky mud.
SEEEEE

OOOOh

AAAAAh
Comment: Singularly unhelpful. My front yard doesn't look like a multi-million dollar xeriscaping job in Marin County. It looks like a slum lord dumped a truckload of ugly crushed gravel  so that 4+ people could park in my front yard. Cause that's what happened. Also my front yard is full shade.
Comment: So, you don't like raised beds & a raised bed won't work, but an in-ground garden will? I'm a bit confused. Do you want all of the gravel gone or just the area of the garden? I will happily update my answer.


Powershell string.split

Question: $version = Get-EventLog
               -Newest 1
               -ComputerName $systemnummer 'Symantec Endpoint Protection Client'
               -Message "*Version*" | Select message
[string]$version = $version
$version = $version.Split(":")

After getting the Eventlog Entry $version contains the following string:
"@{Message=New virus definition file loaded. Version: 150317001.}"
How can i split the String to get only the number "150317001"?
Answer: The problem is that your message string is still a property (Message) of the object, so you need to reference it by that property name:
$version = Get-EventLog
               -Newest 1
               -ComputerName $systemnummer 'Symantec Endpoint Protection Client'
               -Message "*Version*" | Select message
$version = $version.Message.Split(":")[1]

Or use Select -ExpandProperty to get just the value:
$version = Get-EventLog
               -Newest 1
               -ComputerName $systemnummer 'Symantec Endpoint Protection Client'
               -Message "*Version*" | Select -ExpandProperty message
$version = $version.Split(":")[1]

Answer: This should work:
$version = Get-EventLog -Newest 1 -ComputerName $systemnummer 'Symantec Endpoint Protection Client' -Message "*Version*" | Select message
$ver = $version.message -replace ".*(\d+).*", "`$1"

Comment: i tried, but im sorry... your $ver seems to be empty
Comment: Don't cast to `[string]` before doing the code I added, just leave `$version` as it is when returned from `Get-Eventlog`
Comment: Consider using  `Select -expand message` to just get the string back. Remove one hurdle.
Answer: Just use regex for this. Here code for your example:
$content = '@{Message=New virus definition file loaded. Version: 150317001.}';
$regex = 'version\s*:\s*(\d+)';
$resultingMatches = [Regex]::Matches($content, $regex, "IgnoreCase")
$version = $resultingMatches[0].Groups[1].Value

Powershell string.split


Open a link to new tab inside a ifame of iframe

Question: I have a iframe-1 and it contains another iframe-1-1.[1]
Inside iframe-1-1 which contains a link.
When a user click the link:

It should open a new tab (For instance, Firebug/or Chrome).[2]

But it does not work. How can I do that?

[1] Why I have this question: because I code a webpage, it is embedded in Facebook, and I call FB.dialog it will show me a dialog is a iframe too.
[2] It works properly if I use wheel button to click.
Answer: You can't instruct a browser to open a new tab. The best you can do is to use target="_blank" and hope that the user is using a browser that will open a tab and not a new window.
Comment: Why not? You are out of luck then, unless you can use JavaScript to add it to your links ...
Comment: You can not add the script code into a iframe which does not belong to you. (iframe is generated by FB API)


how to disable the alter panel caused by NSAlert automatic?

Question: I find a interest thing: when I used a Browse button to choose a file , if the file have exist
, the NSAlert will cause a alter panel automatic, but I want to make this by my self , how to disable the NSAlert's alter panel automatic? Thanks a lot!
Answer: You need to implement the -panel:userEnteredFilename:confirmed: delegate method. Returning nil will suppress the standard panel. However, I warn you that you better have a good reason for overriding it otherwise there will be plenty of puzzled/irritated users!


Automatically initialize replica set for mongoDB in docker fails

Question: I have a NodeJS Express App that depends on MongoDB change streams. For them to be available, MongoDB has to be configured to run as a replica set (even if there is only one node in that set).
I'm working on Windows 10 pro.
I'm trying to dockerize this App, basing the MongoDB container off the official mongo:5 image.
For this to work, I want an automated way of initializing the DB as a replica set. Tutorials I've found rely on either execing into the container and running rs.initiate() from mongosh (or similar approaches), which is manual work I want to avoid. Or they use hacks like wait-for-it.sh as here.
I feel there must be a better solution, based somehow on the paragraph "Initializing a fresh instance", from the docs.
It describes that

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d.

When exactly in the container lifecycle does that happen? After the container is initialized? Or after the DB is ready? Because this seems to be the perfect place for this initialization logic, which runs flawlessly when executed manually, from within the container.
However, placing
// initReplSet.js
print('Script running');
config={"_id":"rs0", "members":[{"_id":0,"host":"app-db:27017"}]};
print(JSON.stringify(rs.initiate(config)));
print('Script end');

fails with the error {"ok":0,"errmsg":"No host described in new configuration with {version: 1, term: 0} for replica set rs0 maps to this node","code":93,"codeName":"InvalidReplicaSetConfig"}, yet the database is available under the hostname app-db from other containers. This makes me feel that this code runs too early, before all other initialization logic (networking) is done.
Another approach is to place a bash script that executes code via mongosh. Here's what I've tried:
#!/bin/bash
mongosh "mongodb://app-db:27017/app_db" "initiateReplSet"

where initiateReplSet is
config={"_id":"rs0", "members":[{"_id":0,"host":"app-db:27017"}]}
rs.initiate(config)
exit

but this crashes the container with the error
/usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/initiateReplSetWrapper.sh

{"t":{"$date":"2022-02-15T11:31:23.353+00:00"},"s":"I",  "c":"-",        "id":4939300, "ctx":"monitoring-keys-for-HMAC","msg":"Failed to refresh key cache","attr":{"error":"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.","nextWakeupMillis":600}}

Warning: Could not access file: EACCES: permission denied, mkdir '/home/mongodb'

Current Mongosh Log ID: 620b8f0b04b7ad69b446768d

Connecting to: mongodb://app-db:27017/app_db?directConnection=true&appName=mongosh+1.1.9

Only the first and the last three lines seem to really belong to the bash script, the second line is repeated constantly.
I'm not sure whether the error originates at the permission denied issue, or whether the DB really can't be accessed. However, specifying
RUN mkdir -p /home/mongodb/.mongodb
RUN chown -R 777 /home/mongodb

in the Dockerfile did not improve the situation (same error nevertheless).
Could you please explain either why this approach can not work, or how to make it work? Is there another, better, automated way to initialize the replica set? Could the docker image be improved to allow such initialization logic?
Comment: After `rs.initiate` put this line `while (! db.isMaster().ismaster ) { sleep(1000) }` before you exit the script.
Comment: @WernfriedDomscheit I have tried it, but it does not work. The script never completes. I have also checked out your git repo [mongoDB-oneclick](https://github.com/Wernfried/mongoDB-oneclick). I found the line you mentioned there, but this does not appear to run in a docker context, does it?
Comment: My git repro is developed for plain Windows. But the config and `.js` files are independent from technology. What is your config file? Did you specify in configuration file `replication.replSetName: rs0` or start mongod with `--replSet rs0` option?
Answer: I just made it work with a wild experiment. Means I simply left out the config in my call to rs.initiate(), from the JS script. For some reason, the script then runs successfully and change streams become available to my NodeJS backend.
I will post everything that's needed to run a MongoDB docker with change streams enabled:
# Dockerfile
From mongo
WORKDIR .
COPY initiateReplSet.js ./docker-entrypoint-initdb.d/
CMD ["-replSet", "rs0"]

// initiateReplSet.js
rs.initiate()


League of legends to hide HUD and show mini-map only?

Question: I want to hide all HUD boards and display only the mini map.
Searching around in the in-game Hotkeys menu though found nothing related.
So how can we do that?
Answer: As far as I know you cannot hide the HUD while still showing the minimap.
You can hide the HUD (including the minimap) in the Hotkeys menu. Expand the Display section and set a hotkey for Show/Hide HUD. Then while in game you can simply push whatever you set and the HUD will disappear.
Since it hides the minimap you will probably want to have it active most of the time but perhaps hide it when a teamfight is happening/about to happen.
Comment: Thanks for clarifying my question - that's exactly why I asked here.


springboot restcontroller redirect to Angular App URL

Question: I have a scenario where Springboot App receives a restful GET request [from IBM ISAM] with JWT token in the Header. Upon receiving this request, Springboot must redirect it to an Angular App and pass the JWT [either in Header or Query String].
I am trying out this in the Springboot but redirect doesn't happen in the browser.
<code>@RestController
@RequestMapping(value="/token")
public class RedirectController {

    @CrossOrigin
    @RequestMapping(value = "/redirect", method = RequestMethod.GET, produces = "application/json")
    public  ResponseEntity<Object> redirectToAngularApp(@RequestHeader HttpHeaders headerItems) {

        System.out.println("Inside redirect....");

        System.out.println("Header Content::"+headerItems.toString());
        String jwttoken = "";

        if (headerItems != null) {

            String tokenString = headerItems.getValuesAsList("authorization").get(0);

            System.out.println("TOKEN STRING::"+tokenString);
            // && headerItems.startsWith("Bearer ")
            jwttoken = tokenString.substring(7);

            System.out.println("JWT TOKEN::"+jwttoken);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setAccessControlAllowOrigin("*");
        headers.set("Access-Control-Allow-Methods","GET,OPTIONS,HEAD");
        headers.set("Access-Control-Allow-Headers", "Authorization");
        headers.set("Access-Control-Max-Age","86400");
        headers.setLocation(URI.create("http://localhost:4200/#/dpsportal?token="+jwttoken));
        return new ResponseEntity<>(headers, HttpStatus.FOUND);

    }

}
</code>
I get this error in the browser console.
<code>Failed to load http://localhost:4200/#/: Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
jwt.interceptor.ts:111 ERROR::{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}
login.component.ts:68 TypeError: Observable_1.Observable.throw is not a function
    at CatchSubscriber.eval [as selector] (jwt.interceptor.ts:133)
    at CatchSubscriber.error (catchError.js:105)
    at XMLHttpRequest.onError (http.js:2302)
</code>
Please help resolve this issue.
Answer: Try:
<code>@RestController
public class FooController {

  @RequestMapping("/foo")
  void handleFoo(HttpServletResponse response) throws IOException {
    response.sendRedirect("some-url");
  }

}
</code>


PyWebIO button to refresh the page

Question: so I am making a small app, which searches the web via keyword in PyWebIO input() function and then shows results in put_table() and after the results are ready I need to start another search and instead of updating the page with F5 or browser, I want to create a put_button() which will update or get me back to input(), can anyone help, please?
Im just not sure what should I put in onlick= attribute in this case.
Answer: from pywebio.session import run_js

put_button("ReUpload_images",onclick=lambda: run_js('window.location.reload()'))

Answer: First, I'd like to quote from the pywebio documentation:

When you encounter a design problem when using PyWebIO, you can ask yourself a question: What would I do if it is in a terminal program?

The solution in terminal program is to put the input() and put_table() into a while loop. So, in pywebio, you can do the same thing:
from pywebio.input import *
from pywebio.output import *

while True:
    keyword = input()
    # make some query
    put_table(...)

The table will be appended to the page rather than be updated with this code. So do in terminal program. You can call pywebio.output.clear() after the input() to clear the page or use scope feature.
from pywebio.input import *
from pywebio.output import *

while True:
    keyword = input()
    # make some query
    with use_scope('result', clear=True):
        put_table(...)

When you use while True in server mode, you don't need to worry about the session will be running forever, because when you close the broswer tab, the pywebio will raise exception in your session to exit it.
In script mode, if you want to provide a way to exit the loop, you can:
from pywebio.input import *
from pywebio.output import *

while True:
    keyword = input()
    # make some query
    with use_scope('result', clear=True):
        put_table(...)
    if actions("Continue?",["continue", "exit"])=="exit":
        break

Answer: You can add a button at the end and use run_js('window.location.reload()') to refresh the page. Check the demo on pyweb.io, and its source code
Comment: This answers works for me. I just put `run_js('window.location.reload()')` at the end of my callback to refresh the current page.
Comment: Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.

PyWebIO button to refresh the page


Why $y=f(2x-6)$ is a 3 unit rightward shift of $y=f(2x)$

Question: $2.2.4$:
Suppose that $f(4)=8$. Note that the point $(2,8)$ is on the graph of $y=f(2x)$ and that the point $(5,8)$ is on the graph of $y=f(2x-6)$. So, the point we have found on the graph of $y=f(2x-6)$ is $3$ units to the right of the point we found on the graph of $y=f(2x)$. Which of the following is true:

We made a mistake
It's a coincidence
The graph of $y=f(2x-6)$ is a $3$ unit rightward shift of $y=f(2x)$

Explain your answer.

I know that $3$ is correct, but I just don't know how to prove it. I believe that it has something to do with this concept called a horizontal shift, where we have the form $y=f(\frac 1a(x+b))$, but we haven't learned about horizontal shifts yet.
Comment: I suggest you take a few examples, like $f(x)=x$, $f(x)=x^2$ etc. and convince yourself of $3$ first. Once you're done with this, you can see how  these transformations behave by seeing the examples themselves.The proof is rather elementary once you have understood the transformation, but that is why I suggest you take these examples.
Comment: Suppose that $f$ is invertable. Solve for $x$. $f^{-1}(y) = f^{-1}(f(2x-6))$
Answer: Indeed, it is $f[2(x-3)]$, Let's call this function $g$.
Notice how $g(3)=f(2\times 0)=f[2\times (3-3)],\\ g(4)=f(2\times 1)=f[2\times(4-3)],\\ g(5)=f(2\times 2)=f[2\times(5-3)],$
and so on...
That is, for every $t$ we will plug into $g$, we get the same value we get by plugging $t-3$ into $f(2x)$ (easy to prove for all $t$). It therefore means that the whole graph is shifted 3 units right.
I would play a bit more with function graphers to get the drift if you still didn't get the idea. I doubt there's a better way to explain it but I might be wrong.


What defines formation compatibility in FIFA '13 Ultimate Team?

Question: In Fifa 13's Ultimate Team mode, every player (card) has a preferred formation. Every squad is playing in some formation (obviously). When a player card is placed in a squad, the formation compatibility is evaluated. It may receive one of three ratings.
 - Full formation compatibility, provides bonus to Chemistry. This is only awarded if formations of squad and a given player are exactly the same.
 - Formations are somewhat compatible, seems to be neutral to Chemistry.
 - Formations are too different, gives a Chemistry penalty.
Now, the rules that decide whether a formation of a player is at least somewhat compatible with the squad's elude me. What are they?
Answer: The formation needs to be a variation on the preferred formation.
For example, a player who is suited to a 4-4-2 may work well in a 4-4-1-1 as it is a variation, but not well in a 3-4-3.
Comment: True, I managed to observe that much. The troubling concept is what  constitutes a variation worthy of the middle rating. Some ideas that didn't pan out in practice were "same family" (3-, 4-, 5- prefixes) or "same amount of players in the player's tier (defense, middle or attack)". This question looks to clarify what exactly decides between the two latter ratings.
Comment: What exactly decides will be different for each formation, it wont be a universal rule. The prefix you describe is just the number of defenders, so it is no surprise it is not linked to that.


What was the first application to use colon as an emoji picker?

Question: I'm aware of modern colon notation being used in web forums in days gone by — I have fond memories of using :rolleyes: in vBulletin! Indeed I assume (though I'm happy to be corrected!) that this usage directly inspired the thing I'm about to talk about. But I'm curious as to what the first application to use this colon notation for emoji substitution. For instance, on many sites I can type :hammer: and get an interactive picker to replace it with a  character. Though I'd also be interested in seeing early non-interactive examples that work with emoji, as opposed to emoticons, if any exist.
I'm aware that Slack and Discord both support this, so perhaps one of these is a likely source? But I'm wondering if perhaps a more popular social media site might have provided the impetus, as Slack and Discord both seem relatively niche for such a common feature.
I've tried searching around for the answer but I can only find people claiming that this functionality exists, libraries to implement this functionality, or unrelated things. Perhaps my Google Fu is simply not up to snuff.
(Apologies, I'm not sure if "history of UX patterns" is in scope for this site. If it isn't, I'd appreciate a suggestion of a better place to ask this question.)
Answer: Here's an article answering your question: Github did it first.
And a Github post from 2012 announcing the feature
Answer: I think it was just a logical evolution of the colon being used to make smiley faces, being the most constant part of the different faces. So from :) and :( and :-* we went to :hammer:.


Data.Table Merge - Result is larger than input Datatables

Question: I have two data tables. df1, ref_df
Internal Structures are as follows:
Classes 'data.table' and 'data.frame':  10153986 obs. of  18 variables:
 $ chr_no        : chr  "1" "1" "1" "1" ...
 $ pos           : int  238 324 340 353 355 357 380 420 435 571 ...
 $ ref           : chr  "C" "A" "G" "T" ...
 $ id            : logi  NA NA NA NA NA NA ...
 $ alt           : chr  NA NA NA NA ...
 $ af            : num  NA NA NA NA 0.807 NA NA 0.877 NA 0.868 ...
 $ cases_hom     : int  NA NA NA NA 50 NA NA 58 NA 59 ...
 $ cases_het     : int  NA NA NA NA 15 NA NA 7 NA 6 ...
 $ cases_count   : int  NA NA NA NA 115 NA NA 123 NA 124 ...
 $ controls_hom  : int  NA NA NA NA 48 NA NA 55 NA 56 ...
 $ controls_het  : int  NA NA NA NA 13 NA NA 6 NA 5 ...
 $ controls_count: int  NA NA NA NA 109 NA NA 116 NA 117 ...
 $ cc_trend      : num  NA NA NA NA 0.812 ...
 $ cc_geno       : num  NA NA NA NA NA NA NA NA NA NA ...
 $ cc_all        : num  NA NA NA NA 0.492 ...
 $ cc_dom        : num  NA NA NA NA 0.491 ...
 $ cc_rec        : num  NA NA NA NA 1 NA NA 1 NA 1 ...
 $ cmh_p_val     : num  0.9267 0.0672 0.0279 0.3939 0.2522 ...
 - attr(*, ".internal.selfref")=<externalptr>

Classes 'data.table' and 'data.frame':  9915916 obs. of  5 variables:
 $ chr_no  : chr  "10" "10" "10" "10" ...
 $ pos     : int  86 126 148 208 232 396 413 413 454 1173 ...
 $ snp_name: chr  "rs459413697" "rs446265986" "rs460495236" "rs437891922" ...
 $ ref     : chr  "G" "G" "T" "G" ...
 $ alt     : chr  "C,T" "A,T" "C,G" "T" ...
 - attr(*, ".internal.selfref")=<externalptr

I perform a Left Outer Join all.x = TRUE as :
merge(x = df1, y = ref_df, all.x = T,
                     by = c("chr_no" , "pos" , "ref"), suffixes=c(".study", ".ref"))

The resulting data table is
> dim(result_data)
[1] 10154765       20
> sum(duplicated(df1))
[1] 0
> sum(duplicated(ref_df))
[1] 0

So I am not sure what is happening. I have looked into https://github.com/Rdatatable/data.table/issues/508
I am using the latest data.table 1.9.5.
Comment: So what would you expect as a result then?
Comment: check duplication for join columns, instead of all columns; and use regular `data.table` `[` operator for any join that's not a full outer join for max speed.
Answer: Try
>>sum(duplicated(df1[, c("chr_no", "pos", "ref")]))

This will give you the total number of duplicates based on the joining keys.
>>table(duplicated(df1[, c("chr_no", "pos", "ref")]))

This will give you the total number of duplicates and non-duplicates records based on the joining keys.
Similarly for the other dataframe,
>>table(duplicated(ref_df[, c("chr_no", "pos", "ref")]))

Comment: Thanks @Ala. Using your suggestion I was able to identify some fault in the data I was using and it did have duplicate rows. The problem was resolved. :)


ScriptResource.axd path is too long

Question: here is my problem.
I develop web applications, and I use IIS to host them.
I also used the module ARR (application request routing) as a proxy for my server farm. The problem is the ARR cache the pages on disk. I have ScriptResource  cached in the arr cache disk, and when I try to delete the access path is too long.
Is there a way to shorten the name of the script resources?
thank you
Answer: If you use ASP.NET 4.0 you can use CDN version of scripts and get additional benefits. Just set EnableCdn property of your script manager to true and your script links will look like this :
<code><script src="http://ajax.microsoft.com/ajax/4.0/1/WebForms.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/4.0/1/MicrosoftAjax.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/4.0/1/MicrosoftAjaxWebForms.js" type="text/javascript"></script>
</code>
Comment: unfortunatly AFAIK just partial, you can use some scripts from CDN but not all of them, look at http://www.hanselman.com/blog/ASPNETAjaxScriptCombiningAndMovingScriptResourceaxdsToStaticScripts.aspx

ScriptResource.axd path is too long


Django empty label in choice field - no queryset

Question: Setting the empty label for on a choice field is giving me some issues. I've looked at answers like this, but this is just talking about the form.
Suppose I have the following model:
class MyColorModel(models.Model):
    BLUE = 'blue'
    RED = 'red'
    GREEN = 'green'
    COLOR_CHOICES = (
        (BLUE, 'Blue'),
        (RED, 'Red'),
        (GREEN, 'Green'))

   my_color = models.CharField(max_length=5, choices=COLOR_CHOICES, blank=True)

And this form:
class MyColorForm(forms.ModelForm):
   class Meta:
       model = MyColorModel
       fields = ['mycolor']

By default, this will display a choice field, with the blank label set to ------
I've came up with the following options to set the label.
1) Change COLOR_CHOICES in my model to:
COLOR_CHOICES = (
    ('', '---Please select your color---'),
    (BLUE, 'Blue'),
    (RED, 'Red'),
    (GREEN, 'Green'),

2) Change COLOR_CHOICES in my model to:
COLOR_CHOICES = (
    (None, '---Please select your color---'),
    (BLUE, 'Blue'),
    (RED, 'Red'),
    (GREEN, 'Green'),

3) Add the following init method to my model form:
def __init__(*args, **kwargs):
    super(MyColorForm, self).__init__(*args, **kwargs)
    self.fields['my_color'].choices =  [('', '---Please select your color---')] + MyColorModel.COLOR_CHOICES

Options 1 led to some side effects where if statements that I had started failing, that's what led me to create option 2.
Is it fine adding the blank label to my model (option 2)? Any side effects if I add it there, or is it better to add it on the form? It just seems like quite a lot of code just to set the empty label when I do it in the form.
Answer: Setting what you want on the form is a more correct way to do achieve what you want. In Django, models contain the essential fields and behaviors of the data you're storing. That said, they define how your information is structured in the database.
1. I didn't check it, but your first option
COLOR_CHOICES = (
    ('', '---Please select your color---'),
    (BLUE, 'Blue'),
    (RED, 'Red'),
    (GREEN, 'Green'),

my_color = models.CharField(max_length=5, choices=COLOR_CHOICES)

might not work, as your first choice is an empty string, but your my_color field does not contain the blank=True argument. This means it won't allow saving the empty string to the database. But in case you want this field to be mandatory, then your definition of the empty choice should not be here, as it does not bring any added value as it does not hold any additional information regarding your data structure.
2. Your second option is definitely not the way to go [1]:

Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for "no data": NULL, and the empty string. In most cases, it's redundant to have two possible values for "no data;" the Django convention is to use the empty string, not NULL.

3. Your third option looks good. I didn't work for some time with django forms, but if your code works, the Form is a more suitable place to define how your form should look like than doing it in your models, so go for that option.
Or take a look at the solutions from the SO question linked in your post and implement those.
Good luck!
Comment: Thanks! You are correct, I needed blank=True in there for option 1. I was going for option 2, but I'll definitely use one of the others now
Answer: So you want to set empty_label for all model Forms, created from your? Adding an empty option in choices is fine, its even stated in the docs.

Unless blank=False is set on the field along with a default then a
label containing "---------" will be rendered with the select box. To
override this behavior, add a tuple to choices containing None; e.g.
(None, 'Your String For Display'). Alternatively, you can use an empty
string instead of None where this makes sense - such as on a
CharField.

But in order to stop showing the default one you need to set blank=False. So give a try to something like this:
class MyColorModel(models.Model):
    BLUE = 'blue'
    RED = 'red'
    GREEN = 'green'
    COLOR_CHOICES = (
        ('', '---Please select your color---')
        (BLUE, 'Blue'),
        (RED, 'Red'),
        (GREEN, 'Green'))

   my_color = models.CharField(max_length=5, choices=COLOR_CHOICES, blank=False, null=False, default='')

But in my opinion the best way to do it is just to set empty_label on the form.field.
def __init__(*args, **kwargs):
    super(MyColorForm, self).__init__(*args, **kwargs)
    self.fields['my_color'].empty_label = '---Please select your color---'

Comment: Thanks for the answer. I actually also prefer setting the empty label as you've done as the last option, but it seems like this only works when the model field is a ForeignKey field (ie a modelchoicefield). For me setting the empty label on a normal choice field has no effect (using Django 1.9)
Comment: I read this in the docs, so I'm going with option 1: Unless blank=False is set on the field along with a default then a label containing "---------" will be rendered with the select box. To override this behavior, add a tuple to choices containing None; e.g. (None, 'Your String For Display'). Alternatively, you can use an empty string instead of None where this makes sense - such as on a CharField.