Programs & Examples On #Rubygems

RubyGems is a package management tool for the Ruby programming language. It allows users to download and update Ruby libraries, and provides automatic dependency resolution.

'sudo gem install' or 'gem install' and gem locations

Contrary to all the other posts I suggest NOT using sudo when installing gems.

Instead I recommend you install RVM and start a happy life with portable gem homes and different version of Ruby all living under one roof.

For the uninitiated, from the documentation:

RVM is a command line tool which allows us to easily install, manage and work with multiple ruby environments and sets of gems.

The reason why installing gems with sudo is worse than just gem install is because it installs the gems for ALL USERS as root. This might be fine if you're the only person using the machine, but if you're not it can cause weirdness.

If you decide you want to blow away all your gems and start again it's much easier, and safer, to do so as a non-root user.

If you decide you want to use RVM then using sudo will cause all kinds of weirdness because each Ruby version you install through RVM has its own GEM_HOME.

Also, it's nice if you can make your development environment as close to your production environment as possible, and in production you'll most likely install gems as a non-root user.

Uninstall all installed gems, in OSX?

First make sure you have at least gem version 2.1.0

gem update --system
gem --version
# 2.6.4

To uninstall simply run:

gem uninstall --all

You may need to use the sudo command:

sudo gem uninstall --all

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

Try: sudo chmod go-w /usr/local/bin

The /usr/local/bin directory is owned by the root (i.e. administrator) account, so even if you can write to it, you can't change the permissions on it. The sudo command means "run the following command as root", and works a lot like clicking that lock icon in the System Preferences dialogs.

MySQL Install: ERROR: Failed to build gem native extension

on OSX mountain Lion: If you have brew installed, then brew install mysql and follow the instructions on creating a test database with mysql on your machine. You don't have to go all the way through, I didn't need to After I did that I was able to bundle install and rake.

You don't have write permissions for the /var/lib/gems/2.3.0 directory

(January 2019) To install Ruby using the Rbenv script, follow these steps:

1. First, update the packages index and install the packages required for the ruby-build tool to build Ruby from source:

sudo apt-get remove ruby
sudo apt update
sudo apt install git curl libssl-dev libreadline-dev zlib1g-dev autoconf bison build-essential libyaml-dev libreadline-dev libncurses5-dev libffi-dev libgdbm-dev

2. Next, run the following curl command to install both rbenv and ruby-build:

curl -sL https://github.com/rbenv/rbenv-installer/raw/master/bin/rbenv-installer | bash -

3. Add $HOME/.rbenv/bin to the system PATH.

If you are using Bash, run:

echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
source ~/.bashrc

If you are using Zsh run:

echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(rbenv init -)"' >> ~/.zshrc
source ~/.zshrc

4. Install the latest stable version of Ruby and set it as a default version with:

rbenv install 2.5.1
rbenv global 2.5.1

To list all available Ruby versions you can use: rbenv install -l

5. Verify that Ruby was properly installed by printing out the version number:

ruby -v

# Output
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]

SOURCE: How To Install Ruby on Ubuntu 18.04

EDIT: Install rubygems:

sudo apt-get install rubygems

How to remove RVM (Ruby Version Manager) from my system

A lot of people do a common mistake of thinking that 'rvm implode' does it . You need to delete all traces of any .rm files . Also , it will take some manual deletions from root . Make sure , it gets deleted and also all the ruby versions u installed using it .

How can I install a local gem?

If you want to work on a locally modified fork of a gem, the best way to do so is

gem 'pry', path: './pry'

in a Gemfile.

... where ./pry would be the clone of your repository. Simply run bundle install once, and any changes in the gem sources you make are immediately reflected. With gem install pry/pry.gem, the sources are still moved into GEM_PATH and you'll always have to run both bundle gem pry and gem update to test.

How can I set a proxy server for gem?

You can try export http_proxy=http://your_proxy:your_port

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

If you are on a *nix system, use this:

export http_proxy=http://${proxy.host}:${port}
export https_proxy=http://${proxy.host}:${port}

and then try:

gem install ${gem_name}

rmagick gem install "Can't find Magick-config"

If you get an error similar like:

The following packages have unmet dependencies:
 libmagickwand-dev : Depends: libmagickcore4-extra (= 8:6.6.9.7-5ubuntu3.2) but it is not going to be installed
                     Depends: libmagickcore-dev (= 8:6.6.9.7-5ubuntu3.2) but it is not going to be installed

You might want to start with this package: sudo apt-get install libgvc5

For more details: https://askubuntu.com/a/230958/6506

bundle install fails with SSL certificate verification error

Simple copy paste instruction given here about .pem file

https://gist.github.com/luislavena/f064211759ee0f806c88

For certificate verification failed

If you've read the previous sections, you will know what this means (and shame > on you if you have not).

We need to download AddTrustExternalCARoot-2048.pem. Open a Command Prompt and type in:

C:>gem which rubygems C:/Ruby21/lib/ruby/2.1.0/rubygems.rb Now, let's locate that directory. From within the same window, enter the path part up to the file extension, but using backslashes instead:

C:>start C:\Ruby21\lib\ruby\2.1.0\rubygems This will open a Explorer window inside the directory we indicated.

Step 3: Copy new trust certificate

Now, locate ssl_certs directory and copy the .pem file we obtained from previous step inside.

It will be listed with other files like GeoTrustGlobalCA.pem.

Error installing mysql2: Failed to build gem native extension

If you are still having trouble….

Try installing

   sudo apt-get install ruby1.9.1-dev

unable to install pg gem

  • Ubuntu 20.10 (pop!_os)
  • Ruby 2.7.2
  • Rails 3.1.0
  • Postgresql 12

Uninstall and then reinstall postgresql-client libpq5 libpq-dev

sudo apt remove postgresql-client libpq5 libpq-dev
sudo apt install postgresql-client libpq5 libpq-dev

Then install the pg gem again pointing at /usr/lib to find the pg library:

gem install pg  --   --with-pg-lib=/usr/lib

Output (what you should see after the previous command):

Building native extensions with: '--with-pg-lib=/usr/lib'
This could take a while...
Successfully installed pg-1.2.3
Parsing documentation for pg-1.2.3
Installing ri documentation for pg-1.2.3
Done installing documentation for pg after 1 seconds
1 gem installed

Gem should install, then continue with normal bundle install or update:

bundle
bundle install
bundle update

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

A problem I had on my Mac using rbenv was that when I first set it up, it loaded a bunch of ruby executables in /usr/local/bin - these executables loaded the system ruby, rather than the current version.

If you run

which bundle

And it shows /usr/local/bin/bundle you may have this issue.

Search through /usr/local/bin and delete any files that start with #!/user/bin ruby

Then run

rbenv rehash

How to find where gem files are installed

Use gem environment to find out about your gem environment:

RubyGems Environment:
  - RUBYGEMS VERSION: 2.1.5
  - RUBY VERSION: 2.0.0 (2013-06-27 patchlevel 247) [x86_64-darwin12.4.0]
  - INSTALLATION DIRECTORY: /Users/ttm/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0
  - RUBY EXECUTABLE: /Users/ttm/.rbenv/versions/2.0.0-p247/bin/ruby
  - EXECUTABLE DIRECTORY: /Users/ttm/.rbenv/versions/2.0.0-p247/bin
  - SPEC CACHE DIRECTORY: /Users/ttm/.gem/specs
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-12
  - GEM PATHS:
     - /Users/ttm/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0
     - /Users/ttm/.gem/ruby/2.0.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /Users/ttm/.rbenv/versions/2.0.0-p247/bin
     - /Users/ttm/.rbenv/libexec
     - /Users/ttm/.rbenv/plugins/ruby-build/bin
     - /Users/ttm/perl5/perlbrew/bin
     - /Users/ttm/perl5/perlbrew/perls/perl-5.18.1/bin
     - /Users/ttm/.pyenv/shims
     - /Users/ttm/.pyenv/bin
     - /Users/ttm/.rbenv/shims
     - /Users/ttm/.rbenv/bin
     - /Users/ttm/bin
     - /usr/local/mysql-5.6.12-osx10.7-x86_64/bin
     - /Users/ttm/libsmi/bin
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin
     - /usr/local/bin

Notice the two sections for:

  • INSTALLATION DIRECTORY
  • GEM PATHS

Failed to build gem native extension — Rails install

The suggested answer only works for certain versions of ruby. Some commenters suggest using ruby-dev; that didn't work for me either.

sudo apt-get install ruby-all-dev

worked for me.

cannot load such file -- bundler/setup (LoadError)

i had the same issue and tried all the answers without any luck.

steps i did to reproduce:

  1. rvm instal 2.1.10
  2. rvm gemset create my_gemset
  3. rvm use 2.1.10@my_gemset
  4. bundle install

however bundle install installed Rails, but i still got cannot load such file -- bundler/setup (LoadError)

finally running gem install rails -v 4.2 fixed it

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

Uninstall homebrew:

 ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Then reinstall

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Warning: This script will remove: /Library/Caches/Homebrew/ - thks benjaminsila

gem install: Failed to build gem native extension (can't find header files)

Red Hat, Fedora:

yum -y install gcc mysql-devel ruby-devel rubygems
gem install -y mysql -- --with-mysql-config=/usr/bin/mysql_config

Debian, Ubuntu:

apt-get install libmysqlclient-dev ruby-dev
gem install mysql

Arch Linux:

pacman -S libmariadbclient
gem install mysql

How to downgrade or install an older version of Cocoapods

Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.

They can be removed using pod spec remove SPEC_NAME then pod setup

It may help to do pod spec remove master then pod setup

Update just one gem with bundler

bundler update --source gem-name will update the revision hash in Gemfile.lock which you can compare with the last commit hash of that git branch (master by default).

GIT remote: [email protected]:organization/repo-name.git revision: c810f4a29547b60ca8106b7a6b9a9532c392c954

can be found at github.com/organization/repo-name/commits/c810f4a2 (I used shorthand 8 character commit hash for the url)

How do I specify local .gem files in my Gemfile?

Adding .gem to vendor/cache seems to work. No options required in Gemfile.

How to install gem from GitHub source?

In your Gemfile, add the following:

gem 'example', :git => 'git://github.com/example.git'

You can also add ref, branch and tag options,

For example if you want to download from a particular branch:

gem 'example', :git => "git://github.com/example.git", :branch => "my-branch"

Then run:

bundle install

ruby LoadError: cannot load such file

I created my own Gem, but I did it in a directory that is not in my load path:

$ pwd
/Users/myuser/projects
$ gem build my_gem/my_gem.gemspec

Then I ran irb and tried to load the Gem:

> require 'my_gem'
LoadError: cannot load such file -- my_gem

I used the global variable $: to inspect my load path and I realized I am using RVM. And rvm has specific directories in my load path $:. None of those directories included my ~/projects directory where I created the custom gem.

So one solution is to modify the load path itself:

$: << "/Users/myuser/projects/my_gem/lib"

Note that the lib directory is in the path, which holds the my_gem.rb file which will be required in irb:

> require 'my_gem'
 => true 

Now if you want to install the gem in RVM path, then you would need to run:

$ gem install my_gem

But it will need to be in a repository like rubygems.org.

$ gem push my_gem-0.0.0.gem
Pushing gem to RubyGems.org...
Successfully registered gem my_gem

How do I display Ruby on Rails form validation error messages one at a time?

A better idea,

if you want to put the error message just beneath the text field, you can do like this

.row.spacer20top
  .col-sm-6.form-group
    = f.label :first_name, "*Your First Name:"
    = f.text_field :first_name, :required => true, class: "form-control"
    = f.error_message_for(:first_name)

What is error_message_for?
--> Well, this is a beautiful hack to do some cool stuff

# Author Shiva Bhusal
# Aug 2016
# in config/initializers/modify_rails_form_builder.rb
# This will add a new method in the `f` object available in Rails forms
class ActionView::Helpers::FormBuilder
  def error_message_for(field_name)
    if self.object.errors[field_name].present?
      model_name              = self.object.class.name.downcase
      id_of_element           = "error_#{model_name}_#{field_name}"
      target_elem_id          = "#{model_name}_#{field_name}"
      class_name              = 'signup-error alert alert-danger'
      error_declaration_class = 'has-signup-error'

      "<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
      "#{self.object.errors[field_name].join(', ')}"\
      "</div>"\
      "<!-- Later JavaScript to add class to the parent element -->"\
      "<script>"\
          "document.onreadystatechange = function(){"\
            "$('##{id_of_element}').parent()"\
            ".addClass('#{error_declaration_class}');"\
          "}"\
      "</script>".html_safe
    end
  rescue
    nil
  end
end

Result enter image description here

Markup Generated after error

<div id="error_user_email" for="user_email" class="signup-error alert alert-danger">has already been taken</div>
<script>document.onreadystatechange = function(){$('#error_user_email').parent().addClass('has-signup-error');}</script>

Corresponding SCSS

  .has-signup-error{
    .signup-error{
      background: transparent;
      color: $brand-danger;
      border: none;
    }

    input, select{
      background-color: $bg-danger;
      border-color: $brand-danger;
      color: $gray-base;
      font-weight: 500;
    }

    &.checkbox{
      label{
        &:before{
          background-color: $bg-danger;
          border-color: $brand-danger;
        }
      }
    }

Note: Bootstrap variables used here

Can't install gems on OS X "El Capitan"

Reinstalling RVM worked for me, but I had to reinstall all of my gems afterward:

rvm implode
\curl -sSL https://get.rvm.io | bash -s stable --ruby
rvm reload

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

Try updating your Ruby on Rails version to v3.0.5:

gem install rails --version 3.0.5

or v2.3.11:

gem install rails --version 2.3.11

If this isn't a new project you'll have to upgrade your application accordingly. If it was a new project, just delete the directory you created it in and create a new project again.

Error while installing json gem 'mkmf.rb can't find header files for ruby'

You need to install the entire ruby and not just the minimum package. The correct command to use is:

sudo apt install ruby-full

The following command will also not install a complete ruby:

sudo apt-get install ruby2.3-dev

How to install a gem or update RubyGems if it fails with a permissions error

You really should be using a Ruby version manager.

Using one properly would prevent and can resolve your permission problem when executing a gem update command.

I recommend rbenv.

However, even when you use a Ruby version manager, you may still get that same error message.

If you do, and you are using rbenv, just verify that the ~/.rbenv/shims directory is before the path for the system Ruby.

$ echo $PATH will show you the order of your load path.

If you find that your shims directory comes after your system Ruby bin directory, then edit your ~/.bashrc file and put this as your last export PATH command: export PATH=$HOME/.rbenv/shims:$PATH

$ ruby -v shows you what version of Ruby you are using

This shows that I'm currently using the system version of Ruby (usually not good)

$ ruby -v
ruby 1.8.7 (2012-02-08 patchlevel 358) [universal-darwin12.0]

$ rbenv global 1.9.3-p448 switches me to a newer, pre-installed version (see references below).

This shows that I'm using a newer version of Ruby (that likely won't cause the Gem::FilePermissionError)

$ ruby -v
ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.0]

You typically should not need to preface a gem command with sudo. If you feel the need to do so, something is probably misconfigured.

For details about rbenv see the following:

How to remove gem from Ruby on Rails application?

Devise uses some generators to generate views and stuff it needs into your application. If you have run this generator, you can easily undo it with

rails destroy <name_of_generator>

The uninstallation of the gem works as described in the other posts.

Installing RubyGems in Windows

To setup you Ruby development environment on Windows:

  1. Install Ruby via RubyInstaller: http://rubyinstaller.org/downloads/

  2. Check your ruby version: Start - Run - type in cmd to open a windows console

  3. Type in ruby -v
  4. You will get something like that: ruby 2.0.0p353 (2013-11-22) [i386-mingw32]

For Ruby 2.4 or later, run the extra installation at the end to install the DevelopmentKit. If you forgot to do that, run ridk install in your windows console to install it.

For earlier versions:

  1. Download and install DevelopmentKit from the same download page as Ruby Installer. Choose an ?exe file corresponding to your environment (32 bits or 64 bits and working with your version of Ruby).
  2. Follow the installation instructions for DevelopmentKit described at: https://github.com/oneclick/rubyinstaller/wiki/Development-Kit#installation-instructions. Adapt it for Windows.
  3. After installing DevelopmentKit you can install all needed gems by just running from the command prompt (windows console or terminal): gem install {gem name}. For example, to install rails, just run gem install rails.

Hope this helps.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

I have solved this, eventually!

I re-installed Ruby and Rails under RVM. I'm using Ruby version 1.9.2-p136.

After re-installing under rvm, this error was still present.

In the end the magic command that solved it was:

sudo install_name_tool -change libmysqlclient.16.dylib /usr/local/mysql/lib/libmysqlclient.16.dylib ~/.rvm/gems/ruby-1.9.2-p136/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle

Hope this helps someone else!

no such file to load -- rubygems (LoadError)

I have also met the same problem using rbenv + passenger + nginx. my solution is simply adding these 2 line of code to your nginx config:

passenger_default_user root;
passenger_default_group root;

the detailed answer is here: https://stackoverflow.com/a/15777738/445908

How to install CocoaPods?

cocoapod on terminal follow this:

sudo gem update

sudo gem install cocoapods

pod setup

cd (project direct drag link) 

pod init

open -aXcode podfile (if its already open add your pod file name ex:alamofire4.3)

pod install

pod update

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

I had the same issue today. I solve this problem by removing any PATH in .bashrc for older rvm.

List of installed gems?

use this code (in console mode):

Gem::Specification.all_names

Gem Command not found

The following command installs ruby gem for ubuntu:

apt-get install libgemplugin-ruby

I did it after ruby was installed.

How to make --no-ri --no-rdoc the default for gem install?

You can specify default options using the .gemrc configuration file.

Documentation about gem configuration file

The 'json' native gem requires installed build tools

My gem version 2.0.3 and I was getting the same issue. This command resolved it:

gem install json --platform=ruby --verbose

How can I specify a local gem in my Gemfile?

In addition to specifying the path (as Jimmy mentioned) you can also force Bundler to use a local gem for your environment only by using the following configuration option:

$ bundle config local.GEM_NAME /path/to/local/git/repository

This is extremely helpful if you're developing two gems or a gem and a rails app side-by-side.

Note though, that this only works when you're already using git for your dependency, for example:

# In Gemfile
gem 'rack', :github => 'rack/rack', :branch => 'master'

# In your terminal
$ bundle config local.rack ~/Work/git/rack

As seen on the docs.

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

I have faced same issue after install macOS Catalina. I had try below command and its working.

sudo gem update

How to get a DOM Element from a JQuery Selector

I needed to get the element as a string.

jQuery("#bob").get(0).outerHTML;

Which will give you something like:

<input type="text" id="bob" value="hello world" />

...as a string rather than a DOM element.

`&mdash;` or `&#8212;` is there any difference in HTML output?

From W3 web site Common HTML entities used for typography

For the sake of portability, Unicode entity references should be reserved for use in documents certain to be written in the UTF-8 or UTF-16 character sets. In all other cases, the alphanumeric references should be used.

Translation: If you are looking for widest support, go with &mdash;

Print Pdf in C#

The easiest way is to create C# Process and launch external tool to print your PDF file

private static void ExecuteRawFilePrinter() {
    Process process = new Process();
    process.StartInfo.FileName = "c:\\Program Files (x86)\\RawFilePrinter\\RawFilePrinter.exe";
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.Arguments = string.Format("-p \"c:\\Users\\Me\\Desktop\\mypdffile.pdf\" \"gdn02ptr006\"");
    process.Start();
    process.WaitForExit();
}

Code above launches RawFilePrinter.exe (similar to 2Printer.exe), but with better support. It is not free, but by making donation allow you to use it everywhere and redistribute with your application. Latest version to download: http://bigdotsoftware.pl/rawfileprinter

Python - IOError: [Errno 13] Permission denied:

For me nothing from above worked. So I solved my problem with this workaround. Just check that you have added SYSTEM in directory folder. I hope it will help somoene.

import os
# create file
@staticmethod
def create_file(path):
    if not os.path.exists(path):
        os.system('echo # > {}'.format(path))

# append lines to the file
split_text = text_file.split('\n')
    for st in split_text:
        os.system('echo {} >> {}'.format(st,path))

csv.Error: iterator should return strings, not bytes

Your problem is you have the b in the open flag. The flag rt (read, text) is the default, so, using the context manager, simply do this:

with open('sample.csv') as ifile:
    read = csv.reader(ifile) 
    for row in read:
        print (row)  

The context manager means you don't need generic error handling (without which you may get stuck with the file open, especially in an interpreter), because it will automatically close the file on an error, or on exiting the context.

The above is the same as:

with open('sample.csv', 'r') as ifile:
    ...

or

with open('sample.csv', 'rt') as ifile:
    ...

How to convert an int to a hex string?

This worked best for me

"0x%02X" % 5  # => 0x05
"0x%02X" % 17 # => 0x11

Change the (2) if you want a number with a bigger width (2 is for 2 hex printned chars) so 3 will give you the following

"0x%03X" % 5  # => 0x005
"0x%03X" % 17 # => 0x011

What are the best PHP input sanitizing functions?

Sanitizers

Sanitize is a function to check (and remove) harmful data from user input which can harm the software. Sanitizing user input is the most secure method of user input validation to strip out anything that is not on the whitelist.

PHP Support

5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.27, 7.4.0 - 7.4.15, 8.0.0 - 8.0.2

<?php
require_once("path/to/Sanitizers.php");

use Sanitizers\Sanitizers\Sanitizer;

\\ passing `true` in Sanitizer class enables exceptions
$sanitize = new Sanitizer(true);
try {
    echo $sanitize->Username($_GET['username']);
} catch (Exception $e) {
    echo "Could not Sanitize user input." 
    var_dump($e);
}
?>

Download the latest release

See Sanitizers GitHub project.

Android view layout_width - how to change programmatically?

You can set height and width like this also:

viewinstance.setLayoutParams(new LayoutParams(width, height));

Can the Unix list command 'ls' output numerical chmod permissions?

Use this to display the Unix numerical permission values (octal values) and file name.

stat -c '%a %n' *

Use this to display the Unix numerical permission values (octal values) and the folder's sgid and sticky bit, user name of the owner, group name, total size in bytes and file name.

stat -c '%a %A %U %G %s %n' *

enter image description here

Add %y if you need time of last modification in human-readable format. For more options see stat.

Better version using an Alias

Using an alias is a more efficient way to accomplish what you need and it also includes color. The following displays your results organized by group directories first, display in color, print sizes in human readable format (e.g., 1K 234M 2G) edit your ~/.bashrc and add an alias for your account or globally by editing /etc/profile.d/custom.sh

Typing cls displays your new LS command results.

alias cls="ls -lha --color=always -F --group-directories-first |awk '{k=0;s=0;for(i=0;i<=8;i++){;k+=((substr(\$1,i+2,1)~/[rwxst]/)*2^(8-i));};j=4;for(i=4;i<=10;i+=3){;s+=((substr(\$1,i,1)~/[stST]/)*j);j/=2;};if(k){;printf(\"%0o%0o \",s,k);};print;}'"

Alias is the most efficient solution

Folder Tree

While you are editing your bashrc or custom.sh include the following alias to see a graphical representation where typing lstree will display your current folder tree structure

alias lstree="ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'"

It would display:

   |-scripts
   |--mod_cache_disk
   |--mod_cache_d
   |---logs
   |-run_win
   |-scripts.tar.gz

How to add items to array in nodejs

Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:

var array = [];
calendars.forEach(function(item) {
    array.push(item.id);
});

console.log(array);

You can also use the map() method to generate an Array filled with the results of calling the specified function on each element. Something like:

var array = calendars.map(function(item) {
    return item.id;
});

console.log(array);

And, since ECMAScript 2015 has been released, you may start seeing examples using let or const instead of var and the => syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):

let array = calendars.map(item => item.id);
console.log(array);

count distinct values in spreadsheet

=UNIQUE({filter(Core!L8:L27,isblank(Core!L8:L27)=false),query(ArrayFormula(countif(Core!L8:L27,Core!L8:L27)),"select Col1 where Col1 <> 0")})

Core!L8:L27 = list

Python: "TypeError: __str__ returned non-string" but still prints to output?

Just Try this:

def __str__(self):
    return f'Memo={self.memo}, Tag={self.tags}'

How to remove an app with active device admin enabled on Android?

Go to SETTINGS->Location and Security-> Device Administrator and deselect the admin which you want to uninstall.

Now uninstall the application. If it still says you need to deactivate the application before uninstalling, you may need to Force Stop the application before uninstalling.

Call a method of a controller from another controller using 'scope' in AngularJS

The best approach for you to communicate between the two controllers is to use events.

Scope Documentation

In this check out $on, $broadcast and $emit.

In general use case the usage of angular.element(catapp).scope() was designed for use outside the angular controllers, like within jquery events.

Ideally in your usage you would write an event in controller 1 as:

$scope.$on("myEvent", function (event, args) {
   $scope.rest_id = args.username;
   $scope.getMainCategories();
});

And in the second controller you'd just do

$scope.initRestId = function(){
   $scope.$broadcast("myEvent", {username: $scope.user.username });
};

Edit: Realised it was communication between two modules

Can you try including the firstApp module as a dependency to the secondApp where you declare the angular.module. That way you can communicate to the other app.

How to effectively work with multiple files in Vim

You may want to use Vim global marks.

This way you can quickly bounce between files, and even to the marked location in the file. Also, the key commands are short: 'C takes me to the code I'm working with, 'T takes me to the unit test I'm working with.

When you change places, resetting the marks is quick too: mC marks the new code spot, mT marks the new test spot.

How can I work with command line on synology?

for my example:

Windows XP ---> Synology:DS218+

  • Step1:
        > DNS: Control Panel (???)
             > Terminal & SNMP(??? & SNMP)
  • Step2:
        Enable Telnet service (?? Telnet ??)
        or Enable SSH Service (?? SSH ??)


    enter image description here
    enter image description here


  • Step3: Launch the terminal on Windows (or via executing

        cmd
    to launch the terminal)
    enter image description here


  • Step4: type: telnet your_nas_ip_or_domain_name, like below

        telnet 192.168.1.104
    enter image description here



  • Step5:
    demo a terminal application, like compiling the Java code

    Fzz login: tsungjung411

    Password:

    # shows the current working directory (?????????)
    $ pwd
    /var/services/homes/tsungjung411


    # edit a Java file (via vi), then compile and run it 
    # (?? vi ?? Java ??,???????)
    $ vi Main.java

    # show the file content (??????)
    $ cat Main.java
    public class Main {
        public static void main(String [] args) {
            System.out.println("hello, World!");
        }
    }

    # compiles the Java file (?? Java ??)
    javac Main.java

    # executes the Java file (?? Java ??)
    $ java Main
    hello, World!

    # shows the file list (??????)
    $ ls
    CloudStation  Main.class  Main.java  www

enter image description here


    # shows the JRE version on this Synology Disk Station
    $ java -version
    openjdk version "1.8.0_151"
    OpenJDK Runtime Environment (IcedTea 3.6.0) (linux-gnu build 1.8.0_151-b12)
    OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)




  • Step6:
    demo another terminal application, like running the Python code

    $ python
    Python 2.7.12 (default, Nov 10 2017, 20:30:30)
    [GCC 4.9.3 20150311 (prerelease)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    >>> import sys
    >>>
    >>> # shows the the python version
    >>> print(sys.version)
    2.7.12 (default, Nov 10 2017, 20:30:30)
    [GCC 4.9.3 20150311 (prerelease)]
    >>>
    >>> import os
    >>>
    >>> # shows the current working directory
    >>> print(os.getcwd())
    /volume1/homes/tsungjung411

enter image description here


    $ # launch Python 3
    $ python3
    Python 3.5.1 (default, Dec  9 2016, 00:20:03)
    [GCC 4.9.3 20150311 (prerelease)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>>




How to set different colors in HTML in one statement?

Use the span tag

<style>
    .redText
    {
        color:red;
    }
    .blackText
    {
        color:black;
        font-weight:bold;
    }
</style>

<span class="redText">My Name is:</span>&nbsp;<span class="blackText">Tintincute</span>

It's also a good idea to avoid inline styling. Use a custom CSS class instead.

Using ChildActionOnly in MVC

FYI, [ChildActionOnly] is not available in ASP.NET MVC Core. see some info here

python requests file upload

In Ubuntu you can apply this way,

to save file at some location (temporary) and then open and send it to API

      path = default_storage.save('static/tmp/' + f1.name, ContentFile(f1.read()))
      path12 = os.path.join(os.getcwd(), "static/tmp/" + f1.name)
      data={} #can be anything u want to pass along with File
      file1 = open(path12, 'rb')
      header = {"Content-Disposition": "attachment; filename=" + f1.name, "Authorization": "JWT " + token}
       res= requests.post(url,data,header)

Single line sftp from terminal

Or echo 'put {path to file}' | sftp {user}@{host}:{dir}, which would work in both unix and powershell.

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

Just had this happen to me.

Apparently Java's automatic updater installed and configured a new version of the JRE for me, while leaving the old JDK intact. So even though I did have a JDK, it didn't match the currently "active" JRE, which was causing the error.

Download a matching version of the JDK to the JRE you currently have installed, (In OP's case 151) That should do the trick.

Decode UTF-8 with Javascript

To answer the original question: here is how you decode utf-8 in javascript:

http://ecmanaut.blogspot.ca/2006/07/encoding-decoding-utf8-in-javascript.html

Specifically,

function encode_utf8(s) {
  return unescape(encodeURIComponent(s));
}

function decode_utf8(s) {
  return decodeURIComponent(escape(s));
}

We have been using this in our production code for 6 years, and it has worked flawlessly.

Note, however, that escape() and unescape() are deprecated. See this.

Iterating over dictionaries using 'for' loops

It's not that key is a special word, but that dictionaries implement the iterator protocol. You could do this in your class, e.g. see this question for how to build class iterators.

In the case of dictionaries, it's implemented at the C level. The details are available in PEP 234. In particular, the section titled "Dictionary Iterators":

  • Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write

    for k in dict: ...
    

    which is equivalent to, but much faster than

    for k in dict.keys(): ...
    

    as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.

  • Add methods to dictionaries that return different kinds of iterators explicitly:

    for key in dict.iterkeys(): ...
    
    for value in dict.itervalues(): ...
    
    for key, value in dict.iteritems(): ...
    

    This means that for x in dict is shorthand for for x in dict.iterkeys().

In Python 3, dict.iterkeys(), dict.itervalues() and dict.iteritems() are no longer supported. Use dict.keys(), dict.values() and dict.items() instead.

Update rows in one table with data from another table based on one column in each being equal

merge into t2 t2 
using (select * from t1) t1
on (t2.user_id = t1.user_id)
when matched then update
set
   t2.c1 = t1.c1
,  t2.c2 = t1.c2

IDENTITY_INSERT is set to OFF - How to turn it ON?

Add this line above you Query

SET IDENTITY_INSERT tbl_content ON

Print out the values of a (Mat) matrix in OpenCV C++

I think using the matrix.at<type>(x,y) is not the best way to iterate trough a Mat object! If I recall correctly matrix.at<type>(x,y) will iterate from the beginning of the matrix each time you call it(I might be wrong though). I would suggest using cv::MatIterator_

cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
    std::cout << *_it << std::endl;
}

Current time formatting with Javascript

For this true mysql style use this function below: 2019/02/28 15:33:12

  • If you click the
  • 'Run code snippet' button below
  • It will show your an simple realtime digital clock example The demo will appear below the code snippet.

_x000D_
_x000D_
function getDateTime() {_x000D_
        var now     = new Date(); _x000D_
        var year    = now.getFullYear();_x000D_
        var month   = now.getMonth()+1; _x000D_
        var day     = now.getDate();_x000D_
        var hour    = now.getHours();_x000D_
        var minute  = now.getMinutes();_x000D_
        var second  = now.getSeconds(); _x000D_
        if(month.toString().length == 1) {_x000D_
             month = '0'+month;_x000D_
        }_x000D_
        if(day.toString().length == 1) {_x000D_
             day = '0'+day;_x000D_
        }   _x000D_
        if(hour.toString().length == 1) {_x000D_
             hour = '0'+hour;_x000D_
        }_x000D_
        if(minute.toString().length == 1) {_x000D_
             minute = '0'+minute;_x000D_
        }_x000D_
        if(second.toString().length == 1) {_x000D_
             second = '0'+second;_x000D_
        }   _x000D_
        var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;   _x000D_
         return dateTime;_x000D_
    }_x000D_
_x000D_
    // example usage: realtime clock_x000D_
    setInterval(function(){_x000D_
        currentTime = getDateTime();_x000D_
        document.getElementById("digital-clock").innerHTML = currentTime;_x000D_
    }, 1000);
_x000D_
<div id="digital-clock"></div>
_x000D_
_x000D_
_x000D_

Loading basic HTML in Node.js

This is an update to Muhammed Neswine's answer

In Express 4.x, sendfile has been deprecated and sendFile function has to be used. The difference is sendfile takes relative path and sendFile takes absolute path. So, __dirname is used to avoid hardcoding the path.

var express = require('express');
var app = express();
var path = require("path");

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/folder_name/filename.html'));
});

PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?

In 2020 Page Speed Insights user agents are: "Chrome-Lighthouse" for mobile and "Google Page Speed Insights" for desktop.

<?php if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Chrome-Lighthouse') === false  || stripos($_SERVER['HTTP_USER_AGENT'], 'Google Page Speed Insights') === false): ?>
// your google analytics code and other external script you want to hide from PageSpeed Insights here
<?php endif; ?>

how to get login option for phpmyadmin in xampp

Can you set the password to the phpmyadmin here

http://localhost/security/index.php

How to determine whether an object has a given property in JavaScript

includes

Object.keys(x).includes('y');

The Array.prototype.includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

and

Object.keys() returns an array of strings that represent all the enumerable properties of the given object.

.hasOwnProperty() and the ES6+ .? -optional-chaining like: if (x?.y) are very good 2020+ options as well.

Interfaces with static fields in java for sharing 'constants'

There is a lot of hate for this pattern in Java. However, an interface of static constants does sometimes have value. You need to basically fulfill the following conditions:

  1. The concepts are part of the public interface of several classes.

  2. Their values might change in future releases.

  3. Its critical that all implementations use the same values.

For example, suppose that you are writing an extension to a hypothetical query language. In this extension you are going to expand the language syntax with some new operations, which are supported by an index. E.g. You are going to have a R-Tree supporting geospatial queries.

So you write a public interface with the static constant:

public interface SyntaxExtensions {
     // query type
     String NEAR_TO_QUERY = "nearTo";

     // params for query
     String POINT = "coordinate";
     String DISTANCE_KM = "distanceInKm";
}

Now later, a new developer thinks he needs to build a better index, so he comes and builds an R* implementation. By implementing this interface in his new tree he guarantees that the different indexes will have identical syntax in the query language. Moreover, if you later decided that "nearTo" was a confusing name, you could change it to "withinDistanceInKm", and know that the new syntax would be respected by all your index implementations.

PS: The inspiration for this example is drawn from the Neo4j spatial code.

Change the spacing of tick marks on the axis of a plot?

I just discovered the Hmisc package:

Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.

library(Hmisc)    
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th

connecting MySQL server to NetBeans

  1. Download XAMPP
  2. Run XAMPP server. Click on Start button in front of MY SQL. Now you can see that color is changed to green. Now, Click on Admin.The new browser window will be open. Copy the link from browser and paste to the Admin properties as shown in below. Set path in the admin properties of database connection. Click on OK. Now your database is connected. enter image description here

How to get request URI without context path?

request.getRequestURI().substring(request.getContextPath().length())

Check if a user has scrolled to the bottom

i used this test to detect the scroll reached the bottom: event.target.scrollTop === event.target.scrollHeight - event.target.offsetHeight

How do I turn off Unicode in a VC++ project?

None of the above solutions worked for me. But

#include <Windows.h>

worked fine.

Set inputType for an EditText Programmatically?

For Kotlin:

    val password = EditText(this)
    password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
    password.hint = "Password"

$watch an object

you must changes in $watch ....

_x000D_
_x000D_
function MyController($scope) {_x000D_
    $scope.form = {_x000D_
        name: 'my name',_x000D_
    }_x000D_
_x000D_
    $scope.$watch('form.name', function(newVal, oldVal){_x000D_
        console.log('changed');_x000D_
     _x000D_
    });_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>_x000D_
<div ng-app>_x000D_
    <div ng-controller="MyController">_x000D_
        <label>Name:</label> <input type="text" ng-model="form.name"/>_x000D_
            _x000D_
        <pre>_x000D_
            {{ form }}_x000D_
        </pre>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Windows Batch Files: if else

An alternative would be to set a variable, and check whether it is defined:

SET ARG=%1
IF DEFINED ARG (echo "It is defined: %1") ELSE (echo "%%1 is not defined")

Unfortunately, using %1 directly with DEFINED doesn't work.

Can I use Homebrew on Ubuntu?

Because all previous answers doesn't work for me for ubuntu 14.04 here what I did, if any one get the same problem:

git clone https://github.com/Linuxbrew/brew.git ~/.linuxbrew
PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$(brew --prefix)/share/man:$MANPATH"
export INFOPATH="$(brew --prefix)/share/info:$INFOPATH"

then

sudo apt-get install gawk
sudo yum install gawk
brew install hello

you can follow this link for more information.

What does "int 0x80" mean in assembly code?

int is nothing but an interruption i.e the processor will put its current execution to hold.

0x80 is nothing but a system call or the kernel call. i.e the system function will be executed.

To be specific 0x80 represents rt_sigtimedwait/init_module/restart_sys it varies from architecture to architecture.

For more details refer https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md

How to bind DataTable to Datagrid

You could use DataGrid in WPF

SqlDataAdapter da = new SqlDataAdapter("Select * from Table",con);
DataTable dt = new DataTable("Call Reciept");
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.ItemsSource = dt.DefaultView;

How to select some rows with specific rownames from a dataframe?

You can also use this:

DF[paste0("stu",c(2,3,5,9)), ]

How to override the [] operator in Python?

You are looking for the __getitem__ method. See http://docs.python.org/reference/datamodel.html, section 3.4.6

How to delete last item in list?

If you do a lot with timing, I can recommend this little (20 line) context manager:

You code could look like this then:

#!/usr/bin/env python
# coding: utf-8

from timer import Timer

if __name__ == '__main__':
    a, record = None, []
    while not a == '':
        with Timer() as t: # everything in the block will be timed
            a = input('Type: ')
        record.append(t.elapsed_s)
    # drop the last item (makes a copy of the list):
    record = record[:-1] 
    # or just delete it:
    # del record[-1]

Just for reference, here's the content of the Timer context manager in full:

from timeit import default_timer

class Timer(object):
    """ A timer as a context manager. """

    def __init__(self):
        self.timer = default_timer
        # measures wall clock time, not CPU time!
        # On Unix systems, it corresponds to time.time
        # On Windows systems, it corresponds to time.clock

    def __enter__(self):
        self.start = self.timer() # measure start time
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.end = self.timer() # measure end time
        self.elapsed_s = self.end - self.start # elapsed time, in seconds
        self.elapsed_ms = self.elapsed_s * 1000  # elapsed time, in milliseconds

What are Makefile.am and Makefile.in?

DEVELOPER runs autoconf and automake:

  1. autoconf -- creates shippable configure script
    (which the installer will later run to make the Makefile)
  1. automake - creates shippable Makefile.in data file
    (which configure will later read to make the Makefile)

INSTALLER runs configure, make and sudo make install:

./configure       # Creates  Makefile        (from     Makefile.in).  
make              # Creates  the application (from the Makefile just created).  

sudo make install # Installs the application 
                  #   Often, by default its files are installed into /usr/local


INPUT/OUTPUT MAP

Notation below is roughly: inputs --> programs --> outputs

DEVELOPER runs these:

configure.ac -> autoconf -> configure (script) --- (*.ac = autoconf)
configure.in --> autoconf -> configure (script) --- (configure.in depreciated. Use configure.ac)

Makefile.am -> automake -> Makefile.in ----------- (*.am = automake)

INSTALLER runs these:

Makefile.in -> configure -> Makefile (*.in = input file)

Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)


"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."

"automake is a tool for automatically generating Makefile.in files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."

Manuals:

Free online tutorials:


Example:

The main configure.ac used to build LibreOffice is over 12k lines of code, (but there are also 57 other configure.ac files in subfolders.)

From this my generated configure is over 41k lines of code.

And while the Makefile.in and Makefile are both only 493 lines of code. (But, there are also 768 more Makefile.in's in subfolders.)

ExecutorService that interrupts tasks after a timeout

It seems problem is not in JDK bug 6602600 ( it was solved at 2010-05-22), but in incorrect call of sleep(10) in circle. Addition note, that the main Thread must give directly CHANCE to other threads to realize thier tasks by invoke SLEEP(0) in EVERY branch of outer circle. It is better, I think, to use Thread.yield() instead of Thread.sleep(0)

The result corrected part of previous problem code is such like this:

.......................
........................
Thread.yield();         

if (i % 1000== 0) {
System.out.println(i + "/" + counter.get()+ "/"+service.toString());
}

//                
//                while (i > counter.get()) {
//                    Thread.sleep(10);
//                } 

It works correctly with amount of outer counter up to 150 000 000 tested circles.

command/usr/bin/codesign failed with exit code 1- code sign error

I Followed all the things mentioned in this thread but still facing same issue-

/usr/bin/codesign --force --sign A7F8FCD694D7923A3E57826398C3380E2E5A5446 --entitlements  unknown error -1=ffffffffffffffff
Command /usr/bin/codesign failed with exit code 1

I have configured Automatic signing with my code base which will work with xcode run as well as xcodebuild run from terminal from my machine but it gives above error when I run it on jenkins pipeline or try to run on terminal from remotely connected machine

In my case Automatic signing is not working if access remotely. because I need to open keychain before archive using

security unlock-keychain -p "newpassword" "/Users/xyz/Library/Keychains/login.keychain"

keychain passwords & login password for macOS X user was different I change it to new same password and it works for me.

How to generate access token using refresh token through google drive API?

POST /oauth2/v4/token

Host: www.googleapis.com

Headers

Content-length: 163

content-type: application/x-www-form-urlencoded

RequestBody

client_secret=************&grant_type=refresh_token&refresh_token=sasasdsa1312dsfsdf&client_id=************

Replace all particular values in a data frame

If you want to replace multiple values in a data frame, looping through all columns might help.

Say you want to replace "" and 100:

na_codes <- c(100, "")
for (i in seq_along(df)) {
    df[[i]][df[[i]] %in% na_codes] <- NA
}

How to force a SQL Server 2008 database to go Offline

Go offline

USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

Go online

USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

I use ".hpp" for C++ headers and ".h" for C language headers. The ".hpp" reminds me that the file contains statements for the C++ language which are not valid for the C language, such as "class" declarations.

How do I set Tomcat Manager Application User Name and Password for NetBeans?

Go to apache-tomcat\conf folder add these lines in

tomcat-users.xml file

<role rolename="manager-gui"/>
<user username="admin" password="admin" roles="manager-gui"/>

and restart server

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

This is just additional info to answers in order to pass argument into the another file

Where you expect argument

PrintName.ps1

Param(
    [Parameter( Mandatory = $true)]
    $printName = "Joe"    
)


Write-Host $printName

How to call the file

Param(
    [Parameter( Mandatory = $false)]
    $name = "Joe"    
)


& ((Split-Path $MyInvocation.InvocationName) + "\PrintName.ps1") -printName $name

If you do not do not provide any input it will default to "Joe" and this will be passed as argument into printName argument in PrintName.ps1 file which will in turn print out the "Joe" string

Reading large text files with streams in C#

Use a background worker and read only a limited number of lines. Read more only when the user scrolls.

And try to never use ReadToEnd(). It's one of the functions that you think "why did they make it?"; it's a script kiddies' helper that goes fine with small things, but as you see, it sucks for large files...

Those guys telling you to use StringBuilder need to read the MSDN more often:

Performance Considerations
The Concat and AppendFormat methods both concatenate new data to an existing String or StringBuilder object. A String object concatenation operation always creates a new object from the existing string and the new data. A StringBuilder object maintains a buffer to accommodate the concatenation of new data. New data is appended to the end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer. The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs.
A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data. Consequently, the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input.

That means huge allocation of memory, what becomes large use of swap files system, that simulates sections of your hard disk drive to act like the RAM memory, but a hard disk drive is very slow.

The StringBuilder option looks fine for who use the system as a mono-user, but when you have two or more users reading large files at the same time, you have a problem.

How do you use variables in a simple PostgreSQL script?

I had to do something like this

CREATE OR REPLACE FUNCTION MYFUNC()
RETURNS VOID AS $$
DO
$do$
BEGIN
DECLARE
 myvar int;
 ...
END
$do$
$$ LANGUAGE SQL;

Understanding the map function

map doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map.

map in Python 3 is equivalent to this:

def map(func, iterable):
    for i in iterable:
        yield func(i)

and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yielding.

Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map, particularly if you're using a lambda expression as the first argument:

[func(i) for i in iterable]

As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -

 >>> a = "hello, world"
 >>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')

A use of map here would be if you start with a list of strings instead of a single string - map can listify all of them individually:

>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

Note that map(list, a) is equivalent in Python 2, but in Python 3 you need the list call if you want to do anything other than feed it into a for loop (or a processing function such as sum that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:

>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

Multiple conditions in ngClass - Angular 4

You are trying to assign an array to ngClass, but the syntax for the array elements is wrong since you separate them with a || instead of a ,.

Try this:

<section [ngClass]="[menu1 ? 'class1' : '',  menu2 ? 'class1' : '', (something && (menu1 || menu2)) ? 'class2' : '']">

This other option should also work:

<section [ngClass.class1]="menu1 || menu2" [ngClass.class2] = "(menu1 || menu2) && something">    

How to check for DLL dependency?

NDepend was already mentioned by Jesse (if you analyze .NET code) but let's explain exactly how it can help.

Is there a program/script that can scan an executable for DLL dependencies or execute the program in a "clean" DLL-free environment for testing to prevent these oops situations?

In the NDepend Project Properties panel, you can define what application assemblies to analyze (in green) and NDepend will infer Third-Party assemblies used by application ones (in blue). A list of directories where to search application and third-party assemblies is provided.

NDepend Project Properties Application and Third-Party assemblies

If a third-party assembly is not found in these directories, it will be in error mode. For example, if I remove the .NET Fx directory C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319, I can see that .NET Fx third-party assemblies are not resolved:

NDepend Project Properties Application and Third-Party assemblies not resolved

Disclaimer: I work for NDepend

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

In my opinion the easiest and fastest way to get a Google Drive file ID is from Google Drive on the web. Right-click the file name and select Get shareable link. The last part of the link is the file ID. Then you can cancel the sharing.

How to get value in the session in jQuery

Assuming you are using this plugin, you are misusing the .set method. .set must be passed the name of the key as a string as well as the value. I suppose you meant to write:

$.session.set("userName", $("#uname").val());

This sets the userName key in session storage to the value of the input, and allows you to retrieve it using:

$.session.get('userName');

How to center div vertically inside of absolutely positioned parent div

You can do it by using display:table; in parent div and display: table-cell; vertical-align: middle; in child div

_x000D_
_x000D_
<div style="display:table;">_x000D_
      <div style="text-align: left;  height: 56px;  background-color: pink; display: table-cell; vertical-align: middle;">_x000D_
          <div style="background-color: lightblue; ">test</div>_x000D_
      </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

Check orientation on Android phone

It's also worth noting that nowadays, there's less good reason to check for explicit orientation with getResources().getConfiguration().orientation if you're doing so for layout reasons, as Multi-Window Support introduced in Android 7 / API 24+ could mess with your layouts quite a bit in either orientation. Better to consider using <ConstraintLayout>, and alternative layouts dependent on available width or height, along with other tricks for determining which layout is being used, e.g. the presence or not of certain Fragments being attached to your Activity.

Ignore duplicates when producing map using streams

Assuming you have people is List of object

  Map<String, String> phoneBook=people.stream()
                                        .collect(toMap(Person::getName, Person::getAddress));

Now you need two steps :

1)

people =removeDuplicate(people);

2)

Map<String, String> phoneBook=people.stream()
                                        .collect(toMap(Person::getName, Person::getAddress));

Here is method to remove duplicate

public static List removeDuplicate(Collection<Person>  list) {
        if(list ==null || list.isEmpty()){
            return null;
        }

        Object removedDuplicateList =
                list.stream()
                     .distinct()
                     .collect(Collectors.toList());
     return (List) removedDuplicateList;

      }

Adding full example here

 package com.example.khan.vaquar;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class RemovedDuplicate {

    public static void main(String[] args) {
        Person vaquar = new Person(1, "Vaquar", "Khan");
        Person zidan = new Person(2, "Zidan", "Khan");
        Person zerina = new Person(3, "Zerina", "Khan");

        // Add some random persons
        Collection<Person> duplicateList = Arrays.asList(vaquar, zidan, zerina, vaquar, zidan, vaquar);

        //
        System.out.println("Before removed duplicate list" + duplicateList);
        //
        Collection<Person> nonDuplicateList = removeDuplicate(duplicateList);
        //
        System.out.println("");
        System.out.println("After removed duplicate list" + nonDuplicateList);
        ;

        // 1) solution Working code
        Map<Object, Object> k = nonDuplicateList.stream().distinct()
                .collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
        System.out.println("");
        System.out.println("Result 1 using method_______________________________________________");
        System.out.println("k" + k);
        System.out.println("_____________________________________________________________________");

        // 2) solution using inline distinct()
        Map<Object, Object> k1 = duplicateList.stream().distinct()
                .collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
        System.out.println("");
        System.out.println("Result 2 using inline_______________________________________________");
        System.out.println("k1" + k1);
        System.out.println("_____________________________________________________________________");

        //breacking code
        System.out.println("");
        System.out.println("Throwing exception _______________________________________________");
        Map<Object, Object> k2 = duplicateList.stream()
                .collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
        System.out.println("");
        System.out.println("k2" + k2);
        System.out.println("_____________________________________________________________________");
    }

    public static List removeDuplicate(Collection<Person> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }

        Object removedDuplicateList = list.stream().distinct().collect(Collectors.toList());
        return (List) removedDuplicateList;

    }

}

// Model class
class Person {
    public Person(Integer id, String fname, String lname) {
        super();
        this.id = id;
        this.fname = fname;
        this.lname = lname;
    }

    private Integer id;
    private String fname;
    private String lname;

    // Getters and Setters

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", fname=" + fname + ", lname=" + lname + "]";
    }

}

Results :

Before removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan]]

After removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan]]

Result 1 using method_______________________________________________
k{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________

Result 2 using inline_______________________________________________
k1{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________

Throwing exception _______________________________________________
Exception in thread "main" java.lang.IllegalStateException: Duplicate key Person [id=1, fname=Vaquar, lname=Khan]
    at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
    at java.util.HashMap.merge(HashMap.java:1253)
    at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
    at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at com.example.khan.vaquar.RemovedDuplicate.main(RemovedDuplicate.java:48)

Regular expression for first and last name

As macek said:

Don't forget about names like:

Mathias d'Arras

Martin Luther King, Jr.

Hector Sausage-Hausen

and to remove cases like:

..Mathias

Martin king, Jr.-

This will cover more cases:

^([a-z]+[,.]?[ ]?|[a-z]+['-]?)+$

Vertically align text within input field of fixed-height without display: table or padding?

In Opera 9.62, Mozilla 3.0.4, Safari 3.2 (for Windows) it helps, if you put some text or at least a whitespace within the same line as the input field.

<div style="line-height: 60px; height: 60px; border: 1px solid black;">
    <input type="text" value="foo" />&nbsp;
</div>

(imagine an &nbsp after the input-statement)

IE 7 ignores every CSS hack I tried. I would recommend using padding for IE only. Should make it easier for you to position it correctly if it only has to work within one specific browser.

MySQL Database won't start in XAMPP Manager-osx

Try running these two commands in the terminal:

  1. sudo killall mysqld sudo
  2. /Applications/XAMPP/xamppfiles/bin/mysql.server start

Eclipse "this compilation unit is not on the build path of a java project"

This is what was missing in my .project file:

    <projectDescription>
        ...
        <buildSpec>
            <buildCommand>
                <name>org.eclipse.jdt.core.javabuilder</name>
                <arguments>
                </arguments>
            </buildCommand>
        </buildspec>
        ...
        ...
        ...
        <natures>
            <nature>org.eclipse.jdt.core.javanature</nature>
            <nature>org.eclipse.m2e.core.maven2Nature</nature>
        </natures>
        ...
    </projectDescription>

SQL providerName in web.config

 WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;

Apache default VirtualHost

I found the answer: I remembered that Apache uses the first block if no other matching block is found, so I've added a block without a serveralias at the top of the blocks:

NameVirtualHost *

<VirtualHost *>
    DocumentRoot /defaultdir/
</VirtualHost>

<VirtualHost *>
    ServerAdmin [email protected]
    DocumentRoot /someOtherDir/
    ServerAlias ip.of.the.server
</VirtualHost>

<VirtualHost *>
    ServerAdmin [email protected]
    DocumentRoot /someroot/
    ServerAlias domain.com *.domain.com
</VirtualHost>

Can I set an unlimited length for maxJsonLength in web.config?

use lib\Newtonsoft.Json.dll

public string serializeObj(dynamic json) {        
    return JsonConvert.SerializeObject(json);
}

Comment out HTML and PHP together

The <!-- --> is only for HTML commenting and the PHP will still run anyway...

Therefore the best thing I would do is also to comment out the PHP...

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

To minimize the chance of permissions errors, you can configure npm to use a different directory. In this example, you will create and use a hidden directory in your home directory.

Back up your computer. On the command line, in your home directory, create a directory for global installations:

mkdir ~/.npm-global

Configure npm to use the new directory path:

npm config set prefix '~/.npm-global'

In your preferred text editor, open or create a

~/.profile

file and add this line:

export PATH=~/.npm-global/bin:$PATH

On the command line, update your system variables:

source ~/.profile

To test your new configuration, install a package globally without using sudo

Stopping a JavaScript function when a certain condition is met

The return statement exits a function from anywhere within the function:

function something(x)
{
    if (x >= 10)
        // this leaves the function if x is at least 10.
        return;

    // this message displays only if x is less than 10.
    alert ("x is less than 10!");
}

Why is using the JavaScript eval function a bad idea?

Two points come to mind:

  1. Security (but as long as you generate the string to be evaluated yourself, this might be a non-issue)

  2. Performance: until the code to be executed is unknown, it cannot be optimized. (about javascript and performance, certainly Steve Yegge's presentation)

Two Decimal places using c#

I use

decimal Debitvalue = 1156.547m;
decimal DEBITAMT = Convert.ToDecimal(string.Format("{0:F2}", Debitvalue));

How to always show the vertical scrollbar in a browser?

Tried to do the solution with:

body {
  overflow-y: scroll;
}

But I ended up with two scrollbars in Firefox in this case. So I recommend to use it on the html element like this:

html {
  overflow-y: scroll;
}

Why does foo = filter(...) return a <filter object>, not a list?

From the documentation

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)]

In python3, rather than returning a list; filter, map return an iterable. Your attempt should work on python2 but not in python3

Clearly, you are getting a filter object, make it a list.

shesaid = list(filter(greetings(), ["hello", "goodbye"]))

Pass array to where in Codeigniter Active Record

Use where_in()

$ids = array('20', '15', '22', '46', '86');
$this->db->where_in('id', $ids );

Float a div right, without impacting on design

Try setting its position to absolute. That takes it out of the flow of the document.

python and sys.argv

BTW you can pass the error message directly to sys.exit:

if len(sys.argv) < 2:
    sys.exit('Usage: %s database-name' % sys.argv[0])

if not os.path.exists(sys.argv[1]):
    sys.exit('ERROR: Database %s was not found!' % sys.argv[1])

Enable PHP Apache2

You have two ways to enable it.

First, you can set the absolute path of the php module file in your httpd.conf file like this:

LoadModule php5_module /path/to/mods-available/libphp5.so

Second, you can link the module file to the mods-enabled directory:

ln -s /path/to/mods-available/libphp5.so /path/to/mods-enabled/libphp5.so

What is cardinality in Databases?

It depends a bit on context. Cardinality means the number of something but it gets used in a variety of contexts.

  • When you're building a data model, cardinality often refers to the number of rows in table A that relate to table B. That is, are there 1 row in B for every row in A (1:1), are there N rows in B for every row in A (1:N), are there M rows in B for every N rows in A (N:M), etc.
  • When you are looking at things like whether it would be more efficient to use a b*-tree index or a bitmap index or how selective a predicate is, cardinality refers to the number of distinct values in a particular column. If you have a PERSON table, for example, GENDER is likely to be a very low cardinality column (there are probably only two values in GENDER) while PERSON_ID is likely to be a very high cardinality column (every row will have a different value).
  • When you are looking at query plans, cardinality refers to the number of rows that are expected to be returned from a particular operation.

There are probably other situations where people talk about cardinality using a different context and mean something else.

Rails: How can I set default values in ActiveRecord?

This is what constructors are for! Override the model's initialize method.

Use the after_initialize method.

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous ftp logins are usually the username 'anonymous' with the user's email address as the password. Some servers parse the password to ensure it looks like an email address.

User:  anonymous
Password:  [email protected]

How do I finish the merge after resolving my merge conflicts?

Steps to resolve conflict:

  1. First 'checkout' to your branch in which you want to merge from the other branch(BRANCH_NAME_TO_BE_MERGED)

"git checkout "MAIN_BRANCH"
  1. Then merge it with "MAIN_BRANCH" by using command:

"git merge origin/BRANCH_NAME_TO_BE_MERGED"


Auto-merging src/file1.py
CONFLICT (content): Merge conflict in src/file1.py
Auto-merging src/services/docker/filexyz.py
Auto-merging src/cache.py
Auto-merging src/props.py
CONFLICT (content): Merge conflict in src/props.py
Auto-merging src/app.py
CONFLICT (content): Merge conflict in src/app.py
Auto-merging file3
CONFLICT (content): Merge conflict in file3
Automatic merge failed; fix conflicts and then commit the result.

Now you can see it is showing "CONFLICT (content)", to those file which is having "CONFLICT", see your code and resolve them

  1. run "git status" => It will show you what are the files that you need to add (which you have resolved):

 Unmerged paths:
      (use "git add <file>..." to mark resolution)

        both modified:   file3
        both modified:   src/app.py
        both modified:   src/props.py
        both modified:   src/utils/file1.py
  1. Once you have resolved all conflict, add each file one by one by using below git command

git add file3
git add src/app.py
git add src/props.py
git add src/utils/file1.py
  1. "git commit" (add some message when you are going to commit, if not then it will open vi or vim editor where you need to press "esc:q!" then press "enter")
  2. run again "git status"

 On branch MAIN_BRANCH
  Your branch is ahead of 'origin/MAIN_BRANCH' by 10 commits.
  (use "git push" to publish your local commits)

7."git push"

How to load images dynamically (or lazily) when users scrolls them into view

This Link work for me demo

1.Load the jQuery loadScroll plugin after jQuery library, but before the closing body tag.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><script src="jQuery.loadScroll.js"></script>

2.Add the images into your webpage using Html5 data-src attribute. You can also insert placeholders using the regular img's src attribute.

<img data-src="1.jpg" src="Placeholder.jpg" alt="Image Alt"><img data-src="2.jpg" src="Placeholder.jpg" alt="Image Alt"><img data-src="3.jpg" src="Placeholder.jpg" alt="Image Alt">

3.Call the plugin on the img tags and specify the duration of the fadeIn effect as your images are come into view

$('img').loadScroll(500); // in ms

How to set DataGrid's row Background, based on a property value using data bindings

In XAML, add and define a RowStyle Property for the DataGrid with a goal to set the Background of the Row, to the Color defined in my Employee Object.

<DataGrid AutoGenerateColumns="False" ItemsSource="EmployeeList">
   <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
             <Setter Property="Background" Value="{Binding ColorSet}"/>
        </Style>
   </DataGrid.RowStyle>

And in my Employee Class

public class Employee {

    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public string ColorSet { get; set; }

    public Employee() { }

    public Employee(int id, string name, int age)
    {
        Id = id;
        Name = name;
        Age = age;
        if (Age > 50)
        {
            ColorSet = "Green";
        }
        else if (Age > 100)
        {
            ColorSet = "Red";
        }
        else
        {
            ColorSet = "White";
        }
    }
}

This way every Row of the DataGrid has the BackGround Color of the ColorSet Property of my Object.

"cannot resolve symbol R" in Android Studio

In an Instant App activity of a non-base feature you can call R.id.fromFeatureOne and R.is.fromFeatureTwo. So items from different resources are referred as of a single resource origin.

Both will be highlighted as acceptable and you can even jump to source. But build will result in an error: "cannot find symbol R.id" which is quite tricky to find the reason, as nothing is highlighted.

The solution is to call com.example.feature.one.R.is.fromFeatureOne and com.example.feature.two.R.is.fromFeatureTwo.

Also issued a bug at Google: https://issuetracker.google.com/u/0/issues/77537714

What's the effect of adding 'return false' to a click event listener?

using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute.

In other words, adding return false stops the href from working. In your example, this is exactly what you want.

In buttons, it's not necessary because onclick is all it will ever execute -- there is no href to process and go to.

Get all rows from SQLite

public List<String> getAllData(String email)
{

    db = this.getReadableDatabase();
    String[] projection={email};

    List<String> list=new ArrayList<>();

    Cursor cursor = db.query(TABLE_USER, //Table to query
            null,    //columns to return
            "user_email=?",        //columns for the WHERE clause
            projection,        //The values for the WHERE clause
            null,       //group the rows
            null,       //filter by row groups
            null);
    //  cursor.moveToFirst();

    if (cursor.moveToFirst()) {
        do {

            list.add(cursor.getString(cursor.getColumnIndex("user_id")));
            list.add(cursor.getString(cursor.getColumnIndex("user_name")));
            list.add(cursor.getString(cursor.getColumnIndex("user_email")));
            list.add(cursor.getString(cursor.getColumnIndex("user_password")));
            // cursor.moveToNext();

        } while (cursor.moveToNext());
    }
    return list;
}

Char array to hex string C++

Code snippet above provides incorrect byte order in string, so I fixed it a bit.

char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',   'B','C','D','E','F'};

std::string byte_2_str(char* bytes, int size) {
  std::string str;
  for (int i = 0; i < size; ++i) {
    const char ch = bytes[i];
    str.append(&hex[(ch  & 0xF0) >> 4], 1);
    str.append(&hex[ch & 0xF], 1);
  }
  return str;
}

How to get absolute path to file in /resources folder of your project

There are two problems on our way to the absolute path:

  1. The placement found will be not where the source files lie, but where the class is saved. And the resource folder almost surely will lie somewhere in the source folder of the project.
  2. The same functions for retrieving the resource work differently if the class runs in a plugin or in a package directly in the workspace.

The following code will give us all useful paths:

    URL localPackage = this.getClass().getResource("");
    URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
    String localDir = localPackage.getPath();
    String loaderDir = urlLoader.getPath();
    System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);

Here both functions that can be used for localization of the resource folder are researched. As for class, it can be got in either way, statically or dynamically.


If the project is not in the plugin, the code if run in JUnit, will print:

loaderDir = /C:.../ws/source.dir/target/test-classes/
 localDir = /C:.../ws/source.dir/target/test-classes/package/

So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName), for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.


If the class is in the package that is in the plugin, the output of the same test will be:

loaderDir = /C:.../ws/plugin/bin/
 localDir = /C:.../ws/plugin/bin/package/

So, again we should go up and down the folder tree.


The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:

loaderDir = /C:.../ws/plugin/
 localDir = /package/

Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src or src/test/resource here.

You can insert the code into yours and see the paths that you have.

What is the difference between Tomcat, JBoss and Glassfish?

Both JBoss and Tomcat are Java servlet application servers, but JBoss is a whole lot more. The substantial difference between the two is that JBoss provides a full Java Enterprise Edition (Java EE) stack, including Enterprise JavaBeans and many other technologies that are useful for developers working on enterprise Java applications.

Tomcat is much more limited. One way to think of it is that JBoss is a Java EE stack that includes a servlet container and web server, whereas Tomcat, for the most part, is a servlet container and web server.

How to write an inline IF statement in JavaScript?

FYI, you can compose conditional operators

var a = (truthy) ? 1 : (falsy) ? 2 : 3;

If your logic is sufficiently complex, then you might consider using an IIFE

var a = (function () {
  if (truthy) return 1;
  else if (falsy) return 2;
  return 3;
})();

Of course, if you plan to use this logic more than once, then you aught to encapsulate it in a function to keep things nice and DRY.

pip install mysql-python fails with EnvironmentError: mysql_config not found

If you are on MAC Install this globally

brew install mysql

then export path like this

export PATH=$PATH:/usr/local/mysql/bin

Than globally or in your venv whatever you like

pip install MySQL-Python

Note: globally for python3 as Mac can have both python2 & 3

pip3 install MySQL-Python

How do I delete multiple rows with different IDs?

Disclaim: the following suggestion could be an overhead depending on the situation. The function is only tested with MSSQL 2008 R2 but seams be compatible to other versions

if you wane do this with many Id's you may could use a function which creates a temp table where you will be able to DELETE FROM the selection

how the query could look like:

-- not tested
-- @ids will contain a varchar with your ids e.g.'9 12 27 37'
DELETE FROM table WHERE id IN (SELECT i.number FROM iter_intlist_to_tbl(@ids))

here is the function:

ALTER FUNCTION iter_intlist_to_tbl (@list nvarchar(MAX))
   RETURNS @tbl TABLE (listpos int IDENTITY(1, 1) NOT NULL,
                       number  int NOT NULL) AS

   -- funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
   -- dient zum übergeben einer liste von elementen

BEGIN
    -- Deklaration der Variablen
    DECLARE @startpos int,
            @endpos   int,
            @textpos  int,
            @chunklen smallint,
            @str      nvarchar(4000),
            @tmpstr   nvarchar(4000),
            @leftover nvarchar(4000)

    -- Startwerte festlegen
   SET @textpos = 1
   SET @leftover = ''

   -- Loop 1
    WHILE @textpos <= datalength(@list) / 2
    BEGIN

        --
        SET @chunklen = 4000 - datalength(@leftover) / 2 --datalength() gibt die anzahl der bytes zurück (mit Leerzeichen)

        --
        SET @tmpstr = ltrim(@leftover + substring(@list, @textpos, @chunklen))--SUBSTRING ( @string ,start , length ) | ltrim(@string) abschneiden aller Leerzeichen am Begin des Strings

        --hochzählen der TestPosition
        SET @textpos = @textpos + @chunklen

        --start position 0 setzen
        SET @startpos = 0

        -- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
        SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr)--charindex(searchChar,Wo,Startposition)

        -- Loop 2
        WHILE @endpos > 0
        BEGIN
            --str ist der string welcher zwischen den [LEERZEICHEN] steht
            SET @str = substring(@tmpstr, @startpos + 1, @endpos - @startpos - 1) 

            --wenn @str nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
            IF @str <> ''
                INSERT @tbl (number) VALUES(convert(int, @str))-- convert(Ziel-Type,Value)

            -- start wird auf das letzte bekannte end gesetzt
            SET @startpos = @endpos

            -- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
            SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr, @startpos + 1)
        END
        -- Loop 2

        -- dient dafür den letzten teil des strings zu selektieren
        SET @leftover = right(@tmpstr, datalength(@tmpstr) / 2 - @startpos)--right(@string,anzahl der Zeichen) bsp.: right("abcdef",3) => "def"
    END
    -- Loop 1

    --wenn @leftover nach dem entfernen aller [LEERZEICHEN] nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
    IF ltrim(rtrim(@leftover)) <> ''
        INSERT @tbl (number) VALUES(convert(int, @leftover))

    RETURN
END


    -- ############################ WICHTIG ############################
    -- das is ein Beispiel wie man die Funktion benutzt
    --
    --CREATE    PROCEDURE get_product_names_iter 
    --      @ids varchar(50) AS
    --SELECT    P.ProductName, P.ProductID
    --FROM      Northwind.Products P
    --JOIN      iter_intlist_to_tbl(@ids) i ON P.ProductID = i.number
    --go
    --EXEC get_product_names_iter '9 12 27 37'
    --
    -- Funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
    -- dient zum übergeben einer Liste von Id's
    -- ############################ WICHTIG ############################

Client on Node.js: Uncaught ReferenceError: require is not defined

This is because require() does not exist in the browser/client-side JavaScript.

Now you're going to have to make some choices about your client-side JavaScript script management.

You have three options:

  1. Use the <script> tag.
  2. Use a CommonJS implementation. It has synchronous dependencies like Node.js
  3. Use an asynchronous module definition (AMD) implementation.

CommonJS client side-implementations include (most of them require a build step before you deploy):

  1. Browserify - You can use most Node.js modules in the browser. This is my personal favorite.
  2. Webpack - Does everything (bundles JavaScript code, CSS, etc.). It was made popular by the surge of React, but it is notorious for its difficult learning curve.
  3. Rollup - a new contender. It leverages ES6 modules and includes tree-shaking abilities (removes unused code).

You can read more about my comparison of Browserify vs (deprecated) Component.

AMD implementations include:

  1. RequireJS - Very popular amongst client-side JavaScript developers. It is not my taste because of its asynchronous nature.

Note, in your search for choosing which one to go with, you'll read about Bower. Bower is only for package dependencies and is unopinionated on module definitions like CommonJS and AMD.

adding multiple entries to a HashMap at once in one statement

    boolean x;
    for (x = false, 
        map.put("One", new Integer(1)), 
        map.put("Two", new Integer(2)),      
        map.put("Three", new Integer(3)); x;);

Ignoring the declaration of x (which is necessary to avoid an "unreachable statement" diagnostic), technically it's only one statement.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I solved this issue by doing the following:

When using ECMAScript 6 modules from the browser, use the .js extension in your files and in the script tag add type = "module".

When using ECMAScript 6 modules from a Node.js environment, use the extension .mjs in your files and use this command to run the file:

node --experimental-modules filename.mjs

How to run Java program in terminal with external library JAR

For compiling the java file having dependency on a jar

javac -cp path_of_the_jar/jarName.jar className.java

For executing the class file

java -cp .;path_of_the_jar/jarName.jar className

T-SQL How to create tables dynamically in stored procedures?

This is a way to create tables dynamically using T-SQL stored procedures:

declare @cmd nvarchar(1000), @MyTableName nvarchar(100);
set @MyTableName = 'CustomerDetails';
set @cmd = 'CREATE TABLE dbo.' + quotename(@MyTableName, '[') + '(ColumnName1 int not null,ColumnName2 int not null);';

Execute it as:

exec(@cmd);

What's the difference between HEAD^ and HEAD~ in Git?

^ BRANCH Selector
git checkout HEAD^2
Selects the 2nd branch of a (merge) commit by moving onto the selected branch (one step backwards on the commit-tree)

~ COMMIT Selector
git checkout HEAD~2
Moves 2 commits backwards on the default/selected branch


Defining both ~ and ^ relative refs as PARENT selectors is far the dominant definition published everywhere on the internet I have come across so far - including the official Git Book. Yes they are PARENT selectors, but the problem with this "explanation" is that it is completely against our goal: which is how to distinguish the two... :)

The other problem is when we are encouraged to use the ^ BRANCH selector for COMMIT selection (aka HEAD^ === HEAD~).
Again, yes, you can use it this way, but this is not its designed purpose. The ^ BRANCH selector's backwards move behaviour is a side effect not its purpose.

At merged commits only, can a number be assigned to the ^ BRANCH selector. Thus its full capacity can only be utilised where there is a need for selecting among branches. And the most straightforward way to express a selection in a fork is by stepping onto the selected path / branch - that's for the one step backwards on the commit-tree. It is a side effect only, not its main purpose.

Download a div in a HTML page as pdf using javascript

Content inside a <div class='html-content'>....</div> can be downloaded as pdf with styles using jspdf & html2canvas.

You need to refer both js libraries,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

Then call below function,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}

Ref: pdf genration from html canvas and jspdf.

May be this will help someone.

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

I have a case where I am transforming a legacy DB2 z/os database timestamp (formatted as: "yyyy-MM-dd'T'HH:mm:ss.SSSZ") into a SqlServer 2016 datetime2 (formatted as: "yyyy-MM-dd HH:mm:ss.SSS) field that is handled by our Spring/Hibernate Entity Manager instance (in this case, the OldRevision Table). In the Class, I define the date as the java.util type, and write the setter and getter in the normal way. Then, When handling the data, the code I have handling the data related to this question looks like this:

OldRevision revision = new OldRevision();
String oldRevisionDateString= oldRevisionData.getString("originalRevisionDate", "");
Date oldDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
oldDateFormat.parse(oldRevisionDateString);
SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
Date finalFormattedDate= newDateFormat.parse(newDateFormat.format(oldDateFormat));
revision.setOriginalRevisionDate(finalFormattedDate);
em.persist(revision);

A simpler way to do the same case is:

SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
revision.setOriginalRevisionDate(
        newDateFormat.parse(newDateFormat.format(
                new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ")
                        .parse(rs.getString("originalRevisionDate", "")))));

Find where python is installed (if it isn't default dir)

  1. First search for PYTHON IDLE from search bar
  2. Open the IDLE and use below commands.

    import sys print(sys.path)

  3. It will give you the path where the python.exe is installed. For eg: C:\Users\\...\python.exe

  4. Add the same path to system environment variable.

How to avoid reverse engineering of an APK file?

 1. How can I completely avoid reverse engineering of an Android APK? Is this possible?

That is impossible

 2. How can I protect all the app's resources, assets and source code so that hackers can't hack the APK file in any way?

Developers can take steps such as using tools like ProGuard to obfuscate their code, but up until now, it has been quite difficult to completely prevent someone from decompiling an app.

It's a really great tool and can increase the difficulty of 'reversing' your code whilst shrinking your code's footprint.

Integrated ProGuard support: ProGuard is now packaged with the SDK Tools. Developers can now obfuscate their code as an integrated part of a release build.

 3. Is there a way to make hacking more tough or even impossible? What more can I do to protect the source code in my APK file?

While researching, I came to know about HoseDex2Jar. This tool will protect your code from decompiling, but it seems not to be possible to protect your code completely.

Some of helpful links, you can refer to them.

Syntax for async arrow function

My async function

const getAllRedis = async (key) => {
  let obj = [];

  await client.hgetall(key, (err, object) => {
    console.log(object);
    _.map(object, (ob)=>{
      obj.push(JSON.parse(ob));
    })
    return obj;
    // res.send(obj);
});
}

C - freeing structs

You can't free types that aren't dynamically allocated. Although arrays are syntactically similar (int* x = malloc(sizeof(int) * 4) can be used in the same way that int x[4] is), calling free(firstName) would likely cause an error for the latter.

For example, take this code:

int x;
free(&x);

free() is a function which takes in a pointer. &x is a pointer. This code may compile, even though it simply won't work.

If we pretend that all memory is allocated in the same way, x is "allocated" at the definition, "freed" at the second line, and then "freed" again after the end of the scope. You can't free the same resource twice; it'll give you an error.

This isn't even mentioning the fact that for certain reasons, you may be unable to free the memory at x without closing the program.

tl;dr: Just free the struct and you'll be fine. Don't call free on arrays; only call it on dynamically allocated memory.

Using global variables between files?

Hai Vu answer works great, just one comment:

In case you are using the global in other module and you want to set the global dynamically, pay attention to import the other modules after you set the global variables, for example:

# settings.py
def init(arg):
    global myList
    myList = []
    mylist.append(arg)


# subfile.py
import settings

def print():
    settings.myList[0]


# main.py
import settings
settings.init("1st")     # global init before used in other imported modules
                         # Or else they will be undefined

import subfile    
subfile.print()          # global usage

$ is not a function - jQuery error

It's really hard to tell, but one of the 9001 ads on the page may be clobbering the $ object.

jQuery provides the global jQuery object (which is present on your page). You can do the following to "get" $ back:

jQuery(document).ready(function ($) {
    // Your code here
});

If you think you're having jQuery problems, please use the debug (non-production) versions of the library.

Also, it's probably not best to be editing a live site like that ...

How to concatenate strings with padding in sqlite

SQLite has a printf function which does exactly that:

SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable

Twitter Bootstrap add active class to li

To activate the menus and submenus, even with params in the URL, use the code bellow:

// Highlight the active menu
$(document).ready(function () {
    var action = window.location.pathname.split('/')[1];

    // If there's no action, highlight the first menu item
    if (action == "") {
        $('ul.nav li:first').addClass('active');
    } else {
        // Highlight current menu
        $('ul.nav a[href="/' + action + '"]').parent().addClass('active');

        // Highlight parent menu item
        $('ul.nav a[href="/' + action + '"]').parents('li').addClass('active');
    }
});

This accepts URLs like:

/posts
/posts/1
/posts/1/edit

What is the use of ObservableCollection in .net?

class FooObservableCollection : ObservableCollection<Foo>
{
    protected override void InsertItem(int index, Foo item)
    {
        base.Add(index, Foo);

        if (this.CollectionChanged != null)
            this.CollectionChanged(this, new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Add, item, index);
    }
}

var collection = new FooObservableCollection();
collection.CollectionChanged += CollectionChanged;

collection.Add(new Foo());

void CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
{
    Foo newItem = e.NewItems.OfType<Foo>().First();
}

window.print() not working in IE

Add newWin.document.close();, like so:

function printDiv() {
   var divToPrint = document.getElementById('printArea');
   var newWin = window.open();
   newWin.document.write(divToPrint.innerHTML);
   newWin.document.close();
   newWin.print();
   newWin.close();
}

This makes IE happy. HTH, -Ted

Get first date of current month in java

import java.util.Date;
import java.text.SimpleDateFormat;

...
Date currentMonth = new Date();
String yyyyMM = new SimpleDateFormat("yyyyMM").format(currentMonth);
Date firstDateOfMonth = new SimpleDateFormat("yyyyMM").parse(yyyyMM);
...

my stupid solution. but it's work for me :D

Java Initialize an int array in a constructor

The best way is not to write any initializing statements. This is because if you write int a[]=new int[3] then by default, in Java all the values of array i.e. a[0], a[1] and a[2] are initialized to 0! Regarding the local variable hiding a field, post your entire code for us to come to conclusion.

Telling Python to save a .txt file to a certain directory on Windows and Mac

If you want to save a file to a particular DIRECTORY and FILENAME here is some simple example. It also checks to see if the directory has or has not been created.

import os.path
directory = './html/'
filename = "file.html"
file_path = os.path.join(directory, filename)
if not os.path.isdir(directory):
    os.mkdir(directory)
file = open(file_path, "w")
file.write(html)
file.close()

Hope this helps you!

Docker remove <none> TAG images

The dangling images are ghosts from the previous builds and pulls, simply delete them with : docker rmi $(docker images -f "dangling=true" -q)

Get HTML code from website in C#

Best thing to use is HTMLAgilityPack. You can also look into using Fizzler or CSQuery depending on your needs for selecting the elements from the retrieved page. Using LINQ or Regukar Expressions is just to error prone, especially when the HTML can be malformed, missing closing tags, have nested child elements etc.

You need to stream the page into an HtmlDocument object and then select your required element.

// Call the page and get the generated HTML
var doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlNode.ElementsFlags["br"] = HtmlAgilityPack.HtmlElementFlag.Empty;
doc.OptionWriteEmptyNodes = true;

try
{
    var webRequest = HttpWebRequest.Create(pageUrl);
    Stream stream = webRequest.GetResponse().GetResponseStream();
    doc.Load(stream);
    stream.Close();
}
catch (System.UriFormatException uex)
{
    Log.Fatal("There was an error in the format of the url: " + itemUrl, uex);
    throw;
}
catch (System.Net.WebException wex)
{
    Log.Fatal("There was an error connecting to the url: " + itemUrl, wex);
    throw;
}

//get the div by id and then get the inner text 
string testDivSelector = "//div[@id='test']";
var divString = doc.DocumentNode.SelectSingleNode(testDivSelector).InnerHtml.ToString();

[EDIT] Actually, scrap that. The simplest method is to use FizzlerEx, an updated jQuery/CSS3-selectors implementation of the original Fizzler project.

Code sample directly from their site:

using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;

//get the page
var web = new HtmlWeb();
var document = web.Load("http://example.com/page.html");
var page = document.DocumentNode;

//loop through all div tags with item css class
foreach(var item in page.QuerySelectorAll("div.item"))
{
    var title = item.QuerySelector("h3:not(.share)").InnerText;
    var date = DateTime.Parse(item.QuerySelector("span:eq(2)").InnerText);
    var description = item.QuerySelector("span:has(b)").InnerHtml;
}

I don't think it can get any simpler than that.

Losing scope when using ng-include

This is because of ng-include which creates a new child scope, so $scope.lineText isn’t changed. I think that this refers to the current scope, so this.lineText should be set.

How do I sort a table in Excel if it has cell references in it?

create two tabs, one with the formulas and then a second where you paste link the entire table. the second tab should have no problems when sorting!

state machines tutorials

There is a lot of lesson to learn handcrafting state machines in C, but let me also suggest Ragel state machine compiler:

http://www.complang.org/ragel/

It has quite simple way of defining state machines and then you can generate graphs, generate code in different styles (table-driven, goto-driven), analyze that code if you want to, etc. And it's powerful, can be used in production code for various protocols.

How do I call a Django function on button click?

The following answer could be helpful for the first part of your question:

Django: How can I call a view function from template?

Conversion failed when converting the varchar value to data type int in sql

I got the same error message. In my case, it was due to not using quotes.

Although the column was supposed to have only numbers, it was a Varchar column, and one of the rows had a letter in it.

So I was doing this:

select * from mytable where myid = 1234

While I should be doing this:

select * from mytable where myid = '1234'

If the column had all numbers, the conversion would have worked, but not in this case.

How do I convert an existing callback API to promises?

From the future

A simple generic function I normally use.

const promisify = (fn, ...args) => {
  return new Promise((resolve, reject) => {
    fn(...args, (err, data) => {
      if (err) {
        return reject(err);
      }
      resolve(data);
    });
  });
};

How to use it

   promisify(fn, arg1, arg2)

You are probably not looking to this answer, but this will help understand the inner workings of the available utils

SQL Switch/Case in 'where' clause

declare @locationType varchar(50);
declare @locationID int;

SELECT column1, column2
FROM viewWhatever
WHERE
@locationID = 
  CASE @locationType
      WHEN 'location' THEN account_location
      WHEN 'area' THEN xxx_location_area 
      WHEN 'division' THEN xxx_location_division 
  END

How to set upload_max_filesize in .htaccess?

If you are getting 500 - Internal server error that means you don't have permission to set these values by .htaccess. You have to contact your web server providers and ask to set AllowOverride Options for your host or to put these lines in their virtual host configuration file.

Calculating number of full months between two dates in SQL

select case when DATEPART(D,End_dATE) >=DATEPART(D,sTAR_dATE) 
THEN ( case when DATEPART(M,End_dATE) = DATEPART(M,sTAR_dATE) AND DATEPART(YYYY,End_dATE) = DATEPART(YYYY,sTAR_dATE) 
        THEN 0 ELSE DATEDIFF(M,sTAR_dATE,End_dATE)END )
ELSE DATEDIFF(M,sTAR_dATE,End_dATE)-1 END

Make EditText ReadOnly

I had no problem making EditTextPreference read-only, by using:

editTextPref.setSelectable(false);

This works well when coupled with using the 'summary' field to display read-only fields (useful for displaying account info, for example). Updating the summary fields dynamically snatched from http://gmariotti.blogspot.com/2013/01/preferenceactivity-preferencefragment.html

private static final List<String> keyList;

static {
    keyList = new ArrayList<String>();
    keyList.add("field1");
    keyList.add("field2");
    keyList.add("field3");
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    for(int i=0;i<getPreferenceScreen().getPreferenceCount();i++){
        initSummary(getPreferenceScreen().getPreference(i));
    }
}

private void initSummary(Preference p) {
    if (p instanceof PreferenceCategory) {
        PreferenceCategory pCat = (PreferenceCategory) p;
        for (int i = 0; i < pCat.getPreferenceCount(); i++) {
            initSummary(pCat.getPreference(i));
        }
    } else {
        updatePrefSummary(p);
    }
}

private void updatePrefSummary(Preference p) {
    if (p instanceof ListPreference) {
        ListPreference listPref = (ListPreference) p;
        p.setSummary(listPref.getEntry());
    }
    if (p instanceof EditTextPreference) {
        EditTextPreference editTextPref = (EditTextPreference) p;
        //editTextPref.setEnabled(false); // this can be used to 'gray out' as well
        editTextPref.setSelectable(false);
        if (keyList.contains(p.getKey())) {
            p.setSummary(editTextPref.getText());
        }
    }
}

OpenCV & Python - Image too big to display

Looks like opencv lib is pretty sensitive to parameters passed to the methods. The following code worked for me using opencv 4.3.0:

win_name = "visualization"  #  1. use var to specify window name everywhere
cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)  #  2. use 'normal' flag
img = cv2.imread(filename)
h,w = img.shape[:2]  #  suits for image containing any amount of channels
h = int(h / resize_factor)  #  one must compute beforehand
w = int(w / resize_factor)  #  and convert to INT
cv2.resizeWindow(win_name, w, h)  #  use variables defined/computed BEFOREHAND
cv2.imshow(win_name, img)

How can I print using JQuery

Hey If you want to print selected area or div ,Try This.

<style type="text/css">
@media print
{
body * { visibility: hidden; }
.div2 * { visibility: visible; }
.div2 { position: absolute; top: 40px; left: 30px; }
}
</style>

Hope it helps you

How can I perform static code analysis in PHP?

I have tried using php -l and a couple of other tools.

However, the best one in my experience (your mileage may vary, of course) is scheck of pfff toolset. I heard about pfff on Quora (Is there a good PHP lint / static analysis tool?).

You can compile and install it. There are no nice packages (on my Linux Mint Debian system, I had to install the libpcre3-dev, ocaml, libcairo-dev, libgtk-3-dev and libgimp2.0-dev dependencies first) but it should be worth an install.

The results are reported like

$ ~/sw/pfff/scheck ~/code/github/sc/
login-now.php:7:4: CHECK: Unused Local variable $title
go-automatic.php:14:77: CHECK: Use of undeclared variable $goUrl.

Which Eclipse version should I use for an Android app?

I literally did this 1 hour ago.

  1. SDK R7
  2. Get Java - if you don't have (its the first image link JDK)
  3. Get Eclipse - it's the first on the list with the most downloads
  4. Android Plugin

Download the appropriate files for your OS. The Android SDK needs java in order to install. Once you get the Android SDK installed go get eclipse and install that. Basically download the file and unzip then in a directory. The android install is the same but it will install a lot more files. (5) Finally open eclipse and go to help > install new software >> and add the url to the plugin - I used this one https://dl-ssl.google.com/android/eclipse/

HTML Input - already filled in text

You seem to look for the input attribute value, "the initial value of the control"?

<input type="text" value="Morlodenhof 7" />

https://developer.mozilla.org/de/docs/Web/HTML/Element/Input#attr-value

Combine two arrays

Warning! $array1 + $array2 overwrites keys, so my solution (for multidimensional arrays) is to use array_unique()

array_unique(array_merge($a, $b), SORT_REGULAR);

Notice:

5.2.10+ Changed the default value of sort_flags back to SORT_STRING.

5.2.9 Default is SORT_REGULAR.

5.2.8- Default is SORT_STRING

It perfectly works. Hope it helps same.

Having trouble setting working directory

I just had this error message happen. When searching for why, I figured out that there's a related issue that can occur if you're not paying attention - the same error occurs if the directory you are trying to move into does not exist.

How to add leading zeros?

Here is another alternative for adding leading to 0s to strings such as CUSIPs which can sometimes look like a number and which many applications such as Excel will corrupt and remove the leading 0s or convert them to scientific notation.

When I tried the answer provided by @metasequoia the vector returned had leading spaces and not 0s. This was the same problem mentioned by @user1816679 -- and removing the quotes around the 0 or changing from %d to %s did not make a difference either. FYI, I am using RStudio Server running on an Ubuntu Server. This little two-step solution worked for me:

gsub(pattern = " ", replacement = "0", x = sprintf(fmt = "%09s", ids[,CUSIP]))

using the %>% pipe function from the magrittr package it could look like this:

sprintf(fmt = "%09s", ids[,CUSIP]) %>% gsub(pattern = " ", replacement = "0", x = .)

I'd prefer a one-function solution, but it works.

use current date as default value for a column

Table creation Syntax can be like:

Create table api_key(api_key_id INT NOT NULL IDENTITY(1,1) 
PRIMARY KEY, date_added date DEFAULT 
GetDate());

Insertion query syntax can be like:

Insert into api_key values(GETDATE());

Settings to Windows Firewall to allow Docker for Windows to share drive

Ok, so after running in the same issue, I have found a Solution.

This is what I did:


Step 1: Open ESET. Then click on Setup

click setup

Step 2: Click on Network protection

click network protection

Step 3: Click on Troubleshooting wizard

click troubleshooting wizard

Step 4: Find the Communication 10.0.75.2 (Default docker IP setting) Just check what the IP Range is defined inside your docker settings. Then look for for the IP which resides in that range.

find the connection

Step 5: Click on the Unblock button, then you should receive this screen.

click unblock

This solved the issue for myself.

You can then go to the Rules and check the rule that was added.


PS: This is my first post, sorry for any incorrect procedures.

PL/SQL print out ref cursor returned by a stored procedure

You can use a bind variable at the SQLPlus level to do this. Of course you have little control over the formatting of the output.

VAR x REFCURSOR;
EXEC GetGrantListByPI(args, :x);
PRINT x;

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Use component scanning as given below, if com.project.action.PasswordHintAction is annotated with stereotype annotations

<context:component-scan base-package="com.project.action"/>

EDIT

I see your problem, in PasswordHintActionTest you are autowiring PasswordHintAction. But you did not create bean configuration for PasswordHintAction to autowire. Add one of stereotype annotation(@Component, @Service, @Controller) to PasswordHintAction like

@Component
public class PasswordHintAction extends BaseAction {
    private static final long serialVersionUID = -4037514607101222025L;
    private String username;

or create xml configuration in applicationcontext.xml like

<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />

How to get the focused element with jQuery?

Try this:

$(":focus").each(function() {
    alert("Focused Elem_id = "+ this.id );
});

How do I use vim registers?

My friend Brian wrote a comprehensive article on this. I think it is a great intro to how to use topics. https://www.brianstorti.com/vim-registers/

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

There is also another possible source of this error. In some J2EE / web containers (in my experience under Jboss 7.x and Tomcat 7.x) You have to add each class You want to use as a hibernate Entity into the file persistence.xml as

<class>com.yourCompanyName.WhateverEntityClass</class>

In case of jboss this concerns every entity class (local - i.e. within the project You are developing or in a library). In case of Tomcat 7.x this concerns only entity classes within libraries.

(change) vs (ngModelChange) in angular

1 - (change) is bound to the HTML onchange event. The documentation about HTML onchange says the following :

Execute a JavaScript when a user changes the selected option of a <select> element

Source : https://www.w3schools.com/jsref/event_onchange.asp

2 - As stated before, (ngModelChange) is bound to the model variable binded to your input.

So, my interpretation is :

  • (change) triggers when the user changes the input
  • (ngModelChange) triggers when the model changes, whether it's consecutive to a user action or not

Sql query to insert datetime in SQL Server

You will want to use the YYYYMMDD for unambiguous date determination in SQL Server.

insert into table1(approvaldate)values('20120618 10:34:09 AM');

If you are married to the dd-mm-yy hh:mm:ss xm format, you will need to use CONVERT with the specific style.

insert into table1 (approvaldate)
       values (convert(datetime,'18-06-12 10:34:09 PM',5));

5 here is the style for Italian dates. Well, not just Italians, but that's the culture it's attributed to in Books Online.

Is it possible to cast a Stream in Java 8?

I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:

Stream.of(objects)
    .filter(c -> c instanceof Client)
    .map(c -> (Client) c)
    .map(Client::getID)
    .forEach(System.out::println);

or, as suggested in the comments, you could use the cast method - the former may be easier to read though:

Stream.of(objects)
    .filter(Client.class::isInstance)
    .map(Client.class::cast)
    .map(Client::getID)
    .forEach(System.out::println);

How to implement a Keyword Search in MySQL?

Ideally, have a keyword table containing the fields:

Keyword
Id
Count (possibly)

with an index on Keyword. Create an insert/update/delete trigger on the other table so that, when a row is changed, every keyword is extracted and put into (or replaced in) this table.

You'll also need a table of words to not count as keywords (if, and, so, but, ...).

In this way, you'll get the best speed for queries wanting to look for the keywords and you can implement (relatively easily) more complex queries such as "contains Java and RCA1802".

"LIKE" queries will work but they won't scale as well.

CSS Div width percentage and padding without breaking layout

You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.

An example:

width: calc((100%) - (32px))

Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.

_x000D_
_x000D_
.outer {_x000D_
  width: 200px;_x000D_
  height: 120px;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  height: 40px;_x000D_
  top: 30px;_x000D_
  position: relative;_x000D_
  padding: 16px;_x000D_
  background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
  width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
  <div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
  <div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between Console.Read() and Console.ReadLine()?

The basic difference is:

int i = Console.Read();
Console.WriteLine(i);

paste above code and give input 'c', and the output will be 99. That is Console.Read give int value but that value will be the ASCII value of that..

On the other side..

string s = Console.ReadLine();
Console.WriteLine(s);

It gives the string as it is given in the input stream.

"Stack overflow in line 0" on Internet Explorer

You can turn off the "Disable Script Debugging" option inside of Internet Explorer and start debugging with Visual Studio if you happen to have that around.

I've found that it is one of few ways to diagnose some of those IE specific issues.

Find a row in dataGridView based on column and value

This will give you the gridview row index for the value:

String searchValue = "somestring";
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
{
    if(row.Cells[1].Value.ToString().Equals(searchValue))
    {
        rowIndex = row.Index;
        break;
    }
}

Or a LINQ query

int rowIndex = -1;

        DataGridViewRow row = dgv.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue))
            .First();

        rowIndex = row.Index;

then you can do:

dataGridView1.Rows[rowIndex].Selected = true;

How to apply box-shadow on all four sides?

See: http://jsfiddle.net/thirtydot/cMNX2/8/

input {
    -webkit-box-shadow: 0 0 5px 2px #fff;
    -moz-box-shadow: 0 0 5px 2px #fff;
    box-shadow: 0 0 5px 2px #fff;
}

I get exception when using Thread.sleep(x) or wait()

A simpler way to wait is to use System.currentTimeMillis(), which returns the number of milliseconds since midnight on January 1, 1970 UTC. For example, to wait 5 seconds:

public static void main(String[] args) {
    //some code
    long original = System.currentTimeMillis();
    while (true) {
        if (System.currentTimeMillis - original >= 5000) {
            break;
        }
    }
    //more code after waiting
}

This way, you don't have to muck about with threads and exceptions. Hope this helps!

How to export datagridview to excel using vb.net?

A simple way of generating a printable report from a Datagridview is to place the datagridview on a Panel object. It is possible to draw a bitmap of the panel.

Here's how I do it.

'create the bitmap with the dimentions of the Panel Dim bmp As New Bitmap(Panel1.Width, Panel1.Height)

'draw the Panel to the bitmap "bmp" Panel1.DrawToBitmap(bmp, Panel1.ClientRectangle)

I create a multi page tiff by "breaking my datagridview items into pages. this is how i detect the start of a new page:

'i add the rows to my datagrid one at a time and then check if the scrollbar is active. 'if the scrollbar is active i save the row to a variable and then i remove it from the 'datagridview and roll back my counter integer by one(thus the next run will include this 'row.

Private Function VScrollBarVisible() As Boolean
    Dim ctrl As New Control
    For Each ctrl In DataGridView_Results.Controls
        If ctrl.GetType() Is GetType(VScrollBar) Then
            If ctrl.Visible = True Then
                Return True
            Else
                Return False
            End If
        End If
    Next
    Return Nothing
End Function

I hope this helps

How to check if a json key exists?

you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also

use optString instead of getString:

Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists

Returning value from called function in a shell script

A Bash function can't return a string directly like you want it to. You can do three things:

  1. Echo a string
  2. Return an exit status, which is a number, not a string
  3. Share a variable

This is also true for some other shells.

Here's how to do each of those options:

1. Echo strings

lockdir="somedir"
testlock(){
    retval=""
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval="true"
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval="false"
    fi
    echo "$retval"
}

retval=$( testlock )
if [ "$retval" == "true" ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

2. Return exit status

lockdir="somedir"
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
    return "$retval"
}

testlock
retval=$?
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

3. Share variable

lockdir="somedir"
retval=-1
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
}

testlock
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

How to `wget` a list of URLs in a text file?

try:

wget -i text_file.txt

(check man wget)

jQuery - getting custom attribute from selected option

You can also try this one as well with data-myTag

<select id="location">
    <option value="a" data-myTag="123">My option</option>
    <option value="b" data-myTag="456">My other option</option>
</select>

<input type="hidden" id="setMyTag" />

<script>
    $(function() {
        $("#location").change(function(){
           var myTag = $('option:selected', this).data("myTag");

           $('#setMyTag').val(myTag);
        });
    });
</script>

json_decode to array

This is a late contribution, but there is a valid case for casting json_decode with (array).
Consider the following:

$jsondata = '';
$arr = json_decode($jsondata, true);
foreach ($arr as $k=>$v){
    echo $v; // etc.
}

If $jsondata is ever returned as an empty string (as in my experience it often is), json_decode will return NULL, resulting in the error Warning: Invalid argument supplied for foreach() on line 3. You could add a line of if/then code or a ternary operator, but IMO it's cleaner to simply change line 2 to ...

$arr = (array) json_decode($jsondata,true);

... unless you are json_decodeing millions of large arrays at once, in which case as @TCB13 points out, performance could be negatively effected.

Visual Studio Code cannot detect installed git

Three years later, I ran into the same issue. Setting the path in user settings & PATH environment variable didn't help. I updated VSCode and that solved it.

Passing a URL with brackets to curl

I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.

For example (doing this on on mac in iTerm2):

for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done

I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:

curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala

The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.

Solution is to not use match highlighting.

How to do a SQL NOT NULL with a DateTime?

erm it does work? I've just tested it?

/****** Object:  Table [dbo].[DateTest]    Script Date: 09/26/2008 10:44:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DateTest](
    [Date1] [datetime] NULL,
    [Date2] [datetime] NOT NULL
) ON [PRIMARY]

GO
Insert into DateTest (Date1,Date2) VALUES (NULL,'1-Jan-2008')
Insert into DateTest (Date1,Date2) VALUES ('1-Jan-2008','1-Jan-2008')
Go
SELECT * FROM DateTest WHERE Date1 is not NULL
GO
SELECT * FROM DateTest WHERE Date2 is not NULL

Mac SQLite editor

MesaSQLite is the best I've found so far.

www.desertsandsoftware.com

Looks very promising indeed.

What is SaaS, PaaS and IaaS? With examples

There are three major types of cloud services: IaaS, PaaS, and SaaS. You’ve probably seen these abbreviations on the websites of cloud providers. Before going into details, let’s compare IaaS, PaaS, and SaaS to transportation:

enter image description here

  1. On-premises IT infrastructure is like owning a car. When you buy a car, you’re responsible for its maintenance, and upgrading means buying a new car.

  2. IaaS is like leasing a car. When you lease a car, you choose the car you want and drive it wherever you wish, but the car isn’t yours. Want an upgrade? Just lease a different car!

  3. PaaS is like taking a taxi. You don’t drive a taxi yourself, but simply tell the driver where you need to go and relax in the back seat.

  4. SaaS is like going by bus. Buses have assigned routes, and you share the ride with other passengers.

Reference: https://rubygarage.org/blog/iaas-vs-paas-vs-saas

Disabled UIButton not faded or grey

#import "UIButton+My.h"
#import <QuartzCore/QuartzCore.h>
@implementation UIButton (My)


-(void)fade :(BOOL)enable{
    self.enabled=enable;//
    self.alpha=enable?1.0:0.5;
}

@end

.h:

#import <UIKit/UIKit.h>
@interface UIButton (My)

-(void)fade :(BOOL)enable;

@end

Get random item from array

Use PHP Rand function

<?php
  $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
  $rand_keys = array_rand($input, 2);
  echo $input[$rand_keys[0]] . "\n";
  echo $input[$rand_keys[1]] . "\n";
?>

More Help

How To Accept a File POST

API Controller :

[HttpPost]
public HttpResponseMessage Post()
{
    var httpRequest = System.Web.HttpContext.Current.Request;

    if (System.Web.HttpContext.Current.Request.Files.Count < 1)
    {
        //TODO
    }
    else
    {

    try
    { 
        foreach (string file in httpRequest.Files)
        { 
            var postedFile = httpRequest.Files[file];
            BinaryReader binReader = new BinaryReader(postedFile.InputStream);
            byte[] byteArray = binReader.ReadBytes(postedFile.ContentLength);

        }

    }
    catch (System.Exception e)
    {
        //TODO
    }

    return Request.CreateResponse(HttpStatusCode.Created);
}

How to Call a JS function using OnClick event

Inline code takes higher precedence than the other ones. To call your other function func () call it from the f1 ().

Inside your function, add a line,

function fun () {
// Your code here
}

function f1()
    {
       alert("f1 called");
       //form validation that recalls the page showing with supplied inputs.    

fun ();

    }

Rewriting your whole code,

 <!DOCTYPE html>
    <html>
      <head>

      <script>

       function fun()
        {
         alert("hello");
         //validation code to see State field is mandatory.  
        }   

        function f1()
        {
           alert("f1 called");
           //form validation that recalls the page showing with supplied inputs.   
           fun (); 
        }

      </script>
      </head>
      <body>
       <form name="form1" id="form1" method="post">

         State: <select id="state ID">
                   <option></option>
                   <option value="ap">ap</option>
                   <option value="bp">bp</option>
                </select>
       </form>
       <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

      </body>
</html>

How to store an output of shell script to a variable in Unix?

You should probably re-write the script to return a value rather than output it. Instead of:

a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
   success) echo script succeeded;;
   Failed) echo script failed;;
esac

you would be able to do:

if script.sh > /dev/null; then
    echo script succeeded
else
    echo script failed
fi

It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0 instead of printing success, and exit 1 instead of printing Failed. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.

Git SSH error: "Connect to host: Bad file number"

Maybe your firewall or a blocker application (PeerBlock etc.) is blocking your port

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.

What is the proper way to check and uncheck a checkbox in HTML5?

According to HTML5 drafts, the checked attribute is a “boolean attribute”, and “The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.” It is the name of the attribute that matters, and suffices. Thus, to make a checkbox initially checked, you use

<input type=checkbox checked>

By default, in the absence of the checked attribute, a checkbox is initially unchecked:

<input type=checkbox>

Keeping things this way keeps them simple, but if you need to conform to XML syntax (i.e. to use HTML5 in XHTML linearization), you cannot use an attribute name alone. Then the allowed (as per HTML5 drafts) values are the empty string and the string checked, case insensitively. Example:

<input type="checkbox" checked="checked" />

Current date and time - Default in MVC razor

You could initialize ReturnDate on the model before sending it to the view.

In the controller:

[HttpGet]
public ActionResult SomeAction()
{
    var viewModel = new MyActionViewModel
    {
        ReturnDate = System.DateTime.Now
    };

    return View(viewModel);
}

jQuery: Clearing Form Inputs

Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.

I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.

I got this too work by adding a reset button to the form, which had an id of myform:

$("#myform > input[type=reset]").trigger('click');

This for me had the correct outcome on resetting the form, oh and dont forget the

event.preventDefault();

to stop the form submitting in browser, like I did :).

Regards

Jacko

What can MATLAB do that R cannot do?

I have used both R and MATLAB to solve problems and construct models related to Environmental Engineering and there is a lot of overlap between the two systems. In my opinion, the advantages of MATLAB lie in specialized domain-specific applications. Some examples are:

  • Functions such as streamline that aid in fluid dynamics investigations.

  • Toolboxes such as the image processing toolset. I have not found a R package that provides an equivalent implementation of tools like the watershed algorithm.

In my opinion MATLAB provides far better interactive graphics capabilities. However, I think R produces better static print-quality graphics, depending on the application. MATLAB's symbolic math toolbox is also better integrated and more capable than R equivalents such as Ryacas or rSymPy. The existence of the MATLAB compiler also allows systems based on MATLAB code to be deployed independently of the MATLAB environment-- although it's availability will depend on how much money you have to throw around.

Another thing I should note is that the MATLAB debugger is one of the best I have worked with.

The principle advantage I see with R is the openness of the system and the ease with which it can be extended. This has resulted in an incredible diversity of packages on CRAN. I know Mathworks also maintains a repository of user-contributed toolboxes and I can't make a fair comparison as I have not used it that much.

The openness of R also extends to linking in compiled code. A while back I had a model written in Fortran and I was trying to decide between using R or MATLAB as a front-end to help prepare input and process results. I spent an hour reading about the MEX interface to compiled code. When I found that I would have to write and maintain a separate Fortran routine that did some intricate pointer juggling in order to manage the interface, I shelved MATLAB.

The R interface consists of calling .Fortran( [subroutine name], [argument list]) and is simply quicker and cleaner.

How to concatenate columns in a Postgres SELECT?

The problem was in nulls in the values; then the concatenation does not work with nulls. The solution is as follows:

SELECT coalesce(a, '') || coalesce(b, '') FROM foo;

Resize a large bitmap file to scaled output file on Android

Why not use the API?

int h = 48; // height in pixels
int w = 48; // width in pixels    
Bitmap scaled = Bitmap.createScaledBitmap(largeBitmap, w, h, true);

No value accessor for form control

You are adding the formControlName to the label and not the input.

You have this:

<div >
  <div class="input-field col s12">
    <input id="email" type="email"> 
    <label class="center-align" for="email" formControlName="email">Email</label>
  </div>
</div>

Try using this:

<div >
  <div class="input-field col s12">
    <input id="email" type="email" formControlName="email"> 
    <label class="center-align" for="email">Email</label>
  </div>
</div>

Update the other input fields as well.

Git copy file preserving history

Simply copy the file, add and commit it:

cp dir1/A.txt dir2/A.txt
git add dir2/A.txt
git commit -m "Duplicated file from dir1/ to dir2/"

Then the following commands will show the full pre-copy history:

git log --follow dir2/A.txt

To see inherited line-by-line annotations from the original file use this:

git blame -C -C -C dir2/A.txt

Git does not track copies at commit-time, instead it detects them when inspecting history with e.g. git blame and git log.

Most of this information comes from the answers here: Record file copy operation with Git

How do I print out the contents of an object in Rails for easy debugging?

You need to use debug(@var). It's exactly like "print_r".

How to push files to an emulator instance using Android Studio

One easy way is to drag and drop. It will copy files to /sdcard/Download. You can copy whole folders or multiple files. Make sure that "Enable Clipboard Sharing" is enabled. (under ...->Settings)

enter image description here

Sql select rows containing part of string

you can use CHARINDEX in t-sql.

select * from table where CHARINDEX(url, 'http://url.com/url?url...') > 0

Cropping images in the browser BEFORE the upload

#change-avatar-file is a file input #change-avatar-file is a img tag (the target of jcrop) The "key" is FR.onloadend Event https://developer.mozilla.org/en-US/docs/Web/API/FileReader

$('#change-avatar-file').change(function(){
        var currentImg;
        if ( this.files && this.files[0] ) {
            var FR= new FileReader();
            FR.onload = function(e) {
                $('#avatar-change-img').attr( "src", e.target.result );
                currentImg = e.target.result;
            };
            FR.readAsDataURL( this.files[0] );
            FR.onloadend = function(e){
                //console.log( $('#avatar-change-img').attr( "src"));
                var jcrop_api;

                $('#avatar-change-img').Jcrop({
                    bgFade:     true,
                    bgOpacity: .2,
                    setSelect: [ 60, 70, 540, 330 ]
                },function(){
                    jcrop_api = this;
                });
            }
        }
    });

How to use Elasticsearch with MongoDB?

I found mongo-connector useful. It is form Mongo Labs (MongoDB Inc.) and can be used now with Elasticsearch 2.x

Elastic 2.x doc manager: https://github.com/mongodb-labs/elastic2-doc-manager

mongo-connector creates a pipeline from a MongoDB cluster to one or more target systems, such as Solr, Elasticsearch, or another MongoDB cluster. It synchronizes data in MongoDB to the target then tails the MongoDB oplog, keeping up with operations in MongoDB in real-time. It has been tested with Python 2.6, 2.7, and 3.3+. Detailed documentation is available on the wiki.

https://github.com/mongodb-labs/mongo-connector https://github.com/mongodb-labs/mongo-connector/wiki/Usage%20with%20ElasticSearch

Server returned HTTP response code: 401 for URL: https

401 means "Unauthorized", so there must be something with your credentials.

I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());
    }
});

and then simply invoking the regular url, without the credentials.

The other option is to provide the credentials in a Header:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.

JQuery confirm dialog

You can use jQuery UI and do something like this

Html:

<button id="callConfirm">Confirm!</button>

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>?

Javascript:

$("#dialog").dialog({
   autoOpen: false,
   modal: true,
   buttons : {
        "Confirm" : function() {
            alert("You have confirmed!");            
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

$("#callConfirm").on("click", function(e) {
    e.preventDefault();
    $("#dialog").dialog("open");
});

?

React - Display loading screen while DOM is rendering?

You can easily do that by using lazy loading in react. For that you have to use lazy and suspense from react like that.

import React, { lazy, Suspense } from 'react';

const loadable = (importFunc, { fallback = null } = { fallback: null }) => {
  const LazyComponent = lazy(importFunc);

  return props => (
    <Suspense fallback={fallback}>
      <LazyComponent {...props} />
    </Suspense>
  );
};

export default loadable;

After that export your components like this.

export const TeacherTable = loadable(() =>
  import ('./MainTables/TeacherTable'), {
    fallback: <Loading />,
  });

And then in your routes file use it like this.

 <Route exact path="/app/view/teachers" component={TeacherTable} />

Thats it now you are good to go everytime your DOM is rendering your Loading compnent will be displayed as we have specified in the fallback property above. Just make sure that you do any ajax request only in componentDidMount()

Best way to remove an event handler in jQuery?

This also works fine .Simple and easy.see http://jsfiddle.net/uZc8w/570/

$('#myimage').removeAttr("click");

Display text from .txt file in batch file

Here is a good date and time code:

@echo off
if %date:~4,2%==01 set month=January
if %date:~4,2%==02 set month=February
if %date:~4,2%==03 set month=March
if %date:~4,2%==04 set month=April
if %date:~4,2%==05 set month=May
if %date:~4,2%==06 set month=June
if %date:~4,2%==07 set month=July
if %date:~4,2%==08 set month=August
if %date:~4,2%==09 set month=September
if %date:~4,2%==10 set month=October
if %date:~4,2%==11 set month=November
if %date:~4,2%==12 set month=December

if %date:~0,3%==Mon set day=Monday
if %date:~0,3%==Tue set day=Tuesday
if %date:~0,3%==Wed set day=Wednesday
if %date:~0,3%==Thu set day=Thursday
if %date:~0,3%==Fri set day=Friday
if %date:~0,3%==Sat set day=Saturday
if %date:~0,3%==Sun set day=Sunday
echo.
echo The Date is %day%, %month% %date:~7,2%, %date:~10,4% the current time is: %time:~0,5%
pause

Outputs: The Date is Sunday, September 27, 2009 the current time is: 3:07

CardView background color always white

XML code

<android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view_top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:cardCornerRadius="5dp"
        app:contentPadding="25dp"
        app:cardBackgroundColor="#e4bfef"
        app:cardElevation="4dp"
        app:cardMaxElevation="6dp" />

From the code

CardView card = findViewById(R.id.card_view_top);
card.setCardBackgroundColor(Color.parseColor("#E6E6E6"));

nodemon not working: -bash: nodemon: command not found

in Windows OS run:

npx nodemon server.js

or add in package.json config:

...
"scripts": {
    "dev": "npx nodemon server.js"
  },
...

then run:

npm run dev

Write to Windows Application Event Log

Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.

*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.

I used this code to write directly to the event log Application:

using (EventLog eventLog = new EventLog("Application")) 
{
    eventLog.Source = "Application"; 
    eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); 
}

As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):

Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.

Python Timezone conversion

Time conversion

To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():

so, below code is to convert the local time to other time zone.

  • datetime.datetime.today() - return current the local time
  • datetime.astimezone() - convert the time zone, but we have to pass the time zone.
  • pytz.timezone('Asia/Kolkata') -passing the time zone to pytz module
  • Strftime - Convert Datetime to string
# Time conversion from local time
import datetime
import pytz
dt_today = datetime.datetime.today()   # Local time
dt_India = dt_today.astimezone(pytz.timezone('Asia/Kolkata')) 
dt_London = dt_today.astimezone(pytz.timezone('Europe/London'))
India = (dt_India.strftime('%m/%d/%Y %H:%M'))
London = (dt_London.strftime('%m/%d/%Y %H:%M'))
print("Indian standard time: "+India+" IST")
print("British Summer Time: "+London+" BST")

list all the time zone

import pytz
for tz in pytz.all_timezones:
    print(tz)

Count number of rows per group and add result to original data frame

Using sqldf package:

library(sqldf)

sqldf("select a.*, b.cnt
       from df a,
           (select name, type, count(1) as cnt
            from df
            group by name, type) b
      where a.name = b.name and
            a.type = b.type")

#    name  type num cnt
# 1 black chair   4   2
# 2 black chair   5   2
# 3 black  sofa  12   1
# 4   red  sofa   4   1
# 5   red plate   3   1

Is the ternary operator faster than an "if" condition in Java

Try to use switch case statement but normally it's not the performance bottleneck.

How to add header to a dataset in R?

in case you are interested in reading some data from a .txt file and only extract few columns of that file into a new .txt file with a customized header, the following code might be useful:

# input some data from 2 different .txt files:
civit_gps <- read.csv(file="/path2/gpsFile.csv",head=TRUE,sep=",")
civit_cam <- read.csv(file="/path2/cameraFile.txt",head=TRUE,sep=",")

# assign the name for the output file:
seqName <- "seq1_data.txt"

#=========================================================
# Extract data from imported files
#=========================================================
# From Camera:
frame_idx <- civit_cam$X.frame
qx        <- civit_cam$q.x.rad.
qy        <- civit_cam$q.y.rad.
qz        <- civit_cam$q.z.rad.
qw        <- civit_cam$q.w

# From GPS:
gpsT      <- civit_gps$X.gpsTime.sec.
latitude  <- civit_gps$Latitude.deg.
longitude <- civit_gps$Longitude.deg.
altitude  <- civit_gps$H.Ell.m.
heading   <- civit_gps$Heading.deg.
pitch     <- civit_gps$pitch.deg.
roll      <- civit_gps$roll.deg.
gpsTime_corr <- civit_gps[frame_idx,1]

#=========================================================
# Export new data into the output txt file
#=========================================================
myData <- data.frame(c(gpsTime_corr),
                     c(frame_idx),
                     c(qx),
                     c(qy),
                     c(qz),
                     c(qw))
# Write :
cat("#GPSTime,frameIdx,qx,qy,qz,qw\n", file=seqName)
write.table(myData, file = seqName,row.names=FALSE,col.names=FALSE,append=TRUE,sep = ",")

Of course, you should modify this sample script based on your own application.